server

package
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2026 License: MIT Imports: 36 Imported by: 0

Documentation

Overview

Code generated by `go generate`. DO NOT EDIT. source: server/internal/gen/hooks.go.tmpl

Package server provides MCP (Model Context Protocol) server implementations.

Package server provides MCP (Model Context Protocol) server implementations.

Code generated by `go generate`. DO NOT EDIT. source: server/internal/gen/request_handler.go.tmpl

Package server provides MCP (Model Context Protocol) server implementations.

Index

Constants

View Source
const (
	HeaderKeySessionID       = "Mcp-Session-Id"
	HeaderKeyProtocolVersion = "Mcp-Protocol-Version"
)

Common HTTP header constants used across server transports

View Source
const WellKnownProtectedResourcePath = "/.well-known/oauth-protected-resource"

WellKnownProtectedResourcePath is the base well-known URL path for OAuth 2.0 Protected Resource Metadata as defined in RFC 9728.

Variables

View Source
var (
	// ErrNoActiveSession is returned when there is no active session in the context
	ErrNoActiveSession = errors.New("no active session")
	// ErrElicitationNotSupported is returned when the session does not support elicitation
	ErrElicitationNotSupported = errors.New("session does not support elicitation")
)
View Source
var (
	// Common server errors
	ErrUnsupported      = errors.New("not supported")
	ErrResourceNotFound = errors.New("resource not found")
	ErrPromptNotFound   = errors.New("prompt not found")
	ErrToolNotFound     = errors.New("tool not found")

	// Session-related errors
	ErrSessionNotFound                        = errors.New("session not found")
	ErrSessionExists                          = errors.New("session already exists")
	ErrSessionNotInitialized                  = errors.New("session not properly initialized")
	ErrSessionDoesNotSupportTools             = errors.New("session does not support per-session tools")
	ErrSessionDoesNotSupportResources         = errors.New("session does not support per-session resources")
	ErrSessionDoesNotSupportResourceTemplates = errors.New("session does not support resource templates")
	ErrSessionDoesNotSupportLogging           = errors.New("session does not support setting logging level")

	// Notification-related errors
	ErrNotificationNotInitialized = errors.New("notification channel not initialized")
	ErrNotificationChannelBlocked = errors.New("notification channel queue is full - client may not be processing notifications fast enough")

	// ErrRemovedInProtocolVersion indicates the request used a method that was
	// removed in protocol version 2026-07-28. The method remains available to
	// clients using an earlier protocol version.
	ErrRemovedInProtocolVersion = errors.New("was removed in protocol version " + mcp.ProtocolVersion20260728)

	// ErrRequiresModernProtocol indicates the request used a method that was
	// introduced in protocol version 2026-07-28 without declaring that version
	// in its _meta.
	ErrRequiresModernProtocol = errors.New("requires protocol version " + mcp.ProtocolVersion20260728 + " or later")

	// ErrServerInitiatedRequestUnsupported indicates the server tried to send a
	// request to a client using protocol version 2026-07-28 or later, where
	// server-initiated requests were replaced by multi round-trip requests.
	ErrServerInitiatedRequestUnsupported = errors.New(
		"server-initiated requests are not supported in protocol version " + mcp.ProtocolVersion20260728 +
			" or later: return an InputRequests map from the handler instead (multi round-trip requests, SEP-2322)")
)
View Source
var (
	// ErrNoClientSession is returned when there is no active client session in the context
	ErrNoClientSession = errors.New("no active client session")
	// ErrRootsNotSupported is returned when the session does not support roots
	ErrRootsNotSupported = errors.New("session does not support roots")
)
View Source
var ErrLoadShedding = errors.New("the server is busy, retry later")

ErrLoadShedding is returned when a handler sheds load by asking the client to retry later, but the client predates the multi round-trip pattern and has no way to act on that signal.

Callers may detect it with errors.Is to map the condition onto a transport level backpressure response, such as HTTP 503 with Retry-After.

View Source
var ErrUnknownEventID = errors.New("unknown event ID")

ErrUnknownEventID indicates that a lastEventID passed to EventStore.ReplayEventsAfter is not known for the given session.

Functions

func ElicitationResponse

func ElicitationResponse(responses mcp.InputResponses, id string) *mcp.ElicitationResult

ElicitationResponse returns the elicitation result the client supplied under id, or nil when absent.

func FilterSupportedVersions

func FilterSupportedVersions(transport any) []string

FilterSupportedVersions returns the subset of mcp.ValidProtocolVersions that the transport can serve. A transport that does not implement ProtocolVersionSupporter is assumed to support every version.

func GenerateInProcessSessionID

func GenerateInProcessSessionID() string

GenerateInProcessSessionID generates a unique session ID for inprocess clients

func InputResponse

func InputResponse(responses mcp.InputResponses, id string) (mcp.InputResponse, bool)

InputResponse returns the client's answer to the input request recorded under id, and whether it was present.

Use it at the top of a handler to detect a retry:

if answer, ok := server.InputResponse(request.Params.InputResponses, "confirm"); ok {
    // the user answered; finish the work
}

func IsModernRequest

func IsModernRequest(ctx context.Context) bool

IsModernRequest reports whether the request being handled uses the stateless protocol core introduced in 2026-07-28.

func NewHandlerError

func NewHandlerError(provider JSONRPCErrorProvider) error

NewHandlerError marks a typed JSON-RPC error as safe to return from a server handler. Errors are not exposed automatically because they may have originated from another server.

func NewProtectedResourceMetadataHandler

func NewProtectedResourceMetadataHandler(config ProtectedResourceMetadataConfig) http.Handler

NewProtectedResourceMetadataHandler returns an http.Handler that serves the given OAuth 2.0 Protected Resource Metadata as JSON.

The handler responds with:

  • 200 OK and the metadata JSON for GET requests.
  • 204 No Content for OPTIONS (CORS preflight).
  • 405 Method Not Allowed (with Allow header) for any other method.

Permissive CORS headers (Access-Control-Allow-Origin: *) are included so browser-based MCP clients can discover the resource cross-origin, and Cache-Control: no-store is set per the MCP authorization spec guidance to avoid stale metadata during rotation.

Use this handler directly for custom routing setups:

mux := http.NewServeMux()
mux.Handle("/mcp", mcpHandler)
mux.Handle("/.well-known/oauth-protected-resource",
    server.NewProtectedResourceMetadataHandler(server.ProtectedResourceMetadataConfig{
        Resource:             "https://my-server.com",
        AuthorizationServers: []string{"https://auth.example.com"},
        ScopesSupported:      []string{"mcp:read", "mcp:write"},
    }))

For path-qualified resources prefer using ProtectedResourceMetadataPath to derive the correct mount path:

mux.Handle(server.ProtectedResourceMetadataPath(cfg.Resource),
    server.NewProtectedResourceMetadataHandler(cfg))

func ProtectedResourceMetadataPath

func ProtectedResourceMetadataPath(resource string) string

ProtectedResourceMetadataPath returns the well-known URL path that should serve Protected Resource Metadata for the given resource identifier per RFC 9728 §3.1.

For a resource with no path component (e.g. "https://mcp.example.com" or "https://mcp.example.com/") this returns "/.well-known/oauth-protected-resource".

For a path-qualified resource (e.g. "https://mcp.example.com/mcp") the resource path is appended after the well-known segment, producing "/.well-known/oauth-protected-resource/mcp".

If resource is empty, cannot be parsed as a URL, or is not an absolute URI (i.e. lacks a scheme and host), the bare well-known path is returned. RFC 9728 resource identifiers are absolute URIs, so a bare host like "mcp.example.com" or a path-only value like "/mcp" is not a valid resource and must not contribute a path suffix.

func RequestProtocolVersion

func RequestProtocolVersion(ctx context.Context) string

RequestProtocolVersion returns the protocol version in effect for the request being handled.

For modern requests this is the version declared in _meta. For legacy requests it falls back to the version negotiated during initialize, when the session records one.

func RootsResponse

func RootsResponse(responses mcp.InputResponses, id string) *mcp.ListRootsResult

RootsResponse returns the roots list the client supplied under id, or nil when absent.

func SamplingResponse

func SamplingResponse(responses mcp.InputResponses, id string) *mcp.CreateMessageResult

SamplingResponse returns the sampling result the client supplied under id, or nil when absent.

func ServeStdio

func ServeStdio(server *MCPServer, opts ...StdioOption) error

ServeStdio is a convenience function that creates and starts a StdioServer with os.Stdin and os.Stdout. It sets up signal handling for graceful shutdown on SIGTERM and SIGINT. Returns an error if the server encounters any issues during operation.

func SubscriptionIDFromContext

func SubscriptionIDFromContext(ctx context.Context) any

SubscriptionIDFromContext returns the JSON-RPC ID of the subscriptions/listen request that opened the current stream, or nil when the request is not a subscription stream.

func SupportedProtocolVersionsFromContext

func SupportedProtocolVersionsFromContext(ctx context.Context) []string

SupportedProtocolVersionsFromContext returns the protocol versions the current transport can serve, defaulting to every version this SDK implements.

func WithInProcessSamplingHandler

func WithInProcessSamplingHandler(ctx context.Context, handler SamplingHandler) context.Context

WithInProcessSamplingHandler adds a sampling handler to the context for inprocess clients

func WithRequestProtocolInfo

func WithRequestProtocolInfo(ctx context.Context, info *RequestProtocolInfo) context.Context

WithRequestProtocolInfo returns a context carrying the per-request protocol information.

func WithSubscriptionID

func WithSubscriptionID(ctx context.Context, id any) context.Context

WithSubscriptionID returns a context tagged with the JSON-RPC ID of the subscriptions/listen request that opened the current stream.

func WithSupportedProtocolVersions

func WithSupportedProtocolVersions(ctx context.Context, versions []string) context.Context

WithSupportedProtocolVersions returns a context advertising the protocol versions the current transport can serve. Transports set this before dispatching a request; server/discover reports it to the client.

Types

type BeforeAnyHookFunc

type BeforeAnyHookFunc func(ctx context.Context, id any, method mcp.MCPMethod, message any)

BeforeAnyHookFunc is a function that is called after the request is parsed but before the method is called.

See the Hooks type-level documentation for the pairing contract between OnBeforeAny, OnSuccess, and OnError.

type CORSConfig

type CORSConfig struct {
	// AllowedOrigins is the list of origins permitted to access the server.
	// The literal value "*" allows any origin, but is incompatible with
	// AllowCredentials per the CORS specification — when both are set, the
	// server echoes the request's Origin header instead of "*".
	AllowedOrigins []string

	// AllowedMethods is the list of HTTP methods allowed for cross-origin
	// requests. When empty, GET, POST, DELETE and OPTIONS are advertised.
	AllowedMethods []string

	// AllowedHeaders is the list of headers a client may send with the
	// actual request. When empty, a sensible MCP-aware default of
	// Content-Type, Mcp-Session-Id, Last-Event-ID and Authorization is
	// advertised.
	AllowedHeaders []string

	// ExposedHeaders is the list of response headers the browser is
	// permitted to access from JavaScript. When empty, Mcp-Session-Id is
	// exposed by default so clients can read newly-issued session IDs.
	ExposedHeaders []string

	// AllowCredentials, when true, causes the server to send
	// Access-Control-Allow-Credentials: true on cross-origin responses.
	AllowCredentials bool

	// MaxAge is the number of seconds browsers may cache the preflight
	// response. Zero (or negative) omits the header.
	MaxAge int
}

CORSConfig holds the Cross-Origin Resource Sharing configuration shared by the SSE and Streamable HTTP transports. The zero value disables CORS handling entirely; set at least one allowed origin via AllowedOrigins (or the WithCORSAllowedOrigins helper) to enable it.

CORS handling is opt-in: when no origins are configured, the transports do not emit any Access-Control-* response headers and preflight (OPTIONS) requests are passed through to the underlying handlers unchanged.

type CORSOption

type CORSOption func(*CORSConfig)

CORSOption configures a CORSConfig. It is consumed by the per-transport options WithSSECORS and WithStreamableHTTPCORS.

func WithCORSAllowCredentials

func WithCORSAllowCredentials() CORSOption

WithCORSAllowCredentials enables Access-Control-Allow-Credentials: true on cross-origin responses. When combined with an AllowedOrigins value of "*", the server echoes the request's Origin header to remain spec-compliant.

func WithCORSAllowedHeaders

func WithCORSAllowedHeaders(headers ...string) CORSOption

WithCORSAllowedHeaders sets the list of headers advertised in preflight responses via Access-Control-Allow-Headers.

func WithCORSAllowedMethods

func WithCORSAllowedMethods(methods ...string) CORSOption

WithCORSAllowedMethods sets the list of HTTP methods advertised in preflight responses via Access-Control-Allow-Methods.

func WithCORSAllowedOrigins

func WithCORSAllowedOrigins(origins ...string) CORSOption

WithCORSAllowedOrigins sets the list of origins allowed to access the server. Passing "*" allows any origin. Calling this multiple times within a single WithSSECORS / WithStreamableHTTPCORS invocation replaces the previous value.

func WithCORSExposedHeaders

func WithCORSExposedHeaders(headers ...string) CORSOption

WithCORSExposedHeaders sets the list of headers exposed to the browser client via Access-Control-Expose-Headers.

func WithCORSMaxAge

func WithCORSMaxAge(seconds int) CORSOption

WithCORSMaxAge sets the Access-Control-Max-Age header (in seconds) emitted on preflight responses. Zero or negative values omit the header.

type ClientSession

type ClientSession interface {
	// Initialize marks session as fully initialized and ready for notifications
	Initialize()
	// Initialized returns if session is ready to accept notifications
	Initialized() bool
	// NotificationChannel provides a channel suitable for sending notifications to client.
	NotificationChannel() chan<- mcp.JSONRPCNotification
	// SessionID is a unique identifier used to track user session.
	SessionID() string
}

ClientSession represents an active session that can be used by MCPServer to interact with client.

func ClientSessionFromContext

func ClientSessionFromContext(ctx context.Context) ClientSession

ClientSessionFromContext retrieves current client notification context from context.

type DefaultPromptCompletionProvider

type DefaultPromptCompletionProvider struct{}

DefaultCompletionProvider returns no completions (fallback)

func (*DefaultPromptCompletionProvider) CompletePromptArgument

func (p *DefaultPromptCompletionProvider) CompletePromptArgument(ctx context.Context, promptName string, argument mcp.CompleteArgument, context mcp.CompleteContext) (*mcp.Completion, error)

type DefaultResourceCompletionProvider

type DefaultResourceCompletionProvider struct{}

DefaultResourceCompletionProvider returns no completions (fallback)

func (*DefaultResourceCompletionProvider) CompleteResourceArgument

func (p *DefaultResourceCompletionProvider) CompleteResourceArgument(ctx context.Context, uri string, argument mcp.CompleteArgument, context mcp.CompleteContext) (*mcp.Completion, error)

type DefaultSessionIdManagerResolver

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

DefaultSessionIdManagerResolver is a simple resolver that returns the same SessionIdManager for all requests

func NewDefaultSessionIdManagerResolver

func NewDefaultSessionIdManagerResolver(manager SessionIdManager) *DefaultSessionIdManagerResolver

NewDefaultSessionIdManagerResolver creates a new DefaultSessionIdManagerResolver with the given SessionIdManager

func (*DefaultSessionIdManagerResolver) ResolveSessionIdManager

func (r *DefaultSessionIdManagerResolver) ResolveSessionIdManager(_ *http.Request) SessionIdManager

ResolveSessionIdManager returns the configured SessionIdManager for all requests

type DynamicBasePathFunc

type DynamicBasePathFunc func(r *http.Request, sessionID string) string

DynamicBasePathFunc allows the user to provide a function to generate the base path for a given request and sessionID. This is useful for cases where the base path is not known at the time of SSE server creation, such as when using a reverse proxy or when the base path is dynamically generated. The function should return the base path (e.g., "/mcp/tenant123").

type ElicitationHandler

type ElicitationHandler interface {
	Elicit(ctx context.Context, request mcp.ElicitationRequest) (*mcp.ElicitationResult, error)
}

ElicitationHandler defines the interface for handling elicitation requests from servers.

type ErrDynamicPathConfig

type ErrDynamicPathConfig struct {
	Method string
}

ErrDynamicPathConfig is returned when attempting to use static path methods with dynamic path configuration

func (*ErrDynamicPathConfig) Error

func (e *ErrDynamicPathConfig) Error() string

type EventStore

type EventStore interface {
	// StoreEvent records message as the next event on the given stream and
	// returns the event ID assigned to it. The returned ID is attached to the
	// SSE event delivered to the client.
	StoreEvent(ctx context.Context, sessionID, streamID string, message json.RawMessage) (string, error)

	// ReplayEventsAfter invokes send, in insertion order, for every event
	// stored after lastEventID on the same stream as lastEventID, and returns
	// the ID of that stream. It returns an error wrapping ErrUnknownEventID if
	// lastEventID is not known for the given session, or the error returned by
	// send if send fails.
	ReplayEventsAfter(ctx context.Context, sessionID, lastEventID string, send func(eventID string, message json.RawMessage) error) (string, error)

	// PurgeSession removes every event recorded for the given session. It is
	// called when the session terminates (an explicit DELETE or an idle
	// sweep), after which none of the session's event IDs can be resumed from.
	PurgeSession(ctx context.Context, sessionID string) error
}

EventStore records the JSON-RPC messages delivered on a session's SSE streams so that a client can resume a broken stream and be redelivered the messages it missed, per the "Resumability and Redelivery" section of the MCP Streamable HTTP transport specification.

The transport treats event IDs as opaque strings: any non-empty value that contains no carriage returns or newlines is acceptable, as long as IDs are unique within a session across all of its streams. Implementations must be safe for concurrent use.

type HTTPContextFunc

type HTTPContextFunc func(ctx context.Context, r *http.Request) context.Context

HTTPContextFunc is a function that takes an existing context and the current request and returns a potentially modified context based on the request content. This can be used to inject context values from headers, for example.

type HTTPRequest

type HTTPRequest struct {
	// Method is the HTTP method ("POST", "GET", "DELETE"). Required.
	Method string
	// URL is the request URL. Optional; only Path is consulted by mcp-go and
	// only when WithProtectedResourceMetadata is configured. May be nil.
	URL *url.URL
	// Header carries the request headers. Required.
	Header http.Header
	// Body is the (already buffered) request body. May be nil for GET/DELETE.
	Body []byte
	// Context is the request context. Cancellation is honored for streaming
	// responses. Required.
	Context context.Context
	// contains filtered or unexported fields
}

HTTPRequest is a transport-agnostic view of an incoming MCP HTTP request. It contains everything StreamableHTTPServer.Handle needs to process a request without depending on net/http server primitives, allowing integration with frameworks such as fasthttp/fiber.

All fields are read by Handle but never mutated. Body is fully buffered; adapters do not need to keep an io.Reader alive for the duration of streaming responses.

type HTTPResponseWriter

type HTTPResponseWriter interface {
	// Header returns the response header map. The same semantics as
	// http.ResponseWriter.Header apply: changes after WriteHeader has been
	// called may be ignored.
	Header() http.Header
	// WriteHeader sends the HTTP status code. It must be called at most once.
	WriteHeader(statusCode int)
	// Write writes raw response bytes. WriteHeader is implicitly called with
	// 200 if it has not been called yet.
	Write(p []byte) (int, error)
	// Flush forwards any buffered bytes to the client. Implementations whose
	// underlying transport cannot stream may make this a no-op, but in that
	// case CanStream MUST return false.
	Flush()
	// CanStream reports whether Flush actually delivers bytes to the client
	// immediately. When false, the server will not upgrade POST responses to
	// SSE and will reject GET requests with 405 Method Not Allowed.
	CanStream() bool
}

HTTPResponseWriter is the minimum surface mcp-go needs to write a streamable HTTP response. Adapters for fasthttp, fiber, or other transports can implement this directly to avoid going through the net/http server machinery.

Implementations whose underlying transport buffers the response (and so cannot deliver SSE streams) MUST return false from CanStream and SHOULD make Flush a no-op. The server uses CanStream to decide whether to upgrade a POST response to text/event-stream and whether GET (which requires streaming) is supported at all.

type Hooks

type Hooks struct {
	OnRegisterSession             []OnRegisterSessionHookFunc
	OnUnregisterSession           []OnUnregisterSessionHookFunc
	OnBeforeAny                   []BeforeAnyHookFunc
	OnSuccess                     []OnSuccessHookFunc
	OnError                       []OnErrorHookFunc
	OnRequestInitialization       []OnRequestInitializationFunc
	OnBeforeInitialize            []OnBeforeInitializeFunc
	OnAfterInitialize             []OnAfterInitializeFunc
	OnBeforePing                  []OnBeforePingFunc
	OnAfterPing                   []OnAfterPingFunc
	OnBeforeDiscover              []OnBeforeDiscoverFunc
	OnAfterDiscover               []OnAfterDiscoverFunc
	OnBeforeSubscriptionsListen   []OnBeforeSubscriptionsListenFunc
	OnAfterSubscriptionsListen    []OnAfterSubscriptionsListenFunc
	OnBeforeSetLevel              []OnBeforeSetLevelFunc
	OnAfterSetLevel               []OnAfterSetLevelFunc
	OnBeforeListResources         []OnBeforeListResourcesFunc
	OnAfterListResources          []OnAfterListResourcesFunc
	OnBeforeListResourceTemplates []OnBeforeListResourceTemplatesFunc
	OnAfterListResourceTemplates  []OnAfterListResourceTemplatesFunc
	OnBeforeReadResource          []OnBeforeReadResourceFunc
	OnAfterReadResource           []OnAfterReadResourceFunc
	OnBeforeSubscribe             []OnBeforeSubscribeFunc
	OnAfterSubscribe              []OnAfterSubscribeFunc
	OnBeforeUnsubscribe           []OnBeforeUnsubscribeFunc
	OnAfterUnsubscribe            []OnAfterUnsubscribeFunc
	OnBeforeListPrompts           []OnBeforeListPromptsFunc
	OnAfterListPrompts            []OnAfterListPromptsFunc
	OnBeforeGetPrompt             []OnBeforeGetPromptFunc
	OnAfterGetPrompt              []OnAfterGetPromptFunc
	OnBeforeListTools             []OnBeforeListToolsFunc
	OnAfterListTools              []OnAfterListToolsFunc
	OnBeforeCallTool              []OnBeforeCallToolFunc
	OnAfterCallTool               []OnAfterCallToolFunc
	OnBeforeGetTask               []OnBeforeGetTaskFunc
	OnAfterGetTask                []OnAfterGetTaskFunc
	OnBeforeListTasks             []OnBeforeListTasksFunc
	OnAfterListTasks              []OnAfterListTasksFunc
	OnBeforeTaskResult            []OnBeforeTaskResultFunc
	OnAfterTaskResult             []OnAfterTaskResultFunc
	OnBeforeCancelTask            []OnBeforeCancelTaskFunc
	OnAfterCancelTask             []OnAfterCancelTaskFunc
	OnBeforeComplete              []OnBeforeCompleteFunc
	OnAfterComplete               []OnAfterCompleteFunc
}

Hooks is the registry of callbacks that fire around request handling.

Pairing contract

For every invocation of OnBeforeAny for a given request id, exactly one of OnSuccess or OnError will fire for the same id before the request handler returns to the JSON-RPC dispatcher. This makes the OnBeforeAny / OnSuccess / OnError trio safe to use as the building block for per-request bookkeeping such as latency histograms, distributed tracing spans, or slow-request logging.

Two caveats apply:

  1. OnError may fire without a prior OnBeforeAny when the dispatcher rejects a request before invoking the per-method handler. This happens for payload-parse failures (UnparsableMessageError) and capability-not- enabled errors (ErrUnsupported). Per-request bookkeeping consumers must therefore tolerate "id not found" on the OnError path; the natural sync.Map.LoadAndDelete ok-bool already covers this.

  2. If a handler panics and neither WithRecovery nor WithResourceRecovery is installed at server construction, the panic unwinds past the dispatcher and skips both OnSuccess and OnError. OnBeforeAny will already have fired. The process is typically terminating in that case, so the leak is moot in practice; bookkeeping consumers that need to survive unrecovered panics should either install the recovery middleware or run a periodic sweeper. With recovery middleware installed, panics are converted to errors and the contract above holds.

Hooks fire synchronously in the request goroutine, in the order they were registered with the corresponding Add* method. A long-running hook will delay the response to the client; offload heavy work to a separate goroutine if needed.

func (*Hooks) AddAfterCallTool

func (c *Hooks) AddAfterCallTool(hook OnAfterCallToolFunc)

func (*Hooks) AddAfterCancelTask

func (c *Hooks) AddAfterCancelTask(hook OnAfterCancelTaskFunc)

func (*Hooks) AddAfterComplete

func (c *Hooks) AddAfterComplete(hook OnAfterCompleteFunc)

func (*Hooks) AddAfterDiscover

func (c *Hooks) AddAfterDiscover(hook OnAfterDiscoverFunc)

func (*Hooks) AddAfterGetPrompt

func (c *Hooks) AddAfterGetPrompt(hook OnAfterGetPromptFunc)

func (*Hooks) AddAfterGetTask

func (c *Hooks) AddAfterGetTask(hook OnAfterGetTaskFunc)

func (*Hooks) AddAfterInitialize

func (c *Hooks) AddAfterInitialize(hook OnAfterInitializeFunc)

func (*Hooks) AddAfterListPrompts

func (c *Hooks) AddAfterListPrompts(hook OnAfterListPromptsFunc)

func (*Hooks) AddAfterListResourceTemplates

func (c *Hooks) AddAfterListResourceTemplates(hook OnAfterListResourceTemplatesFunc)

func (*Hooks) AddAfterListResources

func (c *Hooks) AddAfterListResources(hook OnAfterListResourcesFunc)

func (*Hooks) AddAfterListTasks

func (c *Hooks) AddAfterListTasks(hook OnAfterListTasksFunc)

func (*Hooks) AddAfterListTools

func (c *Hooks) AddAfterListTools(hook OnAfterListToolsFunc)

func (*Hooks) AddAfterPing

func (c *Hooks) AddAfterPing(hook OnAfterPingFunc)

func (*Hooks) AddAfterReadResource

func (c *Hooks) AddAfterReadResource(hook OnAfterReadResourceFunc)

func (*Hooks) AddAfterSetLevel

func (c *Hooks) AddAfterSetLevel(hook OnAfterSetLevelFunc)

func (*Hooks) AddAfterSubscribe

func (c *Hooks) AddAfterSubscribe(hook OnAfterSubscribeFunc)

func (*Hooks) AddAfterSubscriptionsListen

func (c *Hooks) AddAfterSubscriptionsListen(hook OnAfterSubscriptionsListenFunc)

func (*Hooks) AddAfterTaskResult

func (c *Hooks) AddAfterTaskResult(hook OnAfterTaskResultFunc)

func (*Hooks) AddAfterUnsubscribe

func (c *Hooks) AddAfterUnsubscribe(hook OnAfterUnsubscribeFunc)

func (*Hooks) AddBeforeAny

func (c *Hooks) AddBeforeAny(hook BeforeAnyHookFunc)

func (*Hooks) AddBeforeCallTool

func (c *Hooks) AddBeforeCallTool(hook OnBeforeCallToolFunc)

func (*Hooks) AddBeforeCancelTask

func (c *Hooks) AddBeforeCancelTask(hook OnBeforeCancelTaskFunc)

func (*Hooks) AddBeforeComplete

func (c *Hooks) AddBeforeComplete(hook OnBeforeCompleteFunc)

func (*Hooks) AddBeforeDiscover

func (c *Hooks) AddBeforeDiscover(hook OnBeforeDiscoverFunc)

func (*Hooks) AddBeforeGetPrompt

func (c *Hooks) AddBeforeGetPrompt(hook OnBeforeGetPromptFunc)

func (*Hooks) AddBeforeGetTask

func (c *Hooks) AddBeforeGetTask(hook OnBeforeGetTaskFunc)

func (*Hooks) AddBeforeInitialize

func (c *Hooks) AddBeforeInitialize(hook OnBeforeInitializeFunc)

func (*Hooks) AddBeforeListPrompts

func (c *Hooks) AddBeforeListPrompts(hook OnBeforeListPromptsFunc)

func (*Hooks) AddBeforeListResourceTemplates

func (c *Hooks) AddBeforeListResourceTemplates(hook OnBeforeListResourceTemplatesFunc)

func (*Hooks) AddBeforeListResources

func (c *Hooks) AddBeforeListResources(hook OnBeforeListResourcesFunc)

func (*Hooks) AddBeforeListTasks

func (c *Hooks) AddBeforeListTasks(hook OnBeforeListTasksFunc)

func (*Hooks) AddBeforeListTools

func (c *Hooks) AddBeforeListTools(hook OnBeforeListToolsFunc)

func (*Hooks) AddBeforePing

func (c *Hooks) AddBeforePing(hook OnBeforePingFunc)

func (*Hooks) AddBeforeReadResource

func (c *Hooks) AddBeforeReadResource(hook OnBeforeReadResourceFunc)

func (*Hooks) AddBeforeSetLevel

func (c *Hooks) AddBeforeSetLevel(hook OnBeforeSetLevelFunc)

func (*Hooks) AddBeforeSubscribe

func (c *Hooks) AddBeforeSubscribe(hook OnBeforeSubscribeFunc)

func (*Hooks) AddBeforeSubscriptionsListen

func (c *Hooks) AddBeforeSubscriptionsListen(hook OnBeforeSubscriptionsListenFunc)

func (*Hooks) AddBeforeTaskResult

func (c *Hooks) AddBeforeTaskResult(hook OnBeforeTaskResultFunc)

func (*Hooks) AddBeforeUnsubscribe

func (c *Hooks) AddBeforeUnsubscribe(hook OnBeforeUnsubscribeFunc)

func (*Hooks) AddOnError

func (c *Hooks) AddOnError(hook OnErrorHookFunc)

AddOnError registers a hook function that will be called when an error occurs. The error parameter contains the actual error object, which can be interrogated using Go's error handling patterns like errors.Is and errors.As.

Example: ``` // Create a channel to receive errors for testing errChan := make(chan error, 1)

// Register hook to capture and inspect errors hooks := &Hooks{}

hooks.AddOnError(func(ctx context.Context, id any, method mcp.MCPMethod, message any, err error) {
    // For capability-related errors
    if errors.Is(err, ErrUnsupported) {
        // Handle capability not supported
        errChan <- err
        return
    }

    // For parsing errors
    var parseErr = &UnparsableMessageError{}
    if errors.As(err, &parseErr) {
        // Handle unparsable message errors
        fmt.Printf("Failed to parse %s request: %v\n",
                   parseErr.GetMethod(), parseErr.Unwrap())
        errChan <- parseErr
        return
    }

    // For resource/prompt/tool not found errors
    if errors.Is(err, ErrResourceNotFound) ||
       errors.Is(err, ErrPromptNotFound) ||
       errors.Is(err, ErrToolNotFound) {
        // Handle not found errors
        errChan <- err
        return
    }

    // For other errors
    errChan <- err
})

server := NewMCPServer("test-server", "1.0.0", WithHooks(hooks)) ```

func (*Hooks) AddOnRegisterSession

func (c *Hooks) AddOnRegisterSession(hook OnRegisterSessionHookFunc)

func (*Hooks) AddOnRequestInitialization

func (c *Hooks) AddOnRequestInitialization(hook OnRequestInitializationFunc)

func (*Hooks) AddOnSuccess

func (c *Hooks) AddOnSuccess(hook OnSuccessHookFunc)

func (*Hooks) AddOnUnregisterSession

func (c *Hooks) AddOnUnregisterSession(hook OnUnregisterSessionHookFunc)

func (*Hooks) RegisterSession

func (c *Hooks) RegisterSession(ctx context.Context, session ClientSession)

func (*Hooks) UnregisterSession

func (c *Hooks) UnregisterSession(ctx context.Context, session ClientSession)

type InMemoryEventStore

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

InMemoryEventStore is an EventStore that keeps events in process memory. It is suitable for single-process deployments; multi-node deployments should implement EventStore on top of shared storage instead.

A session's events are retained until PurgeSession is called for it, which the streamable HTTP server does when the session terminates.

func NewInMemoryEventStore

func NewInMemoryEventStore() *InMemoryEventStore

NewInMemoryEventStore creates an empty in-memory event store.

func (*InMemoryEventStore) PurgeSession

func (s *InMemoryEventStore) PurgeSession(_ context.Context, sessionID string) error

PurgeSession removes every event recorded for the given session.

func (*InMemoryEventStore) ReplayEventsAfter

func (s *InMemoryEventStore) ReplayEventsAfter(_ context.Context, sessionID, lastEventID string, send func(eventID string, message json.RawMessage) error) (string, error)

ReplayEventsAfter invokes send for every event stored after lastEventID on the stream that produced it, in insertion order, and returns that stream's ID. It returns an error wrapping ErrUnknownEventID if lastEventID was never issued for the given session or the session's events have been purged.

func (*InMemoryEventStore) StoreEvent

func (s *InMemoryEventStore) StoreEvent(_ context.Context, sessionID, streamID string, message json.RawMessage) (string, error)

StoreEvent records message as the next event on the given stream and returns the store-wide sequence number assigned to it as the event ID.

type InProcessSession

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

func NewInProcessSession

func NewInProcessSession(sessionID string, samplingHandler SamplingHandler) *InProcessSession

func NewInProcessSessionWithHandlers

func NewInProcessSessionWithHandlers(sessionID string, samplingHandler SamplingHandler, elicitationHandler ElicitationHandler, rootsHandler RootsHandler) *InProcessSession

func (*InProcessSession) ClientNotifications

func (s *InProcessSession) ClientNotifications() <-chan mcp.JSONRPCNotification

ClientNotifications returns the receive-only endpoint of the session's notification channel. In-process transports use this to drain server-to-client notifications (progress, list-changed, resource updates, etc.) queued via NotificationChannel and forward them to the client's registered notification handler.

func (*InProcessSession) GetClientCapabilities

func (s *InProcessSession) GetClientCapabilities() mcp.ClientCapabilities

GetClientCapabilities returns the stored client capabilities, or the zero value of mcp.ClientCapabilities if they have not been set.

func (*InProcessSession) GetClientInfo

func (s *InProcessSession) GetClientInfo() mcp.Implementation

GetClientInfo returns the stored client info, or the zero value of mcp.Implementation if it has not been set.

func (*InProcessSession) GetLogLevel

func (s *InProcessSession) GetLogLevel() mcp.LoggingLevel

func (*InProcessSession) Initialize

func (s *InProcessSession) Initialize()

func (*InProcessSession) Initialized

func (s *InProcessSession) Initialized() bool

func (*InProcessSession) ListRoots

ListRoots sends a list roots request to the client and waits for the response. Returns an error if no roots handler is available.

func (*InProcessSession) NotificationChannel

func (s *InProcessSession) NotificationChannel() chan<- mcp.JSONRPCNotification

func (*InProcessSession) ProtocolVersion

func (s *InProcessSession) ProtocolVersion() string

ProtocolVersion returns the protocol version in effect for this session, or "" when none has been recorded.

For sessions established through the initialize handshake this is the negotiated version. For requests using protocol version 2026-07-28 or later, where there is no handshake, it is the version the request declared in its _meta.

func (*InProcessSession) RequestElicitation

func (s *InProcessSession) RequestElicitation(ctx context.Context, request mcp.ElicitationRequest) (*mcp.ElicitationResult, error)

func (*InProcessSession) RequestSampling

func (*InProcessSession) SessionID

func (s *InProcessSession) SessionID() string

func (*InProcessSession) SetClientCapabilities

func (s *InProcessSession) SetClientCapabilities(clientCapabilities mcp.ClientCapabilities)

SetClientCapabilities replaces the stored client capabilities.

func (*InProcessSession) SetClientInfo

func (s *InProcessSession) SetClientInfo(clientInfo mcp.Implementation)

SetClientInfo replaces the stored client info.

func (*InProcessSession) SetLogLevel

func (s *InProcessSession) SetLogLevel(level mcp.LoggingLevel)

func (*InProcessSession) SetProtocolVersion

func (s *InProcessSession) SetProtocolVersion(version string)

SetProtocolVersion records the protocol version in effect for this session.

type InputRequestBuilder

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

InputRequestBuilder accumulates the requests a handler needs answered before it can complete, and renders them as an mcp.InputRequiredResult.

The zero value is ready to use.

func NewInputRequestBuilder

func NewInputRequestBuilder(requestState string) *InputRequestBuilder

NewInputRequestBuilder returns a builder for the input a handler needs. requestState is an opaque token the client echoes back on retry; use it to resume where the handler left off. It may be empty.

func (*InputRequestBuilder) Elicit

Elicit asks the client to collect information from the user, keyed by id.

func (*InputRequestBuilder) PromptResult

func (b *InputRequestBuilder) PromptResult() *mcp.GetPromptResult

PromptResult renders the accumulated requests as a prompts/get result asking the client for more input.

func (*InputRequestBuilder) RequestState

func (b *InputRequestBuilder) RequestState(state string) *InputRequestBuilder

RequestState sets the opaque token the client echoes back on retry.

func (*InputRequestBuilder) ResourceResult

func (b *InputRequestBuilder) ResourceResult() *mcp.ReadResourceResult

ResourceResult renders the accumulated requests as a resources/read result asking the client for more input.

Resource handlers registered with AddResource return contents rather than a full result, so this is for servers that construct resources/read responses directly.

func (*InputRequestBuilder) Roots

Roots asks the client for its list of roots, keyed by id.

func (*InputRequestBuilder) Sample

Sample asks the client to run an LLM completion, keyed by id.

func (*InputRequestBuilder) ToolResult

func (b *InputRequestBuilder) ToolResult() *mcp.CallToolResult

ToolResult renders the accumulated requests as a tools/call result asking the client for more input.

type InsecureStatefulSessionIdManager

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

InsecureStatefulSessionIdManager generate id with uuid and tracks active sessions. It validates both format and existence of session IDs. For more secure session id, use a more complex generator, like a JWT.

func (*InsecureStatefulSessionIdManager) Generate

func (*InsecureStatefulSessionIdManager) Terminate

func (s *InsecureStatefulSessionIdManager) Terminate(sessionID string) (isNotAllowed bool, err error)

func (*InsecureStatefulSessionIdManager) Validate

func (s *InsecureStatefulSessionIdManager) Validate(sessionID string) (isTerminated bool, err error)

type JSONRPCErrorProvider

type JSONRPCErrorProvider interface {
	error
	JSONRPCError() mcp.JSONRPCError
}

JSONRPCErrorProvider provides a typed JSON-RPC error response.

type MCPServer

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

MCPServer implements a Model Context Protocol server that can handle various types of requests including resources, prompts, and tools.

func NewMCPServer

func NewMCPServer(
	name, version string,
	opts ...ServerOption,
) *MCPServer

NewMCPServer creates a new MCP server instance with the given name, version and options

func ServerFromContext

func ServerFromContext(ctx context.Context) *MCPServer

ServerFromContext retrieves the MCPServer instance from a context

func (*MCPServer) AddNotificationHandler

func (s *MCPServer) AddNotificationHandler(
	method string,
	handler NotificationHandlerFunc,
)

AddNotificationHandler registers a new handler for incoming notifications

func (*MCPServer) AddPrompt

func (s *MCPServer) AddPrompt(prompt mcp.Prompt, handler PromptHandlerFunc)

AddPrompt registers a new prompt handler with the given name

func (*MCPServer) AddPrompts

func (s *MCPServer) AddPrompts(prompts ...ServerPrompt)

AddPrompts registers multiple prompts at once

func (*MCPServer) AddResource

func (s *MCPServer) AddResource(
	resource mcp.Resource,
	handler ResourceHandlerFunc,
)

AddResource registers a new resource and its handler

func (*MCPServer) AddResourceTemplate

func (s *MCPServer) AddResourceTemplate(
	template mcp.ResourceTemplate,
	handler ResourceTemplateHandlerFunc,
)

AddResourceTemplate registers a new resource template and its handler

func (*MCPServer) AddResourceTemplates

func (s *MCPServer) AddResourceTemplates(resourceTemplates ...ServerResourceTemplate)

AddResourceTemplates registers multiple resource templates at once

func (*MCPServer) AddResources

func (s *MCPServer) AddResources(resources ...ServerResource)

AddResources registers multiple resources at once

func (*MCPServer) AddSessionResource

func (s *MCPServer) AddSessionResource(sessionID string, resource mcp.Resource, handler ResourceHandlerFunc) error

AddSessionResource adds a resource for a specific session

func (*MCPServer) AddSessionResourceTemplate

func (s *MCPServer) AddSessionResourceTemplate(sessionID string, template mcp.ResourceTemplate, handler ResourceTemplateHandlerFunc) error

AddSessionResourceTemplate adds a resource template for a specific session

func (*MCPServer) AddSessionResourceTemplates

func (s *MCPServer) AddSessionResourceTemplates(sessionID string, templates ...ServerResourceTemplate) error

AddSessionResourceTemplates adds resource templates for a specific session

func (*MCPServer) AddSessionResources

func (s *MCPServer) AddSessionResources(sessionID string, resources ...ServerResource) error

AddSessionResources adds resources for a specific session

func (*MCPServer) AddSessionTool

func (s *MCPServer) AddSessionTool(sessionID string, tool mcp.Tool, handler ToolHandlerFunc) error

AddSessionTool adds a tool for a specific session

func (*MCPServer) AddSessionTools

func (s *MCPServer) AddSessionTools(sessionID string, tools ...ServerTool) error

AddSessionTools adds tools for a specific session

func (*MCPServer) AddTaskTool

func (s *MCPServer) AddTaskTool(tool mcp.Tool, handler TaskToolHandlerFunc)

AddTaskTool registers a new task tool and its handler

func (*MCPServer) AddTaskTools

func (s *MCPServer) AddTaskTools(taskTools ...ServerTaskTool)

AddTaskTools registers multiple task tools at once

func (*MCPServer) AddTool

func (s *MCPServer) AddTool(tool mcp.Tool, handler ToolHandlerFunc)

AddTool registers a new tool and its handler

func (*MCPServer) AddTools

func (s *MCPServer) AddTools(tools ...ServerTool)

AddTools registers multiple tools at once

func (*MCPServer) DeletePrompts

func (s *MCPServer) DeletePrompts(names ...string)

DeletePrompts removes prompts from the server

func (*MCPServer) DeleteResources

func (s *MCPServer) DeleteResources(uris ...string)

DeleteResources removes resources from the server

func (*MCPServer) DeleteSessionResourceTemplates

func (s *MCPServer) DeleteSessionResourceTemplates(sessionID string, uriTemplates ...string) error

DeleteSessionResourceTemplates removes resource templates from a specific session

func (*MCPServer) DeleteSessionResources

func (s *MCPServer) DeleteSessionResources(sessionID string, uris ...string) error

DeleteSessionResources removes resources from a specific session

func (*MCPServer) DeleteSessionTools

func (s *MCPServer) DeleteSessionTools(sessionID string, names ...string) error

DeleteSessionTools removes tools from a specific session

func (*MCPServer) DeleteTools

func (s *MCPServer) DeleteTools(names ...string)

DeleteTools removes tools from the server

func (*MCPServer) EnableSampling

func (s *MCPServer) EnableSampling()

EnableSampling enables sampling capabilities for the server. This allows the server to send sampling requests to clients that support it.

func (*MCPServer) GenerateInProcessSessionID

func (s *MCPServer) GenerateInProcessSessionID() string

GenerateInProcessSessionID generates a unique session ID for inprocess clients

func (*MCPServer) GetHooks

func (s *MCPServer) GetHooks() *Hooks

GetHooks returns the server's current Hooks instance, or nil if no hooks have been configured. The returned pointer can be used to add additional hooks via the Add* methods without replacing existing hook registrations.

func (*MCPServer) GetTool

func (s *MCPServer) GetTool(toolName string) *ServerTool

GetTool retrieves the specified tool

func (*MCPServer) HandleMessage

func (s *MCPServer) HandleMessage(
	ctx context.Context,
	message json.RawMessage,
) (resp mcp.JSONRPCMessage)

HandleMessage processes an incoming JSON-RPC message and returns an appropriate response

func (*MCPServer) ListPrompts

func (s *MCPServer) ListPrompts() map[string]*ServerPrompt

ListPrompts returns a copy of the registered prompts map.

func (*MCPServer) ListResources

func (s *MCPServer) ListResources() map[string]*ServerResource

ListResources returns a copy of the registered resources map.

func (*MCPServer) ListTools

func (s *MCPServer) ListTools() map[string]*ServerTool

func (*MCPServer) RegisterSession

func (s *MCPServer) RegisterSession(
	ctx context.Context,
	session ClientSession,
) error

RegisterSession saves session that should be notified in case if some server attributes changed.

func (*MCPServer) RemoveResource

func (s *MCPServer) RemoveResource(uri string)

RemoveResource removes a resource from the server

func (*MCPServer) RequestElicitation

func (s *MCPServer) RequestElicitation(ctx context.Context, request mcp.ElicitationRequest) (*mcp.ElicitationResult, error)

RequestElicitation sends an elicitation request to the client. The client must have declared elicitation capability during initialization. The session must implement SessionWithElicitation to support this operation.

func (*MCPServer) RequestRoots

func (s *MCPServer) RequestRoots(ctx context.Context, request mcp.ListRootsRequest) (*mcp.ListRootsResult, error)

RequestRoots sends an list roots request to the client. The client must have declared roots capability during initialization. The session must implement SessionWithRoots to support this operation.

func (*MCPServer) RequestSampling deprecated

func (s *MCPServer) RequestSampling(ctx context.Context, request mcp.CreateMessageRequest) (*mcp.CreateMessageResult, error)

RequestSampling sends a sampling request to the client. The client must have declared sampling capability during initialization.

Protocol version 2026-07-28 removed server-initiated requests (SEP-2322): against a client using that version or later, a handler must instead return an input_required result carrying the request. Use InputRequestBuilder to build one; the same handler still works with older clients, because this package issues the server-initiated request on their behalf.

Deprecated: the Sampling feature is deprecated as of protocol version 2026-07-28 (SEP-2577). Integrate with an LLM provider API directly.

func (*MCPServer) RequestURLElicitation

func (s *MCPServer) RequestURLElicitation(
	ctx context.Context,
	session ClientSession,
	elicitationID string,
	url string,
	message string,
) (*mcp.ElicitationResult, error)

RequestURLElicitation sends a URL mode elicitation request to the client. This is used when the server needs the user to perform an out-of-band interaction.

func (*MCPServer) SendElicitationComplete

func (s *MCPServer) SendElicitationComplete(
	ctx context.Context,
	session ClientSession,
	elicitationID string,
) error

SendElicitationComplete sends a notification that a URL mode elicitation has completed SendElicitationComplete sends a notification that a URL mode elicitation has completed

func (*MCPServer) SendLogMessageToClient

func (s *MCPServer) SendLogMessageToClient(ctx context.Context, notification mcp.LoggingMessageNotification) error

func (*MCPServer) SendLogMessageToSpecificClient

func (s *MCPServer) SendLogMessageToSpecificClient(sessionID string, notification mcp.LoggingMessageNotification) error

func (*MCPServer) SendNotificationToAllClients

func (s *MCPServer) SendNotificationToAllClients(
	method string,
	params map[string]any,
)

SendNotificationToAllClients sends a notification to all the currently active clients.

func (*MCPServer) SendNotificationToClient

func (s *MCPServer) SendNotificationToClient(
	ctx context.Context,
	method string,
	params map[string]any,
) error

SendNotificationToClient sends a notification to the current client

func (*MCPServer) SendNotificationToSpecificClient

func (s *MCPServer) SendNotificationToSpecificClient(
	sessionID string,
	method string,
	params map[string]any,
) error

SendNotificationToSpecificClient sends a notification to a specific client by session ID

func (*MCPServer) SetPrompts

func (s *MCPServer) SetPrompts(prompts ...ServerPrompt)

SetPrompts replaces all existing prompts with the provided list

func (*MCPServer) SetResourceTemplates

func (s *MCPServer) SetResourceTemplates(templates ...ServerResourceTemplate)

SetResourceTemplates replaces all existing resource templates with the provided list

func (*MCPServer) SetResources

func (s *MCPServer) SetResources(resources ...ServerResource)

SetResources replaces all existing resources with the provided list

func (*MCPServer) SetTools

func (s *MCPServer) SetTools(tools ...ServerTool)

SetTools replaces all existing tools with the provided list

func (*MCPServer) UnregisterSession

func (s *MCPServer) UnregisterSession(
	ctx context.Context,
	sessionID string,
)

UnregisterSession removes from storage session that is shut down.

func (*MCPServer) Use

func (s *MCPServer) Use(mw ...ToolHandlerMiddleware)

Use adds one or more tool handler middlewares to the server. Middleware is applied in the order added (outermost first), matching net/http convention.

func (*MCPServer) WithContext

func (s *MCPServer) WithContext(
	ctx context.Context,
	session ClientSession,
) context.Context

WithContext sets the current client session and returns the provided context

type NotificationHandlerFunc

type NotificationHandlerFunc func(ctx context.Context, notification mcp.JSONRPCNotification)

NotificationHandlerFunc handles incoming notifications.

type OnAfterCallToolFunc

type OnAfterCallToolFunc func(ctx context.Context, id any, message *mcp.CallToolRequest, result any)

type OnAfterCancelTaskFunc

type OnAfterCancelTaskFunc func(ctx context.Context, id any, message *mcp.CancelTaskRequest, result *mcp.CancelTaskResult)

type OnAfterCompleteFunc

type OnAfterCompleteFunc func(ctx context.Context, id any, message *mcp.CompleteRequest, result *mcp.CompleteResult)

type OnAfterDiscoverFunc

type OnAfterDiscoverFunc func(ctx context.Context, id any, message *mcp.DiscoverRequest, result *mcp.DiscoverResult)

type OnAfterGetPromptFunc

type OnAfterGetPromptFunc func(ctx context.Context, id any, message *mcp.GetPromptRequest, result *mcp.GetPromptResult)

type OnAfterGetTaskFunc

type OnAfterGetTaskFunc func(ctx context.Context, id any, message *mcp.GetTaskRequest, result *mcp.GetTaskResult)

type OnAfterInitializeFunc

type OnAfterInitializeFunc func(ctx context.Context, id any, message *mcp.InitializeRequest, result *mcp.InitializeResult)

type OnAfterListPromptsFunc

type OnAfterListPromptsFunc func(ctx context.Context, id any, message *mcp.ListPromptsRequest, result *mcp.ListPromptsResult)

type OnAfterListResourceTemplatesFunc

type OnAfterListResourceTemplatesFunc func(ctx context.Context, id any, message *mcp.ListResourceTemplatesRequest, result *mcp.ListResourceTemplatesResult)

type OnAfterListResourcesFunc

type OnAfterListResourcesFunc func(ctx context.Context, id any, message *mcp.ListResourcesRequest, result *mcp.ListResourcesResult)

type OnAfterListTasksFunc

type OnAfterListTasksFunc func(ctx context.Context, id any, message *mcp.ListTasksRequest, result *mcp.ListTasksResult)

type OnAfterListToolsFunc

type OnAfterListToolsFunc func(ctx context.Context, id any, message *mcp.ListToolsRequest, result *mcp.ListToolsResult)

type OnAfterPingFunc

type OnAfterPingFunc func(ctx context.Context, id any, message *mcp.PingRequest, result *mcp.EmptyResult)

type OnAfterReadResourceFunc

type OnAfterReadResourceFunc func(ctx context.Context, id any, message *mcp.ReadResourceRequest, result *mcp.ReadResourceResult)

type OnAfterSetLevelFunc

type OnAfterSetLevelFunc func(ctx context.Context, id any, message *mcp.SetLevelRequest, result *mcp.EmptyResult)

type OnAfterSubscribeFunc

type OnAfterSubscribeFunc func(ctx context.Context, id any, message *mcp.SubscribeRequest, result *mcp.EmptyResult)

type OnAfterSubscriptionsListenFunc

type OnAfterSubscriptionsListenFunc func(ctx context.Context, id any, message *mcp.SubscriptionsListenRequest, result *mcp.SubscriptionsListenResult)

type OnAfterTaskResultFunc

type OnAfterTaskResultFunc func(ctx context.Context, id any, message *mcp.TaskResultRequest, result *mcp.TaskResultResult)

type OnAfterUnsubscribeFunc

type OnAfterUnsubscribeFunc func(ctx context.Context, id any, message *mcp.UnsubscribeRequest, result *mcp.EmptyResult)

type OnBeforeCallToolFunc

type OnBeforeCallToolFunc func(ctx context.Context, id any, message *mcp.CallToolRequest)

type OnBeforeCancelTaskFunc

type OnBeforeCancelTaskFunc func(ctx context.Context, id any, message *mcp.CancelTaskRequest)

type OnBeforeCompleteFunc

type OnBeforeCompleteFunc func(ctx context.Context, id any, message *mcp.CompleteRequest)

type OnBeforeDiscoverFunc

type OnBeforeDiscoverFunc func(ctx context.Context, id any, message *mcp.DiscoverRequest)

type OnBeforeGetPromptFunc

type OnBeforeGetPromptFunc func(ctx context.Context, id any, message *mcp.GetPromptRequest)

type OnBeforeGetTaskFunc

type OnBeforeGetTaskFunc func(ctx context.Context, id any, message *mcp.GetTaskRequest)

type OnBeforeInitializeFunc

type OnBeforeInitializeFunc func(ctx context.Context, id any, message *mcp.InitializeRequest)

type OnBeforeListPromptsFunc

type OnBeforeListPromptsFunc func(ctx context.Context, id any, message *mcp.ListPromptsRequest)

type OnBeforeListResourceTemplatesFunc

type OnBeforeListResourceTemplatesFunc func(ctx context.Context, id any, message *mcp.ListResourceTemplatesRequest)

type OnBeforeListResourcesFunc

type OnBeforeListResourcesFunc func(ctx context.Context, id any, message *mcp.ListResourcesRequest)

type OnBeforeListTasksFunc

type OnBeforeListTasksFunc func(ctx context.Context, id any, message *mcp.ListTasksRequest)

type OnBeforeListToolsFunc

type OnBeforeListToolsFunc func(ctx context.Context, id any, message *mcp.ListToolsRequest)

type OnBeforePingFunc

type OnBeforePingFunc func(ctx context.Context, id any, message *mcp.PingRequest)

type OnBeforeReadResourceFunc

type OnBeforeReadResourceFunc func(ctx context.Context, id any, message *mcp.ReadResourceRequest)

type OnBeforeSetLevelFunc

type OnBeforeSetLevelFunc func(ctx context.Context, id any, message *mcp.SetLevelRequest)

type OnBeforeSubscribeFunc

type OnBeforeSubscribeFunc func(ctx context.Context, id any, message *mcp.SubscribeRequest)

type OnBeforeSubscriptionsListenFunc

type OnBeforeSubscriptionsListenFunc func(ctx context.Context, id any, message *mcp.SubscriptionsListenRequest)

type OnBeforeTaskResultFunc

type OnBeforeTaskResultFunc func(ctx context.Context, id any, message *mcp.TaskResultRequest)

type OnBeforeUnsubscribeFunc

type OnBeforeUnsubscribeFunc func(ctx context.Context, id any, message *mcp.UnsubscribeRequest)

type OnErrorHookFunc

type OnErrorHookFunc func(ctx context.Context, id any, method mcp.MCPMethod, message any, err error)

OnErrorHookFunc is a hook that will be called when an error occurs, either during the request parsing or the method execution.

See the Hooks type-level documentation for the pairing contract between OnBeforeAny, OnSuccess, and OnError, including the cases in which OnError may fire without a prior OnBeforeAny.

Example usage: ```

hooks.AddOnError(func(ctx context.Context, id any, method mcp.MCPMethod, message any, err error) {
  // Check for specific error types using errors.Is
  if errors.Is(err, ErrUnsupported) {
    // Handle capability not supported errors
    log.Printf("Capability not supported: %v", err)
  }

  // Use errors.As to get specific error types
  var parseErr = &UnparsableMessageError{}
  if errors.As(err, &parseErr) {
    // Access specific methods/fields of the error type
    log.Printf("Failed to parse message for method %s: %v",
               parseErr.GetMethod(), parseErr.Unwrap())
    // Access the raw message that failed to parse
    rawMsg := parseErr.GetMessage()
  }

  // Check for specific resource/prompt/tool errors
  switch {
  case errors.Is(err, ErrResourceNotFound):
    log.Printf("Resource not found: %v", err)
  case errors.Is(err, ErrPromptNotFound):
    log.Printf("Prompt not found: %v", err)
  case errors.Is(err, ErrToolNotFound):
    log.Printf("Tool not found: %v", err)
  }
})

type OnRegisterSessionHookFunc

type OnRegisterSessionHookFunc func(ctx context.Context, session ClientSession)

OnRegisterSessionHookFunc is a hook that will be called when a new session is registered.

type OnRequestInitializationFunc

type OnRequestInitializationFunc func(ctx context.Context, id any, message any) error

OnRequestInitializationFunc is a function that called before handle diff request method Should any errors arise during func execution, the service will promptly return the corresponding error message.

type OnSuccessHookFunc

type OnSuccessHookFunc func(ctx context.Context, id any, method mcp.MCPMethod, message any, result any)

OnSuccessHookFunc is a hook that will be called after the request successfully generates a result, but before the result is sent to the client.

See the Hooks type-level documentation for the pairing contract between OnBeforeAny, OnSuccess, and OnError.

type OnTaskCancelledHookFunc

type OnTaskCancelledHookFunc func(ctx context.Context, metrics TaskMetrics)

OnTaskCancelledHookFunc is called when a task is cancelled. Use this to track cancellation metrics or clean up resources.

type OnTaskCompletedHookFunc

type OnTaskCompletedHookFunc func(ctx context.Context, metrics TaskMetrics)

OnTaskCompletedHookFunc is called when a task completes successfully. Use this to track completion metrics, record duration, or trigger follow-up actions.

type OnTaskCreatedHookFunc

type OnTaskCreatedHookFunc func(ctx context.Context, metrics TaskMetrics)

OnTaskCreatedHookFunc is called when a new task is created. Use this to track task creation metrics, initialize monitoring, or log task starts.

type OnTaskFailedHookFunc

type OnTaskFailedHookFunc func(ctx context.Context, metrics TaskMetrics)

OnTaskFailedHookFunc is called when a task fails with an error. Use this to track failure metrics, alert on errors, or log failure details.

type OnTaskStatusChangedHookFunc

type OnTaskStatusChangedHookFunc func(ctx context.Context, metrics TaskMetrics)

OnTaskStatusChangedHookFunc is called whenever a task's status changes. This is a catch-all hook that fires for all status transitions. Use this for general monitoring or when you need to track all state changes.

type OnUnregisterSessionHookFunc

type OnUnregisterSessionHookFunc func(ctx context.Context, session ClientSession)

OnUnregisterSessionHookFunc is a hook that will be called when a session is being unregistered.

type PromptCompletionProvider

type PromptCompletionProvider interface {
	// CompletePromptArgument provides completions for a prompt argument
	CompletePromptArgument(ctx context.Context, promptName string, argument mcp.CompleteArgument, context mcp.CompleteContext) (*mcp.Completion, error)
}

type PromptFilterFunc

type PromptFilterFunc func(ctx context.Context, prompts []mcp.Prompt) []mcp.Prompt

PromptFilterFunc is a function that filters prompts based on context, typically using session information. Filters are applied both when listing prompts (prompts/list) and when retrieving prompts (prompts/get), so a filtered-out prompt cannot be discovered or accessed. During prompts/get, filters receive only the requested prompt to keep the get-time access check off the full-list hot path.

type PromptHandlerFunc

type PromptHandlerFunc func(ctx context.Context, request mcp.GetPromptRequest) (*mcp.GetPromptResult, error)

PromptHandlerFunc handles prompt requests with given arguments.

type PromptHandlerMiddleware

type PromptHandlerMiddleware func(PromptHandlerFunc) PromptHandlerFunc

PromptHandlerMiddleware is a middleware function that wraps a PromptHandlerFunc.

type ProtectedResourceMetadataConfig

type ProtectedResourceMetadataConfig struct {
	// Resource is the protected resource's identifier URI. Required.
	Resource string `json:"resource"`

	// AuthorizationServers lists the OAuth authorization server issuer
	// identifiers that may be used to obtain access tokens for this resource.
	AuthorizationServers []string `json:"authorization_servers,omitempty"`

	// ScopesSupported lists OAuth scope values used in authorization requests
	// to access this resource.
	ScopesSupported []string `json:"scopes_supported,omitempty"`

	// BearerMethodsSupported lists supported methods for presenting an OAuth
	// 2.0 bearer token to the resource (e.g. "header", "body", "query").
	BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`

	// ResourceName is a human-readable name for the protected resource.
	ResourceName string `json:"resource_name,omitempty"`

	// ResourceDocumentation is a URL of human-readable documentation for
	// developers using this resource.
	ResourceDocumentation string `json:"resource_documentation,omitempty"`

	// ResourcePolicyURI is a URL of the resource's privacy policy.
	ResourcePolicyURI string `json:"resource_policy_uri,omitempty"`

	// ResourceTosURI is a URL of the resource's terms of service.
	ResourceTosURI string `json:"resource_tos_uri,omitempty"`

	// JWKSURI is the URL of the resource's JWK Set document used to validate
	// signed responses from the resource.
	JWKSURI string `json:"jwks_uri,omitempty"`

	// ResourceSigningAlgValuesSupported lists JWS algorithms supported for
	// signing resource responses.
	ResourceSigningAlgValuesSupported []string `json:"resource_signing_alg_values_supported,omitempty"`

	// TLSClientCertificateBoundAccessTokens indicates support for mTLS-bound
	// access tokens (RFC 8705). Pointer so that "false" can be expressed
	// explicitly and "unset" omits the field.
	TLSClientCertificateBoundAccessTokens *bool `json:"tls_client_certificate_bound_access_tokens,omitempty"`

	// AuthorizationDetailsTypesSupported lists supported authorization_details
	// type values (RFC 9396).
	AuthorizationDetailsTypesSupported []string `json:"authorization_details_types_supported,omitempty"`

	// DPoPSigningAlgValuesSupported lists JWS algorithms supported for DPoP
	// proof JWTs.
	DPoPSigningAlgValuesSupported []string `json:"dpop_signing_alg_values_supported,omitempty"`

	// DPoPBoundAccessTokensRequired indicates whether DPoP-bound tokens are
	// required by this resource. Pointer so "false" can be encoded explicitly.
	DPoPBoundAccessTokensRequired *bool `json:"dpop_bound_access_tokens_required,omitempty"`
}

ProtectedResourceMetadataConfig holds OAuth 2.0 Protected Resource Metadata as defined in RFC 9728 (https://datatracker.ietf.org/doc/html/rfc9728).

The MCP authorization spec (https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization) references this metadata for server discovery: clients fetch it from /.well-known/oauth-protected-resource to learn which authorization servers, scopes, and bearer methods the resource supports.

Resource is REQUIRED. AuthorizationServers is RECOMMENDED. All other fields are optional and will be omitted from the JSON response when empty.

type ProtocolVersionSupporter

type ProtocolVersionSupporter interface {
	// SupportsProtocolVersion reports whether the transport can serve the
	// given protocol version.
	SupportsProtocolVersion(version string) bool
}

ProtocolVersionSupporter is implemented by transports that cannot serve every protocol version this SDK knows about.

The stateless protocol core introduced in 2026-07-28 cannot be served over a session-oriented transport, so a stateful Streamable HTTP server reports only the legacy versions. Clients learn the restriction from server/discover and can explicitly select a supported legacy version for the initialize handshake.

type RequestProtocolInfo

type RequestProtocolInfo struct {
	// Modern reports whether the request declared a protocol version of
	// 2026-07-28 or later in its _meta.
	Modern bool

	// ProtocolVersion is the version declared in _meta. It is empty for legacy
	// requests, whose version was fixed by the initialize handshake.
	ProtocolVersion string

	// ClientInfo identifies the client software, when it chose to say.
	ClientInfo *mcp.Implementation

	// ClientCapabilities are the capabilities the client declared for this
	// request. Servers MUST NOT infer capabilities from prior requests.
	ClientCapabilities *mcp.ClientCapabilities

	// LogLevel is the log level requested for this request. When empty, the
	// server MUST NOT emit notifications/message for the request.
	LogLevel mcp.LoggingLevel
}

RequestProtocolInfo describes the protocol era and per-request metadata of an incoming request.

Protocol version 2026-07-28 removed the initialize handshake: every request carries its own protocol version, client identity, client capabilities, and desired log level in _meta (SEP-2575). This type normalizes that information so the rest of the server can treat both eras uniformly.

func RequestProtocolInfoFromContext

func RequestProtocolInfoFromContext(ctx context.Context) *RequestProtocolInfo

RequestProtocolInfoFromContext returns the per-request protocol information stored in ctx, or nil when the request did not carry any (that is, when it used a protocol version earlier than 2026-07-28).

type ResourceCompletionProvider

type ResourceCompletionProvider interface {
	// CompleteResourceArgument provides completions for a resource template argument
	CompleteResourceArgument(ctx context.Context, uri string, argument mcp.CompleteArgument, context mcp.CompleteContext) (*mcp.Completion, error)
}

type ResourceHandlerFunc

type ResourceHandlerFunc func(ctx context.Context, request mcp.ReadResourceRequest) ([]mcp.ResourceContents, error)

ResourceHandlerFunc is a function that returns resource contents.

type ResourceHandlerMiddleware

type ResourceHandlerMiddleware func(ResourceHandlerFunc) ResourceHandlerFunc

ResourceHandlerMiddleware is a middleware function that wraps a ResourceHandlerFunc.

type ResourceTemplateHandlerFunc

type ResourceTemplateHandlerFunc func(ctx context.Context, request mcp.ReadResourceRequest) ([]mcp.ResourceContents, error)

ResourceTemplateHandlerFunc is a function that returns a resource template.

type RootsHandler

type RootsHandler interface {
	ListRoots(ctx context.Context, request mcp.ListRootsRequest) (*mcp.ListRootsResult, error)
}

RootsHandler defines the interface for handling roots list requests from servers.

type SSEContextFunc

type SSEContextFunc func(ctx context.Context, r *http.Request) context.Context

SSEContextFunc is a function that takes an existing context and the current request and returns a potentially modified context based on the request content. This can be used to inject context values from headers, for example.

type SSEOption

type SSEOption func(*SSEServer)

SSEOption defines a function type for configuring SSEServer

func WithAppendQueryToMessageEndpoint

func WithAppendQueryToMessageEndpoint() SSEOption

WithAppendQueryToMessageEndpoint configures the SSE server to append the original request's query parameters to the message endpoint URL that is sent to clients during the SSE connection initialization. This is useful when you need to preserve query parameters from the initial SSE connection request and carry them over to subsequent message requests, maintaining context or authentication details across the communication channel.

func WithBasePath deprecated

func WithBasePath(basePath string) SSEOption

WithBasePath adds a new option for setting a static base path.

Deprecated: Use WithStaticBasePath instead. This will be removed in a future version.

func WithBaseURL

func WithBaseURL(baseURL string) SSEOption

WithBaseURL sets the base URL for the SSE server

func WithDynamicBasePath

func WithDynamicBasePath(fn DynamicBasePathFunc) SSEOption

WithDynamicBasePath accepts a function for generating the base path. This is useful for cases where the base path is not known at the time of SSE server creation, such as when using a reverse proxy or when the server is mounted at a dynamic path.

func WithHTTPServer

func WithHTTPServer(srv *http.Server) SSEOption

WithHTTPServer sets the HTTP server instance. NOTE: When providing a custom HTTP server, you must handle routing yourself If routing is not set up, the server will start but won't handle any MCP requests.

func WithKeepAlive

func WithKeepAlive(keepAlive bool) SSEOption

func WithKeepAliveInterval

func WithKeepAliveInterval(keepAliveInterval time.Duration) SSEOption

func WithMessageEndpoint

func WithMessageEndpoint(endpoint string) SSEOption

WithMessageEndpoint sets the message endpoint path

func WithSSECORS

func WithSSECORS(opts ...CORSOption) SSEOption

WithSSECORS configures Cross-Origin Resource Sharing for the SSE server.

CORS handling is opt-in: callers must specify at least one allowed origin via WithCORSAllowedOrigins for any Access-Control-* headers to be emitted. When enabled, preflight (OPTIONS) requests are handled directly by the server and simple cross-origin responses get the appropriate Allow-Origin, Allow-Credentials, Expose-Headers and Vary headers attached.

Example:

srv := server.NewSSEServer(mcpServer,
    server.WithSSECORS(
        server.WithCORSAllowedOrigins("https://example.com"),
        server.WithCORSAllowCredentials(),
    ),
)

func WithSSEContextFunc

func WithSSEContextFunc(fn SSEContextFunc) SSEOption

WithSSEContextFunc sets a function that will be called to customise the context to the server using the incoming request.

func WithSSEDisableLocalhostProtection

func WithSSEDisableLocalhostProtection(disable bool) SSEOption

WithSSEDisableLocalhostProtection disables the automatic DNS rebinding protection of the SSE server.

By default, requests arriving over a loopback connection (127.0.0.1, [::1]) whose Host header is not a localhost value are rejected with 403 Forbidden. This protects local MCP servers against DNS rebinding attacks, where a malicious website rebinds its own domain to 127.0.0.1 to make a victim's browser issue requests against a local server. The protection applies regardless of whether the server listens on localhost specifically or on 0.0.0.0, and never affects requests arriving via non-loopback addresses.

Disable it only if you understand the security implications, for example when a reverse proxy on the same host forwards requests via localhost while preserving the original Host header. In that case, prefer configuring the proxy to rewrite the Host header to localhost instead.

See https://modelcontextprotocol.io/specification/2025-11-25/basic/security_best_practices#local-mcp-server-compromise

func WithSSEEndpoint

func WithSSEEndpoint(endpoint string) SSEOption

WithSSEEndpoint sets the SSE endpoint path

func WithSSEProtectedResourceMetadata

func WithSSEProtectedResourceMetadata(config ProtectedResourceMetadataConfig) SSEOption

WithSSEProtectedResourceMetadata configures the SSEServer to serve OAuth 2.0 Protected Resource Metadata (RFC 9728) at the well-known endpoint derived from the configured Resource (see ProtectedResourceMetadataPath).

The metadata is served both when the server is started via Start (the well-known path is dispatched from ServeHTTP) and when the server is used directly as an http.Handler. When using WithHTTPServer with a custom http.Server whose Handler is not the SSEServer itself, mount the metadata endpoint manually via NewProtectedResourceMetadataHandler.

func WithSessionIDGenerator

func WithSessionIDGenerator(fn SessionIDGenFunc) SSEOption

WithSessionIDGenerator sets a custom session ID generator. If fn == nil the call is ignored.

func WithStaticBasePath

func WithStaticBasePath(basePath string) SSEOption

WithStaticBasePath adds a new option for setting a static base path

func WithUseFullURLForMessageEndpoint

func WithUseFullURLForMessageEndpoint(useFullURLForMessageEndpoint bool) SSEOption

WithUseFullURLForMessageEndpoint controls whether the SSE server returns a complete URL (including baseURL) or just the path portion for the message endpoint. Set to false when clients will concatenate the baseURL themselves to avoid malformed URLs like "http://localhost/mcphttp://localhost/mcp/message".

type SSEServer

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

SSEServer implements a Server-Sent Events (SSE) based MCP server. It provides real-time communication capabilities over HTTP using the SSE protocol.

func NewSSEServer

func NewSSEServer(server *MCPServer, opts ...SSEOption) *SSEServer

NewSSEServer creates a new SSE server instance with the given MCP server and options.

func (*SSEServer) CloseSessions

func (s *SSEServer) CloseSessions()

CloseSessions terminates all active SSE sessions without stopping the HTTP server. This is useful when the SSE server is embedded within another HTTP service and you need to disconnect all clients independently of the server lifecycle (e.g., during a configuration reload or maintenance window). This signals termination; in-flight handlers exit asynchronously. Sessions connecting concurrently with this call may not be terminated.

func (*SSEServer) CompleteMessageEndpoint

func (s *SSEServer) CompleteMessageEndpoint() (string, error)

func (*SSEServer) CompleteMessagePath

func (s *SSEServer) CompleteMessagePath() string

func (*SSEServer) CompleteSseEndpoint

func (s *SSEServer) CompleteSseEndpoint() (string, error)

func (*SSEServer) CompleteSsePath

func (s *SSEServer) CompleteSsePath() string

func (*SSEServer) GetMessageEndpointForClient

func (s *SSEServer) GetMessageEndpointForClient(r *http.Request, sessionID string) string

GetMessageEndpointForClient returns the appropriate message endpoint URL with session ID for the given request. This is the canonical way to compute the message endpoint for a client. It handles both dynamic and static path modes, and honors the WithUseFullURLForMessageEndpoint flag.

func (*SSEServer) GetUrlPath

func (s *SSEServer) GetUrlPath(input string) (string, error)

func (*SSEServer) MessageHandler

func (s *SSEServer) MessageHandler() http.Handler

MessageHandler returns an http.Handler for the message endpoint.

This method allows you to mount the message handler at any arbitrary path using your own router (e.g. net/http, gorilla/mux, chi, etc.). It is intended for advanced scenarios where you want to control the routing or support dynamic segments.

IMPORTANT: When using this handler in advanced/dynamic mounting scenarios, you must use the WithDynamicBasePath option to ensure the correct base path is communicated to clients.

Example usage:

// Advanced/dynamic:
sseServer := NewSSEServer(mcpServer,
	WithDynamicBasePath(func(r *http.Request, sessionID string) string {
		tenant := r.PathValue("tenant")
		return "/mcp/" + tenant
	}),
	WithBaseURL("http://localhost:8080")
)
mux.Handle("/mcp/{tenant}/sse", sseServer.SSEHandler())
mux.Handle("/mcp/{tenant}/message", sseServer.MessageHandler())

For non-dynamic cases, use ServeHTTP method instead.

func (*SSEServer) SSEHandler

func (s *SSEServer) SSEHandler() http.Handler

SSEHandler returns an http.Handler for the SSE endpoint.

When CORS has been configured via WithSSECORS, the returned handler transparently handles preflight requests and applies the appropriate Access-Control-* headers to simple responses.

This method allows you to mount the SSE handler at any arbitrary path using your own router (e.g. net/http, gorilla/mux, chi, etc.). It is intended for advanced scenarios where you want to control the routing or support dynamic segments.

IMPORTANT: When using this handler in advanced/dynamic mounting scenarios, you must use the WithDynamicBasePath option to ensure the correct base path is communicated to clients.

Example usage:

// Advanced/dynamic:
sseServer := NewSSEServer(mcpServer,
	WithDynamicBasePath(func(r *http.Request, sessionID string) string {
		tenant := r.PathValue("tenant")
		return "/mcp/" + tenant
	}),
	WithBaseURL("http://localhost:8080")
)
mux.Handle("/mcp/{tenant}/sse", sseServer.SSEHandler())
mux.Handle("/mcp/{tenant}/message", sseServer.MessageHandler())

For non-dynamic cases, use ServeHTTP method instead.

func (*SSEServer) SendEventToSession

func (s *SSEServer) SendEventToSession(
	sessionID string,
	event any,
) error

SendEventToSession sends an event to a specific SSE session identified by sessionID. Returns an error if the session is not found or closed.

func (*SSEServer) ServeHTTP

func (s *SSEServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface.

When CORS is configured via WithSSECORS, preflight (OPTIONS) requests are answered directly and simple cross-origin responses are decorated with the configured Access-Control-* headers before being dispatched to the SSE or message handlers.

Requests arriving over a loopback connection with a non-localhost Host header are rejected with 403 Forbidden to protect against DNS rebinding attacks, unless WithSSEDisableLocalhostProtection is set.

func (*SSEServer) Shutdown

func (s *SSEServer) Shutdown(ctx context.Context) error

Shutdown gracefully stops the SSE server, closing all active sessions and shutting down the HTTP server.

func (*SSEServer) Start

func (s *SSEServer) Start(addr string) error

Start begins serving SSE connections on the specified address. It sets up HTTP handlers for SSE and message endpoints.

type SamplingHandler

type SamplingHandler interface {
	CreateMessage(ctx context.Context, request mcp.CreateMessageRequest) (*mcp.CreateMessageResult, error)
}

SamplingHandler defines the interface for handling sampling requests from servers.

func InProcessSamplingHandlerFromContext

func InProcessSamplingHandlerFromContext(ctx context.Context) SamplingHandler

InProcessSamplingHandlerFromContext retrieves the inprocess sampling handler from context

type ServerOption

type ServerOption func(*MCPServer)

ServerOption is a function that configures an MCPServer.

func WithCacheHints

func WithCacheHints(ttlMs int64, scope mcp.CacheScope) ServerOption

WithCacheHints sets the default SEP-2549 caching hints advertised on tools/list, prompts/list, resources/list, resources/templates/list, resources/read, and server/discover results.

ttlMs is a freshness hint in milliseconds: clients may reuse a cached response for that long before re-fetching. Zero, the default, asks clients to revalidate every time. scope controls whether shared intermediaries may cache the response across authorization contexts.

The hints are only emitted to clients using protocol version 2026-07-28 or later, which is where the fields were introduced.

func WithCompletions

func WithCompletions() ServerOption

WithCompletions enables the completion capability

func WithDescription

func WithDescription(description string) ServerOption

WithDescription sets the description for the server implementation.

func WithElicitation

func WithElicitation() ServerOption

WithElicitation enables elicitation capabilities for the server

func WithExperimental

func WithExperimental(experimental map[string]any) ServerOption

WithExperimental sets experimental, non-standard capabilities on the server.

func WithExtensions

func WithExtensions(extensions map[string]any) ServerOption

WithExtensions advertises support for optional MCP extensions beyond the core protocol, as a map of extension identifier to that extension's settings object. An empty object means the extension is supported with no additional settings.

Extension identifiers follow the _meta key naming rules, so they carry a mandatory prefix - for example "io.modelcontextprotocol/tasks" for the Tasks extension, or "io.modelcontextprotocol/ui" for MCP Apps.

Extensions were formalized in protocol version 2026-07-28. When one party supports an extension and the other does not, the supporting party must either fall back to core protocol behaviour or reject the request.

func WithHooks

func WithHooks(hooks *Hooks) ServerOption

WithHooks allows adding hooks that will be called before or after either [all] requests or before / after specific request methods, or else prior to returning an error to the client.

func WithIcons

func WithIcons(icons ...mcp.Icon) ServerOption

WithIcons sets the server icons for the implementation metadata returned during initialization. The icons slice and nested Sizes fields are defensively copied to prevent external mutation.

func WithInputSchemaValidation

func WithInputSchemaValidation() ServerOption

WithInputSchemaValidation enables server-side validation of tool call arguments against each tool's declared inputSchema. When validation fails the server returns a tool execution error result (CallToolResult with IsError: true) per SEP-1303 so that the language model receives the failure details in its context window and can self-correct (for example, when it sends an unknown parameter name).

Validation is opt-in to preserve backwards compatibility with servers whose hand-written schemas may not perfectly describe the arguments their handlers actually accept. Enabling it is recommended for new servers and for any server whose schemas are accurate.

Tools whose input schemas cannot be compiled (malformed JSON Schema) are silently skipped, so a single broken schema cannot block tool calls.

func WithInstructions

func WithInstructions(instructions string) ServerOption

WithInstructions sets the server instructions for the client returned in the initialize response

func WithLegacyServerInitiatedRequests deprecated

func WithLegacyServerInitiatedRequests() ServerOption

WithLegacyServerInitiatedRequests keeps MCPServer.RequestSampling, MCPServer.RequestElicitation, and MCPServer.RequestRoots usable against clients speaking protocol version 2026-07-28 or later.

That revision replaced server-initiated requests with multi round-trip requests (SEP-2322), so by default those methods return ErrServerInitiatedRequestUnsupported rather than sending a request the client is not obliged to answer. Enabling this option restores the old behaviour, which still works over genuinely bidirectional transports such as stdio and in-process, but not over stateless Streamable HTTP.

Deprecated: server-initiated requests were removed in protocol version 2026-07-28 (SEP-2322). Prefer InputRequestBuilder, which produces handlers that work against clients of either protocol era. This option exists to ease migration and will be removed once the deprecation window closes.

func WithLogger

func WithLogger(logger *slog.Logger) ServerOption

WithLogger installs a structured logger on the server. The server emits:

  • One mcp.request line per dispatched JSON-RPC method, at level INFO, with attributes mcp.method, mcp.session.id (when set), mcp.protocol.version (from the Mcp-Protocol-Version header), duration_s, outcome (ok|error), and error (when set).
  • One mcp.tool line per tool handler invocation, at level INFO, with attributes mcp.tool.name, duration_s, outcome (ok|error|error_result), and error (when set).

A nil logger is treated as a no-op (no lines are emitted).

The provided slog.Handler is invoked with the request's context.Context, so handlers that read trace context (e.g. the OpenTelemetry slog bridge at go.opentelemetry.io/contrib/bridges/otelslog) automatically annotate records with the active span's TraceID/SpanID when a Tracer is also installed via WithTracer.

func WithLogging

func WithLogging() ServerOption

WithLogging enables logging capabilities for the server

func WithMaxConcurrentTasks

func WithMaxConcurrentTasks(limit int) ServerOption

WithMaxConcurrentTasks sets a limit on the maximum number of concurrent running tasks. When this limit is reached, attempts to create new tasks will fail with an error. If not set (or set to 0), there is no limit on concurrent tasks.

func WithMetaPropagator

func WithMetaPropagator(p tracing.MetaPropagator) ServerOption

WithMetaPropagator installs a propagator that extracts trace context from the MCP _meta property bag of inbound requests (per SEP-414). It covers all transports including stdio, where HTTP headers are unavailable. A nil propagator is treated as a no-op.

func WithMethodCacheHints

func WithMethodCacheHints(method mcp.MCPMethod, ttlMs int64, scope mcp.CacheScope) ServerOption

WithMethodCacheHints sets the SEP-2549 caching hints advertised on the result of a single method, overriding any default set by WithCacheHints.

func WithOutputSchemaValidation

func WithOutputSchemaValidation() ServerOption

WithOutputSchemaValidation enables server-side validation of tool call results against each tool's declared outputSchema. When a tool returns a CallToolResult whose StructuredContent does not conform to the schema, the server replaces the result with a tool execution error (CallToolResult with IsError: true) so the client never sees a result that violates the declared contract.

The MCP tools specification states that when an outputSchema is provided, the tool result MUST include structuredContent conforming to that schema. Enabling this option enforces that contract at runtime.

Validation is skipped for results whose StructuredContent is nil and for error results (IsError: true). Tools whose output schemas cannot be compiled (malformed JSON Schema) are silently skipped, matching the behaviour of WithInputSchemaValidation, so a single broken schema cannot block tool calls.

This option is opt-in to preserve backwards compatibility with servers whose hand-written output schemas may not perfectly describe the values their handlers actually return. Enabling it is recommended for any server whose schemas are accurate.

func WithPaginationLimit

func WithPaginationLimit(limit int) ServerOption

WithPaginationLimit sets the maximum page size for list results. Zero and negative limits leave the list unpaged.

func WithPromptCapabilities

func WithPromptCapabilities(listChanged bool) ServerOption

WithPromptCapabilities configures prompt-related server capabilities

func WithPromptCompletionProvider

func WithPromptCompletionProvider(provider PromptCompletionProvider) ServerOption

WithPromptCompletionProvider sets a custom prompt completion provider

func WithPromptFilter

func WithPromptFilter(
	promptFilter PromptFilterFunc,
) ServerOption

WithPromptFilter adds a filter function that controls prompt visibility and access. The filter is applied both when listing prompts (prompts/list) and when retrieving a prompt (prompts/get). A prompt that is filtered out cannot be discovered or accessed. Get-time checks pass only the requested prompt to the filter, while list-time checks pass the full candidate list.

func WithPromptHandlerMiddleware

func WithPromptHandlerMiddleware(
	promptHandlerMiddleware PromptHandlerMiddleware,
) ServerOption

WithPromptHandlerMiddleware allows adding a middleware for the prompt handler call chain.

func WithPropagator

func WithPropagator(p tracing.Propagator) ServerOption

WithPropagator installs a propagator that extracts trace context from inbound request headers. A nil propagator is treated as a no-op.

func WithRecovery

func WithRecovery() ServerOption

WithRecovery adds a middleware that recovers from panics in tool handlers.

func WithResourceCapabilities

func WithResourceCapabilities(subscribe, listChanged bool) ServerOption

WithResourceCapabilities configures resource-related server capabilities

func WithResourceCompletionProvider

func WithResourceCompletionProvider(provider ResourceCompletionProvider) ServerOption

WithResourceCompletionProvider sets a custom resource completion provider

func WithResourceHandlerMiddleware

func WithResourceHandlerMiddleware(
	resourceHandlerMiddleware ResourceHandlerMiddleware,
) ServerOption

WithResourceHandlerMiddleware allows adding a middleware for the resource handler call chain.

func WithResourceRecovery

func WithResourceRecovery() ServerOption

WithResourceRecovery adds a middleware that recovers from panics in resource handlers.

func WithRoots

func WithRoots() ServerOption

WithRoots returns a ServerOption that enables the roots capability on the MCPServer

func WithStrictInputSchemaDefault

func WithStrictInputSchemaDefault() ServerOption

WithStrictInputSchemaDefault sets additionalProperties:false on every registered tool's input schema when the tool author has not configured the field explicitly. Tools published by such a server reject unknown property names — at the client (which sees the strict schema in tools/list) and at the server when WithInputSchemaValidation is also enabled.

Tools that supply mcp.Tool.RawInputSchema are not modified: those authors have opted out of the structured-schema helpers and own additionalProperties themselves. Tools that explicitly call mcp.WithSchemaAdditionalProperties are left untouched, so a single tool can opt back into permissive behaviour while the server default stays strict.

The option is independent of WithInputSchemaValidation: setting strict schemas without server-side enforcement still steers schema-aware clients and language models away from unknown arguments.

func WithTaskCapabilities

func WithTaskCapabilities(list, cancel, toolCallTasks bool) ServerOption

WithTaskCapabilities configures task-related server capabilities

func WithTaskHooks

func WithTaskHooks(taskHooks *TaskHooks) ServerOption

WithTaskHooks allows adding hooks for task lifecycle events. Use these hooks to monitor task execution, track metrics, and observe task-augmented tool behavior.

func WithTitle

func WithTitle(title string) ServerOption

WithTitle sets the human-readable display title for the server implementation.

func WithToolCapabilities

func WithToolCapabilities(listChanged bool) ServerOption

WithToolCapabilities configures tool-related server capabilities

func WithToolFilter

func WithToolFilter(
	toolFilter ToolFilterFunc,
) ServerOption

WithToolFilter adds a filter function that controls tool visibility and access. The filter is applied both when listing tools (tools/list) and when calling tools (tools/call). A tool that is filtered out cannot be discovered or invoked, ensuring that filters act as an access control boundary rather than just a visibility hint. Call-time checks pass only the requested tool to the filter, while list-time checks pass the full candidate list.

func WithToolHandlerMiddleware

func WithToolHandlerMiddleware(
	toolHandlerMiddleware ToolHandlerMiddleware,
) ServerOption

WithToolHandlerMiddleware allows adding a middleware for the tool handler call chain.

func WithToolResultSizeLimit

func WithToolResultSizeLimit(maxBytes int) ServerOption

WithToolResultSizeLimit replaces a tool result whose JSON encoding is larger than maxBytes with an error result. The oversized payload is not sent. The same check runs for a synchronous call and for both task execution paths, before the result is stored. Zero and negative limits disable the check.

func WithTracer

func WithTracer(tracer tracing.Tracer) ServerOption

WithTracer installs a tracer on the server. Spans:

  • mcp.<method> (server) around every dispatched JSON-RPC method
  • tool.<name> (internal) around every tool handler invocation

Span attributes: mcp.method, mcp.tool.name (tools/call), mcp.session.id (when set), mcp.protocol.version (from the Mcp-Protocol-Version header).

For end-to-end propagation install a Propagator with WithPropagator as well. Tool-handler panics surface in span status only when paired with WithRecovery. A nil tracer is treated as a no-op.

func WithWebsiteURL

func WithWebsiteURL(websiteURL string) ServerOption

WithWebsiteURL sets the website URL for the server implementation.

type ServerPrompt

type ServerPrompt struct {
	Prompt  mcp.Prompt
	Handler PromptHandlerFunc
}

ServerPrompt combines a Prompt with its handler function.

type ServerResource

type ServerResource struct {
	Resource mcp.Resource
	Handler  ResourceHandlerFunc
}

ServerResource combines a Resource with its handler function.

type ServerResourceTemplate

type ServerResourceTemplate struct {
	Template mcp.ResourceTemplate
	Handler  ResourceTemplateHandlerFunc
}

ServerResourceTemplate combines a ResourceTemplate with its handler function.

type ServerTaskTool

type ServerTaskTool struct {
	Tool    mcp.Tool
	Handler TaskToolHandlerFunc
}

ServerTaskTool combines a Tool with its TaskToolHandlerFunc.

type ServerTool

type ServerTool struct {
	Tool    mcp.Tool
	Handler ToolHandlerFunc
}

ServerTool combines a Tool with its ToolHandlerFunc.

type SessionIDGenFunc

type SessionIDGenFunc func(ctx context.Context, r *http.Request) (string, error)

SessionIDGenFunc is a function that produces a session ID for a new SSE connection. It receives the request context and the HTTP request, and should return a session identifier (string) or an error.

type SessionIdManager

type SessionIdManager interface {
	Generate() string
	// Validate checks if a session ID is valid and not terminated.
	// Returns isTerminated=true if the ID is valid but belongs to a terminated session.
	// Returns err!=nil if the ID format is invalid or lookup failed.
	Validate(sessionID string) (isTerminated bool, err error)
	// Terminate marks a session ID as terminated.
	// Returns isNotAllowed=true if the server policy prevents client termination.
	// Returns err!=nil if the ID is invalid or termination failed.
	Terminate(sessionID string) (isNotAllowed bool, err error)
}

type SessionIdManagerResolver

type SessionIdManagerResolver interface {
	ResolveSessionIdManager(r *http.Request) SessionIdManager
}

SessionIdManagerResolver resolves a SessionIdManager based on the HTTP request. Implementations must handle a nil r, which may be passed from non-request contexts such as the session idle TTL sweeper.

type SessionWithClientInfo

type SessionWithClientInfo interface {
	ClientSession
	// GetClientInfo returns the client information for this session
	GetClientInfo() mcp.Implementation
	// SetClientInfo sets the client information for this session
	SetClientInfo(clientInfo mcp.Implementation)
	// GetClientCapabilities returns the client capabilities for this session
	GetClientCapabilities() mcp.ClientCapabilities
	// SetClientCapabilities sets the client capabilities for this session
	SetClientCapabilities(clientCapabilities mcp.ClientCapabilities)
}

SessionWithClientInfo is an extension of ClientSession that can store client info

type SessionWithElicitation

type SessionWithElicitation interface {
	ClientSession
	// RequestElicitation sends an elicitation request to the client and waits for response
	RequestElicitation(ctx context.Context, request mcp.ElicitationRequest) (*mcp.ElicitationResult, error)
}

SessionWithElicitation is an extension of ClientSession that can send elicitation requests

type SessionWithLogging

type SessionWithLogging interface {
	ClientSession
	// SetLogLevel sets the minimum log level
	SetLogLevel(level mcp.LoggingLevel)
	// GetLogLevel retrieves the minimum log level
	GetLogLevel() mcp.LoggingLevel
}

SessionWithLogging is an extension of ClientSession that can receive log message notifications and set log level

type SessionWithProtocolVersion

type SessionWithProtocolVersion interface {
	ClientSession
	// ProtocolVersion returns the negotiated protocol version, or "" when the
	// session has not been initialized.
	ProtocolVersion() string
}

SessionWithProtocolVersion is implemented by sessions that remember the protocol version negotiated during initialize.

type SessionWithResourceSubscriptions

type SessionWithResourceSubscriptions interface {
	ClientSession
	// SubscribeToResource records that this session has subscribed to updates
	// for the given resource URI. Subscribing the same URI twice is a no-op.
	SubscribeToResource(uri string)
	// UnsubscribeFromResource removes a previously recorded subscription for
	// the given resource URI. Unsubscribing a URI that was never subscribed
	// to is a no-op.
	UnsubscribeFromResource(uri string)
	// SubscribedResources returns a snapshot of the URIs this session is
	// currently subscribed to. The returned slice is owned by the caller and
	// safe to mutate.
	SubscribedResources() []string
	// IsSubscribedToResource reports whether the session is currently
	// subscribed to updates for the given resource URI.
	IsSubscribedToResource(uri string) bool
}

SessionWithResourceSubscriptions is an optional extension of ClientSession implemented by sessions that track resources/subscribe state. When the default subscribe/unsubscribe handlers in MCPServer service a request, they will invoke SubscribeToResource or UnsubscribeFromResource on the active session if it implements this interface, allowing servers to later target notifications/resources/updated only at sessions that asked for updates.

Implementations must be safe for concurrent use because requests and notifications may run on independent goroutines.

type SessionWithResourceSubscriptionsErr

type SessionWithResourceSubscriptionsErr interface {
	SessionWithResourceSubscriptions
	// SubscribeToResourceErr records that this session has subscribed to updates
	// for the given resource URI, or returns an error if the URI cannot be
	// subscribed to.
	SubscribeToResourceErr(uri string) error
}

SessionWithResourceSubscriptionsErr is an optional extension of SessionWithResourceSubscriptions whose SubscribeToResourceErr method can reject a subscription. When a session implements this interface, MCPServer uses SubscribeToResourceErr in preference to SubscribeToResource and returns RESOURCE_NOT_FOUND if it reports an error.

Implementations must be safe for concurrent use because requests and notifications may run on independent goroutines.

type SessionWithResourceTemplates

type SessionWithResourceTemplates interface {
	ClientSession
	// GetSessionResourceTemplates returns the resource templates specific to this session, if any
	// This method must be thread-safe for concurrent access
	GetSessionResourceTemplates() map[string]ServerResourceTemplate
	// SetSessionResourceTemplates sets resource templates specific to this session
	// This method must be thread-safe for concurrent access
	SetSessionResourceTemplates(templates map[string]ServerResourceTemplate)
}

SessionWithResourceTemplates is an extension of ClientSession that can store session-specific resource template data

type SessionWithResources

type SessionWithResources interface {
	ClientSession
	// GetSessionResources returns the resources specific to this session, if any
	// This method must be thread-safe for concurrent access
	GetSessionResources() map[string]ServerResource
	// SetSessionResources sets resources specific to this session
	// This method must be thread-safe for concurrent access
	SetSessionResources(resources map[string]ServerResource)
}

SessionWithResources is an extension of ClientSession that can store session-specific resource data

type SessionWithRoots

type SessionWithRoots interface {
	ClientSession
	// ListRoots sends an list roots request to the client and waits for response
	ListRoots(ctx context.Context, request mcp.ListRootsRequest) (*mcp.ListRootsResult, error)
}

SessionWithRoots is an extension of ClientSession that can send list roots requests

type SessionWithSampling

type SessionWithSampling interface {
	ClientSession
	RequestSampling(ctx context.Context, request mcp.CreateMessageRequest) (*mcp.CreateMessageResult, error)
}

SessionWithSampling extends ClientSession to support sampling requests.

type SessionWithStreamableHTTPConfig

type SessionWithStreamableHTTPConfig interface {
	ClientSession
	// UpgradeToSSEWhenReceiveNotification upgrades the client-server communication to SSE stream when the server
	// sends notifications to the client
	//
	// The protocol specification:
	// - If the server response contains any JSON-RPC notifications, it MUST either:
	//   - Return Content-Type: text/event-stream to initiate an SSE stream, OR
	//   - Return Content-Type: application/json for a single JSON object
	// - The client MUST support both response types.
	//
	// Reference: https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#sending-messages-to-the-server
	UpgradeToSSEWhenReceiveNotification()
}

SessionWithStreamableHTTPConfig extends ClientSession to support streamable HTTP transport configurations

type SessionWithSubscriptionFilter

type SessionWithSubscriptionFilter interface {
	ClientSession
	// SetSubscriptionFilter records the notification types the client opted
	// in to. Passing the zero filter clears the subscription.
	SetSubscriptionFilter(filter mcp.SubscriptionFilter)
	// SubscriptionFilter returns the notification types the client opted in
	// to, and whether a subscription is currently active.
	SubscriptionFilter() (mcp.SubscriptionFilter, bool)
}

SessionWithSubscriptionFilter is implemented by sessions that can record which notification types a client opted in to through subscriptions/listen.

Protocol version 2026-07-28 makes every server-to-client notification opt-in: a server MUST NOT deliver a notification type the client did not explicitly request (SEP-2575).

Implementations must be safe for concurrent use: the filter is written by the goroutine serving the subscriptions/listen request and read by the notification fan-out running on independent goroutines.

type SessionWithTools

type SessionWithTools interface {
	ClientSession
	// GetSessionTools returns the tools specific to this session, if any
	// This method must be thread-safe for concurrent access
	GetSessionTools() map[string]ServerTool
	// SetSessionTools sets tools specific to this session
	// This method must be thread-safe for concurrent access
	SetSessionTools(tools map[string]ServerTool)
}

SessionWithTools is an extension of ClientSession that can store session-specific tool data

type StatelessGeneratingSessionIdManager

type StatelessGeneratingSessionIdManager struct{}

StatelessGeneratingSessionIdManager generates session IDs but doesn't validate them locally. This allows session IDs to be generated for clients while working across multiple instances.

func (*StatelessGeneratingSessionIdManager) Generate

func (*StatelessGeneratingSessionIdManager) Terminate

func (s *StatelessGeneratingSessionIdManager) Terminate(sessionID string) (isNotAllowed bool, err error)

func (*StatelessGeneratingSessionIdManager) Validate

func (s *StatelessGeneratingSessionIdManager) Validate(sessionID string) (isTerminated bool, err error)

type StatelessSessionIdManager

type StatelessSessionIdManager struct{}

StatelessSessionIdManager does nothing, which means it has no session management, which is stateless.

func (*StatelessSessionIdManager) Generate

func (s *StatelessSessionIdManager) Generate() string

func (*StatelessSessionIdManager) Terminate

func (s *StatelessSessionIdManager) Terminate(sessionID string) (isNotAllowed bool, err error)

func (*StatelessSessionIdManager) Validate

func (s *StatelessSessionIdManager) Validate(sessionID string) (isTerminated bool, err error)

type StdioContextFunc

type StdioContextFunc func(ctx context.Context) context.Context

StdioContextFunc is a function that takes an existing context and returns a potentially modified context. This can be used to inject context values from environment variables, for example.

type StdioOption

type StdioOption func(*StdioServer)

StdioOption defines a function type for configuring StdioServer

func WithErrorLogger

func WithErrorLogger(logger *log.Logger) StdioOption

WithErrorLogger sets the error logger for the server

func WithQueueSize

func WithQueueSize(size int) StdioOption

WithQueueSize sets the size of the tool call queue

func WithStdioContextFunc

func WithStdioContextFunc(fn StdioContextFunc) StdioOption

WithStdioContextFunc sets a function that will be called to customise the context to the server. Note that the stdio server uses the same context for all requests, so this function will only be called once per server instance.

func WithWorkerPoolSize

func WithWorkerPoolSize(size int) StdioOption

WithWorkerPoolSize sets the number of workers for processing tool calls

type StdioServer

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

StdioServer wraps a MCPServer and handles stdio communication. It provides a simple way to create command-line MCP servers that communicate via standard input/output streams using JSON-RPC messages.

func NewStdioServer

func NewStdioServer(server *MCPServer) *StdioServer

NewStdioServer creates a new stdio server wrapper around an MCPServer. It initializes the server with a default error logger that discards all output.

func (*StdioServer) Listen

func (s *StdioServer) Listen(
	ctx context.Context,
	stdin io.Reader,
	stdout io.Writer,
) error

Listen starts listening for JSON-RPC messages on the provided input and writes responses to the provided output. It runs until the context is cancelled or an error occurs. Returns an error if there are issues with reading input or writing output.

func (*StdioServer) SetContextFunc

func (s *StdioServer) SetContextFunc(fn StdioContextFunc)

SetContextFunc sets a function that will be called to customise the context to the server. Note that the stdio server uses the same context for all requests, so this function will only be called once per server instance.

func (*StdioServer) SetErrorLogger

func (s *StdioServer) SetErrorLogger(logger *log.Logger)

SetErrorLogger configures where error messages from the StdioServer are logged. The provided logger will receive all error messages generated during server operation.

type StreamableHTTPOption

type StreamableHTTPOption func(*StreamableHTTPServer)

StreamableHTTPOption defines a function type for configuring StreamableHTTPServer

func WithDisableLocalhostProtection

func WithDisableLocalhostProtection(disable bool) StreamableHTTPOption

WithDisableLocalhostProtection disables the automatic DNS rebinding protection of the streamable HTTP server.

By default, requests arriving over a loopback connection (127.0.0.1, [::1]) whose Host header is not a localhost value are rejected with 403 Forbidden. This protects local MCP servers against DNS rebinding attacks, where a malicious website rebinds its own domain to 127.0.0.1 to make a victim's browser issue requests against a local server. The protection applies regardless of whether the server listens on localhost specifically or on 0.0.0.0, and never affects requests arriving via non-loopback addresses.

Disable it only if you understand the security implications, for example when a reverse proxy on the same host forwards requests via localhost while preserving the original Host header. In that case, prefer configuring the proxy to rewrite the Host header to localhost instead.

See https://modelcontextprotocol.io/specification/2025-11-25/basic/security_best_practices#local-mcp-server-compromise

func WithDisableStreaming

func WithDisableStreaming(disable bool) StreamableHTTPOption

WithDisableStreaming prevents the server from responding to GET requests with a streaming response. Instead, it will respond with a 405 Method Not Allowed status. This can be useful in scenarios where streaming is not desired or supported. The default is false, meaning streaming is enabled.

func WithEndpointPath

func WithEndpointPath(endpointPath string) StreamableHTTPOption

WithEndpointPath sets the endpoint path for the server. The default is "/mcp". It's only works for `Start` method. When used as a http.Handler, it has no effect.

func WithEventStore

func WithEventStore(store EventStore) StreamableHTTPOption

WithEventStore enables stream resumability, per the "Resumability and Redelivery" section of the MCP Streamable HTTP transport specification.

Every JSON-RPC message delivered on an SSE stream is recorded in store before it is sent and carries the store-issued event ID in the SSE id field. A client whose connection broke can then reconnect with a GET carrying the standard Last-Event-ID header to be redelivered everything it missed on that stream and keep receiving from it.

With an event store configured, session transport state survives client disconnects so that messages produced while no client is connected can still be recorded. It is reclaimed, and the session's events are purged from the store, when the session is terminated (DELETE) or, with WithSessionIdleTTL configured, when the session idles out.

func WithHTTPContextFunc

func WithHTTPContextFunc(fn HTTPContextFunc) StreamableHTTPOption

WithHTTPContextFunc sets a function that will be called to customise the context to the server using the incoming request. This can be used to inject context values from headers, for example.

func WithHeartbeatInterval

func WithHeartbeatInterval(interval time.Duration) StreamableHTTPOption

WithHeartbeatInterval sets the heartbeat interval. Positive interval means the server will send a heartbeat to the client through the GET connection, to keep the connection alive from being closed by the network infrastructure (e.g. gateways). If the client does not establish a GET connection, it has no effect. The default is not to send heartbeats.

func WithProtectedResourceMetadata

func WithProtectedResourceMetadata(config ProtectedResourceMetadataConfig) StreamableHTTPOption

WithProtectedResourceMetadata configures the StreamableHTTPServer to serve OAuth 2.0 Protected Resource Metadata (RFC 9728) at the well-known endpoint derived from the configured Resource (see ProtectedResourceMetadataPath).

The metadata is served both when the server is started via Start (registered on the internal mux) and when the server is used directly as an http.Handler via ServeHTTP. To mount the metadata endpoint manually on a custom router, use NewProtectedResourceMetadataHandler instead.

func WithSessionIdManager

func WithSessionIdManager(manager SessionIdManager) StreamableHTTPOption

WithSessionIdManager sets a custom session id generator for the server. By default, the server uses StatelessGeneratingSessionIdManager (generates IDs but no local validation). Note: Options are applied in order; the last one wins. If combined with WithStateLess or WithSessionIdManagerResolver, whichever is applied last takes effect.

func WithSessionIdManagerResolver

func WithSessionIdManagerResolver(resolver SessionIdManagerResolver) StreamableHTTPOption

WithSessionIdManagerResolver sets a custom session id manager resolver for the server. This allows for request-based session id management strategies. Note: Options are applied in order; the last one wins. If combined with WithStateLess or WithSessionIdManager, whichever is applied last takes effect.

func WithSessionIdleTTL

func WithSessionIdleTTL(ttl time.Duration) StreamableHTTPOption

WithSessionIdleTTL sets the idle TTL for per-session transport state. When enabled, a background sweeper periodically removes entries from per-session stores (tools, resources, resource templates, log levels, request IDs) for sessions that have been idle longer than the given duration. This prevents memory leaks when clients disconnect without sending a DELETE request. A zero or negative value disables the sweeper (the default).

func WithStateLess

func WithStateLess(stateLess bool) StreamableHTTPOption

WithStateLess sets the server to stateless mode. If true, the server will manage no session information. Every request will be treated as a new session. No session id returned to the client. The default is false.

Note: This is a convenience method. It's identical to set WithSessionIdManager option to StatelessSessionIdManager.

func WithStateful

func WithStateful(stateful bool) StreamableHTTPOption

WithStateful enables stateful session management using InsecureStatefulSessionIdManager. This requires sticky sessions in multi-instance deployments.

func WithStreamableHTTPCORS

func WithStreamableHTTPCORS(opts ...CORSOption) StreamableHTTPOption

WithStreamableHTTPCORS configures Cross-Origin Resource Sharing for the Streamable HTTP server.

CORS handling is opt-in: callers must specify at least one allowed origin via WithCORSAllowedOrigins for any Access-Control-* headers to be emitted. When enabled, preflight (OPTIONS) requests are answered directly by the server and simple cross-origin responses are decorated with the configured Allow-Origin, Allow-Credentials, Expose-Headers and Vary headers.

Example:

srv := server.NewStreamableHTTPServer(mcpServer,
    server.WithEndpointPath("/mcp"),
    server.WithStreamableHTTPCORS(
        server.WithCORSAllowedOrigins("https://my-ai-app.com"),
        server.WithCORSAllowCredentials(),
    ),
)

func WithStreamableHTTPLogger

func WithStreamableHTTPLogger(logger *slog.Logger) StreamableHTTPOption

WithStreamableHTTPLogger sets the structured logger for transport-level events emitted by the HTTP server (panics in goroutines, SSE event-write errors, session expiry, etc.). It is renamed from WithLogger so that server-level structured logging — see WithLogger — can carry that name on the MCPServer. A nil logger falls back to slog.Default().

func WithStreamableHTTPProtocolVersions

func WithStreamableHTTPProtocolVersions(versions ...string) StreamableHTTPOption

WithStreamableHTTPProtocolVersions restricts the protocol versions this transport advertises through server/discover.

By default every version this SDK implements is advertised, including the stateless 2026-07-28 core. Restricting the list is useful for deployments that depend on protocol-level session state - per-session tools, for example - and therefore need clients to stay on a session-oriented revision.

Passing no versions restores the default.

func WithStreamableHTTPServer

func WithStreamableHTTPServer(srv *http.Server) StreamableHTTPOption

WithStreamableHTTPServer sets the HTTP server instance for StreamableHTTPServer. NOTE: When providing a custom HTTP server, you must handle routing yourself If routing is not set up, the server will start but won't handle any MCP requests.

func WithTLSCert

func WithTLSCert(certFile, keyFile string) StreamableHTTPOption

WithTLSCert sets the TLS certificate and key files for HTTPS support. Both certFile and keyFile must be provided to enable TLS.

type StreamableHTTPServer

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

StreamableHTTPServer implements a Streamable-http based MCP server. It communicates with clients over HTTP protocol, supporting both direct HTTP responses, and SSE streams. https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http

Usage:

server := NewStreamableHTTPServer(mcpServer)
server.Start(":8080") // The final url for client is http://xxxx:8080/mcp by default

or the server itself can be used as a http.Handler, which is convenient to integrate with existing http servers, or advanced usage:

handler := NewStreamableHTTPServer(mcpServer)
http.Handle("/streamable-http", handler)
http.ListenAndServe(":8080", nil)

Notice: Except for the GET handlers(listening), the POST handlers(request/notification) will not trigger the session registration. So the methods like `SendNotificationToSpecificClient` or `hooks.onRegisterSession` will not be triggered for POST messages.

Stream resumability (redelivery of the messages a client missed while its SSE connection was broken) is opt-in via WithEventStore.

func NewStreamableHTTPServer

func NewStreamableHTTPServer(server *MCPServer, opts ...StreamableHTTPOption) *StreamableHTTPServer

NewStreamableHTTPServer creates a new streamable-http server instance

func (*StreamableHTTPServer) CloseSessions

func (s *StreamableHTTPServer) CloseSessions(ctx context.Context)

CloseSessions terminates all active streamable HTTP listening sessions without stopping the HTTP server. This unblocks long-lived GET handlers so Shutdown can complete while clients are still connected.

func (*StreamableHTTPServer) Handle

Handle dispatches a single MCP request through the streamable HTTP state machine using transport-agnostic primitives.

This is the framework-agnostic entry point intended for callers integrating MCP into HTTP frameworks other than net/http (e.g. fasthttp/fiber). For net/http callers, ServeHTTP is the conventional and equivalent entry point; in fact, ServeHTTP is implemented as a thin wrapper around Handle.

Behavioral notes for callers integrating via Handle:

  • WithStreamableHTTPCORS is NOT applied. Frameworks should use their native CORS middleware.
  • DNS rebinding protection is NOT applied, because Handle has no access to the connection's local address. Adapters for localhost-reachable servers should validate the Host header themselves (reject non-loopback Host values on loopback connections with 403 Forbidden).
  • WithProtectedResourceMetadata is NOT applied. The caller should mount the metadata route separately if needed (see ProtectedResourceMetadataHandler).
  • WithHTTPContextFunc is honored for backwards compatibility; it receives a synthetic *http.Request derived from r so existing options keep working. Callers may also pre-populate r.Context with any values they need.
  • When w.CanStream() returns false, GET (SSE listening) is rejected with 405 Method Not Allowed and POST responses that would otherwise upgrade to text/event-stream stay as a single buffered application/json reply.

func (*StreamableHTTPServer) ServeHTTP

func (s *StreamableHTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface.

When WithProtectedResourceMetadata has been configured, requests to the derived /.well-known/oauth-protected-resource path are dispatched to the metadata handler so that the same StreamableHTTPServer can be mounted as a single http.Handler while still exposing OAuth discovery metadata.

When WithStreamableHTTPCORS has been configured, CORS preflight (OPTIONS) requests are answered directly and simple cross-origin responses are decorated with the configured Access-Control-* headers before dispatch.

Requests arriving over a loopback connection with a non-localhost Host header are rejected with 403 Forbidden to protect against DNS rebinding attacks, unless WithDisableLocalhostProtection is set.

ServeHTTP is the conventional net/http entry point; for non-net/http HTTP frameworks (fasthttp, fiber, etc.), see Handle.

func (*StreamableHTTPServer) Shutdown

func (s *StreamableHTTPServer) Shutdown(ctx context.Context) error

Shutdown gracefully stops the server, closing all active sessions and shutting down the HTTP server.

func (*StreamableHTTPServer) Start

func (s *StreamableHTTPServer) Start(addr string) error

Start begins serving the http server on the specified address and path (endpointPath). like:

s.Start(":8080")

func (*StreamableHTTPServer) SupportsProtocolVersion

func (s *StreamableHTTPServer) SupportsProtocolVersion(version string) bool

SupportsProtocolVersion reports whether this transport can serve the given protocol version. It implements ProtocolVersionSupporter.

type TaskHooks

type TaskHooks struct {
	OnTaskCreated       []OnTaskCreatedHookFunc
	OnTaskCompleted     []OnTaskCompletedHookFunc
	OnTaskFailed        []OnTaskFailedHookFunc
	OnTaskCancelled     []OnTaskCancelledHookFunc
	OnTaskStatusChanged []OnTaskStatusChangedHookFunc
}

TaskHooks contains lifecycle hooks for task execution. These hooks enable observability and monitoring of task-augmented tools.

func (*TaskHooks) AddOnTaskCancelled

func (h *TaskHooks) AddOnTaskCancelled(hook OnTaskCancelledHookFunc)

AddOnTaskCancelled registers a hook for task cancellation events.

func (*TaskHooks) AddOnTaskCompleted

func (h *TaskHooks) AddOnTaskCompleted(hook OnTaskCompletedHookFunc)

AddOnTaskCompleted registers a hook for task completion events.

func (*TaskHooks) AddOnTaskCreated

func (h *TaskHooks) AddOnTaskCreated(hook OnTaskCreatedHookFunc)

AddOnTaskCreated registers a hook for task creation events.

func (*TaskHooks) AddOnTaskFailed

func (h *TaskHooks) AddOnTaskFailed(hook OnTaskFailedHookFunc)

AddOnTaskFailed registers a hook for task failure events.

func (*TaskHooks) AddOnTaskStatusChanged

func (h *TaskHooks) AddOnTaskStatusChanged(hook OnTaskStatusChangedHookFunc)

AddOnTaskStatusChanged registers a hook for all task status changes.

type TaskMetrics

type TaskMetrics struct {
	TaskID        string         // Unique identifier for the task
	ToolName      string         // Name of the tool that created the task
	Status        mcp.TaskStatus // Current status of the task
	StatusMessage string         // Optional status message
	CreatedAt     time.Time      // When the task was created
	CompletedAt   *time.Time     // When the task completed (nil if not completed)
	Duration      time.Duration  // How long the task took (0 if not completed)
	SessionID     string         // Session that owns this task
	Error         error          // Error if task failed (nil otherwise)
}

TaskMetrics contains metrics about task execution. This struct is passed to observability hooks to enable monitoring and analysis.

type TaskToolHandlerFunc

type TaskToolHandlerFunc func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CreateTaskResult, error)

TaskToolHandlerFunc handles tool calls that execute asynchronously. It returns immediately with task creation info; the actual result is retrieved later via tasks/result.

type ToolFilterFunc

type ToolFilterFunc func(ctx context.Context, tools []mcp.Tool) []mcp.Tool

ToolFilterFunc is a function that filters tools based on context, typically using session information. Filters are applied both when listing tools (tools/list) and when calling tools (tools/call), so a filtered-out tool cannot be discovered or invoked. During tools/call, filters receive only the requested tool to keep the call-time access check off the full-list hot path.

type ToolHandlerFunc

type ToolHandlerFunc func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)

ToolHandlerFunc handles tool calls with given arguments.

type ToolHandlerMiddleware

type ToolHandlerMiddleware func(ToolHandlerFunc) ToolHandlerFunc

ToolHandlerMiddleware is a middleware function that wraps a ToolHandlerFunc.

type UnparsableMessageError

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

UnparsableMessageError is attached to the RequestError when json.Unmarshal fails on the request.

func (*UnparsableMessageError) Error

func (e *UnparsableMessageError) Error() string

func (*UnparsableMessageError) GetMessage

func (e *UnparsableMessageError) GetMessage() json.RawMessage

func (*UnparsableMessageError) GetMethod

func (e *UnparsableMessageError) GetMethod() mcp.MCPMethod

func (*UnparsableMessageError) Unwrap

func (e *UnparsableMessageError) Unwrap() error

Directories

Path Synopsis
internal
gen command
Package servertest provides test helpers for the server package.
Package servertest provides test helpers for the server package.

Jump to

Keyboard shortcuts

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