Documentation
¶
Overview ¶
Package mcp implements the Model Context Protocol (MCP) over JSON-RPC 2.0.
The package is transport-agnostic: HTTP, Server-Sent Events (SSE), and stdio transports are all provided, but the protocol Handler does not depend on any specific transport. The HTTP-server integration lives in pkg/server; the built-in tools and resources that need a *server.Server live in pkg/mcp/builtin.
Index ¶
- Constants
- func NewStdioTransport(logger *slog.Logger) *stdioTransport
- func NewStdioTransportWithIO(r io.Reader, w io.Writer, logger *slog.Logger) *stdioTransport
- type Capabilities
- type ClientInfo
- type DiscoveryConfig
- type DiscoveryInfo
- type DiscoveryPolicy
- type Extension
- type ExtensionBuilder
- func (b *ExtensionBuilder) Build() Extension
- func (b *ExtensionBuilder) WithConfiguration(fn func(*Handler) error) *ExtensionBuilder
- func (b *ExtensionBuilder) WithDescription(desc string) *ExtensionBuilder
- func (b *ExtensionBuilder) WithResource(resource Resource) *ExtensionBuilder
- func (b *ExtensionBuilder) WithTool(tool Tool) *ExtensionBuilder
- type Handler
- func (h *Handler) BuildDiscoveryInfo(r *http.Request, cfg DiscoveryConfig) DiscoveryInfo
- func (h *Handler) Capabilities() Capabilities
- func (h *Handler) GetMetrics() map[string]any
- func (h *Handler) GetRegisteredResources() []string
- func (h *Handler) GetRegisteredTools() []string
- func (h *Handler) GetToolByName(name string) (Tool, bool)
- func (h *Handler) HasNamespace(name string) bool
- func (h *Handler) HasResource(uri string) bool
- func (h *Handler) HasTool(name string) bool
- func (h *Handler) Logger() *slog.Logger
- func (h *Handler) ProcessRequest(requestData []byte) []byte
- func (h *Handler) ProcessRequestWithTransport(transport Transport) error
- func (h *Handler) RPCEngine() *jsonrpc.Engine
- func (h *Handler) RegisterExtension(ext Extension) error
- func (h *Handler) RegisterNamespace(name string, configs ...NamespaceConfig) error
- func (h *Handler) RegisterResource(resource Resource)
- func (h *Handler) RegisterResourceInNamespace(resource Resource, namespace string)
- func (h *Handler) RegisterTool(tool Tool)
- func (h *Handler) RegisterToolInNamespace(tool Tool, namespace string)
- func (h *Handler) ResourceCount() int
- func (h *Handler) RunStdioLoop() error
- func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (h *Handler) ServerInfo() ServerInfo
- func (h *Handler) SetLogger(l *slog.Logger)
- func (h *Handler) SetToolCallTimeout(d time.Duration)
- func (h *Handler) ToolCount() int
- type InitializeParams
- type InitializeResult
- type Metrics
- type Namespace
- type NamespaceConfig
- type Resource
- type ResourceBuilder
- func (b *ResourceBuilder) Build() Resource
- func (b *ResourceBuilder) WithDescription(desc string) *ResourceBuilder
- func (b *ResourceBuilder) WithMimeType(mimeType string) *ResourceBuilder
- func (b *ResourceBuilder) WithName(name string) *ResourceBuilder
- func (b *ResourceBuilder) WithRead(fn func() (any, error)) *ResourceBuilder
- type ResourceContent
- type ResourceInfo
- type ResourceReadParams
- type ResourcesCapability
- type SSECapability
- type SSEClient
- type SSEManager
- type ServerInfo
- type SimpleResource
- type SimpleTool
- type Tool
- type ToolBuilder
- type ToolCallParams
- type ToolInfo
- type ToolResult
- type ToolWithContext
- type ToolsCapability
- type Transport
- type TransportConfig
- type TransportInfo
- type TransportOptions
- type TransportType
Constants ¶
const ProtocolVersion = "2024-11-05"
ProtocolVersion is the MCP protocol version implemented by this package.
Variables ¶
This section is empty.
Functions ¶
func NewStdioTransport ¶
NewStdioTransport creates a new stdio transport using os.Stdin / os.Stdout.
Types ¶
type Capabilities ¶
type Capabilities struct {
Resources *ResourcesCapability `json:"resources,omitempty"`
Tools *ToolsCapability `json:"tools,omitempty"`
SSE *SSECapability `json:"sse,omitempty"`
}
Capabilities represents the server's advertised MCP capabilities. Add fields here only when the corresponding capability is actually wired in Handler.Capabilities() and exercised on the wire; advertising an unsupported capability is worse than omitting it.
type ClientInfo ¶
ClientInfo identifies an MCP client.
type DiscoveryConfig ¶
type DiscoveryConfig struct {
// MCPEndpoint is the URL path the MCP handler is mounted on (e.g. "/mcp").
MCPEndpoint string
// DefaultAddr is used to derive the base URL when the request has no Host header.
DefaultAddr string
// Transport identifies the transport in use (HTTP / Stdio).
Transport TransportType
// Policy controls discovery list visibility.
Policy DiscoveryPolicy
// Dev indicates the server is running in MCP developer mode and may
// therefore expose tools that would otherwise be hidden.
Dev bool
// Filter, if non-nil, makes the final decision per tool. It overrides the
// default rules entirely.
Filter func(toolName string, r *http.Request) bool
}
DiscoveryConfig groups the inputs needed to build a DiscoveryInfo response.
type DiscoveryInfo ¶
type DiscoveryInfo struct {
Version string `json:"version"`
Transports []TransportInfo `json:"transports"`
Endpoints map[string]string `json:"endpoints"`
Capabilities map[string]any `json:"capabilities,omitempty"`
}
DiscoveryInfo describes the MCP endpoints surfaced by the discovery API.
type DiscoveryPolicy ¶
type DiscoveryPolicy int
DiscoveryPolicy controls how MCP tools and resources are exposed via the discovery endpoints (/.well-known/mcp.json and /mcp/discover).
const ( // DiscoveryPublic shows all discoverable tools/resources (default). DiscoveryPublic DiscoveryPolicy = iota // DiscoveryCount only exposes counts, not names. DiscoveryCount // DiscoveryAuthenticated returns the full list only when the request // carries an Authorization header. DiscoveryAuthenticated // DiscoveryNone hides all tool/resource information. DiscoveryNone )
type Extension ¶
type Extension interface {
// Name returns the extension name (e.g., "e-commerce", "blog").
Name() string
// Description returns a human-readable description.
Description() string
// Tools returns the tools provided by this extension.
Tools() []Tool
// Resources returns the resources provided by this extension.
Resources() []Resource
// Configure runs before registration with the supplied handler. Use it to
// wire the extension up to the handler (e.g. capture a reference, register
// extra namespaces).
Configure(h *Handler) error
}
Extension represents a collection of MCP tools and resources that can be registered as a group. It's the lightweight way to package related functionality together.
type ExtensionBuilder ¶
type ExtensionBuilder struct {
// contains filtered or unexported fields
}
ExtensionBuilder provides a fluent API for building Extensions.
func NewExtension ¶
func NewExtension(name string) *ExtensionBuilder
NewExtension creates a new extension builder.
func (*ExtensionBuilder) Build ¶
func (b *ExtensionBuilder) Build() Extension
func (*ExtensionBuilder) WithConfiguration ¶
func (b *ExtensionBuilder) WithConfiguration(fn func(*Handler) error) *ExtensionBuilder
func (*ExtensionBuilder) WithDescription ¶
func (b *ExtensionBuilder) WithDescription(desc string) *ExtensionBuilder
func (*ExtensionBuilder) WithResource ¶
func (b *ExtensionBuilder) WithResource(resource Resource) *ExtensionBuilder
func (*ExtensionBuilder) WithTool ¶
func (b *ExtensionBuilder) WithTool(tool Tool) *ExtensionBuilder
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler manages MCP protocol communication with multiple namespace support. The SSE state machine (client registry + per-client request channels) lives entirely in sseManager — Handler stays focused on JSON-RPC dispatch.
func NewHandler ¶
func NewHandler(serverInfo ServerInfo) *Handler
NewHandler creates a new MCP handler instance.
func (*Handler) BuildDiscoveryInfo ¶
func (h *Handler) BuildDiscoveryInfo(r *http.Request, cfg DiscoveryConfig) DiscoveryInfo
BuildDiscoveryInfo constructs the discovery payload based on the supplied configuration and request. The caller is responsible for marshalling and writing the response.
func (*Handler) Capabilities ¶
func (h *Handler) Capabilities() Capabilities
Capabilities returns the server's MCP capabilities.
func (*Handler) GetMetrics ¶
GetMetrics returns the current MCP metrics summary.
func (*Handler) GetRegisteredResources ¶
GetRegisteredResources returns all registered resource URIs. Returns a non-nil slice even when no resources are registered.
func (*Handler) GetRegisteredTools ¶
GetRegisteredTools returns all registered tool names. Returns a non-nil slice even when no tools are registered.
func (*Handler) GetToolByName ¶
GetToolByName returns a tool by its (possibly prefixed) name.
func (*Handler) HasNamespace ¶
HasNamespace reports whether a namespace with the given name has been registered via RegisterNamespace.
func (*Handler) HasResource ¶
HasResource reports whether a resource with the given URI is registered.
func (*Handler) HasTool ¶
HasTool reports whether a tool with the given (possibly prefixed) name is registered.
func (*Handler) ProcessRequest ¶
ProcessRequest processes a single MCP request (raw JSON).
func (*Handler) ProcessRequestWithTransport ¶
ProcessRequestWithTransport processes an MCP request using the provided transport.
func (*Handler) RPCEngine ¶
RPCEngine returns the underlying JSON-RPC engine. Exposed so tests and transports can dispatch a parsed request without re-marshalling.
func (*Handler) RegisterExtension ¶
RegisterExtension wires all of an Extension's tools and resources into the handler. It calls Configure(h) first so the extension can hook in.
func (*Handler) RegisterNamespace ¶
func (h *Handler) RegisterNamespace(name string, configs ...NamespaceConfig) error
RegisterNamespace registers an entire namespace with its tools and resources.
func (*Handler) RegisterResource ¶
RegisterResource registers an MCP resource without namespace prefixing.
func (*Handler) RegisterResourceInNamespace ¶
RegisterResourceInNamespace registers an MCP resource in the specified namespace.
func (*Handler) RegisterTool ¶
RegisterTool registers an MCP tool without namespace prefixing.
func (*Handler) RegisterToolInNamespace ¶
RegisterToolInNamespace registers an MCP tool in the specified namespace.
func (*Handler) ResourceCount ¶
ResourceCount returns the number of registered resources.
func (*Handler) RunStdioLoop ¶
RunStdioLoop runs the MCP handler in stdio mode until EOF is received. EOF is treated as a normal shutdown signal.
func (*Handler) ServeHTTP ¶
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler for the MCP endpoint.
func (*Handler) ServerInfo ¶
func (h *Handler) ServerInfo() ServerInfo
ServerInfo returns the server info associated with this handler.
func (*Handler) SetLogger ¶
SetLogger overrides the handler's logger. Useful for tests that want to silence output.
func (*Handler) SetToolCallTimeout ¶ added in v0.27.0
SetToolCallTimeout overrides the per-call timeout used when dispatching tools/call. Zero or negative values reset to defaultToolCallTimeout.
type InitializeParams ¶
type InitializeParams struct {
ProtocolVersion string `json:"protocolVersion"`
Capabilities any `json:"capabilities"`
ClientInfo ClientInfo `json:"clientInfo"`
}
InitializeParams is the parameter struct for the "initialize" method.
type InitializeResult ¶
type InitializeResult struct {
ProtocolVersion string `json:"protocolVersion"`
Capabilities Capabilities `json:"capabilities"`
ServerInfo ServerInfo `json:"serverInfo"`
}
InitializeResult is the result returned by the "initialize" method.
type Metrics ¶
type Metrics struct {
// contains filtered or unexported fields
}
Metrics tracks performance metrics for MCP operations.
func (*Metrics) GetMetricsSummary ¶
GetMetricsSummary returns a summary of collected metrics.
type NamespaceConfig ¶
type NamespaceConfig func(*Namespace)
NamespaceConfig configures a Namespace.
func WithNamespaceResources ¶
func WithNamespaceResources(resources ...Resource) NamespaceConfig
WithNamespaceResources adds resources to a namespace.
func WithNamespaceTools ¶
func WithNamespaceTools(tools ...Tool) NamespaceConfig
WithNamespaceTools adds tools to a namespace.
type Resource ¶
type Resource interface {
URI() string
Name() string
Description() string
MimeType() string
Read() (any, error)
List() ([]string, error)
}
Resource defines the interface for Model Context Protocol resources.
type ResourceBuilder ¶
type ResourceBuilder struct {
// contains filtered or unexported fields
}
ResourceBuilder provides a fluent API for building Resources.
func NewResource ¶
func NewResource(uri string) *ResourceBuilder
NewResource creates a new resource builder.
func (*ResourceBuilder) Build ¶
func (b *ResourceBuilder) Build() Resource
func (*ResourceBuilder) WithDescription ¶
func (b *ResourceBuilder) WithDescription(desc string) *ResourceBuilder
func (*ResourceBuilder) WithMimeType ¶
func (b *ResourceBuilder) WithMimeType(mimeType string) *ResourceBuilder
func (*ResourceBuilder) WithName ¶
func (b *ResourceBuilder) WithName(name string) *ResourceBuilder
func (*ResourceBuilder) WithRead ¶
func (b *ResourceBuilder) WithRead(fn func() (any, error)) *ResourceBuilder
type ResourceContent ¶
type ResourceContent struct {
URI string `json:"uri"`
MimeType string `json:"mimeType"`
Text any `json:"text"`
}
ResourceContent represents the content body of a resource.
type ResourceInfo ¶
type ResourceInfo struct {
URI string `json:"uri"`
Name string `json:"name"`
Description string `json:"description"`
MimeType string `json:"mimeType"`
}
ResourceInfo describes a resource in resources/list responses.
type ResourceReadParams ¶
type ResourceReadParams struct {
URI string `json:"uri"`
}
ResourceReadParams is the parameter struct for "resources/read".
type ResourcesCapability ¶
type ResourcesCapability struct {
Subscribe bool `json:"subscribe,omitempty"`
ListChanged bool `json:"listChanged,omitempty"`
}
ResourcesCapability represents the server's resource management capabilities.
type SSECapability ¶
type SSECapability struct {
Enabled bool `json:"enabled"`
Endpoint string `json:"endpoint"`
HeaderRouting bool `json:"headerRouting"`
}
SSECapability represents the server's Server-Sent Events capability.
type SSEClient ¶
type SSEClient struct {
// contains filtered or unexported fields
}
SSEClient represents a connected SSE client.
func (*SSEClient) SetInitialized ¶
func (c *SSEClient) SetInitialized()
SetInitialized marks the client as initialized.
func (*SSEClient) VerifyBinding ¶ added in v0.27.0
VerifyBinding constant-time-compares the supplied token to this client's binding token. Returns false for empty supplied token (no compatibility shortcut for missing header).
type SSEManager ¶
type SSEManager struct {
// contains filtered or unexported fields
}
SSEManager owns the per-connection client state plus the per-client request channels used by the SSE-routed POST flow. Previously the channel map lived on Handler (`sseRequests`/`sseMutex`), forming a parallel state machine; consolidated here so HandleSSE and handleSSERoutedRequest agree on a single source of truth.
func NewSSEManager ¶
func NewSSEManager() *SSEManager
NewSSEManager creates a new SSE connection manager.
func (*SSEManager) BroadcastToAll ¶
func (m *SSEManager) BroadcastToAll(response *jsonrpc.Response)
BroadcastToAll sends a response to all connected SSE clients.
func (*SSEManager) GetClientCount ¶
func (m *SSEManager) GetClientCount() int
GetClientCount returns the number of connected SSE clients.
func (*SSEManager) HandleSSE ¶
func (m *SSEManager) HandleSSE(w http.ResponseWriter, r *http.Request, mcpHandler *Handler)
HandleSSE handles SSE connections for MCP.
func (*SSEManager) SendToClient ¶
func (m *SSEManager) SendToClient(clientID string, response *jsonrpc.Response) error
SendToClient sends a response to a specific SSE client.
type ServerInfo ¶
ServerInfo identifies an MCP server.
type SimpleResource ¶
type SimpleResource struct {
URIFunc func() string
NameFunc func() string
DescriptionFunc func() string
MimeTypeFunc func() string
ReadFunc func() (any, error)
ListFunc func() ([]string, error)
}
SimpleResource is a Resource implementation backed by function fields.
func (*SimpleResource) Description ¶
func (r *SimpleResource) Description() string
func (*SimpleResource) List ¶
func (r *SimpleResource) List() ([]string, error)
func (*SimpleResource) MimeType ¶
func (r *SimpleResource) MimeType() string
func (*SimpleResource) Name ¶
func (r *SimpleResource) Name() string
func (*SimpleResource) Read ¶
func (r *SimpleResource) Read() (any, error)
func (*SimpleResource) URI ¶
func (r *SimpleResource) URI() string
type SimpleTool ¶
type SimpleTool struct {
NameFunc func() string
DescriptionFunc func() string
SchemaFunc func() map[string]any
ExecuteFunc func(map[string]any) (any, error)
}
SimpleTool is a Tool implementation backed by function fields. Use it when you want a one-off tool without defining a new struct.
func (*SimpleTool) Description ¶
func (t *SimpleTool) Description() string
func (*SimpleTool) Name ¶
func (t *SimpleTool) Name() string
func (*SimpleTool) Schema ¶
func (t *SimpleTool) Schema() map[string]any
type Tool ¶
type Tool interface {
Name() string
Description() string
Schema() map[string]any
Execute(params map[string]any) (any, error)
}
Tool defines the interface for Model Context Protocol tools.
type ToolBuilder ¶
type ToolBuilder struct {
// contains filtered or unexported fields
}
ToolBuilder provides a fluent API for building Tools.
func (*ToolBuilder) Build ¶
func (b *ToolBuilder) Build() Tool
func (*ToolBuilder) WithDescription ¶
func (b *ToolBuilder) WithDescription(desc string) *ToolBuilder
func (*ToolBuilder) WithExecute ¶
func (b *ToolBuilder) WithExecute(fn func(map[string]any) (any, error)) *ToolBuilder
func (*ToolBuilder) WithParameter ¶
func (b *ToolBuilder) WithParameter(name, paramType, description string, required bool) *ToolBuilder
type ToolCallParams ¶
type ToolCallParams struct {
Name string `json:"name"`
Arguments map[string]any `json:"arguments"`
}
ToolCallParams is the parameter struct for "tools/call".
type ToolInfo ¶
type ToolInfo struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema map[string]any `json:"inputSchema"`
}
ToolInfo describes a tool in tools/list responses.
type ToolResult ¶
type ToolResult struct {
Content []map[string]any `json:"content"`
IsError bool `json:"isError,omitempty"`
}
ToolResult represents the result of a tool execution.
type ToolWithContext ¶
type ToolWithContext interface {
Tool
ExecuteWithContext(ctx context.Context, params map[string]any) (any, error)
}
ToolWithContext is an enhanced Tool that supports context for cancellation and timeouts during ExecuteWithContext.
type ToolsCapability ¶
type ToolsCapability struct {
ListChanged bool `json:"listChanged,omitempty"`
}
ToolsCapability represents the server's tool execution capabilities.
type Transport ¶
type Transport interface {
Send(response *jsonrpc.Response) error
Receive() (*jsonrpc.Request, error)
Close() error
}
Transport defines the interface for MCP communication transports.
type TransportConfig ¶
type TransportConfig func(*TransportOptions)
TransportConfig configures MCP transport options.
func OverStdio ¶
func OverStdio() TransportConfig
OverStdio configures MCP to use stdio transport.
The HTTP/SSE counterparts that used to live here were unused (no caller outside this file); HTTP is the default when no Over* config is supplied, and SSE shares the HTTP endpoint via Accept-header routing. Configure the endpoint path with WithMCPEndpoint from pkg/server instead.
func WithDeveloperMode ¶
func WithDeveloperMode() TransportConfig
WithDeveloperMode marks the transport options as opting into the developer preset.
func WithObservabilityMode ¶
func WithObservabilityMode() TransportConfig
WithObservabilityMode marks the transport options as opting into the observability preset. The preset itself is implemented by callers (e.g. pkg/mcp/builtin) which read this flag.
type TransportInfo ¶
type TransportInfo struct {
Type string `json:"type"`
Endpoint string `json:"endpoint"`
Description string `json:"description"`
Headers map[string]string `json:"headers,omitempty"`
}
TransportInfo describes one available transport mechanism.
type TransportOptions ¶
type TransportOptions struct {
Transport TransportType
Endpoint string
ObservabilityMode bool
DeveloperMode bool
}
TransportOptions holds transport configuration. It is exported so callers (most notably pkg/server) can inspect the resolved transport selection after applying a series of TransportConfig functions.
type TransportType ¶
type TransportType int
TransportType identifies the kind of transport used for MCP communication.
const ( // HTTPTransport selects HTTP-based MCP communication. HTTPTransport TransportType = iota // StdioTransport selects stdin/stdout MCP communication. StdioTransport )