mcp

package
v1.5.4 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2026 License: Apache-2.0 Imports: 16 Imported by: 4

Documentation

Index

Constants

View Source
const DefaultMaxProcesses = 0

DefaultMaxProcesses is the default maximum number of concurrent MCP processes. 0 means unlimited.

View Source
const ProtocolVersion = "2025-06-18"

ProtocolVersion defines the MCP protocol version (as of 2025-06-18).

Variables

View Source
var (
	// ErrClientNotInitialized is returned when attempting operations on uninitialized client
	ErrClientNotInitialized = errors.New("mcp: client not initialized")
	// ErrClientClosed is returned when attempting operations on closed client
	ErrClientClosed = errors.New("mcp: client closed")
	// ErrServerUnresponsive is returned when server doesn't respond
	ErrServerUnresponsive = errors.New("mcp: server unresponsive")
	// ErrProcessDied is returned when server process dies unexpectedly
	ErrProcessDied = errors.New("mcp: server process died")
)
View Source
var (
	// ErrMaxProcessesReached is returned when the concurrent process limit has been reached.
	ErrMaxProcessesReached = errors.New("mcp: maximum concurrent processes reached")
)

Functions

This section is empty.

Types

type Client

type Client interface {
	// Initialize establishes the MCP connection and negotiates capabilities
	Initialize(ctx context.Context) (*InitializeResponse, error)

	// ListTools retrieves all available tools from the server
	ListTools(ctx context.Context) ([]Tool, error)

	// CallTool executes a tool with the given arguments
	CallTool(ctx context.Context, name string, arguments json.RawMessage) (*ToolCallResponse, error)

	// Close terminates the connection to the MCP server
	Close() error

	// IsAlive checks if the connection is still active
	IsAlive() bool
}

Client interface defines the MCP client operations

type ClientCapabilities

type ClientCapabilities struct {
	Elicitation *ElicitationCapability `json:"elicitation,omitempty"`
	Sampling    *SamplingCapability    `json:"sampling,omitempty"`
	Logging     *LoggingCapability     `json:"logging,omitempty"`
}

ClientCapabilities describes what the client supports

type ClientOptions

type ClientOptions struct {
	// RequestTimeout is the default timeout for RPC requests
	RequestTimeout time.Duration
	// InitTimeout is the timeout for the initialization handshake
	InitTimeout time.Duration
	// MaxRetries is the number of times to retry failed requests
	MaxRetries int
	// RetryDelay is the initial delay between retries (exponential backoff)
	RetryDelay time.Duration
	// EnableGracefulDegradation allows operations to continue even if MCP is unavailable
	EnableGracefulDegradation bool
	// MaxReconnectAttempts is the maximum number of times to attempt reconnection
	// when a process death is detected. 0 disables auto-reconnection.
	MaxReconnectAttempts int
}

ClientOptions configures MCP client behavior

func DefaultClientOptions

func DefaultClientOptions() ClientOptions

DefaultClientOptions returns sensible defaults

type Content

type Content struct {
	Type     string `json:"type"` // "text", "image", "resource", etc.
	Text     string `json:"text,omitempty"`
	Data     string `json:"data,omitempty"`     // Base64 encoded data
	MimeType string `json:"mimeType,omitempty"` // MIME type for data
	URI      string `json:"uri,omitempty"`      // URI for resources
}

Content represents a content item in MCP responses

type ElicitationCapability

type ElicitationCapability struct{}

ElicitationCapability indicates the client supports elicitation

type Implementation

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

Implementation describes client or server implementation details

type InitializeRequest

type InitializeRequest struct {
	ProtocolVersion string             `json:"protocolVersion"`
	Capabilities    ClientCapabilities `json:"capabilities"`
	ClientInfo      Implementation     `json:"clientInfo"`
}

InitializeRequest represents the initialization request params

type InitializeResponse

type InitializeResponse struct {
	ProtocolVersion string             `json:"protocolVersion"`
	Capabilities    ServerCapabilities `json:"capabilities"`
	ServerInfo      Implementation     `json:"serverInfo"`
}

InitializeResponse represents the initialization response

type JSONRPCError

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

JSONRPCError represents a JSON-RPC 2.0 error

type JSONRPCMessage

type JSONRPCMessage struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      interface{}     `json:"id,omitempty"`     // Request ID (number or string)
	Method  string          `json:"method,omitempty"` // Method name for requests/notifications
	Params  json.RawMessage `json:"params,omitempty"` // Parameters for method
	Result  json.RawMessage `json:"result,omitempty"` // Result for responses
	Error   *JSONRPCError   `json:"error,omitempty"`  // Error for error responses
}

JSONRPCMessage represents a JSON-RPC 2.0 message

type LoggingCapability

type LoggingCapability struct{}

LoggingCapability indicates the client supports logging

type PromptsCapability

type PromptsCapability struct {
	ListChanged bool `json:"listChanged,omitempty"`
}

PromptsCapability indicates the server supports prompts

type Registry

type Registry interface {
	// RegisterServer adds a new MCP server configuration
	RegisterServer(config ServerConfig) error

	// UnregisterServer closes the client (if any) and removes the server
	// from the registry. Unknown names are no-ops.
	UnregisterServer(name string) error

	// GetClient returns an active client for the given server name
	GetClient(ctx context.Context, serverName string) (Client, error)

	// GetClientForTool returns the client that provides the specified tool
	GetClientForTool(ctx context.Context, toolName string) (Client, error)

	// ListServers returns all registered server names
	ListServers() []string

	// ListAllTools returns all tools from all connected servers
	ListAllTools(ctx context.Context) (map[string][]Tool, error)

	// GetServerConfig returns the configuration for a registered server.
	GetServerConfig(serverName string) (ServerConfig, bool)

	// Close shuts down all MCP servers and connections
	Close() error
}

Registry interface defines the MCP server registry operations

type RegistryImpl

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

RegistryImpl implements the Registry interface

func NewRegistry

func NewRegistry() *RegistryImpl

NewRegistry creates a new MCP server registry with default options (unlimited processes).

func NewRegistryWithOptions added in v1.3.10

func NewRegistryWithOptions(opts RegistryOptions) *RegistryImpl

NewRegistryWithOptions creates a new MCP server registry with custom options.

func NewRegistryWithServers

func NewRegistryWithServers(serverConfigs []ServerConfigData) (*RegistryImpl, error)

NewRegistryWithServers creates a registry and registers multiple servers. Returns error if any server registration fails.

func (*RegistryImpl) ActiveProcessCount added in v1.3.10

func (r *RegistryImpl) ActiveProcessCount() int

ActiveProcessCount returns the number of active MCP processes. Returns -1 if no process limit is configured.

func (*RegistryImpl) Close

func (r *RegistryImpl) Close() error

Close shuts down all MCP servers and connections

func (*RegistryImpl) Fork added in v1.4.7

func (r *RegistryImpl) Fork() *RegistryImpl

Fork returns a child registry that shares this registry's static servers and clients via lookup fall-through, but has its own per-instance dynamic state. Children can register their own servers (including names that exist in the parent) without colliding; this is the mechanism that lets concurrent runs each open their own session-scoped MCP source while sharing static client connections.

Registration on the child is local-only: the parent never sees the child's entries. Lookups (GetServerConfig, GetClient, GetClientForTool, ListServers) try local state first, then fall through to the parent. UnregisterServer is local-only.

Cycle safety is the caller's responsibility; in practice forks only chain one level deep (engine → run).

func (*RegistryImpl) GetClient

func (r *RegistryImpl) GetClient(ctx context.Context, serverName string) (Client, error)

GetClient returns an active client for the given server name. For child registries (Fork), if the name resolves only to the parent, the parent's client is returned — preserving connection sharing for static servers across all per-run forks.

func (*RegistryImpl) GetClientForTool

func (r *RegistryImpl) GetClientForTool(ctx context.Context, toolName string) (Client, error)

GetClientForTool returns the client that provides the specified tool. Child registries (Fork) check their own tool index first; if the tool is not owned by a locally-registered server, the lookup falls through to the parent's tool index.

func (*RegistryImpl) GetServerConfig added in v1.3.11

func (r *RegistryImpl) GetServerConfig(serverName string) (ServerConfig, bool)

GetServerConfig returns the configuration for a registered server. Child registries fall through to the parent when the name is not registered locally.

func (*RegistryImpl) GetToolSchema

func (r *RegistryImpl) GetToolSchema(ctx context.Context, toolName string) (*Tool, error)

GetToolSchema returns the schema for a specific tool

func (*RegistryImpl) ListAllTools

func (r *RegistryImpl) ListAllTools(ctx context.Context) (map[string][]Tool, error)

ListAllTools returns all tools from all connected servers

func (*RegistryImpl) ListServers

func (r *RegistryImpl) ListServers() []string

ListServers returns all registered server names. For child registries (produced by Fork), this is the union of local and parent entries — child names override parent names with the same key.

func (*RegistryImpl) RegisterServer

func (r *RegistryImpl) RegisterServer(config ServerConfig) error

RegisterServer adds a new MCP server configuration. Child registries (produced by Fork) accept names that exist in the parent — registration is local-only.

func (*RegistryImpl) UnregisterServer added in v1.4.7

func (r *RegistryImpl) UnregisterServer(name string) error

UnregisterServer closes the client if one exists, removes the server from the registry, and prunes its tool-index entries. Unknown names are no-ops; already-closed clients are not an error.

type RegistryOptions added in v1.3.10

type RegistryOptions struct {
	// MaxProcesses limits the number of concurrent MCP server processes.
	// 0 means unlimited (no limit enforced).
	MaxProcesses int
}

RegistryOptions configures the MCP registry behavior.

type ResourcesCapability

type ResourcesCapability struct {
	ListChanged bool `json:"listChanged,omitempty"`
}

ResourcesCapability indicates the server supports resources

type SSEClient added in v1.4.7

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

SSEClient is the HTTP+SSE transport implementation of the Client interface. Wire-level details (endpoint discovery, request correlation) live in sse_transport.go; this file owns the public lifecycle.

func NewSSEClient added in v1.4.7

func NewSSEClient(config ServerConfig) *SSEClient

NewSSEClient creates a new MCP client using HTTP+SSE transport.

func NewSSEClientWithOptions added in v1.4.7

func NewSSEClientWithOptions(config ServerConfig, options ClientOptions) *SSEClient

NewSSEClientWithOptions creates an SSE client with custom options.

func (*SSEClient) CallTool added in v1.4.7

func (c *SSEClient) CallTool(ctx context.Context, name string, arguments json.RawMessage) (*ToolCallResponse, error)

CallTool executes a tool with the given arguments.

func (*SSEClient) Close added in v1.4.7

func (c *SSEClient) Close() error

Close terminates the SSE connection. Idempotent.

func (*SSEClient) Initialize added in v1.4.7

func (c *SSEClient) Initialize(ctx context.Context) (*InitializeResponse, error)

Initialize establishes the SSE connection and negotiates capabilities.

func (*SSEClient) IsAlive added in v1.4.7

func (c *SSEClient) IsAlive() bool

IsAlive reports whether the SSE stream is currently open.

func (*SSEClient) ListTools added in v1.4.7

func (c *SSEClient) ListTools(ctx context.Context) ([]Tool, error)

ListTools retrieves all available tools from the server.

type SamplingCapability

type SamplingCapability struct{}

SamplingCapability indicates the client supports sampling

type ServerCapabilities

type ServerCapabilities struct {
	Tools     *ToolsCapability     `json:"tools,omitempty"`
	Resources *ResourcesCapability `json:"resources,omitempty"`
	Prompts   *PromptsCapability   `json:"prompts,omitempty"`
}

ServerCapabilities describes what the server supports

type ServerConfig

type ServerConfig struct {
	Name    string            `json:"name" yaml:"name"`
	Command string            `json:"command,omitempty" yaml:"command,omitempty"`
	Args    []string          `json:"args,omitempty" yaml:"args,omitempty"`
	Env     map[string]string `json:"env,omitempty" yaml:"env,omitempty"`
	// WorkingDir sets the working directory for the server process (stdio only).
	WorkingDir string `json:"working_dir,omitempty" yaml:"working_dir,omitempty"`
	// URL is the base URL for an HTTP MCP server. When set without an
	// explicit TransportName, the registry uses the legacy SSE adapter for
	// back-compat. Set TransportName to TransportStreamableHTTP to opt into
	// the modern transport.
	URL string `json:"url,omitempty" yaml:"url,omitempty"`
	// Headers are sent on HTTP transports (both SSE and Streamable HTTP).
	Headers map[string]string `json:"headers,omitempty" yaml:"headers,omitempty"`
	// TransportName selects the transport adapter explicitly. When empty, the
	// legacy inference applies (URL → SSE, Command → Stdio) for back-compat.
	// Set to TransportStreamableHTTP to opt into the modern Streamable HTTP
	// transport against a URL.
	TransportName Transport `json:"transport,omitempty" yaml:"transport,omitempty"`
	// TimeoutMs sets the per-request timeout in milliseconds.
	TimeoutMs int `json:"timeout_ms,omitempty" yaml:"timeout_ms,omitempty"`
	// ToolFilter controls which tools from this server are exposed.
	ToolFilter *ToolFilter `json:"tool_filter,omitempty" yaml:"tool_filter,omitempty"`
}

ServerConfig represents configuration for an MCP server.

Exactly one transport should be specified:

  • Command: stdio transport — PromptKit spawns a local subprocess.
  • URL: HTTP transport — by default the legacy SSE adapter is used. Set TransportName to TransportStreamableHTTP to opt into the modern Streamable HTTP transport (MCP 2025-03-26).

The registry selects the adapter via Transport(). Headers applies to all HTTP transports (SSE and Streamable HTTP).

func (*ServerConfig) Transport added in v1.4.7

func (c *ServerConfig) Transport() Transport

Transport returns the resolved transport. An explicit TransportName field wins; otherwise URL → TransportSSE (back-compat), Command → TransportStdio. Pointer receiver to avoid copying the (~120-byte) struct.

type ServerConfigData

type ServerConfigData struct {
	Name          string
	Command       string
	Args          []string
	Env           map[string]string
	WorkingDir    string
	URL           string
	Headers       map[string]string
	TransportName Transport
	TimeoutMs     int
	ToolFilter    *ToolFilter
}

ServerConfigData holds MCP server configuration matching config.MCPServerConfig. Kept in field-for-field sync with ServerConfig; adding a field here that isn't on ServerConfig (or vice versa) breaks the direct conversion used in NewRegistryWithServers.

type StdioClient

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

StdioClient implements the MCP Client interface using stdio transport

func NewStdioClient

func NewStdioClient(config ServerConfig) *StdioClient

NewStdioClient creates a new MCP client using stdio transport

func NewStdioClientWithOptions

func NewStdioClientWithOptions(config ServerConfig, options ClientOptions) *StdioClient

NewStdioClientWithOptions creates a client with custom options

func (*StdioClient) CallTool

func (c *StdioClient) CallTool(ctx context.Context, name string, arguments json.RawMessage) (*ToolCallResponse, error)

CallTool executes a tool with the given arguments

func (*StdioClient) Close

func (c *StdioClient) Close() error

Close terminates the connection to the MCP server

func (*StdioClient) Initialize

func (c *StdioClient) Initialize(ctx context.Context) (*InitializeResponse, error)

Initialize establishes the MCP connection and negotiates capabilities

func (*StdioClient) IsAlive

func (c *StdioClient) IsAlive() bool

IsAlive checks if the connection is still active

func (*StdioClient) ListTools

func (c *StdioClient) ListTools(ctx context.Context) ([]Tool, error)

ListTools retrieves all available tools from the server

type StreamableClient added in v1.4.11

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

StreamableClient is the MCP 2025-03-26 Streamable HTTP transport implementation of the Client interface. Wire-level details live in streamable_transport.go; this file owns the public lifecycle.

func NewStreamableClient added in v1.4.11

func NewStreamableClient(config ServerConfig) *StreamableClient

NewStreamableClient creates an MCP client using the Streamable HTTP transport.

func NewStreamableClientWithOptions added in v1.4.11

func NewStreamableClientWithOptions(config ServerConfig, options ClientOptions) *StreamableClient

NewStreamableClientWithOptions creates a Streamable HTTP client with custom options.

func (*StreamableClient) CallTool added in v1.4.11

func (c *StreamableClient) CallTool(
	ctx context.Context, name string, arguments json.RawMessage,
) (*ToolCallResponse, error)

CallTool executes a tool with the given arguments.

func (*StreamableClient) Close added in v1.4.11

func (c *StreamableClient) Close() error

Close marks the client closed. Idempotent.

func (*StreamableClient) Initialize added in v1.4.11

func (c *StreamableClient) Initialize(ctx context.Context) (*InitializeResponse, error)

Initialize sends the initialize request and negotiates capabilities.

func (*StreamableClient) IsAlive added in v1.4.11

func (c *StreamableClient) IsAlive() bool

IsAlive reports whether the transport has completed at least one successful request since the last close.

func (*StreamableClient) ListTools added in v1.4.11

func (c *StreamableClient) ListTools(ctx context.Context) ([]Tool, error)

ListTools retrieves all available tools from the server.

type Tool

type Tool struct {
	Name        string          `json:"name"`
	Description string          `json:"description,omitempty"`
	InputSchema json.RawMessage `json:"inputSchema"` // JSON Schema for tool input
}

Tool represents an MCP tool definition

type ToolCallRequest

type ToolCallRequest struct {
	Name      string          `json:"name"`
	Arguments json.RawMessage `json:"arguments,omitempty"`
}

ToolCallRequest represents a request to execute a tool

type ToolCallResponse

type ToolCallResponse struct {
	Content []Content `json:"content"`
	IsError bool      `json:"isError,omitempty"`
}

ToolCallResponse represents the response from a tool execution

type ToolFilter added in v1.3.11

type ToolFilter struct {
	Allowlist []string `json:"allowlist,omitempty" yaml:"allowlist,omitempty"`
	Blocklist []string `json:"blocklist,omitempty" yaml:"blocklist,omitempty"`
}

ToolFilter controls which tools from an MCP server are exposed to the LLM. If Allowlist is non-empty, only those tools are included. If Blocklist is non-empty, those tools are excluded. Allowlist takes precedence over Blocklist.

func (ToolFilter) Includes added in v1.3.11

func (f ToolFilter) Includes(name string) bool

Includes returns true if the given tool name passes the filter.

type ToolsCapability

type ToolsCapability struct {
	ListChanged bool `json:"listChanged,omitempty"` // Server can send notifications
}

ToolsCapability indicates the server supports tools

type ToolsListRequest

type ToolsListRequest struct {
}

ToolsListRequest represents a request to list available tools

type ToolsListResponse

type ToolsListResponse struct {
	Tools []Tool `json:"tools"`
}

ToolsListResponse represents the response to a tools/list request

type Transport added in v1.4.7

type Transport string

Transport identifies which transport adapter should serve a config.

const (
	// TransportUnknown means the config specifies no usable transport.
	TransportUnknown Transport = ""
	// TransportStdio is the local-subprocess transport.
	TransportStdio Transport = "stdio"
	// TransportSSE is the legacy HTTP+SSE transport (MCP 2024-11-05 spec).
	TransportSSE Transport = "sse"
	// TransportStreamableHTTP is the Streamable HTTP transport
	// (MCP 2025-03-26 spec). A single POST endpoint that returns either
	// application/json or text/event-stream.
	TransportStreamableHTTP Transport = "streamable_http"
)

Jump to

Keyboard shortcuts

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