Documentation
¶
Overview ¶
Package server implements a stateless MCP server for protocol revision 2026-07-28. A Server is a pure function over messages: transports feed it one message at a time via Handle and receive the emitted stream of notifications followed by exactly one response. There is no session object; all per-request context travels in _meta.
Index ¶
- Constants
- func AddTool[In, Out any](s *Server, tool *protocol.Tool, handler ToolHandlerFor[In, Out])
- func ValidateToolOutput(schema protocol.JSONSchema, res *protocol.CallToolResult) error
- type CallRequest
- type Extension
- type Middleware
- type Options
- type PromptHandler
- type PromptRequest
- type RawHandler
- type Request
- func (r *Request) ClientCapabilities() *protocol.ClientCapabilities
- func (r *Request) ClientInfo() *protocol.Implementation
- func (r *Request) Extension(id string) (json.RawMessage, bool)
- func (r *Request) ID() protocol.RequestID
- func (r *Request) Method() string
- func (r *Request) ProtocolVersion() string
- func (r *Request) RawParams() json.RawMessage
- func (r *Request) ReportProgress(ctx context.Context, progress, total float64, message string) error
- func (r *Request) SupportsElicitation() (form, url bool)
- func (r *Request) TemplateVars() map[string]string
- type ResourceHandler
- type ResourceRequest
- type Server
- func (s *Server) AddExtension(e Extension)
- func (s *Server) AddPrompt(p *protocol.Prompt, h PromptHandler)
- func (s *Server) AddResource(r *protocol.Resource, h ResourceHandler)
- func (s *Server) AddResourceTemplate(t *protocol.ResourceTemplate, h ResourceHandler)
- func (s *Server) AddTool(t *protocol.Tool, h ToolHandler)
- func (s *Server) Handle(ctx context.Context, msg *protocol.Message, emit func(*protocol.Message) error)
- func (s *Server) MethodNameParam(method string) (string, bool)
- func (s *Server) Publish(topic, method string, params any) error
- func (s *Server) RemovePrompts(names ...string)
- func (s *Server) RemoveResourceTemplates(uriTemplates ...string)
- func (s *Server) RemoveResources(uris ...string)
- func (s *Server) RemoveTools(names ...string)
- func (s *Server) ResourceUpdated(uri string)
- func (s *Server) SignState(payload []byte) (string, error)
- func (s *Server) ToolHeaderBindings(name string) []headerbind.Binding
- func (s *Server) Use(m ...Middleware)
- func (s *Server) VerifyState(state string) ([]byte, error)
- type ToolHandler
- type ToolHandlerFor
Constants ¶
const DefaultPageSize = 1000
DefaultPageSize is the default page size for list pagination.
Variables ¶
This section is empty.
Functions ¶
func AddTool ¶ added in v1.2.1
func AddTool[In, Out any](s *Server, tool *protocol.Tool, handler ToolHandlerFor[In, Out])
AddTool registers a type-safe tool handler. It is a package-level function because Go does not support method-level type parameters.
If the tool's input schema is nil it is inferred from In, which must be a struct or map so the schema has the "object" root the spec requires (`any` infers an empty object schema). If the output schema is nil and Out is not `any`, it is inferred from Out — any root type is allowed (SEP-2106).
func ValidateToolOutput ¶ added in v1.3.0
func ValidateToolOutput(schema protocol.JSONSchema, res *protocol.CallToolResult) error
ValidateToolOutput checks a final tool result against a declared outputSchema, sharing the compiled-validator cache tools/call uses. It is the seam for extensions that execute tools out of band (e.g. tasks): capture the schema at registration and pass it here, so in-flight work is validated against the schema it was created under — immune to the tool being removed or re-registered meanwhile. A nil schema and execution errors (isError) pass; a nil result counts as an empty result and fails when a schema is declared.
Types ¶
type CallRequest ¶ added in v1.3.0
type CallRequest struct {
*Request
Params *protocol.CallToolParams
}
CallRequest is the typed request handed to tool handlers.
type Extension ¶ added in v1.3.0
type Extension struct {
// ID is the extension identifier, e.g. "io.modelcontextprotocol/tasks".
ID string
// Settings is marshaled into capabilities.extensions[ID]. Use struct{}{}
// for "supported, no settings".
Settings any
// Methods maps additional RPC method names to handlers.
Methods map[string]RawHandler
// NameParams maps extension methods to the params key whose string value
// clients send as the Mcp-Name routing header over Streamable HTTP (the
// tasks draft maps its methods to "taskId"). The transport validates the
// header against the body via Server.MethodNameParam.
NameParams map[string]string
// Topics translates one extension field of a subscription filter (key,
// raw value) into hub topics. Returning ok=false leaves the field to
// other extensions; ok=true with no topics leaves it unhonored. A non-nil
// err rejects the whole listen request (e.g. a missing client capability).
Topics func(req *Request, key string, value json.RawMessage) (topics []string, ok bool, err error)
}
Extension plugs additional methods and subscription topics into the server (e.g. the official tasks extension). The server itself knows nothing about any specific extension.
type Middleware ¶ added in v1.2.1
type Middleware func(RawHandler) RawHandler
Middleware wraps a RawHandler. Middleware is applied at dispatch time, so registration order of tools and middleware does not matter.
func Recovery ¶ added in v1.3.0
func Recovery() Middleware
Recovery converts handler panics into -32603 errors. The stack trace goes to slog, never to the wire.
func Timeout ¶ added in v1.3.0
func Timeout(d time.Duration) Middleware
Timeout bounds each request. subscriptions/listen is exempt: its lifetime is the stream itself.
type Options ¶ added in v1.3.0
type Options struct {
// Impl is stamped as serverInfo into every result's _meta unless
// OmitServerInfo is set.
Impl protocol.Implementation
Instructions string
OmitServerInfo bool
// PageSize bounds list results. Defaults to DefaultPageSize.
PageSize int
// ListCache is the default cache control applied to cacheable results the
// handler left unset. The zero value ({0, private}) is the safest choice
// and therefore the default.
ListCache protocol.CacheControl
// StateKey enables the SignState/VerifyState HMAC helpers for MRTR
// requestState integrity.
StateKey []byte
// MaxConcurrency bounds concurrently executing requests. 0 means
// unlimited (appropriate for HTTP, where the listener governs).
MaxConcurrency int
// OnDiscover mutates the assembled DiscoverResult before it is sent
// (e.g. tenant-specific instructions or _meta annotations). It edits the
// presentation only: capabilities and method availability derive from
// registrations, so hiding a capability here does not gate its methods.
// Per-tenant access control belongs in a Middleware, which sees every
// request.
OnDiscover func(ctx context.Context, req *Request, d *protocol.DiscoverResult) error
// CompletionHandler enables the completions capability.
CompletionHandler func(ctx context.Context, req *Request, p *protocol.CompleteParams) (*protocol.CompleteResult, error)
}
type PromptHandler ¶
type PromptHandler func(ctx context.Context, req *PromptRequest) (protocol.PromptResponse, error)
PromptHandler resolves prompts/get. Return *protocol.GetPromptResult or an MRTR interim result via protocol.RequireInput.
type PromptRequest ¶ added in v1.3.0
type PromptRequest struct {
*Request
Params *protocol.GetPromptParams
}
PromptRequest is the typed request handed to prompt handlers.
type RawHandler ¶ added in v1.3.0
RawHandler is the uniform shape every method resolves to at dispatch time.
type Request ¶ added in v1.3.0
type Request struct {
// contains filtered or unexported fields
}
Request is the per-request context of the stateless server. It replaces the former ServerSession entirely: everything a handler may need travels in the request's _meta.
func (*Request) ClientCapabilities ¶ added in v1.3.0
func (r *Request) ClientCapabilities() *protocol.ClientCapabilities
func (*Request) ClientInfo ¶ added in v1.3.0
func (r *Request) ClientInfo() *protocol.Implementation
ClientInfo is self-reported and unverified; never use it for security decisions. It may be nil.
func (*Request) Extension ¶ added in v1.3.0
func (r *Request) Extension(id string) (json.RawMessage, bool)
Extension returns the per-request settings the client declared for an extension, and whether it declared the extension at all. Servers must gate extension behavior on this per request, regardless of prior declarations.
func (*Request) ProtocolVersion ¶ added in v1.3.0
func (*Request) RawParams ¶ added in v1.3.0
func (r *Request) RawParams() json.RawMessage
RawParams exposes the undecoded params, mainly for middleware and extension handlers.
func (*Request) ReportProgress ¶ added in v1.3.0
func (r *Request) ReportProgress(ctx context.Context, progress, total float64, message string) error
ReportProgress emits a notifications/progress on this request's response stream. It is a no-op when the client did not supply a progressToken. Successive calls must report increasing progress.
func (*Request) SupportsElicitation ¶ added in v1.3.0
SupportsElicitation reports which elicitation modes the client declared for this request. Handlers should check before returning an elicitation InputRequired.
func (*Request) TemplateVars ¶ added in v1.3.0
TemplateVars returns the variables captured by resource template matching, or nil for non-template requests.
type ResourceHandler ¶
type ResourceHandler func(ctx context.Context, req *ResourceRequest) (protocol.ResourceResponse, error)
ResourceHandler resolves resources/read. Return *protocol.ReadResourceResult or an MRTR interim result via protocol.RequireInput.
func FileResourceHandler ¶ added in v1.3.0
func FileResourceHandler(dir string) ResourceHandler
FileResourceHandler returns a ResourceHandler serving files under dir as base64 blobs. It protects against path traversal with filepath.Localize and os.OpenRoot.
type ResourceRequest ¶ added in v1.3.0
type ResourceRequest struct {
*Request
Params *protocol.ReadResourceParams
}
ResourceRequest is the typed request handed to resource handlers.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
func (*Server) AddExtension ¶ added in v1.3.0
AddExtension registers an extension. It panics on ID or method collisions and on unmarshalable Settings — registration errors are programmer errors and must fail loudly, not degrade silently at discover time.
func (*Server) AddPrompt ¶ added in v1.2.0
func (s *Server) AddPrompt(p *protocol.Prompt, h PromptHandler)
func (*Server) AddResource ¶ added in v1.2.0
func (s *Server) AddResource(r *protocol.Resource, h ResourceHandler)
func (*Server) AddResourceTemplate ¶ added in v1.2.0
func (s *Server) AddResourceTemplate(t *protocol.ResourceTemplate, h ResourceHandler)
AddResourceTemplate registers a URI template. Templates support single- segment {var} placeholders (e.g. "log://app/{date}"); matched variables are exposed to the handler via req.TemplateVars().
func (*Server) AddTool ¶ added in v1.2.0
func (s *Server) AddTool(t *protocol.Tool, h ToolHandler)
AddTool registers a tool. It panics on invalid registration (empty name, invalid x-mcp-header bindings): configuration errors must fail loudly, not surface as silently missing tools.
func (*Server) Handle ¶ added in v1.3.0
func (s *Server) Handle(ctx context.Context, msg *protocol.Message, emit func(*protocol.Message) error)
Handle processes one message. For requests, emit is called zero or more times with request-scoped notifications and then exactly once with the final response (subscriptions/listen keeps emitting until ctx ends). Cancelling ctx aborts the in-flight handler; transports translate their native cancellation signal (HTTP stream close, stdio notifications/cancelled) into ctx cancellation.
func (*Server) MethodNameParam ¶ added in v1.3.0
MethodNameParam reports the params key backing the Mcp-Name routing header for an extension method, if the extension registered one. It is the seam the Streamable HTTP transport uses to validate headers on extension methods; core methods are built into the transport.
func (*Server) Publish ¶ added in v1.3.0
Publish delivers a notification to all subscription streams listening on topic. Intended for extensions; core notifications flow through the same hub internally. Delivery itself is best-effort (an overflowing stream is terminated visibly on its own side); the returned error reports encoding failures, which mean the notification reached no subscriber at all.
func (*Server) RemovePrompts ¶ added in v1.3.0
func (*Server) RemoveResourceTemplates ¶ added in v1.3.0
func (*Server) RemoveResources ¶ added in v1.3.0
func (*Server) RemoveTools ¶ added in v1.3.0
RemoveTools removes tools by name.
func (*Server) ResourceUpdated ¶ added in v1.3.0
ResourceUpdated publishes notifications/resources/updated to subscription streams that subscribed to uri.
func (*Server) SignState ¶ added in v1.3.0
SignState wraps an MRTR requestState payload with an HMAC-SHA256 tag. The spec requires integrity protection whenever inbound state influences authorization, resource access or business logic.
func (*Server) ToolHeaderBindings ¶ added in v1.3.0
func (s *Server) ToolHeaderBindings(name string) []headerbind.Binding
ToolHeaderBindings exposes a tool's x-mcp-header bindings. It is the seam the streamhttp transport uses for header/body validation; applications normally have no reason to call it.
func (*Server) Use ¶ added in v1.2.1
func (s *Server) Use(m ...Middleware)
Use appends middleware. The first Use'd middleware is outermost.
type ToolHandler ¶
type ToolHandler func(ctx context.Context, req *CallRequest) (protocol.ToolResponse, error)
ToolHandler is the low-level tool handler: raw params in, response sum out. Return *protocol.CallToolResult for a final answer or *protocol.InputRequired (via protocol.RequireInput) for an MRTR interim result.
type ToolHandlerFor ¶ added in v1.2.1
type ToolHandlerFor[In, Out any] func(ctx context.Context, req *CallRequest, input In) (protocol.ToolResponse, Out, error)
ToolHandlerFor is the type-safe tool handler. The SDK infers and validates the input schema from In, deserializes arguments into In, and populates structuredContent from Out (mirrored as JSON text per spec recommendation).
Return conventions:
- return nil, out, nil → result built from out
- return res, _, nil → res used as-is (*CallToolResult or RequireInput)
- return nil, _, err → tool execution error (isError: true)
- return nil, _, *protocol.Error → JSON-RPC protocol error