registry

package
v0.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 2, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package registry provides high-level helpers for building MCP servers with tool discovery, registration, and execution.

Registry combines toolfoundation/model, tooldiscovery/index, and tooldiscovery/search into a unified API for creating MCP servers quickly.

Features:

  • Local tool registration with handlers
  • MCP backend connections (streamable HTTP, SSE, stdio)
  • BM25-based tool search
  • MCP protocol handlers (initialize, tools/list, tools/call)
  • Multiple transports (stdio, HTTP, SSE)

Example usage:

reg := registry.New(registry.Config{
    ServerInfo: registry.ServerInfo{
        Name:    "my-server",
        Version: "1.0.0",
    },
})

reg.RegisterLocalFunc(
    "echo",
    "Echoes back the input",
    map[string]any{
        "type": "object",
        "properties": map[string]any{
            "message": map[string]any{"type": "string"},
        },
    },
    func(ctx context.Context, args map[string]any) (any, error) {
        return args, nil
    },
)

ctx := context.Background()
reg.Start(ctx)
defer reg.Stop()

registry.ServeStdio(ctx, reg)

Index

Constants

View Source
const (
	ErrCodeParseError     = -32700
	ErrCodeInvalidRequest = -32600
	ErrCodeMethodNotFound = -32601
	ErrCodeInvalidParams  = -32602
	ErrCodeInternal       = -32603
	ErrCodeToolNotFound   = -32001
	ErrCodeToolExecFailed = -32002
)

MCP JSON-RPC 2.0 error codes as per the spec.

Variables

View Source
var (
	ErrNotStarted      = errors.New("registry not started")
	ErrAlreadyStarted  = errors.New("registry already started")
	ErrToolNotFound    = errors.New("tool not found")
	ErrBackendNotFound = errors.New("backend not found")
	ErrHandlerNotFound = errors.New("handler not found")
	ErrExecutionFailed = errors.New("tool execution failed")
	ErrInvalidRequest  = errors.New("invalid request")
)

Sentinel errors for consistent error handling.

Functions

func ServeHTTP

func ServeHTTP(r *Registry) http.Handler

ServeHTTP returns an http.Handler for streamable HTTP transport. Handles POST requests with JSON-RPC bodies, returns JSON responses.

func ServeSSE

func ServeSSE(r *Registry) http.Handler

ServeSSE returns an http.Handler for Server-Sent Events transport. Clients POST to establish connection, receive events via SSE stream.

func ServeStdio

func ServeStdio(ctx context.Context, r *Registry) error

ServeStdio runs the registry as an MCP server over stdio. Blocks until stdin is closed or context is cancelled.

Types

type BackendConfig

type BackendConfig struct {
	// Name is a unique identifier for the backend.
	Name string
	// URL is the MCP server URL (http(s)://, sse://, stdio://).
	URL string
	// Headers are optional HTTP headers for authenticated backends.
	Headers map[string]string
	// MaxRetries controls reconnect attempts for streamable HTTP transport.
	MaxRetries int
	// RetryInterval is reserved for future use.
	RetryInterval time.Duration
	// Transport overrides URL handling when provided (useful for tests).
	Transport mcp.Transport
}

BackendConfig describes an MCP backend connection.

type Config

type Config struct {
	SearchConfig    *search.BM25Config
	ServerInfo      ServerInfo
	BackendSelector index.BackendSelector
}

Config configures a Registry.

type LocalToolOption

type LocalToolOption func(*localToolConfig)

LocalToolOption configures local tool registration.

func WithNamespace

func WithNamespace(ns string) LocalToolOption

WithNamespace sets the namespace for a local tool.

func WithTags

func WithTags(tags ...string) LocalToolOption

WithTags sets the tags for a local tool.

func WithVersion

func WithVersion(v string) LocalToolOption

WithVersion sets the version for a local tool.

type MCPError

type MCPError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
}

MCPError is a JSON-RPC error object.

type MCPRequest

type MCPRequest struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      any             `json:"id"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
}

MCPRequest represents an incoming MCP JSON-RPC request.

type MCPResponse

type MCPResponse struct {
	JSONRPC string    `json:"jsonrpc"`
	ID      any       `json:"id"`
	Result  any       `json:"result,omitempty"`
	Error   *MCPError `json:"error,omitempty"`
}

MCPResponse represents an MCP JSON-RPC response.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry is a high-level MCP tool registry with built-in search, local tool registration, and MCP backend connection.

func New

func New(cfg Config) *Registry

New creates a new Registry with the given config.

func (*Registry) Execute

func (r *Registry) Execute(ctx context.Context, name string, args map[string]any) (any, error)

Execute runs a tool by name with the given arguments.

func (*Registry) GetTool

func (r *Registry) GetTool(ctx context.Context, id string) (model.Tool, error)

GetTool returns a tool by ID.

func (*Registry) HandleRequest

func (r *Registry) HandleRequest(ctx context.Context, req MCPRequest) MCPResponse

HandleRequest processes an MCP request and returns a response.

func (*Registry) HealthCheck

func (r *Registry) HealthCheck(ctx context.Context) error

HealthCheck returns nil if the registry is healthy.

func (*Registry) ListAll

func (r *Registry) ListAll(ctx context.Context) ([]model.Tool, error)

ListAll returns all registered tools.

func (*Registry) ListNamespaces

func (r *Registry) ListNamespaces(ctx context.Context) ([]string, error)

ListNamespaces returns all tool namespaces.

func (*Registry) Refresh

func (r *Registry) Refresh() uint64

Refresh triggers a refresh of search indexes.

func (*Registry) RegisterLocal

func (r *Registry) RegisterLocal(tool model.Tool, handler ToolHandler) error

RegisterLocal registers a tool with a local execution handler.

func (*Registry) RegisterLocalFunc

func (r *Registry) RegisterLocalFunc(
	name, description string,
	inputSchema map[string]any,
	handler ToolHandler,
	opts ...LocalToolOption,
) error

RegisterLocalFunc is a convenience for inline tool definition.

func (*Registry) RegisterMCP

func (r *Registry) RegisterMCP(cfg BackendConfig) error

RegisterMCP registers an MCP server as a backend. Tools from this backend are discovered and registered on Start.

func (*Registry) Search

func (r *Registry) Search(ctx context.Context, query string, limit int) ([]model.Tool, error)

Search performs a BM25 search and returns ranked tools.

func (*Registry) SearchSummaries

func (r *Registry) SearchSummaries(ctx context.Context, query string, limit int) ([]index.Summary, error)

SearchSummaries returns lightweight summaries (faster for listing).

func (*Registry) Start

func (r *Registry) Start(ctx context.Context) error

Start initializes the registry and connects MCP backends.

func (*Registry) Stats

func (r *Registry) Stats() RegistryStats

Stats returns registry statistics.

func (*Registry) Stop

func (r *Registry) Stop() error

Stop gracefully shuts down all backend connections.

func (*Registry) UnregisterMCP

func (r *Registry) UnregisterMCP(name string) error

UnregisterMCP removes a registered MCP backend.

type RegistryStats

type RegistryStats struct {
	TotalTools   int
	LocalTools   int
	MCPTools     int
	Backends     int
	IndexVersion uint64
}

RegistryStats returns registry statistics.

type ServerInfo

type ServerInfo struct {
	Name    string
	Version string
}

ServerInfo describes this MCP server for initialize response.

type ToolHandler

type ToolHandler func(ctx context.Context, args map[string]any) (any, error)

ToolHandler executes a local tool with the given arguments. It receives a context for cancellation and a map of arguments parsed from the MCP request. It returns the result as any (typically a map or struct) and an error if execution fails.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL