Documentation
¶
Overview ¶
Package mcp is PromptKit's Model Context Protocol client.
It speaks both generations of the protocol: the stateless revision (2026-07-28), where every request carries its version and the client's capabilities, and the handshake revisions up to 2025-11-25, detecting which a server speaks. Transports are stdio, Streamable HTTP and the deprecated HTTP+SSE. Authorization and user interaction (elicitation) are delegated to the host through Authorizer and ElicitationHandler.
Conformance with the claimed revision (ProtocolVersion) is checked by spec_parity_test.go against a mirror of the published schema, and by the official conformance suite (make mcp-conformance).
Index ¶
- Constants
- Variables
- type Annotations
- type AuthChallenge
- type AuthError
- type Authorizer
- type Client
- type ClientCapabilities
- type ClientOptions
- type Content
- type DiscoverResult
- type ElicitRequest
- type ElicitResult
- type ElicitationCapability
- type ElicitationHandler
- type Icon
- type Implementation
- type InitializeRequest
- type InitializeResponse
- type InputRequest
- type InputRequiredResult
- type JSONRPCError
- type JSONRPCMessage
- type LoggingCapabilitydeprecated
- type PromptsCapability
- type RPCError
- type Registry
- type RegistryImpl
- func (r *RegistryImpl) ActiveProcessCount() int
- func (r *RegistryImpl) Close() error
- func (r *RegistryImpl) Fork() *RegistryImpl
- func (r *RegistryImpl) GetClient(ctx context.Context, serverName string) (Client, error)
- func (r *RegistryImpl) GetClientForTool(ctx context.Context, toolName string) (Client, error)
- func (r *RegistryImpl) GetServerConfig(serverName string) (ServerConfig, bool)
- func (r *RegistryImpl) GetToolSchema(ctx context.Context, toolName string) (*Tool, error)
- func (r *RegistryImpl) ListAllTools(ctx context.Context) (map[string][]Tool, error)
- func (r *RegistryImpl) ListServers() []string
- func (r *RegistryImpl) RegisterServer(config ServerConfig) error
- func (r *RegistryImpl) UnregisterServer(name string) error
- type RegistryOptions
- type ResourceContents
- type ResourcesCapability
- type SSEClient
- func (c *SSEClient) CallTool(ctx context.Context, name string, arguments json.RawMessage) (*ToolCallResponse, error)
- func (c *SSEClient) Close() error
- func (c *SSEClient) Initialize(ctx context.Context) (*InitializeResponse, error)
- func (c *SSEClient) IsAlive() bool
- func (c *SSEClient) ListTools(ctx context.Context) ([]Tool, error)
- type SamplingCapability
- type ServerCapabilities
- type ServerConfig
- type ServerConfigData
- type StdioClient
- func (c *StdioClient) CallTool(ctx context.Context, name string, arguments json.RawMessage) (*ToolCallResponse, error)
- func (c *StdioClient) Close() error
- func (c *StdioClient) Initialize(ctx context.Context) (*InitializeResponse, error)
- func (c *StdioClient) IsAlive() bool
- func (c *StdioClient) ListTools(ctx context.Context) ([]Tool, error)
- type StreamableClient
- func (c *StreamableClient) CallTool(ctx context.Context, name string, arguments json.RawMessage) (*ToolCallResponse, error)
- func (c *StreamableClient) Close() error
- func (c *StreamableClient) Initialize(ctx context.Context) (*InitializeResponse, error)
- func (c *StreamableClient) IsAlive() bool
- func (c *StreamableClient) ListTools(ctx context.Context) ([]Tool, error)
- type Tool
- type ToolAnnotations
- type ToolCallRequest
- type ToolCallResponse
- type ToolExecution
- type ToolFilter
- type ToolsCapability
- type ToolsListRequest
- type ToolsListResponse
- type Transport
- type WWWAuthenticate
Constants ¶
const ( ElicitModeForm = "form" ElicitModeURL = "url" )
Elicitation modes (MCP client/elicitation).
const ( ElicitActionAccept = "accept" ElicitActionDecline = "decline" ElicitActionCancel = "cancel" )
Elicitation actions a user's answer can carry.
const ( ContentTypeText = "text" ContentTypeImage = "image" ContentTypeAudio = "audio" ContentTypeResourceLink = "resource_link" ContentTypeResource = "resource" )
Content types a ContentBlock can have.
const DefaultMaxProcesses = 0
DefaultMaxProcesses is the default maximum number of concurrent MCP processes. 0 means unlimited.
const LegacyProtocolVersion = "2025-11-25"
LegacyProtocolVersion is the newest handshake-era revision the client speaks, with servers that predate ProtocolVersion's stateless protocol. The client also accepts the earlier handshake revisions a server may choose (2025-06-18, 2025-03-26, 2024-11-05).
const ProtocolVersion = "2026-07-28"
ProtocolVersion is the newest MCP protocol revision the client speaks: the stateless revision it uses with servers that support it.
ProtocolVersion and LegacyProtocolVersion are the claims the conformance checks grade against: the mirrored schemas in testdata/spec, the parity test, the generated docs and the official suite all follow them.
Variables ¶
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") )
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 Annotations ¶ added in v2.10.0
type Annotations struct {
Audience []string `json:"audience,omitempty"`
Priority *float64 `json:"priority,omitempty"`
LastModified string `json:"lastModified,omitempty"`
}
Annotations tell a client how to use a content block: who it is for and how important it is.
type AuthChallenge ¶ added in v2.10.0
type AuthChallenge struct {
// Server is the server's name in the client configuration.
Server string
// ResourceURL is the URL of the request the server refused: the MCP
// endpoint, which is the protected resource.
ResourceURL string
// Status is 401 (missing or invalid credentials) or 403 (insufficient
// scope).
Status int
// Challenges are the parsed WWW-Authenticate challenges.
Challenges []WWWAuthenticate
// ResourceMetadata, Scope, Error and ErrorDescription are the parameters
// of the Bearer challenge, if there is one. ResourceMetadata is the
// protected resource metadata URL (RFC 9728); Scope is the scope the
// server needs.
ResourceMetadata string
Scope string
Error string
ErrorDescription string
// Header is the response's full header.
Header http.Header
// Attempt counts the challenges for this request, starting at 1.
Attempt int
}
AuthChallenge describes a server's refusal of a request for lack of authorization.
type AuthError ¶ added in v2.10.0
AuthError is returned when a request stays unauthorized: the Authorizer failed, or the server kept refusing after maxAuthChallenges challenges.
type Authorizer ¶ added in v2.10.0
type Authorizer interface {
// Authorize adds credentials to an outgoing HTTP request: typically an
// Authorization header, and a DPoP proof where one is used. It is
// called for every request, including retries after a challenge.
Authorize(ctx context.Context, req *http.Request) error
// Challenge is called when the server rejects a request with 401, or
// with 403 and error="insufficient_scope" (scope step-up). Return nil
// once new credentials are ready: the request is built and sent again,
// through Authorize. Return an error to fail the request.
Challenge(ctx context.Context, challenge *AuthChallenge) error
}
Authorizer supplies credentials for an HTTP MCP server and handles its authorization challenges (MCP basic/authorization).
PromptKit runs no OAuth flow and stores no secrets. Discovering the authorization server (RFC 9728 protected resource metadata, RFC 8414), registering the client, obtaining the user's consent, validating the issuer, and storing and refreshing tokens belong to the host — the hosting runtime that owns secret storage and the user. The client calls the Authorizer at the two points the protocol defines, and bounds the retries.
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"`
// Deprecated: logging is a server capability; MCP defines no client
// "logging" capability. The client never sets this.
Logging *LoggingCapability `json:"logging,omitempty"`
// Extensions advertises optional protocol extensions, keyed by
// identifier (2026-07-28). The client advertises none.
Extensions map[string]json.RawMessage `json:"extensions,omitempty"`
}
ClientCapabilities describes what the client supports
type ClientOptions ¶
type ClientOptions struct {
// RequestTimeout is the default timeout for RPC requests, on every
// transport. A request that outlives it is abandoned and the server told so.
RequestTimeout time.Duration
// InitTimeout is the timeout for the initialization handshake
InitTimeout time.Duration
// MaxRetries is the number of times an idempotent request (initialize,
// tools/list) is retried after a transport failure. tools/call is never
// retried, and neither is a request the server answered with an error.
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
// ElicitationHandler, when set, answers servers' requests for user input
// and makes the client advertise the elicitation capability (form mode).
// Without it the client does not advertise elicitation, and refuses
// elicitation requests.
ElicitationHandler ElicitationHandler
// DisableModernProtocol skips stateless (2026-07-28) detection and always
// uses the initialize handshake. For servers that misbehave when probed.
DisableModernProtocol bool
// EraProbeTimeout bounds how long the client waits for a stdio server to
// answer the server/discover probe before treating it as a handshake-era
// server, which may never answer a request sent before initialize.
// Defaults to 3s. A server slower than that to start is treated as
// handshake-era: raise it for modern-only servers with slow starts. HTTP
// servers always answer, so over HTTP the probe is bounded by InitTimeout
// and running out of time is an error.
EraProbeTimeout time.Duration
// Authorizer, when set, supplies credentials for an HTTP server and
// handles its authorization challenges. The host implements it; see
// Authorizer. Static credentials can go in ServerConfig.Headers instead.
Authorizer Authorizer
}
ClientOptions configures MCP client behavior
func DefaultClientOptions ¶
func DefaultClientOptions() ClientOptions
DefaultClientOptions returns sensible defaults
type Content ¶
type Content struct {
Type string `json:"type"` // one of the ContentType constants
Text string `json:"text,omitempty"`
Data string `json:"data,omitempty"` // Base64 encoded data (image, audio)
MimeType string `json:"mimeType,omitempty"` // MIME type for data
URI string `json:"uri,omitempty"` // URI for resource_link
// Name, Title, Description and Size describe a resource_link.
Name string `json:"name,omitempty"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Size *int64 `json:"size,omitempty"`
Icons []Icon `json:"icons,omitempty"`
// Resource is an embedded resource's contents.
Resource *ResourceContents `json:"resource,omitempty"`
Annotations *Annotations `json:"annotations,omitempty"`
Meta map[string]json.RawMessage `json:"_meta,omitempty"`
}
Content is one content block of a tool result. It is a flattened union of the spec's text, image, audio, resource_link and embedded resource blocks; Type says which fields apply.
type DiscoverResult ¶ added in v2.10.0
type DiscoverResult struct {
SupportedVersions []string `json:"supportedVersions"`
Capabilities ServerCapabilities `json:"capabilities"`
Instructions string `json:"instructions,omitempty"`
ResultType string `json:"resultType"`
TTLMs *int64 `json:"ttlMs"`
CacheScope string `json:"cacheScope"`
Meta map[string]json.RawMessage `json:"_meta,omitempty"`
}
DiscoverResult is a server's answer to server/discover: its supported versions, capabilities and identity (2026-07-28 server/discover).
type ElicitRequest ¶ added in v2.10.0
type ElicitRequest struct {
// Mode is ElicitModeForm (the default when absent) or ElicitModeURL.
Mode string `json:"mode,omitempty"`
Message string `json:"message"`
RequestedSchema json.RawMessage `json:"requestedSchema,omitempty"`
URL string `json:"url,omitempty"`
}
ElicitRequest is a server's request for information from the user (MCP client/elicitation). In form mode the answer is structured input matching RequestedSchema.
type ElicitResult ¶ added in v2.10.0
type ElicitResult struct {
// Action is ElicitActionAccept, ElicitActionDecline or ElicitActionCancel.
Action string `json:"action"`
// Content is the submitted input, for an accepted form request.
Content json.RawMessage `json:"content,omitempty"`
}
ElicitResult is the user's answer to an ElicitRequest.
type ElicitationCapability ¶
type ElicitationCapability struct {
Form *struct{} `json:"form,omitempty"`
URL *struct{} `json:"url,omitempty"`
}
ElicitationCapability indicates the client supports elicitation. An empty object means form mode only; Form and URL name the modes explicitly (2025-11-25).
type ElicitationHandler ¶ added in v2.10.0
type ElicitationHandler func(ctx context.Context, server string, req ElicitRequest) (ElicitResult, error)
ElicitationHandler asks the user for what a server requested and returns their answer. server is the name of the MCP server asking.
PromptKit does not talk to users; the host does. Setting a handler on ClientOptions is what makes the client advertise the elicitation capability, so a client without one is never asked.
type Icon ¶ added in v2.10.0
type Icon struct {
Src string `json:"src"`
MimeType string `json:"mimeType,omitempty"`
Sizes []string `json:"sizes,omitempty"`
// Theme is "light" or "dark", the background the icon is designed for.
Theme string `json:"theme,omitempty"`
}
Icon is a display icon for an implementation, tool or resource (2025-11-25).
type Implementation ¶
type Implementation struct {
Name string `json:"name"`
Version string `json:"version"`
// Title is a display name.
Title string `json:"title,omitempty"`
// Description is a human-readable summary (2025-11-25).
Description string `json:"description,omitempty"`
// WebsiteURL links to the implementation's site (2025-11-25).
WebsiteURL string `json:"websiteUrl,omitempty"`
// Icons are display icons (2025-11-25).
Icons []Icon `json:"icons,omitempty"`
}
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"`
// Instructions is the server's guidance on how to use it.
Instructions string `json:"instructions,omitempty"`
}
InitializeResponse represents the initialization response. For a modern (2026-07-28) server, which has no handshake, the client builds it from the server/discover result.
type InputRequest ¶ added in v2.10.0
type InputRequest struct {
Method string `json:"method"`
Params json.RawMessage `json:"params,omitempty"`
}
InputRequest is one request for input inside an InputRequiredResult.
type InputRequiredResult ¶ added in v2.10.0
type InputRequiredResult struct {
ResultType string `json:"resultType"`
InputRequests map[string]InputRequest `json:"inputRequests,omitempty"`
RequestState json.RawMessage `json:"requestState,omitempty"`
Meta map[string]json.RawMessage `json:"_meta,omitempty"`
}
InputRequiredResult is a server's interim answer asking for input before it completes a request.
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
deprecated
type LoggingCapability struct{}
LoggingCapability is not an MCP client capability: logging is declared by servers (ServerCapabilities.logging), not clients.
Deprecated: the client never sends it. Setting ClientCapabilities.Logging sends a field the MCP spec does not define for clients.
type PromptsCapability ¶
type PromptsCapability struct {
ListChanged bool `json:"listChanged,omitempty"`
}
PromptsCapability indicates the server supports prompts
type RPCError ¶ added in v2.10.0
type RPCError struct {
Code int
Message string
Data json.RawMessage
}
RPCError is a JSON-RPC error returned by an MCP server. Callers can errors.As a request error into it to read the code and data.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
GetToolSchema returns the schema for a specific tool
func (*RegistryImpl) ListAllTools ¶
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 ¶
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 ¶
type RegistryOptions struct {
// MaxProcesses limits the number of concurrent MCP server processes.
// 0 means unlimited (no limit enforced).
MaxProcesses int
// ConfigureClient, when set, adjusts the options of each server's client
// before it is created: the place a host supplies an Authorizer or an
// ElicitationHandler per server. The options arrive with the defaults
// and the server's TimeoutMs applied.
ConfigureClient func(config ServerConfig, options *ClientOptions)
}
RegistryOptions configures the MCP registry behavior.
type ResourceContents ¶ added in v2.10.0
type ResourceContents struct {
URI string `json:"uri"`
MimeType string `json:"mimeType,omitempty"`
Text string `json:"text,omitempty"`
Blob string `json:"blob,omitempty"`
Meta map[string]json.RawMessage `json:"_meta,omitempty"`
}
ResourceContents is the content of an embedded resource: Text for a text resource, Blob (base64) for a binary one.
type ResourcesCapability ¶
type ResourcesCapability struct {
ListChanged bool `json:"listChanged,omitempty"`
}
ResourcesCapability indicates the server supports resources
type SSEClient ¶
type SSEClient struct {
// contains filtered or unexported fields
}
SSEClient is the HTTP+SSE transport implementation of the Client interface. The protocol lives in session; wire-level details (endpoint discovery, request correlation) in sse_transport.go; the lifecycle in httpClient.
func NewSSEClient ¶
func NewSSEClient(config ServerConfig) *SSEClient
NewSSEClient creates a new MCP client using HTTP+SSE transport.
func NewSSEClientWithOptions ¶
func NewSSEClientWithOptions(config ServerConfig, options ClientOptions) *SSEClient
NewSSEClientWithOptions creates an SSE client with custom options.
func (*SSEClient) CallTool ¶
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 ¶
func (c *SSEClient) Close() error
Close ends the client and its transport (and any server session). Idempotent.
func (*SSEClient) Initialize ¶
func (c *SSEClient) Initialize(ctx context.Context) (*InitializeResponse, error)
Initialize establishes the connection and negotiates the protocol.
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"`
// Extensions lists the optional protocol extensions the server supports,
// keyed by identifier (2026-07-28).
Extensions map[string]json.RawMessage `json:"extensions,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 URL of an HTTP MCP server. Without a TransportName the
// registry uses Streamable HTTP, falling back to HTTP+SSE if the server
// does not host a Streamable HTTP endpoint at it.
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 it
// is inferred: URL → Streamable HTTP (with the HTTP+SSE fallback),
// Command → stdio.
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 — Streamable HTTP, falling back to the deprecated HTTP+SSE transport when the server does not host a Streamable HTTP endpoint. Set TransportName to pin one.
The registry selects the adapter via Transport(). Headers applies to all HTTP transports (SSE and Streamable HTTP).
func (*ServerConfig) Transport ¶
func (c *ServerConfig) Transport() Transport
Transport returns the resolved transport. An explicit TransportName field wins; otherwise URL → TransportStreamableHTTP, Command → TransportStdio. For a URL with no TransportName the registry also falls back to HTTP+SSE when the server does not host a Streamable HTTP endpoint. 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
type StreamableClient ¶
type StreamableClient struct {
// contains filtered or unexported fields
}
StreamableClient is the Streamable HTTP transport implementation of the Client interface. The protocol lives in session; wire-level details in streamable_transport.go; the lifecycle in httpClient.
func NewStreamableClient ¶
func NewStreamableClient(config ServerConfig) *StreamableClient
NewStreamableClient creates an MCP client using the Streamable HTTP transport.
func NewStreamableClientWithOptions ¶
func NewStreamableClientWithOptions(config ServerConfig, options ClientOptions) *StreamableClient
NewStreamableClientWithOptions creates a Streamable HTTP client with custom options.
func (*StreamableClient) CallTool ¶
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 ¶
func (c *StreamableClient) Close() error
Close ends the client and its transport (and any server session). Idempotent.
func (*StreamableClient) Initialize ¶
func (c *StreamableClient) Initialize(ctx context.Context) (*InitializeResponse, error)
Initialize establishes the connection and negotiates the protocol.
type Tool ¶
type Tool struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
InputSchema json.RawMessage `json:"inputSchema"` // JSON Schema for tool input
// Title is a display name.
Title string `json:"title,omitempty"`
// OutputSchema is the JSON Schema the tool's structuredContent conforms to.
OutputSchema json.RawMessage `json:"outputSchema,omitempty"`
// Annotations are hints about the tool's behavior. They are not
// guaranteed: a client MUST NOT trust them from an untrusted server.
Annotations *ToolAnnotations `json:"annotations,omitempty"`
// Icons are display icons (2025-11-25).
Icons []Icon `json:"icons,omitempty"`
// Execution says whether the tool runs as a task (2025-11-25). The
// client does not implement tasks, so it never lists a tool that
// requires one.
Execution *ToolExecution `json:"execution,omitempty"`
Meta map[string]json.RawMessage `json:"_meta,omitempty"`
}
Tool represents an MCP tool definition
type ToolAnnotations ¶ added in v2.10.0
type ToolAnnotations struct {
Title string `json:"title,omitempty"`
ReadOnlyHint *bool `json:"readOnlyHint,omitempty"`
DestructiveHint *bool `json:"destructiveHint,omitempty"`
IdempotentHint *bool `json:"idempotentHint,omitempty"`
OpenWorldHint *bool `json:"openWorldHint,omitempty"`
}
ToolAnnotations are hints about a tool's behavior (server/tools).
type ToolCallRequest ¶
type ToolCallRequest struct {
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments,omitempty"`
// InputResponses answers a modern server's input_required result, keyed
// as the server keyed its inputRequests (2026-07-28 MRTR).
InputResponses map[string]json.RawMessage `json:"inputResponses,omitempty"`
// RequestState echoes, unchanged, the requestState of the input_required
// result being answered.
RequestState json.RawMessage `json:"requestState,omitempty"`
}
ToolCallRequest represents a request to execute a tool
type ToolCallResponse ¶
type ToolCallResponse struct {
Content []Content `json:"content"`
// StructuredContent is the tool's structured result (MCP 2025-06-18).
// Servers SHOULD mirror it as serialized JSON in Content, but are not
// required to, so it is the authoritative result when present.
StructuredContent json.RawMessage `json:"structuredContent,omitempty"`
IsError bool `json:"isError,omitempty"`
// ResultType is "complete" from a 2026-07-28 server (absent before).
ResultType string `json:"resultType,omitempty"`
Meta map[string]json.RawMessage `json:"_meta,omitempty"`
}
ToolCallResponse represents the response from a tool execution
func (*ToolCallResponse) HasStructuredContent ¶ added in v2.10.0
func (r *ToolCallResponse) HasStructuredContent() bool
HasStructuredContent reports whether the response carries a non-null structuredContent payload.
type ToolExecution ¶ added in v2.10.0
type ToolExecution struct {
// TaskSupport is "forbidden" (the default), "optional" or "required".
TaskSupport string `json:"taskSupport,omitempty"`
}
ToolExecution holds a tool's execution properties (2025-11-25).
type ToolFilter ¶
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 ¶
func (f ToolFilter) Includes(name string) bool
Includes returns true if the given tool name passes the filter. Allowlist and blocklist entries may use a trailing-"*" prefix wildcard.
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 {
// Cursor requests the page after the one that returned it as NextCursor.
Cursor string `json:"cursor,omitempty"`
}
ToolsListRequest represents a request to list available tools
type ToolsListResponse ¶
type ToolsListResponse struct {
Tools []Tool `json:"tools"`
// NextCursor is set when more tools follow; the client requests the next
// page with it.
NextCursor string `json:"nextCursor,omitempty"`
// ResultType, TTLMs and CacheScope are set by 2026-07-28 servers.
// TTLMs is how long the list may be cached; CacheScope is "public" or
// "private". The client does not cache tool lists.
ResultType string `json:"resultType,omitempty"`
TTLMs *int64 `json:"ttlMs,omitempty"`
CacheScope string `json:"cacheScope,omitempty"`
Meta map[string]json.RawMessage `json:"_meta,omitempty"`
}
ToolsListResponse represents the response to a tools/list request
type Transport ¶
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" )