Documentation
¶
Overview ¶
Package mcp implements a Model Context Protocol client and server over stdio and Streamable HTTP, with OAuth authorization, and adapts MCP tools to agentx tools and agentx tools to MCP.
Index ¶
- Constants
- Variables
- func AgentTool(a agent.Agent, o AgentToolOptions) tool.Tool
- func CompleteElicitation(ctx context.Context, elicitationID string) error
- func DefaultEnvironment() []string
- func ElicitApproval(ctx context.Context, req *loop.ApprovalRequest) (loop.Approval, error)
- func FormatContent(res *CallToolResult) string
- func HookCaller(clients map[string]*Client) hook.MCPCaller
- func Log(ctx context.Context, level LogLevel, logger string, data any) error
- func OpenBrowser(authURL string) error
- func PrivateKeyJWT(clientID string, key crypto.Signer, keyID string) func(ctx context.Context, issuer, tokenEndpoint string) (string, error)
- func Progress(ctx context.Context, progress, total float64, message string) error
- func ProtectedResourceMetadataHandler(md *ProtectedResourceMetadata) http.Handler
- func ProtectedResourceMetadataURL(resource string) string
- func SupportedProtocolVersions() []string
- func ToolName(server, name string) string
- func ToolResultFrom(res *CallToolResult) *tool.Result
- func Tools(ctx context.Context, c *Client, server string, opts ...AdapterOption) ([]tool.Tool, error)
- type AdapterOption
- type AgentToolOptions
- type AuthOptions
- type AuthorizationResponse
- type AuthorizationServerMetadata
- type CallToolResult
- type Client
- func (c *Client) Call(ctx context.Context, method string, params, out any) error
- func (c *Client) CallTool(ctx context.Context, name string, args json.RawMessage) (*CallToolResult, error)
- func (c *Client) Close() error
- func (c *Client) Done() <-chan struct{}
- func (c *Client) Err() error
- func (c *Client) GetPrompt(ctx context.Context, name string, args map[string]string) (*GetPromptResult, error)
- func (c *Client) ListPrompts(ctx context.Context) ([]Prompt, error)
- func (c *Client) ListResourceTemplates(ctx context.Context) ([]ResourceTemplate, error)
- func (c *Client) ListResources(ctx context.Context) ([]Resource, error)
- func (c *Client) ListTools(ctx context.Context) ([]Tool, error)
- func (c *Client) Listen(ctx context.Context, s Subscription) error
- func (c *Client) Notify(ctx context.Context, method string, params any) error
- func (c *Client) Ping(ctx context.Context) error
- func (c *Client) ProtocolVersion() string
- func (c *Client) ReadResource(ctx context.Context, uri string) ([]ResourceContents, error)
- func (c *Client) RootsChanged(ctx context.Context) error
- func (c *Client) Server() DiscoverResult
- func (c *Client) SetLogLevel(ctx context.Context, level LogLevel) error
- type ClientOption
- func OnNotification(fn func(method string, params json.RawMessage)) ClientOption
- func WithClientInfo(name, version string) ClientOption
- func WithElicitation(h ElicitationHandler, modes ...string) ClientOption
- func WithLogHandler(fn func(LogMessage)) ClientOption
- func WithLogLevel(level LogLevel) ClientOption
- func WithLogger(l *slog.Logger) ClientOption
- func WithOAuth(cfg OAuthConfig) ClientOption
- func WithProbeTimeout(d time.Duration) ClientOption
- func WithProtocolVersion(v string) ClientOption
- func WithRoots(fn RootsFunc) ClientOption
- func WithSampling(h SamplingHandler, opts ...SamplingOption) ClientOption
- type ClientRegistration
- type Content
- type DiscoverResult
- type ElicitRequest
- type ElicitResult
- type ElicitationHandler
- type Error
- type GetPromptResult
- type HTTPHandler
- type HTTPOptions
- type HTTPStatusError
- type HTTPTransport
- type IOTransport
- type Icon
- type Implementation
- type InputRequiredError
- type LogLevel
- type LogMessage
- type LoopbackRedirect
- type MemoryTokenStore
- func (s *MemoryTokenStore) Client(_ context.Context, issuer string) (*ClientRegistration, error)
- func (s *MemoryTokenStore) SetClient(_ context.Context, issuer string, reg *ClientRegistration) error
- func (s *MemoryTokenStore) SetToken(_ context.Context, server string, tok *Token) error
- func (s *MemoryTokenStore) Token(_ context.Context, server string) (*Token, error)
- type MissingCapabilityError
- type ModelHint
- type ModelPreferences
- type OAuthConfig
- type OAuthError
- type Prompt
- type PromptArgument
- type PromptHandler
- type PromptMessage
- type PromptSource
- type ProtectedResourceMetadata
- type RequestInfo
- type Resource
- type ResourceContents
- type ResourceHandler
- type ResourceSource
- type ResourceTemplate
- type ResourceTemplateSource
- type Root
- type RootsFunc
- type SamplingContent
- type SamplingContents
- type SamplingHandler
- type SamplingMessage
- type SamplingOption
- type SamplingRequest
- type SamplingResult
- type SamplingToolChoice
- type Server
- func (s *Server) AddPrompt(p Prompt, h PromptHandler)
- func (s *Server) AddResource(r Resource, h ResourceHandler)
- func (s *Server) AddResourceTemplate(t ResourceTemplate, h TemplateHandler) error
- func (s *Server) AddTools(tools ...tool.Tool) error
- func (s *Server) Close() error
- func (s *Server) HTTPHandler(opts HTTPOptions) *HTTPHandler
- func (s *Server) Info() Implementation
- func (s *Server) PromptsChanged()
- func (s *Server) Registry() *tool.Registry
- func (s *Server) RemovePrompts(names ...string)
- func (s *Server) RemoveResources(uris ...string)
- func (s *Server) RemoveTools(names ...string)
- func (s *Server) ResourceUpdated(uri string)
- func (s *Server) ResourcesChanged()
- func (s *Server) ServeStdio(ctx context.Context, r io.Reader, w io.Writer) error
- func (s *Server) ToolsChanged()
- type ServerOptions
- type StdioTransport
- type Subscription
- type TemplateHandler
- type Token
- type TokenInfo
- type TokenStore
- type TokenVerifier
- type Tool
- type ToolAnnotations
- type Transport
Constants ¶
const ( CodeParseError = -32700 CodeInvalidRequest = -32600 CodeMethodNotFound = -32601 CodeInvalidParams = -32602 CodeInternalError = -32603 CodeHeaderMismatch = -32020 CodeMissingRequiredClientCapability = -32021 CodeUnsupportedProtocolVersion = -32022 )
JSON-RPC and MCP error codes.
const ( StopEndTurn = "endTurn" StopSequence = "stopSequence" StopMaxTokens = "maxTokens" StopToolUse = "toolUse" )
Stop reasons of a SamplingResult. Implementations may report others.
const ( ElicitationForm = "form" ElicitationURL = "url" )
Elicitation modes.
const ( ElicitAccept = "accept" ElicitDecline = "decline" ElicitCancel = "cancel" )
Elicitation actions.
const ( GrantAuthorizationCode = "authorization_code" GrantClientCredentials = "client_credentials" )
OAuth grants.
const ( AuthMethodNone = "none" AuthMethodClientSecretBasic = "client_secret_basic" AuthMethodClientSecretPost = "client_secret_post" AuthMethodPrivateKeyJWT = "private_key_jwt" )
Client authentication methods at the token endpoint.
const ( CachePublic = "public" CachePrivate = "private" )
Cache scopes of list and read results; see ServerOptions.CacheScope.
const CodeResourceNotFound = -32002
CodeResourceNotFound is the error code with which revision 2025-11-25 and earlier report an unknown resource. ProtocolVersion uses CodeInvalidParams instead.
const CodeURLElicitationRequired = -32042
CodeURLElicitationRequired is the error code of a request that an initialization-based server cannot process until the user completes URL mode elicitations.
const LegacyProtocolVersion = "2025-11-25"
LegacyProtocolVersion is the initialization-based revision Connect offers in its initialize request when a server does not speak ProtocolVersion.
const ProtocolVersion = "2026-07-28"
ProtocolVersion is the MCP revision this client prefers. The revision is stateless: every request declares the version in its _meta and there is no initialization handshake. Connect falls back to the initialization-based revisions listed by SupportedProtocolVersions for servers that do not implement it.
Variables ¶
var ErrAuthorization = errors.New("mcp: authorization failed")
ErrAuthorization is wrapped by the errors of a failed authorization.
var ErrClosed = errors.New("mcp: transport closed")
ErrClosed is returned when using a closed transport.
var ErrMaybeSent = errors.New("mcp: message may have been sent")
ErrMaybeSent is wrapped by the error of a Send that failed after the message may already have reached the peer, such as a Send whose context was done while the message was being written. The client then treats a request as issued and asks the server to cancel it.
var ErrNoRequest = errors.New("mcp: not called from a request handler")
ErrNoRequest is returned by the handler functions, such as Sample and Log, when ctx does not belong to a request served by a Server.
var ErrPromptNotFound = errors.New("mcp: prompt not found")
ErrPromptNotFound is returned by prompt sources for an unknown prompt.
var ErrResourceNotFound = errors.New("mcp: resource not found")
ErrResourceNotFound is returned by resource handlers and sources for an unknown resource. The client receives the error code the request's protocol revision defines for it.
var ErrSamplingRejected = errors.New("mcp: sampling request rejected")
ErrSamplingRejected is wrapped by the error returned for a sampling request that the approval or review hook of WithSampling rejected, or that a SamplingHandler rejected by returning an error wrapping it.
var ErrSessionClosed = errors.New("mcp: session closed")
ErrSessionClosed is returned by handlers' requests to a client whose session ended.
var ErrSessionExpired = errors.New("mcp: session expired")
ErrSessionExpired is returned when a server ended the session of an initialization-based revision. The client then starts a new session and issues the request again once.
var ErrStreamLost = errors.New("mcp: response stream ended without a response")
ErrStreamLost is returned when a response stream ends before the response arrives and cannot be resumed; the request may be issued again. Only the streams of the initialization-based revisions can be resumed.
Functions ¶
func AgentTool ¶
func AgentTool(a agent.Agent, o AgentToolOptions) tool.Tool
AgentTool exposes an agent as a tool to serve with a Server: each call runs the agent on the prompt without history and returns its final answer. When the agent needs approval for a tool call, the call asks Approve and resumes the agent with the decisions, which the agent must support (agent.StateResumer or agent.Resumer, as LLMAgent does).
agent.AsTool serves an agent too, but outside a run it cannot obtain approvals.
func CompleteElicitation ¶
CompleteElicitation tells the client of a session of revision 2025-11-25 that the URL mode elicitation with the given ID is complete (notifications/elicitation/complete). ProtocolVersion has no such notification, since the client learns the outcome by retrying the request, so CompleteElicitation then does nothing.
func DefaultEnvironment ¶
func DefaultEnvironment() []string
DefaultEnvironment returns the KEY=value entries of the current environment a StdioTransport passes to its server unless InheritEnv is set: on Unix HOME, LOGNAME, PATH, SHELL, TERM, TMPDIR, USER, LANG and LC_ALL, on Windows the variables programs need to start. Values that are shell functions are left out.
func ElicitApproval ¶
ElicitApproval asks the MCP client's user to approve a tool call with a form elicitation. A user who declines or cancels denies the call, as does a client without the elicitation capability.
func FormatContent ¶
func FormatContent(res *CallToolResult) string
FormatContent renders a tool result as text, describing images, audio and blobs in brackets. ToolResultFrom keeps them as parts instead.
func HookCaller ¶
HookCaller returns a hook.MCPCaller for hook.MCPTool hooks, and for mcp_tool handlers in hook settings, that calls tools on clients by server name. As for Claude Code, the hook reads the text content of the result.
func Log ¶
Log sends a log message (notifications/message) about the current request, if the client asked for messages of that level: with ProtocolVersion in the request's _meta, otherwise with logging/setLevel. Messages of other levels are dropped without an error. data must encode as JSON. Logging is deprecated as of ProtocolVersion but still part of it.
func OpenBrowser ¶
OpenBrowser prints authURL to standard error and tries to open it in the default browser.
func PrivateKeyJWT ¶
func PrivateKeyJWT(clientID string, key crypto.Signer, keyID string) func(ctx context.Context, issuer, tokenEndpoint string) (string, error)
PrivateKeyJWT returns an OAuthConfig.ClientAssertion that signs RFC 7523 client assertions for clientID with key: an *rsa.PrivateKey (RS256) or an *ecdsa.PrivateKey on P-256 (ES256). keyID, if set, is the kid of the key in the client's JWKS. Each assertion is valid for five minutes and names the token endpoint as its audience.
func Progress ¶
Progress reports the progress of the current request (notifications/progress), if the client asked for it with a progress token. progress must increase with every call; total and message are optional and omitted when zero.
func ProtectedResourceMetadataHandler ¶
func ProtectedResourceMetadataHandler(md *ProtectedResourceMetadata) http.Handler
ProtectedResourceMetadataHandler serves md as JSON, to any origin. Mount it at the path of ProtectedResourceMetadataURL(md.Resource) when the MCP handler does not receive that path itself.
func ProtectedResourceMetadataURL ¶
ProtectedResourceMetadataURL returns the URL at which RFC 9728 serves the Protected Resource Metadata of resource: the well-known path inserted between its host and path, as in https://example.com/.well-known/oauth-protected-resource/mcp for https://example.com/mcp.
func SupportedProtocolVersions ¶
func SupportedProtocolVersions() []string
SupportedProtocolVersions returns the revisions the client speaks, newest first: ProtocolVersion, then the initialization-based revisions it accepts from a server's initialize response.
func ToolName ¶
ToolName returns the agentx name of an MCP tool: mcp__<server>__<tool>, sanitized and limited to 64 characters. A name that is too long is cut and ends with a hash of the server and tool names, so that names sharing a long prefix stay distinct. Tools may use a different name: see Tools.
func ToolResultFrom ¶
func ToolResultFrom(res *CallToolResult) *tool.Result
ToolResultFrom converts the result of tools/call to a tool result. Text content and text resources become Content. Images, audio and embedded resource blobs become Parts, of the type their MIME type tells (see model.MediaPart), with the file name of the resource URI, so models that take media see them; a provider that cannot take one fails the request as for any other part. Resource links stay text, since models cannot fetch their URIs, as does media whose data is not valid base64. A result without text or media gives its structured content as text.
func Tools ¶
func Tools(ctx context.Context, c *Client, server string, opts ...AdapterOption) ([]tool.Tool, error)
Tools lists the server's tools and adapts them to tool.Tool. server names the server in tool names. Tools whose sanitized names collide, such as "a.b" and "a_b", are told apart by a hash suffix on the names that sanitization changed. A tool's name therefore depends on the other tools in the list and may change when the server's tool list changes, for example between a run and its resumption.
Types ¶
type AdapterOption ¶
type AdapterOption func(*adapter)
AdapterOption configures adapted tools.
func Filter ¶
func Filter(keep func(Tool) bool) AdapterOption
Filter keeps only tools for which keep returns true.
func RequireApprovalFor ¶
func RequireApprovalFor(fn func(Tool) bool) AdapterOption
RequireApprovalFor marks tools for which fn returns true as requiring approval, replacing the default: by default a tool requires approval unless the server hints it is not destructive, since the MCP default of destructiveHint is true. With TrustReadOnlyHint, tools hinted read-only do not require approval either. RequireApprovalFor(nil) requires approval for no tool at all.
func TrustReadOnlyHint ¶
func TrustReadOnlyHint() AdapterOption
TrustReadOnlyHint trusts the server's readOnlyHint annotations: tools hinted read-only are marked tool.Info.ReadOnly, so adjacent calls run concurrently, and they skip the default approval. Annotations are self-reported by the server, so use this only with servers you trust.
Without this option a hint that removes approval is still trusted: the default approval relies on destructiveHint, so a server that declares a tool destructiveHint: false, truthfully or not, gets it called without approval. Use RequireApprovalFor to decide approval without annotations.
func WithoutPrefix ¶
func WithoutPrefix() AdapterOption
WithoutPrefix keeps the server's original tool names.
type AgentToolOptions ¶
type AgentToolOptions struct {
// Name and Description default to the agent's.
Name string
Description string
// Approve decides the tool calls the agent needs approval for. It
// defaults to ElicitApproval, which asks the MCP client's user.
Approve func(ctx context.Context, req *loop.ApprovalRequest) (loop.Approval, error)
// MaxApprovalRounds bounds how often a call resumes the agent after
// approvals. Defaults to 16.
MaxApprovalRounds int
}
AgentToolOptions configures AgentTool. The zero value gives the defaults.
type AuthOptions ¶
type AuthOptions struct {
// Verify validates bearer tokens. It is required.
Verify TokenVerifier
// Metadata is the server's Protected Resource Metadata. The handler
// serves it at MetadataURL when that request reaches it, and names
// that URL in its challenges.
Metadata *ProtectedResourceMetadata
// MetadataURL is where the metadata is served. Defaults to
// ProtectedResourceMetadataURL(Metadata.Resource).
MetadataURL string
// Scopes are required for every request.
Scopes []string
// OperationScopes, if set, returns the scopes an operation needs
// beyond Scopes: name is the tool or prompt name or resource URI of
// tools/call, prompts/get and resources/read. A token without them is
// refused with 403 insufficient_scope naming every scope the operation
// needs, so that the client can step up its authorization.
OperationScopes func(method, name string) []string
}
AuthOptions makes the HTTP handler a protected resource.
type AuthorizationResponse ¶
type AuthorizationResponse struct {
Code string
State string
Issuer string
Error string
ErrorDescription string
}
AuthorizationResponse is the authorization server's response at the redirect URL (RFC 6749, section 4.1.2), with the issuer of RFC 9207.
func ParseAuthorizationResponse ¶
func ParseAuthorizationResponse(q url.Values) *AuthorizationResponse
ParseAuthorizationResponse reads an authorization response from the query of the redirect.
type AuthorizationServerMetadata ¶
type AuthorizationServerMetadata struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint,omitempty"`
TokenEndpoint string `json:"token_endpoint,omitempty"`
RegistrationEndpoint string `json:"registration_endpoint,omitempty"`
JWKSURI string `json:"jwks_uri,omitempty"`
ScopesSupported []string `json:"scopes_supported,omitempty"`
ResponseTypesSupported []string `json:"response_types_supported,omitempty"`
GrantTypesSupported []string `json:"grant_types_supported,omitempty"`
TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"`
TokenEndpointAuthSigningAlgValuesSupported []string `json:"token_endpoint_auth_signing_alg_values_supported,omitempty"`
CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported,omitempty"`
ClientIDMetadataDocumentSupported bool `json:"client_id_metadata_document_supported,omitempty"`
AuthorizationResponseISSParameterSupported bool `json:"authorization_response_iss_parameter_supported,omitempty"`
}
AuthorizationServerMetadata is the metadata of an authorization server (RFC 8414, section 2, and OpenID Connect Discovery).
type CallToolResult ¶
type CallToolResult struct {
Content []Content `json:"content"`
StructuredContent json.RawMessage `json:"structuredContent,omitempty"`
IsError bool `json:"isError,omitempty"`
}
CallToolResult is the result of tools/call.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is an MCP client connected to one server.
func Connect ¶
Connect starts the transport and finds a protocol revision the server speaks, as the backward compatibility rules of revision 2026-07-28 describe. It first sends server/discover with ProtocolVersion. A DiscoverResult or an error only servers implementing that revision return, such as an unsupported protocol version, identifies a modern server. Any other JSON-RPC error, an HTTP 4xx response without such an error (other than 401, 403, 407, 408 and 429) or, on transports other than Streamable HTTP, no answer within the probe timeout identifies a server implementing an earlier revision: Connect then sends initialize offering LegacyProtocolVersion, accepts any revision of SupportedProtocolVersions the server answers with, and sends notifications/initialized. ctx bounds these requests. See WithProtocolVersion to pin a revision, and WithProbeTimeout for servers that start slowly.
The client features configured with WithSampling, WithElicitation and WithRoots are declared in initialize or, with ProtocolVersion, in the _meta of every request.
func (*Client) Call ¶
Call sends a request and decodes its result into out, which may be nil. params must encode as a JSON object or null. With ProtocolVersion, the protocol fields of _meta are added to it; with an initialization-based revision it is sent as given.
With ProtocolVersion, a server may answer with an input_required result. Call then runs the handlers for its inputRequests (see WithSampling, WithElicitation and WithRoots) and issues the request again with their inputResponses and the result's requestState, up to 8 times. If the client has no handler for one of the requests, Call returns an *InputRequiredError; if a handler fails, Call returns its error.
func (*Client) CallTool ¶
func (c *Client) CallTool(ctx context.Context, name string, args json.RawMessage) (*CallToolResult, error)
CallTool invokes a tool. Tool failures are reported in the result's IsError field; the error return is for protocol failures.
func (*Client) Close ¶
Close ends the connection. Over Streamable HTTP, a session of an initialization-based revision is ended with an HTTP DELETE first.
func (*Client) Done ¶
func (c *Client) Done() <-chan struct{}
Done is closed when the connection ends.
func (*Client) GetPrompt ¶
func (c *Client) GetPrompt(ctx context.Context, name string, args map[string]string) (*GetPromptResult, error)
GetPrompt renders a prompt.
func (*Client) ListPrompts ¶
ListPrompts returns every prompt the server offers. A server implementing an initialization-based revision that does not advertise the prompts capability offers none.
func (*Client) ListResourceTemplates ¶
func (c *Client) ListResourceTemplates(ctx context.Context) ([]ResourceTemplate, error)
ListResourceTemplates returns every resource template the server offers. A server implementing an initialization-based revision that does not advertise the resources capability offers none.
func (*Client) ListResources ¶
ListResources returns every resource the server offers. A server implementing an initialization-based revision that does not advertise the resources capability offers none.
func (*Client) ListTools ¶
ListTools returns every tool the server offers. Over Streamable HTTP with ProtocolVersion, tools with invalid x-mcp-header annotations are left out. A server implementing an initialization-based revision that does not advertise the tools capability offers no tools.
func (*Client) Listen ¶
func (c *Client) Listen(ctx context.Context, s Subscription) error
Listen opens a subscriptions/listen stream and blocks until ctx is done or the stream ends. Notifications, starting with notifications/subscriptions/acknowledged, go to the OnNotification handler. It returns nil when the server ends the subscription gracefully, ctx.Err() when ctx is done, and ErrStreamLost when the stream drops; a caller may then listen again. ProtocolVersion does not resume streams.
The initialization-based revisions have no subscriptions/listen, so with them Listen emulates it. It sends resources/subscribe for each resource subscription, which requires the server's resources.subscribe capability, and resources/unsubscribe when it returns. Over Streamable HTTP it opens the session's GET stream, which carries the notifications that belong to no request, resumes it with Last-Event-ID when it ends early, as HTTPTransport describes, and returns ErrStreamLost when it cannot; over other transports notifications arrive on the connection itself, and Listen returns once ctx is done or the connection ends. Listen then reports notifications/subscriptions/acknowledged itself, without a subscription ID in _meta and with the list-change notifications limited to those the server advertises listChanged for. The server's notifications carry no subscription ID either and are not filtered: such a server sends every change notification it supports, and over transports other than Streamable HTTP it sends them while no Listen runs too.
func (*Client) Ping ¶
Ping checks that the server is responsive. With an initialization-based revision it sends ping. ProtocolVersion has no ping, so Ping sends server/discover, which every such server answers, and checks that the answer is a discovery result.
func (*Client) ProtocolVersion ¶
ProtocolVersion returns the revision in use: the package constant ProtocolVersion, or the initialization-based revision negotiated with initialize.
func (*Client) ReadResource ¶
ReadResource reads a resource.
func (*Client) RootsChanged ¶
RootsChanged tells the server that the roots WithRoots returns changed. With an initialization-based revision it sends notifications/roots/list_changed, after which the server lists the roots again. ProtocolVersion has no such notification, since the server asks for the roots with each request that needs them, so RootsChanged then does nothing.
func (*Client) Server ¶
func (c *Client) Server() DiscoverResult
Server returns what the server reported about itself: the discovery result, or for an initialization-based revision the initialize result, whose SupportedVersions holds the negotiated revision alone.
func (*Client) SetLogLevel ¶
SetLogLevel sets the minimum level of the log messages the server sends as notifications/message, which WithLogHandler and OnNotification receive. With an initialization-based revision it sends logging/setLevel, which requires the server's logging capability, and sends it again for every renewed session. ProtocolVersion has no logging/setLevel: the level is sent in the _meta of every later request instead, and the server sends the log messages of a request before its response. Logging is deprecated as of ProtocolVersion but still part of it.
type ClientOption ¶
type ClientOption func(*Client)
ClientOption configures a Client.
func OnNotification ¶
func OnNotification(fn func(method string, params json.RawMessage)) ClientOption
OnNotification registers a handler for server notifications, such as notifications/progress or the change notifications delivered by Listen. It runs on the receive goroutine and must not block.
func WithClientInfo ¶
func WithClientInfo(name, version string) ClientOption
WithClientInfo sets the implementation reported to servers.
func WithElicitation ¶
func WithElicitation(h ElicitationHandler, modes ...string) ClientOption
WithElicitation declares the elicitation capability for the given modes, ElicitationForm if none are given, and answers the server's elicitation/create requests with h. Requests for other modes are rejected. The content of accepted form elicitations is checked against the requested schema before it is sent.
With URL mode and an initialization-based revision, a request that fails with CodeURLElicitationRequired runs h for each elicitation in the error. If the user accepts all of them, the client waits, bounded by the request's context, until the server reports them complete with notifications/elicitation/complete and then issues the request again once. Otherwise the request fails with the server's error.
func WithLogHandler ¶
func WithLogHandler(fn func(LogMessage)) ClientOption
WithLogHandler delivers the server's log messages (notifications/message) to fn. It runs on the receive goroutine and must not block. Servers send log messages only once a level is set: see WithLogLevel and Client.SetLogLevel.
func WithLogLevel ¶
func WithLogLevel(level LogLevel) ClientOption
WithLogLevel sets the minimum level of the log messages the server sends, as Client.SetLogLevel does, from the start of the connection and, with an initialization-based revision, of every renewed session. An invalid level makes Connect fail.
func WithLogger ¶
func WithLogger(l *slog.Logger) ClientOption
WithLogger sets the logger for warnings, such as tools rejected for invalid x-mcp-header annotations. Defaults to slog.Default.
func WithOAuth ¶
func WithOAuth(cfg OAuthConfig) ClientOption
WithOAuth authorizes the requests of a Streamable HTTP transport as cfg describes. Connect fails for other transports. It wraps the transport of the HTTPTransport's Client; see OAuthConfig.Transport to authorize other HTTP clients. The client keeps a copy of cfg.
func WithProbeTimeout ¶
func WithProbeTimeout(d time.Duration) ClientOption
WithProbeTimeout sets how long Connect waits for the answer to its server/discover probe over transports other than Streamable HTTP, such as stdio, before it assumes the server implements an initialization-based revision and sends initialize. Defaults to 10 seconds; zero or less waits for the answer as long as Connect's context allows.
The timeout only decides when initialize is sent, not which revision is used: Connect keeps waiting for the probe's answer while it waits for the answer to initialize, and whichever identifies the server first wins. A server that starts slowly and implements ProtocolVersion, which answers the probe first and rejects initialize, is therefore still used with ProtocolVersion. A shorter timeout makes Connect faster with servers of earlier revisions that ignore requests before initialize; it then sends initialize to more modern servers, which they reject or, if they serve both eras, answer for a session the client abandons.
func WithProtocolVersion ¶
func WithProtocolVersion(v string) ClientOption
WithProtocolVersion pins the protocol revision, which must be one of SupportedProtocolVersions. Connect then neither probes nor falls back: with ProtocolVersion it requires server/discover to succeed, and with an initialization-based revision it sends initialize right away and fails unless the server agrees to exactly that revision.
func WithRoots ¶
func WithRoots(fn RootsFunc) ClientOption
WithRoots declares the roots capability and answers the server's roots/list requests with fn. Call Client.RootsChanged when the roots change. Roots are deprecated as of ProtocolVersion but still part of it.
func WithSampling ¶
func WithSampling(h SamplingHandler, opts ...SamplingOption) ClientOption
WithSampling declares the sampling capability and answers the server's sampling/createMessage requests with h. See ModelSampler for a handler backed by an agentx model. Sampling is deprecated as of ProtocolVersion but still part of it.
type ClientRegistration ¶
type ClientRegistration struct {
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret,omitempty"`
ClientIDIssuedAt int64 `json:"client_id_issued_at,omitempty"`
ClientSecretExpiresAt int64 `json:"client_secret_expires_at,omitempty"`
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`
RedirectURIs []string `json:"redirect_uris,omitempty"`
}
ClientRegistration is a client registered with an authorization server (RFC 7591, section 3.2.1).
type Content ¶
type Content struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
Data string `json:"data,omitempty"`
MimeType string `json:"mimeType,omitempty"`
URI string `json:"uri,omitempty"`
Name string `json:"name,omitempty"`
Resource *ResourceContents `json:"resource,omitempty"`
}
Content is a content block in tool results and prompts.
type DiscoverResult ¶
type DiscoverResult struct {
SupportedVersions []string `json:"supportedVersions"`
Capabilities json.RawMessage `json:"capabilities"`
Instructions string `json:"instructions,omitempty"`
// ServerInfo is self-reported by the server and is only meant for
// display and logging.
ServerInfo Implementation `json:"-"`
}
DiscoverResult is the server's answer to server/discover.
type ElicitRequest ¶
type ElicitRequest struct {
// Mode is ElicitationForm or ElicitationURL. Requests without a mode
// are form requests; the client fills in the mode.
Mode string `json:"mode,omitempty"`
Message string `json:"message"`
// RequestedSchema describes the form: a flat object of primitive
// properties.
RequestedSchema json.RawMessage `json:"requestedSchema,omitempty"`
// URL is the page a URL mode elicitation asks the user to open. The
// client must show it in full, must not open or prefetch it without the
// user's consent, and must open it so that neither it nor the model can
// see what the user enters.
URL string `json:"url,omitempty"`
// ElicitationID identifies a URL mode elicitation of revision
// 2025-11-25. Later revisions have none.
ElicitationID string `json:"elicitationId,omitempty"`
}
ElicitRequest holds the parameters of elicitation/create.
type ElicitResult ¶
type ElicitResult struct {
// Action is ElicitAccept, ElicitDecline or ElicitCancel.
Action string `json:"action"`
// Content holds the submitted form data of an accepted form mode
// elicitation: strings, numbers, booleans and string arrays.
Content map[string]any `json:"content,omitempty"`
}
ElicitResult is the user's answer to an elicitation.
func Elicit ¶
func Elicit(ctx context.Context, req *ElicitRequest) (*ElicitResult, error)
Elicit asks the user for information through the client, from a tool, resource or prompt handler of a Server. A request without a mode is a form request. URL mode needs the client's elicitation.url capability; in sessions of revision 2025-11-25 a URL request without an ElicitationID gets a random one, and with ProtocolVersion, which has none, the ElicitationID is dropped.
type ElicitationHandler ¶
type ElicitationHandler func(ctx context.Context, req *ElicitRequest) (*ElicitResult, error)
ElicitationHandler asks the user for the information an elicitation requests. For a URL mode elicitation, accepting means that the user consented to open the URL, not that the interaction is complete.
type Error ¶
type Error struct {
Code int `json:"code"`
Message string `json:"message"`
Data json.RawMessage `json:"data,omitempty"`
}
Error is a JSON-RPC error returned by the server.
func URLElicitationRequired ¶
func URLElicitationRequired(message string, elicitations ...*ElicitRequest) *Error
URLElicitationRequired returns the error with which a handler in a session of revision 2025-11-25 tells the client that the user must complete URL mode elicitations first (code -32042). ProtocolVersion has no such error: handlers call Elicit with URL mode instead.
type GetPromptResult ¶
type GetPromptResult struct {
Description string `json:"description,omitempty"`
Messages []PromptMessage `json:"messages"`
}
GetPromptResult is the result of prompts/get.
type HTTPHandler ¶
type HTTPHandler struct {
// contains filtered or unexported fields
}
HTTPHandler serves a Server over Streamable HTTP. Mount it at the MCP endpoint, such as "/mcp".
Requests with the protocol version in _meta follow https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http: each POST is answered with JSON or, once the handler sends notifications, with an SSE stream, and closing the stream cancels the request. The handler checks that MCP-Protocol-Version, Mcp-Method, Mcp-Name and the Mcp-Param headers of x-mcp-header tool parameters match the body.
An initialize request starts a session of an initialization-based revision (https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#streamable-http): the response carries its Mcp-Session-Id, requests are answered with resumable SSE streams whose events have IDs, GET opens a stream for notifications that belong to no request, GET with Last-Event-ID resumes any stream of the session, and DELETE ends it. In a session, closing a stream does not cancel its request; notifications/cancelled does.
func (*HTTPHandler) Close ¶
func (h *HTTPHandler) Close() error
Close ends the subscriptions/listen streams gracefully and ends every session.
func (*HTTPHandler) ServeHTTP ¶
func (h *HTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler.
type HTTPOptions ¶
type HTTPOptions struct {
// AllowedOrigins lists the Origin header values accepted, such as
// "https://app.example.com"; "*" accepts any. Requests from loopback
// origins (localhost, 127.0.0.1, [::1]) are always accepted. Requests
// with any other Origin are refused with 403 Forbidden, which protects
// local servers from DNS rebinding attacks; requests without an Origin,
// which do not come from browsers, are accepted.
AllowedOrigins []string
// AllowedHosts, if set, lists the Host header values accepted, such as
// "localhost:8080". Servers bound to a loopback address should set it,
// as a second defense against DNS rebinding.
AllowedHosts []string
// Auth, if set, requires bearer tokens; see AuthOptions.
Auth *AuthOptions
// SessionTimeout ends sessions of initialization-based revisions that
// were idle that long, without requests or open streams. Defaults to
// 30 minutes; negative never ends them.
SessionTimeout time.Duration
// PollInterval, if positive, closes the SSE connections of sessions
// after that long, sending a retry field first, without ending their
// streams: the client reconnects with Last-Event-ID, as revision
// 2025-11-25 allows servers to do to avoid long-lived connections.
PollInterval time.Duration
// RetryInterval is the reconnection time sent on those streams.
// Defaults to 1 second.
RetryInterval time.Duration
// KeepAlive is the interval of the comments sent on quiet long-lived
// streams: subscriptions/listen responses and session GET streams.
// Defaults to 25 seconds; negative disables them.
KeepAlive time.Duration
// MaxBodyBytes bounds the size of a POST body. Defaults to 4 MiB.
MaxBodyBytes int64
// MaxStreamEvents bounds the events kept per session stream for
// resumption. Defaults to 1024; older events cannot be replayed.
MaxStreamEvents int
}
HTTPOptions configures the Streamable HTTP handler of a Server.
type HTTPStatusError ¶
type HTTPStatusError struct {
StatusCode int
// Body is the start of the response body.
Body string
}
HTTPStatusError is an HTTP error response whose body is not a JSON-RPC error.
func (*HTTPStatusError) Error ¶
func (e *HTTPStatusError) Error() string
type HTTPTransport ¶
type HTTPTransport struct {
URL string
Client *http.Client
Header http.Header
// ReconnectDelay is how long to wait before resuming a stream whose
// server set no reconnection time. Defaults to 1 second.
ReconnectDelay time.Duration
// MaxReconnectAttempts bounds the consecutive failed attempts to resume
// a stream. Defaults to 5.
MaxReconnectAttempts int
// contains filtered or unexported fields
}
HTTPTransport implements the Streamable HTTP transport. Each message is a POST whose response, a JSON object or an SSE stream, belongs to that request alone; with ProtocolVersion, closing it cancels the request.
With an initialization-based revision, the transport keeps the session ID the server assigns in its initialize response and sends it, with the negotiated MCP-Protocol-Version, on every later request, and Close ends the session with a DELETE. While a new session is being initialized, other messages wait for it and then carry its ID. An SSE stream that ends early, because the connection broke or because the server polls by closing it, is resumed: after the reconnection time the server set with a retry field (ReconnectDelay if none), the transport sends a GET with the ID of the last event received as Last-Event-ID. It gives up after MaxReconnectAttempts consecutive failed attempts, when the server refuses resumption, or when no event had an ID; a request whose stream is lost fails with ErrStreamLost. ProtocolVersion has no resumption, so its streams are never resumed.
func HTTP ¶
func HTTP(url string) *HTTPTransport
HTTP returns a Streamable HTTP transport for the endpoint URL.
func (*HTTPTransport) Close ¶
func (t *HTTPTransport) Close() error
Close implements Transport. A session of an initialization-based revision is ended with an HTTP DELETE, waiting up to 5 seconds for the server. Open response streams are then closed, which with ProtocolVersion cancels their requests.
func (*HTTPTransport) Receive ¶
func (t *HTTPTransport) Receive() <-chan []byte
Receive implements Transport.
type IOTransport ¶
type IOTransport struct {
// contains filtered or unexported fields
}
IOTransport exchanges newline-delimited JSON over a reader and writer.
func NewIOTransport ¶
NewIOTransport returns a transport reading from r and writing to w. If closer is non-nil it is called by Close.
func (*IOTransport) Receive ¶
func (t *IOTransport) Receive() <-chan []byte
Receive implements Transport.
func (*IOTransport) Send ¶
func (t *IOTransport) Send(ctx context.Context, msg []byte) error
Send implements Transport. Messages are written whole and in the order their Sends acquire the writer. If ctx is done while the message waits for an earlier write, Send returns ctx.Err() without writing it; if ctx is done while the message is being written, the write completes in the background, so the stream stays well formed and the peer may still receive the message, and Send returns an error wrapping both ErrMaybeSent and ctx.Err(). Close unblocks such writes when its closer closes the writer, as StdioTransport does.
type Icon ¶
type Icon struct {
Src string `json:"src"`
MimeType string `json:"mimeType,omitempty"`
Sizes []string `json:"sizes,omitempty"`
Theme string `json:"theme,omitempty"`
}
Icon is an icon for an implementation, tool, resource or prompt.
type Implementation ¶
type Implementation struct {
Name string `json:"name"`
Title string `json:"title,omitempty"`
Version string `json:"version"`
Description string `json:"description,omitempty"`
WebsiteURL string `json:"websiteUrl,omitempty"`
Icons []Icon `json:"icons,omitempty"`
}
Implementation identifies a client or server.
type InputRequiredError ¶
type InputRequiredError struct {
InputRequests map[string]json.RawMessage
RequestState string
}
InputRequiredError reports an input_required result asking for client input, such as elicitation or sampling, that this client has no handler for: see WithSampling, WithElicitation and WithRoots.
func (*InputRequiredError) Error ¶
func (e *InputRequiredError) Error() string
type LogMessage ¶
type LogMessage struct {
Level LogLevel `json:"level"`
Logger string `json:"logger,omitempty"`
Data json.RawMessage `json:"data"`
}
LogMessage is a server log message from notifications/message.
type LoopbackRedirect ¶
type LoopbackRedirect struct {
// Open shows the authorization URL to the user. Defaults to
// OpenBrowser.
Open func(authURL string) error
// contains filtered or unexported fields
}
LoopbackRedirect receives authorization responses on a local HTTP listener, the redirect of native applications in RFC 8252, section 7.3. Use its URL as OAuthConfig.RedirectURL and its Authorize method as OAuthConfig.Authorize; Configure does both.
func NewLoopbackRedirect ¶
func NewLoopbackRedirect(addr string) (*LoopbackRedirect, error)
NewLoopbackRedirect starts listening on addr, "127.0.0.1:0" (a free port of the IPv4 loopback address) if empty, for redirects to /callback.
func (*LoopbackRedirect) Authorize ¶
func (l *LoopbackRedirect) Authorize(ctx context.Context, authURL string) (*AuthorizationResponse, error)
Authorize shows authURL to the user with Open and waits, bounded by ctx, for the authorization response with the request's state.
func (*LoopbackRedirect) Configure ¶
func (l *LoopbackRedirect) Configure(cfg *OAuthConfig)
Configure sets the redirect URL and the Authorize function of cfg.
func (*LoopbackRedirect) URL ¶
func (l *LoopbackRedirect) URL() string
URL returns the redirect URL.
type MemoryTokenStore ¶
type MemoryTokenStore struct {
// contains filtered or unexported fields
}
MemoryTokenStore keeps tokens in memory for the life of the process.
func NewMemoryTokenStore ¶
func NewMemoryTokenStore() *MemoryTokenStore
NewMemoryTokenStore returns an empty in-memory store.
func (*MemoryTokenStore) Client ¶
func (s *MemoryTokenStore) Client(_ context.Context, issuer string) (*ClientRegistration, error)
Client implements TokenStore.
func (*MemoryTokenStore) SetClient ¶
func (s *MemoryTokenStore) SetClient(_ context.Context, issuer string, reg *ClientRegistration) error
SetClient implements TokenStore.
type MissingCapabilityError ¶
type MissingCapabilityError struct {
Method string
// Required is the missing capability in the form of
// ClientCapabilities, such as {"sampling": {}}.
Required map[string]any
}
MissingCapabilityError is returned by Sample, Elicit and ListRoots when the client did not declare the capability the input request needs. A handler that fails with it, or returns an error result, makes the server answer with the MissingRequiredClientCapability error (-32021) instead. It wraps errors.ErrUnsupported.
func (*MissingCapabilityError) Error ¶
func (e *MissingCapabilityError) Error() string
func (*MissingCapabilityError) Unwrap ¶
func (e *MissingCapabilityError) Unwrap() error
Unwrap returns errors.ErrUnsupported.
type ModelHint ¶
type ModelHint struct {
Name string `json:"name,omitempty"`
}
ModelHint suggests a model by name or name substring.
type ModelPreferences ¶
type ModelPreferences struct {
Hints []ModelHint `json:"hints,omitempty"`
CostPriority *float64 `json:"costPriority,omitempty"`
SpeedPriority *float64 `json:"speedPriority,omitempty"`
IntelligencePriority *float64 `json:"intelligencePriority,omitempty"`
}
ModelPreferences are the server's advisory model preferences. The priorities range from 0 to 1.
type OAuthConfig ¶
type OAuthConfig struct {
// Grant is GrantAuthorizationCode, the default, or
// GrantClientCredentials for machine-to-machine access without a user,
// as the OAuth client credentials extension of MCP
// (io.modelcontextprotocol/oauth-client-credentials) describes. The
// latter needs a pre-registered ClientID with ClientSecret or
// ClientAssertion.
Grant string
// ClientID and ClientSecret are pre-registered client credentials,
// which take precedence over the other ways to obtain a client ID.
ClientID string
ClientSecret string
// ClientIssuer, if set, is the issuer of the authorization server the
// pre-registered credentials belong to. Authorization fails if the
// server names another one, rather than sending it the credentials.
ClientIssuer string
// TokenEndpointAuthMethod is how the pre-registered client
// authenticates at the token endpoint. Defaults to
// AuthMethodClientSecretBasic, or AuthMethodClientSecretPost when the
// server supports only that, with a secret; to AuthMethodPrivateKeyJWT
// with ClientAssertion; and to AuthMethodNone otherwise.
TokenEndpointAuthMethod string
// ClientAssertion returns a signed JWT for AuthMethodPrivateKeyJWT
// (RFC 7523); see PrivateKeyJWT.
ClientAssertion func(ctx context.Context, issuer, tokenEndpoint string) (string, error)
// ClientMetadataURL is the HTTPS URL of the client's Client ID Metadata
// Document, used as the client ID with authorization servers that
// declare client_id_metadata_document_supported. The document must list
// RedirectURL.
ClientMetadataURL string
// ClientName, ClientURI and ApplicationType describe the client in
// Dynamic Client Registration, the fallback for servers that support
// neither of the above. ApplicationType defaults to "native" for a
// loopback RedirectURL and "web" otherwise.
ClientName string
ClientURI string
ApplicationType string
// RedirectURL receives the authorization response; it must be a
// loopback or HTTPS URL. See LoopbackRedirect.
RedirectURL string
// Authorize lets the user authorize the client: it shows authURL to
// the user, usually by opening a browser, and returns the authorization
// response delivered to RedirectURL. It is required for
// GrantAuthorizationCode. LoopbackRedirect.Authorize implements it.
Authorize func(ctx context.Context, authURL string) (*AuthorizationResponse, error)
// Scopes are requested when neither the challenge nor the Protected
// Resource Metadata names any.
Scopes []string
// Store keeps tokens and dynamic client registrations. Defaults to a
// MemoryTokenStore.
Store TokenStore
// HTTPClient sends the requests to the authorization server and for the
// metadata. Defaults to an http.Client with the wrapped transport.
HTTPClient *http.Client
// SelectAuthorizationServer chooses among the authorization servers of
// the Protected Resource Metadata. Defaults to the first.
SelectAuthorizationServer func(issuers []string) string
}
OAuthConfig configures the authorization of MCP requests over Streamable HTTP; see WithOAuth.
func (*OAuthConfig) Transport ¶
func (cfg *OAuthConfig) Transport(base http.RoundTripper) http.RoundTripper
Transport returns a round tripper that authorizes the requests it sends with base (http.DefaultTransport if nil) to MCP servers, as the package documentation of the OAuth flow describes. Each call returns a round tripper with state of its own; tokens persist in the Store. Tokens are kept by server URL and sent only to the server they were obtained for, so one round tripper may serve several servers. The client using it should not follow redirects to other origins; WithOAuth refuses them.
type OAuthError ¶
type OAuthError struct {
StatusCode int `json:"-"`
Code string `json:"error"`
Description string `json:"error_description,omitempty"`
URI string `json:"error_uri,omitempty"`
}
OAuthError is an error response of an authorization server (RFC 6749, section 5.2). It wraps ErrAuthorization.
func (*OAuthError) Error ¶
func (e *OAuthError) Error() string
type Prompt ¶
type Prompt struct {
Name string `json:"name"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Arguments []PromptArgument `json:"arguments,omitempty"`
Icons []Icon `json:"icons,omitempty"`
}
Prompt is a prompt template offered by a server.
type PromptArgument ¶
type PromptArgument struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Required bool `json:"required,omitempty"`
}
PromptArgument describes a prompt parameter.
type PromptHandler ¶
PromptHandler renders a prompt with its arguments. The server checks that the required arguments are present first.
type PromptMessage ¶
PromptMessage is a message produced by a prompt.
type PromptSource ¶
type PromptSource interface {
// Prompts lists the prompts, in a stable order.
Prompts(ctx context.Context) ([]Prompt, error)
// GetPrompt renders one; it returns an error wrapping
// ErrPromptNotFound for a name it does not know.
GetPrompt(ctx context.Context, name string, args map[string]string) (*GetPromptResult, error)
}
PromptSource offers prompts that change outside the server.
type ProtectedResourceMetadata ¶
type ProtectedResourceMetadata struct {
// Resource is the server's resource identifier: its canonical URI,
// such as https://mcp.example.com/mcp.
Resource string `json:"resource"`
// AuthorizationServers lists the issuer identifiers of the
// authorization servers; MCP requires at least one.
AuthorizationServers []string `json:"authorization_servers,omitempty"`
JWKSURI string `json:"jwks_uri,omitempty"`
ScopesSupported []string `json:"scopes_supported,omitempty"`
BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`
ResourceSigningAlgValuesSupported []string `json:"resource_signing_alg_values_supported,omitempty"`
ResourceName string `json:"resource_name,omitempty"`
ResourceDocumentation string `json:"resource_documentation,omitempty"`
ResourcePolicyURI string `json:"resource_policy_uri,omitempty"`
ResourceTOSURI string `json:"resource_tos_uri,omitempty"`
}
ProtectedResourceMetadata is the OAuth 2.0 Protected Resource Metadata of an MCP server (RFC 9728, section 2).
type RequestInfo ¶
type RequestInfo struct {
Method string
// ProtocolVersion is ProtocolVersion, or the revision of the session.
ProtocolVersion string
// Client is what the client reports about itself; it is not verified.
Client Implementation
// SessionID is the Streamable HTTP session of an initialization-based
// revision, if any.
SessionID string
// Token is the verified access token, when the HTTP handler checks
// tokens.
Token *TokenInfo
}
RequestInfo describes the request a handler serves.
func CurrentRequest ¶
func CurrentRequest(ctx context.Context) (*RequestInfo, bool)
CurrentRequest returns information about the request a handler serves.
type Resource ¶
type Resource struct {
URI string `json:"uri"`
Name string `json:"name"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
MimeType string `json:"mimeType,omitempty"`
Icons []Icon `json:"icons,omitempty"`
}
Resource describes a resource offered by a server.
type ResourceContents ¶
type ResourceContents struct {
URI string `json:"uri"`
MimeType string `json:"mimeType,omitempty"`
Text string `json:"text,omitempty"`
Blob string `json:"blob,omitempty"`
}
ResourceContents holds the text or base64 blob of a resource.
type ResourceHandler ¶
type ResourceHandler func(ctx context.Context, uri string) ([]ResourceContents, error)
ResourceHandler reads a resource. It returns an error wrapping ErrResourceNotFound for an unknown URI.
type ResourceSource ¶
type ResourceSource interface {
// Resources lists the resources, in a stable order.
Resources(ctx context.Context) ([]Resource, error)
// ReadResource reads one; it returns an error wrapping
// ErrResourceNotFound for a URI it does not know.
ReadResource(ctx context.Context, uri string) ([]ResourceContents, error)
}
ResourceSource offers resources that change outside the server, such as the files of a directory. Sources are consulted after the resources added with Server.AddResource and AddResourceTemplate.
type ResourceTemplate ¶
type ResourceTemplate struct {
URITemplate string `json:"uriTemplate"`
Name string `json:"name"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
MimeType string `json:"mimeType,omitempty"`
Icons []Icon `json:"icons,omitempty"`
}
ResourceTemplate describes parameterized resources by an RFC 6570 URI template.
type ResourceTemplateSource ¶
type ResourceTemplateSource interface {
ResourceTemplates(ctx context.Context) ([]ResourceTemplate, error)
}
ResourceTemplateSource is implemented by resource sources that also list resource templates.
type Root ¶
type Root struct {
// URI must be a file:// URI.
URI string `json:"uri"`
Name string `json:"name,omitempty"`
}
Root is a directory or file the client exposes to servers.
type RootsFunc ¶
RootsFunc returns the current roots.
func StaticRoots ¶
StaticRoots returns a RootsFunc that always returns roots.
type SamplingContent ¶
type SamplingContent struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
// Data is the base64 data of an image or audio block.
Data string `json:"data,omitempty"`
MimeType string `json:"mimeType,omitempty"`
// ID, Name and Input describe a tool_use block.
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Input json.RawMessage `json:"input,omitempty"`
// ToolUseID, Content, StructuredContent and IsError describe a
// tool_result block.
ToolUseID string `json:"toolUseId,omitempty"`
Content []Content `json:"content,omitempty"`
StructuredContent json.RawMessage `json:"structuredContent,omitempty"`
IsError bool `json:"isError,omitempty"`
}
SamplingContent is a content block of a sampling message: text, image or audio, and with tool use a tool_use block in assistant messages or a tool_result block in user messages.
func (SamplingContent) MarshalJSON ¶
func (b SamplingContent) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler. It keeps the fields that text and tool_result blocks require even when they are empty.
type SamplingContents ¶
type SamplingContents []SamplingContent
SamplingContents is the content of a sampling message. It decodes from a single block or an array of blocks, and encodes one block as an object and several as an array.
func (SamplingContents) MarshalJSON ¶
func (c SamplingContents) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
func (*SamplingContents) UnmarshalJSON ¶
func (c *SamplingContents) UnmarshalJSON(b []byte) error
UnmarshalJSON implements json.Unmarshaler.
type SamplingHandler ¶
type SamplingHandler func(ctx context.Context, req *SamplingRequest) (*SamplingResult, error)
SamplingHandler generates a message for a sampling request.
func ModelSampler ¶
func ModelSampler(m model.Model) SamplingHandler
ModelSampler returns a SamplingHandler that generates with m. It converts the request with ModelRequest and the response with SamplingResultFrom. Model preferences are advisory and ignored, as are includeContext and metadata; to pick a model from the hints, set the Model field of the converted request in a handler of your own. Pair it with ApproveSampling so that a human can review what servers ask the model.
type SamplingMessage ¶
type SamplingMessage struct {
// Role is "user" or "assistant".
Role string `json:"role"`
Content SamplingContents `json:"content"`
}
SamplingMessage is a message of a sampling request.
type SamplingOption ¶
type SamplingOption func(*samplingConfig)
SamplingOption configures sampling.
func ApproveSampling ¶
func ApproveSampling(fn func(ctx context.Context, req *SamplingRequest) error) SamplingOption
ApproveSampling sets a hook that reviews every sampling request before the handler runs, as the specification asks clients to let a human do. An error rejects the request: an initialization-based server receives the error code -1, and with ProtocolVersion the request that asked for the sample fails with an error wrapping ErrSamplingRejected.
func ReviewSampling ¶
func ReviewSampling(fn func(ctx context.Context, req *SamplingRequest, res *SamplingResult) error) SamplingOption
ReviewSampling sets a hook that reviews every generated message before it is returned to the server. An error rejects it, as with ApproveSampling.
func SamplingTools ¶
func SamplingTools() SamplingOption
SamplingTools declares the sampling.tools capability, so that servers may include tools and toolChoice in sampling requests. Without it, such requests are rejected.
type SamplingRequest ¶
type SamplingRequest struct {
Messages []SamplingMessage `json:"messages"`
ModelPreferences *ModelPreferences `json:"modelPreferences,omitempty"`
SystemPrompt string `json:"systemPrompt,omitempty"`
// IncludeContext is "none", or the deprecated "thisServer" or
// "allServers"; the client may ignore it.
IncludeContext string `json:"includeContext,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
// MaxTokens is the most tokens to sample; the client must respect it.
MaxTokens int `json:"maxTokens"`
StopSequences []string `json:"stopSequences,omitempty"`
Metadata json.RawMessage `json:"metadata,omitempty"`
// Tools and ToolChoice are set only for a client that declared tool
// use with SamplingTools.
Tools []Tool `json:"tools,omitempty"`
ToolChoice *SamplingToolChoice `json:"toolChoice,omitempty"`
}
SamplingRequest holds the parameters of sampling/createMessage.
func (*SamplingRequest) ModelRequest ¶
func (r *SamplingRequest) ModelRequest() (*model.Request, error)
ModelRequest converts the sampling request into a model request: the system prompt, messages with text, image, audio, tool use and tool result content, maxTokens, temperature, stop sequences, tools and the tool choice. Media in tool results becomes the parts of the result, as in ToolResultFrom.
type SamplingResult ¶
type SamplingResult struct {
// Role is "assistant"; it defaults to that when empty.
Role string `json:"role"`
Content SamplingContents `json:"content"`
// Model names the model that generated the message.
Model string `json:"model"`
StopReason string `json:"stopReason,omitempty"`
}
SamplingResult is the result of sampling/createMessage.
func Sample ¶
func Sample(ctx context.Context, req *SamplingRequest) (*SamplingResult, error)
Sample asks the client to sample from its language model, from a tool, resource or prompt handler of a Server. It needs the client's sampling capability, and sampling.tools for requests with tools; without it, it returns a *MissingCapabilityError. Sampling is deprecated as of ProtocolVersion but still part of it.
func SamplingResultFrom ¶
func SamplingResultFrom(resp *model.Response) (*SamplingResult, error)
SamplingResultFrom converts a model response into a sampling result: text, image, audio and tool call parts become text, image, audio and tool_use blocks, and the finish reason becomes the stop reason (endTurn, maxTokens or toolUse; other reasons pass through as they are).
type SamplingToolChoice ¶
type SamplingToolChoice struct {
Mode string `json:"mode,omitempty"`
}
SamplingToolChoice controls tool use during sampling: Mode is "auto" (the default), "required" or "none".
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is an MCP server. It serves tools, resources and prompts over stdio (ServeStdio) and Streamable HTTP (HTTPHandler), to clients of ProtocolVersion and of the initialization-based revisions alike.
func NewServer ¶
func NewServer(info Implementation, opts ServerOptions) *Server
NewServer returns a server identifying itself with info; a zero info becomes agentx and its version; the zero opts serves nothing until tools, resources or prompts are added. It panics if the options' tools have invalid or duplicate names.
func (*Server) AddPrompt ¶
func (s *Server) AddPrompt(p Prompt, h PromptHandler)
AddPrompt adds a prompt, replacing one with the same name, and notifies clients that the prompt list changed.
func (*Server) AddResource ¶
func (s *Server) AddResource(r Resource, h ResourceHandler)
AddResource adds a resource, replacing one with the same URI, and notifies clients that the resource list changed.
func (*Server) AddResourceTemplate ¶
func (s *Server) AddResourceTemplate(t ResourceTemplate, h TemplateHandler) error
AddResourceTemplate adds a resource template. Reading a URI that matches it calls h with the values of its variables. Simple ({var}) and reserved ({+var}) expansions are matched; a simple variable does not match "/", "?" or "#". It fails for other expressions.
func (*Server) Close ¶
Close ends the server's subscriptions gracefully, ends its sessions and cancels the handlers waiting for client input. Serving continues for new requests; stop the transports to end it.
func (*Server) HTTPHandler ¶
func (s *Server) HTTPHandler(opts HTTPOptions) *HTTPHandler
HTTPHandler returns a Streamable HTTP handler of the server; the zero opts gives the defaults.
func (*Server) Info ¶
func (s *Server) Info() Implementation
Info returns the implementation the server reports.
func (*Server) PromptsChanged ¶
func (s *Server) PromptsChanged()
PromptsChanged notifies clients that the prompt list changed.
func (*Server) RemovePrompts ¶
RemovePrompts removes prompts by name and notifies clients.
func (*Server) RemoveResources ¶
RemoveResources removes resources and resource templates by URI or URI template and notifies clients.
func (*Server) RemoveTools ¶
RemoveTools removes tools by name and notifies clients.
func (*Server) ResourceUpdated ¶
ResourceUpdated notifies the clients subscribed to a resource that it changed: with ProtocolVersion through subscriptions/listen, otherwise through resources/subscribe.
func (*Server) ResourcesChanged ¶
func (s *Server) ResourcesChanged()
ResourcesChanged notifies clients that the resource list changed.
func (*Server) ServeStdio ¶
ServeStdio serves one client over newline-delimited JSON-RPC, reading from r and writing to w, as the stdio transport (https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/stdio) does with a server process's standard input and output; any reliable byte stream works the same way. Requests run concurrently. Requests with the protocol version in _meta are served statelessly; initialize starts a session of an initialization-based revision for the rest of the connection, in which handlers' Sample, Elicit and ListRoots send the client requests on w.
The client cancels a request with notifications/cancelled. ServeStdio returns nil when r reaches end of file, and ctx.Err() when ctx is done, after ending subscriptions gracefully, cancelling the other requests and waiting for their handlers to return. A read blocked on r is abandoned then; close r to end it.
Servers launched as a process serve with
err := srv.ServeStdio(ctx, os.Stdin, os.Stdout)
and must write nothing else to standard output.
func (*Server) ToolsChanged ¶
func (s *Server) ToolsChanged()
ToolsChanged notifies clients that the tool list changed: subscriptions that asked for it with ProtocolVersion, and every session of an earlier revision. AddTools and RemoveTools call it.
type ServerOptions ¶
type ServerOptions struct {
// Instructions tell models how to use the server.
Instructions string
// Registry is served live: tools registered or removed later are
// listed too. Call Server.ToolsChanged after changing it directly.
// Defaults to a new registry.
Registry *tool.Registry
// Tools are registered in the registry.
Tools []tool.Tool
// ToolMiddleware wraps every tool call, as tool.Executor does.
ToolMiddleware []tool.Middleware
// Resources and Prompts are consulted after the resources and prompts
// added to the server.
Resources ResourceSource
Prompts PromptSource
// Logger receives the server's own warnings. Defaults to slog.Default.
Logger *slog.Logger
// PageSize, if positive, paginates list results.
PageSize int
// CacheTTL and CacheScope are the caching hints of list and read
// results with ProtocolVersion
// (https://modelcontextprotocol.io/specification/2026-07-28/server/utilities/caching).
// They default to 0, immediately stale, and CachePrivate.
CacheTTL time.Duration
CacheScope string
// StateKey authenticates the requestState of input_required results.
// Servers behind a load balancer need the same key on every instance;
// it defaults to a random key.
StateKey []byte
// InputTimeout bounds how long a handler waiting for client input with
// ProtocolVersion is kept for the client's retry. Defaults to 10
// minutes.
InputTimeout time.Duration
// ModernOnly serves ProtocolVersion alone: initialize is rejected with
// an error naming the supported version, and HTTP GET and DELETE are
// refused with 405 Method Not Allowed, as
// https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http#earlier-streamable-http-revisions
// describes.
ModernOnly bool
}
ServerOptions configures a Server. The zero value serves no tools, resources or prompts until they are added.
type StdioTransport ¶
type StdioTransport struct {
Command string
Args []string
// Env holds KEY=value entries added to the server's environment. The
// server inherits only a few variables of the current process, those
// DefaultEnvironment lists, unless InheritEnv is set: a third-party
// server must not read the API keys and tokens in the client's
// environment.
Env []string
// InheritEnv passes the whole environment of the current process to
// the server, before Env.
InheritEnv bool
Dir string
// Stderr receives the server's standard error. Defaults to discarding.
Stderr io.Writer
// ShutdownTimeout bounds how long Close waits for the process to exit
// after closing its input. Defaults to 5 seconds.
ShutdownTimeout time.Duration
// contains filtered or unexported fields
}
StdioTransport launches a server process and talks to it over its standard input and output.
func Stdio ¶
func Stdio(command string, args ...string) *StdioTransport
Stdio returns a transport for the given command.
func (*StdioTransport) Receive ¶
func (t *StdioTransport) Receive() <-chan []byte
Receive implements Transport.
type Subscription ¶
type Subscription struct {
ToolsListChanged bool `json:"toolsListChanged,omitempty"`
PromptsListChanged bool `json:"promptsListChanged,omitempty"`
ResourcesListChanged bool `json:"resourcesListChanged,omitempty"`
ResourceSubscriptions []string `json:"resourceSubscriptions,omitempty"`
}
Subscription selects the change notifications delivered by Listen.
type TemplateHandler ¶
type TemplateHandler func(ctx context.Context, uri string, vars map[string]string) ([]ResourceContents, error)
TemplateHandler reads a resource matching a resource template; vars holds the values of the template's variables.
type Token ¶
type Token struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
Expiry time.Time `json:"expiry,omitzero"`
// Scope is the space-separated scope granted, or requested if the
// server did not say.
Scope string `json:"scope,omitempty"`
// Issuer is the authorization server that issued the token, and
// Resource the resource it was requested for.
Issuer string `json:"issuer,omitempty"`
Resource string `json:"resource,omitempty"`
}
Token is an OAuth access token with its refresh token.
type TokenInfo ¶
type TokenInfo struct {
// Subject identifies the principal. Sessions and the requestState of
// input_required results are bound to it.
Subject string
// Scopes are the scopes the token grants.
Scopes []string
// Audience, if set, must include the resource of the Protected
// Resource Metadata.
Audience []string
// ExpiresAt, if set, is checked on every request.
ExpiresAt time.Time
// Extra holds verifier-specific claims.
Extra map[string]any
}
TokenInfo describes a verified access token.
type TokenStore ¶
type TokenStore interface {
// Token returns the token for server, or nil if there is none.
Token(ctx context.Context, server string) (*Token, error)
// SetToken saves the token for server; nil deletes it.
SetToken(ctx context.Context, server string, tok *Token) error
// Client returns the registration with issuer, or nil.
Client(ctx context.Context, issuer string) (*ClientRegistration, error)
// SetClient saves the registration with issuer; nil deletes it.
SetClient(ctx context.Context, issuer string, reg *ClientRegistration) error
}
TokenStore keeps OAuth tokens, by the canonical URL of the MCP server, and dynamic client registrations, by the issuer of the authorization server that issued them: registrations must not be used with another authorization server. Tokens and client secrets are credentials; stores must keep them confidential.
type TokenVerifier ¶
TokenVerifier validates an access token and describes it. It must reject tokens not issued for this server (RFC 8707 audience) and return an error for invalid or expired tokens, which the client gets as 401 invalid_token.
type Tool ¶
type Tool struct {
Name string `json:"name"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
InputSchema json.RawMessage `json:"inputSchema"`
OutputSchema json.RawMessage `json:"outputSchema,omitempty"`
Annotations *ToolAnnotations `json:"annotations,omitempty"`
Icons []Icon `json:"icons,omitempty"`
}
Tool is a tool offered by a server.
type ToolAnnotations ¶
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 tool behavior. Clients must not rely on them for security decisions.
type Transport ¶
type Transport interface {
// Start connects the transport. It is called once before Send.
Start(ctx context.Context) error
// Send writes one JSON-RPC message. If it fails after the message may
// have reached the peer, the error wraps ErrMaybeSent.
Send(ctx context.Context, msg []byte) error
// Receive returns incoming messages. The channel is closed when the
// connection ends; Err then reports why.
Receive() <-chan []byte
// Err returns the error that ended the connection, if any.
Err() error
// Close shuts the transport down.
Close() error
}
Transport carries JSON-RPC messages between client and server.