Documentation
¶
Overview ¶
Package stateless holds the SEP-2575 stateless wire's public types and configuration: the wire Mode a server serves, the server/discover result, the subscriptions/listen frames, and the JSON-RPC code to HTTP status mapping. The dispatch itself lives in the parent server package, where both wires share one request path and method table (#1625).
Spec: https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2575
Index ¶
- Constants
- Variables
- func HTTPStatusForCode(code int) int
- func ParamsAsObject(origParams any) map[string]any
- func RequestMetaFromContext(ctx context.Context) *core.RequestMeta
- func SetDefaultMode(m Mode)
- type AcknowledgedFrame
- type AcknowledgedFrameParams
- type DiscoverResult
- type Mode
- type SubscribeParams
- type TaggedFrame
Constants ¶
const ModeEnvVar = "MCPKIT_STATELESS_MODE"
ModeEnvVar names the override-via-environment knob. Public so callers can read or mutate it in tests (e.g., t.Setenv(stateless.ModeEnvVar, "legacy")).
Variables ¶
var DefaultMode = ModeDual
DefaultMode is the wire mode used when no WithStatelessMode option is passed and no MCPKIT_STATELESS_MODE env var is set.
Default: ModeDual — a fresh server.New() gains SEP-2575 wire support automatically. Integrators that need to pin the old behavior without per-construction plumbing can flip this in init():
func init() { stateless.DefaultMode = stateless.ModeLegacyOnly }
Tests can flip with t.Cleanup-style restore. Reads serialize via defaultModeMu so concurrent test flips don't race with constructors.
Functions ¶
func HTTPStatusForCode ¶
HTTPStatusForCode maps a SEP-2575 JSON-RPC error code to the HTTP status the transport must return. Codes the spec does not pin map to 200 (the legacy behavior of "JSON-RPC error in a 200 body").
Transport-aware error mapping is required by SEP-2575: a stateless client MAY use the HTTP status as a fast-path signal before parsing the JSON body. Specifically:
-32601 Method not found → 404 Not Found -32020 HeaderMismatch → 400 Bad Request -32021 MissingRequiredClientCap → 400 Bad Request -32022 UnsupportedProtocolVersion → 400 Bad Request -32602 Invalid params → 400 Bad Request (missing _meta etc.) -32700 Parse / -32600 InvalidRequest → 400 Bad Request -32010 SubscriptionLimitExceeded → 429 Too Many Requests everything else → 200 OK (body carries the error)
Notification frames (no id, no error) are out of scope for this mapper; the transport applies its own status for those.
func ParamsAsObject ¶ added in v0.7.2
ParamsAsObject returns notification params as a fresh JSON object map, the form a subscription frame and a filter matcher both work on. nil gives an empty map. A map[string]any is copied shallowly. Anything else round-trips through encoding/json, and a value that is not an object lands under "data".
func RequestMetaFromContext ¶
func RequestMetaFromContext(ctx context.Context) *core.RequestMeta
RequestMetaFromContext returns the validated SEP-2575 _meta envelope attached to ctx for a request that arrived over the stateless wire, or nil otherwise. Thin re-export of core.RequestMetaFromContext so packages already importing server/stateless don't need a core import for this one accessor.
Handlers that just want to know whether a capability is declared should prefer the typed ctx.ClientCaps() accessor on ToolContext or PromptContext; this raw view is for the rare path that needs protocolVersion or clientInfo directly.
func SetDefaultMode ¶
func SetDefaultMode(m Mode)
SetDefaultMode mutates DefaultMode under write-lock. Test helpers should prefer this over direct assignment so the read-lock in ResolveMode sees a consistent value.
Types ¶
type AcknowledgedFrame ¶
type AcknowledgedFrame struct {
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params AcknowledgedFrameParams `json:"params"`
}
AcknowledgedFrame is the very first frame the server emits on every subscriptions/listen stream. The frame is a notification (no id), method = `notifications/subscriptions/acknowledged`, carrying the subscription's ID on params._meta and the honored filter on params.notifications.
Used by the streaming handler to construct the ack body; not part of the dispatcher's synchronous path.
func NewAcknowledgedFrame ¶
func NewAcknowledgedFrame(subscriptionID json.RawMessage, honored core.SubscriptionFilter) AcknowledgedFrame
NewAcknowledgedFrame builds the ack frame for a subscription. subscriptionID is the JSON-RPC id of the subscriptions/listen request, carried verbatim so a numeric id stays numeric. A nil honored filter is sent as {}.
type AcknowledgedFrameParams ¶
type AcknowledgedFrameParams struct {
Meta map[string]any `json:"_meta"`
Notifications core.SubscriptionFilter `json:"notifications"`
}
AcknowledgedFrameParams carries the subscriptionId under _meta where the SEP-2575 conformance suite (and any other listener) expects it, and the subset of the requested filter the server agreed to honor. Notifications is always present, as {} when nothing was honored.
type DiscoverResult ¶
type DiscoverResult struct {
SupportedVersions []string `json:"supportedVersions"`
Capabilities core.ServerCapabilities `json:"capabilities"`
// Instructions is the server's guidance for the model, a top-level
// field of DiscoverResult in the 2026-07-28 schema. Omitted when empty.
Instructions string `json:"instructions,omitempty"`
// TTLMs and CacheScope are required on DiscoverResult in the
// 2026-07-28 final schema (the SEP-2549 hints extended to
// server/discover). Always emitted; the defaults mirror the
// conformant-by-default list-response posture from issue 496:
// immediately stale, publicly cacheable.
TTLMs int `json:"ttlMs"`
CacheScope string `json:"cacheScope"`
}
DiscoverResult is the SEP-2575 server/discover response payload.
Wire shape:
{
"supportedVersions": ["2026-07-28"],
"capabilities": { ...ServerCapabilities... },
"_meta": { "io.modelcontextprotocol/serverInfo": { "name": "...", "version": "..." } }
}
Server identity moved from the result body to _meta in spec PR 3002; the server stamps it onto every stateless result, this one included.
Per the spec, clients MAY call server/discover up front to negotiate version + capability shape, OR call any other RPC inline and handle UnsupportedProtocolVersionError as a probe. Both paths are supported.
type Mode ¶
type Mode int
Mode selects which protocol wire(s) the Streamable HTTP transport will serve on a single URL. Distinct from the parent server package's WithStateless option, which controls process-architecture (no in-process session storage) — the two are orthogonal and may be combined freely.
Example: pure SEP-2575 wire + no session storage (the common serverless/Lambda deployment shape):
server.New(impl,
server.WithStatelessMode(stateless.ModeStateless),
server.WithStateless(true),
)
Default Dual mode + session-backed legacy clients allowed:
server.New(impl) // implicit stateless.ModeDual + WithStateless(false)
const ( // ModeLegacyOnly accepts only the legacy session wire // (initialize/notifications/initialized handshake; Mcp-Session-Id // header). server/discover is rejected with -32601 + HTTP 404. // Zero-value-compatible with the previous default behavior, so a // build that explicitly opts out of SEP-2575 keeps the old shape. ModeLegacyOnly Mode = iota // ModeDual accepts both wires on the same URL, branching per-request // on the shape of the incoming payload (method == initialize / // presence of Mcp-Session-Id → legacy; MCP-Protocol-Version header // or _meta protocolVersion field → stateless). Default. ModeDual // ModeStateless accepts only the SEP-2575 stateless wire. initialize, // notifications/initialized, ping, logging/setLevel, and // resources/(un)subscribe are all rejected with -32601 + HTTP 404. ModeStateless )
func ParseMode ¶
ParseMode decodes a mode token (the inverse of String). Accepts "legacy", "dual", "stateless"; case-insensitive; empty string maps to the caller's fallback via the returned ok=false.
func ResolveMode ¶
func ResolveMode() Mode
ResolveMode seeds the runtime mode from the env var or, failing that, DefaultMode. Server constructors call this to seed transportConfig; the WithStatelessMode option clobbers the seed when present.
Precedence (high → low):
- WithStatelessMode (applied post-seed)
- MCPKIT_STATELESS_MODE environment variable
- DefaultMode (under read-lock)
type SubscribeParams ¶
type SubscribeParams struct {
Notifications core.SubscriptionFilter `json:"notifications"`
}
SubscribeParams is the params shape clients post to subscriptions/listen.
_meta carries the standard SEP-2575 envelope (validated upstream by the dispatcher) plus optional client identifiers. Notifications carries the subscription filter and is required. A key the server does not recognise, or declines, is simply not honored: it is left out of the acknowledgement and nothing it names is delivered.
type TaggedFrame ¶
type TaggedFrame struct {
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params map[string]any `json:"params"`
}
TagFrameWithSubscriptionID wraps any outbound notification in the SEP-2575-required envelope: jsonrpc, method, and a params._meta block carrying the subscriptionId. The original params are preserved verbatim under the same key. The transport calls this for every notification it fans out to an open stream.
origParams may be nil (notification with no params); the result still carries _meta.subscriptionId so clients can route the frame.
func NewTaggedFrame ¶
func NewTaggedFrame(method string, origParams any, subscriptionID json.RawMessage) TaggedFrame
NewTaggedFrame builds a notification frame stamped with the given subscriptionId under params._meta[io.modelcontextprotocol/subscriptionId]. subscriptionID is the listen request's JSON-RPC id, carried verbatim.
origParams may be nil, a map, or any value that marshals to a JSON object (an extension's typed params struct). Its fields keep their keys, and any _meta it already carries (a traceparent, say) is kept alongside the subscriptionId. A value that does not marshal to an object is stashed under "data" so it is not lost.