mcp

package
v0.26.0 Latest Latest
Warning

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

Go to latest
Published: May 18, 2026 License: MIT Imports: 17 Imported by: 0

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

View Source
const ProtocolVersion = "2024-11-05"

ProtocolVersion is the MCP protocol version implemented by this package.

Variables

This section is empty.

Functions

func DefaultLogger

func DefaultLogger() *slog.Logger

DefaultLogger returns the logger used by the mcp package.

func NewStdioTransport

func NewStdioTransport(logger *slog.Logger) *stdioTransport

NewStdioTransport creates a new stdio transport using os.Stdin / os.Stdout.

func NewStdioTransportWithIO

func NewStdioTransportWithIO(r io.Reader, w io.Writer, logger *slog.Logger) *stdioTransport

NewStdioTransportWithIO creates a new stdio transport with custom IO.

func SetDefaultLogger

func SetDefaultLogger(l *slog.Logger)

SetDefaultLogger overrides the logger used by the mcp package.

Types

type Capabilities

type Capabilities struct {
	Experimental map[string]any       `json:"experimental,omitempty"`
	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

type ClientInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

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.

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

func (h *Handler) GetMetrics() map[string]any

GetMetrics returns the current MCP metrics summary.

func (*Handler) GetRegisteredResources

func (h *Handler) GetRegisteredResources() []string

GetRegisteredResources returns all registered resource URIs. Returns a non-nil slice even when no resources are registered.

func (*Handler) GetRegisteredTools

func (h *Handler) GetRegisteredTools() []string

GetRegisteredTools returns all registered tool names. Returns a non-nil slice even when no tools are registered.

func (*Handler) GetToolByName

func (h *Handler) GetToolByName(name string) (Tool, bool)

GetToolByName returns a tool by its (possibly prefixed) name.

func (*Handler) HasNamespace

func (h *Handler) HasNamespace(name string) bool

HasNamespace reports whether a namespace with the given name has been registered via RegisterNamespace.

func (*Handler) HasResource

func (h *Handler) HasResource(uri string) bool

HasResource reports whether a resource with the given URI is registered.

func (*Handler) HasTool

func (h *Handler) HasTool(name string) bool

HasTool reports whether a tool with the given (possibly prefixed) name is registered.

func (*Handler) Logger

func (h *Handler) Logger() *slog.Logger

Logger returns the handler's logger.

func (*Handler) ProcessRequest

func (h *Handler) ProcessRequest(requestData []byte) []byte

ProcessRequest processes a single MCP request (raw JSON).

func (*Handler) ProcessRequestWithTransport

func (h *Handler) ProcessRequestWithTransport(transport Transport) error

ProcessRequestWithTransport processes an MCP request using the provided transport.

func (*Handler) RPCEngine

func (h *Handler) RPCEngine() *jsonrpc.Engine

RPCEngine returns the underlying JSON-RPC engine. Exposed so tests and transports can dispatch a parsed request without re-marshalling.

func (*Handler) RegisterExtension

func (h *Handler) RegisterExtension(ext Extension) error

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

func (h *Handler) RegisterResource(resource Resource)

RegisterResource registers an MCP resource without namespace prefixing.

func (*Handler) RegisterResourceInNamespace

func (h *Handler) RegisterResourceInNamespace(resource Resource, namespace string)

RegisterResourceInNamespace registers an MCP resource in the specified namespace.

func (*Handler) RegisterSSEClient

func (h *Handler) RegisterSSEClient(clientID string) chan *jsonrpc.Request

RegisterSSEClient registers a new SSE client for request routing.

func (*Handler) RegisterTool

func (h *Handler) RegisterTool(tool Tool)

RegisterTool registers an MCP tool without namespace prefixing.

func (*Handler) RegisterToolInNamespace

func (h *Handler) RegisterToolInNamespace(tool Tool, namespace string)

RegisterToolInNamespace registers an MCP tool in the specified namespace.

func (*Handler) ResourceCount

func (h *Handler) ResourceCount() int

ResourceCount returns the number of registered resources.

func (*Handler) RunStdioLoop

func (h *Handler) RunStdioLoop() error

RunStdioLoop runs the MCP handler in stdio mode until EOF is received. EOF is treated as a normal shutdown signal.

func (*Handler) SendSSENotification

func (h *Handler) SendSSENotification(clientID string, method string, params any) error

SendSSENotification sends a notification to a specific SSE client.

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

func (h *Handler) SetLogger(l *slog.Logger)

SetLogger overrides the handler's logger. Useful for tests that want to silence output.

func (*Handler) ToolCount

func (h *Handler) ToolCount() int

ToolCount returns the number of registered tools.

func (*Handler) UnregisterSSEClient

func (h *Handler) UnregisterSSEClient(clientID string)

UnregisterSSEClient removes an SSE client.

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

func (m *Metrics) GetMetricsSummary() map[string]any

GetMetricsSummary returns a summary of collected metrics.

type Namespace

type Namespace struct {
	Name      string
	Tools     []Tool
	Resources []Resource
}

Namespace represents a named collection of MCP tools and resources.

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) Close

func (c *SSEClient) Close()

Close closes the SSE client connection.

func (*SSEClient) IsReady

func (c *SSEClient) IsReady() bool

IsReady reports whether the client is ready to receive messages.

func (*SSEClient) Send

func (c *SSEClient) Send(response *jsonrpc.Response) (err error)

Send sends a JSON-RPC response to the SSE client.

func (*SSEClient) SetInitialized

func (c *SSEClient) SetInitialized()

SetInitialized marks the client as initialized.

func (*SSEClient) SetReady

func (c *SSEClient) SetReady()

SetReady marks the client as ready.

type SSEManager

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

SSEManager manages SSE connections for MCP.

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

type ServerInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

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) Execute

func (t *SimpleTool) Execute(params map[string]any) (any, error)

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 NewTool

func NewTool(name string) *ToolBuilder

NewTool creates a new tool builder.

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 OverHTTP

func OverHTTP(endpoint string) TransportConfig

OverHTTP configures MCP to use HTTP transport with the specified endpoint.

func OverSSE

func OverSSE(endpoint string) TransportConfig

OverSSE configures MCP to use SSE transport. SSE shares the HTTP endpoint; transport selection happens per-request based on the Accept header.

func OverStdio

func OverStdio() TransportConfig

OverStdio configures MCP to use stdio transport.

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
)

Directories

Path Synopsis
Package builtin provides ready-to-register MCP tools and resources.
Package builtin provides ready-to-register MCP tools and resources.

Jump to

Keyboard shortcuts

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