Skip to content

[P3] server: serve 2026-07-28 stateless requests - #368

Merged
jeanmatthieu merged 3 commits into
rel/1.0.0from
conformance/p3-stateless-server
Nov 25, 2026
Merged

jeanmatthieu merged 3 commits into
rel/1.0.0from
conformance/p3-stateless-server

Conversation

@jeanmatthieu

@jeanmatthieu jeanmatthieu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor
Part P3 of P0–P35, merged into rel/1.0.0 in order (previous: P2 (#369) · next: P4 (#367))
Branch conformance/p3-stateless-server
Base conformance/p2-foundations (stacked: GitHub retargets this PR to rel/1.0.0 when the previous part merges)
Commits bb7b0a3 server: serve 2026-07-28 stateless requests
751aab8 server: review fixes
c39779d server: third-pass review fixes
Size 17 files, +2301 / -356

Summary

Server serves self-contained 2026-07-28 requests (SEP-2575) alongside initialize-based connections. The server classifies each request by the protocol version in its _meta. Requests at 2026-07-28 and later are validated, gated by method and server capability, and answered with annotated results (resultType, serverInfo, SEP-2549 cache hints). server/discover gets a default handler. StatelessHTTPServerTransport is reworked to serve these requests over HTTP, and StatefulHTTPServerTransport rejects them with -32022 so a client can fall back to the handshake.

A server that gates clients with an initializeHook refuses stateless requests unless it also passes a statelessRequestHook, so stateless requests cannot bypass the gate. StatelessHTTPServerTransport bounds the messages it buffers per request, cancels a request whose client goes away, and honors notifications/cancelled only from the client that sent the request.

Motivation

Protocol 2026-07-28 removes initialize, ping, logging/setLevel, resources/subscribe and resources/unsubscribe. Instead, every request carries io.modelcontextprotocol/protocolVersion, clientCapabilities, and optionally clientInfo and logLevel in _meta. Clients discover a server with server/discover. Results carry resultType, _meta["io.modelcontextprotocol/serverInfo"] and cache hints. Over HTTP, the MCP-Protocol-Version header must agree with _meta, and JSON-RPC errors map to HTTP status codes. Before this PR the server handled every request as part of a handshake connection, so 108 server entries failed in the 2026-07-28 leg. One more issue: dns-rebinding-protection:localhost-host-valid-accepted failed because the fixture's HTTPApp rejected sessionless POSTs before validation.

Changes

Server

  • Sources/MCP/Server/StatelessRequests.swift (new, internal):
    • RequestEra (.handshake / .stateless(StatelessRequestInfo)).
    • StatelessRequests.classify(_:served:) assigns the era:
      • No protocolVersion key, or a served handshake revision, is the handshake era. A handshake revision that is not in served is -32022.
      • A non-string or empty version is -32602.
      • A missing or invalid clientCapabilities, or an invalid clientInfo, is -32602.
      • A version that is not in served is -32022 with data.supported set to the served versions.
    • Method sets: removedMethods, statelessOnlyMethods (server/discover, subscriptions/listen) and cacheableMethods.
    • isDeclared(_:in:) gates tools, prompts, resources and completion methods on the server capability.
    • annotate(...) adds resultType, _meta.serverInfo and, for cacheable methods with a complete result, ttlMs and cacheScope when the handler did not set them.
  • CacheHint (public): ttlMs and scope. .uncached is 0 ms with .private scope.
  • Sources/MCP/Server/Server.swift:
    • Server.Configuration gains an explicit init(strict:protocolVersions:cacheHints:defaultCacheHint:).
      • protocolVersions defaults to Version.stateless + Version.handshake.
      • cacheHints holds hints per method name.
      • defaultCacheHint defaults to .uncached.
    • Request dispatch:
      • Classifies the request first.
      • Handshake era: server/discover and subscriptions/listen are -32601. The existing strict-mode initialize check still applies.
      • Stateless era: removed methods and methods of undeclared capabilities are -32601.
      • Stateless results pass through annotate.
    • HandlerContext gains protocolVersion, clientCapabilities, clientInfo, logLevel, isStateless and profile. For handshake requests, the context holds the negotiated version and the capabilities from initialize.
    • log(...) inside a stateless request sends a notification only when the request set a log level, and only at or above that level.
    • A server-to-client request from a stateless handler throws MCPError.invalidRequest, because the profile does not allow server requests.
    • The strict client-capability check prefers the per-request capabilities.
    • initialize negotiates among the configured handshake versions; with none configured it is -32022.
    • Default server/discover handler: returns supportedVersions (the configured protocolVersions), capabilities and instructions.
  • Sources/MCP/Base/Discover.swift (new): ServerDiscover method. Its Result has supportedVersions, capabilities, instructions, _meta, ttlMs, cacheScope and serverInfo (read from _meta).
  • Sources/MCP/Server/Logging.swift: LogLevel: Comparable, in severity order.
  • Sources/MCP/Base/Messages.swift: TypedRequestHandler maps a parameter decoding failure to MCPError.invalidParams (-32602), with the member path and the kind of problem.

Transports

  • Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift:
    • HTTPRequest.statelessProtocolVersion: the MCP-Protocol-Version header when it is not a handshake revision. Use it to route requests.
    • JSONRPCErrorStatus (internal) maps JSON-RPC codes to HTTP status: -32601 is 404; -32600, -32602, -32020, -32021 and -32022 are 400; all other codes are 200.
    • HTTPResponse.data gains statusCode:.
    • HTTPResponse.error gains id:. The error body is encoded from MCPError, so it carries data, and id is the request ID when known (otherwise null).
    • HTTPResponse.withRequestID(_:) fills in the ID of an error response that has none.
  • Sources/MCP/Base/Transports/HTTPServer/HTTPRequestValidation.swift: ProtocolVersionValidator rejects an unknown version with unsupportedProtocolVersion(supported:requested:) (-32022 with data). It used to reject with invalidRequest.
  • Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift (rewritten):
    • Each request is handed to the server under an internal ID mcp-http-<uuid>, and the client's ID is restored on the response, so concurrent clients may reuse IDs.
    • Validation accepts stateless and handshake versions. Validation errors carry the request ID.
    • Header and _meta checks:
      • a stateless header without a _meta version is -32602;
      • a header that differs from the _meta version is -32020;
      • a stateless _meta version without a matching header is -32020.
    • JSON responses to stateless requests use JSONRPCErrorStatus. Legacy requests keep 200, except -32022, which is 400.
    • When the handler sends related notifications before the response and the client accepts text/event-stream, the response is an SSE stream that carries the notifications and ends with the response. Otherwise those notifications are dropped.
    • Termination before a response yields 503 with connectionClosed. It used to yield 500.
    • JSONRPCMessageFields (internal) reads and rewrites the id, the _meta protocol version and error.code of a message.
  • Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift: a non-initialize request whose header or _meta names a stateless version gets 400 -32022 with supported: Version.handshake.

Fixtures

  • Sources/MCPConformance/Server/HTTPApp.swift:
    • A request without a session ID whose header names a stateless version goes to one shared Server on a StatelessHTTPServerTransport, created on first use with its own validation pipeline.
    • ServerFactory now takes (String?, any Transport).
  • Sources/MCPConformance/Server/main.swift:
    • New tools: test_missing_capability (throws -32021 unless the request declares sampling), test_logging_tool and test_streaming_elicitation.
    • json_schema_2020_12_tool uses more JSON Schema 2020-12 keywords: $anchor, enum, allOf/anyOf, if/then/else.
    • test_tool_with_logging uses Server.log.
    • test_reconnection closes the stream only on the stateful transport.

Docs

  • README.md: the transport table states which revisions each HTTP server transport serves. A new section, "Serving 2026-07-28 and Earlier Clients", covers routing by statelessProtocolVersion, the per-request handler context, result annotation, log gating, removed methods and per-request capability checks.

Baselines

  • conformance-baseline.2026-07-28.yml and conformance-baseline.yml are regenerated.

Review fixes

Server (Sources/MCP/Server/Server.swift, StatelessRequests.swift)

  • An initializeHook gated only handshake clients: a request with a 2026-07-28 _meta never sends initialize and skipped it. start(transport:initializeHook:statelessRequestHook:) takes a new statelessRequestHook (Server.StatelessRequestHook), which runs before each stateless request with the client info and capabilities from _meta, with Server.currentHandlerContext set. Throwing an MCPError refuses the request with that error, any other error with -32600. A server with an initializeHook and no statelessRequestHook refuses stateless requests with -32022 listing its handshake versions, so clients fall back to initialize.
  • Configuration.strict is documented as applying to handshake-era clients only.
  • A handshake revision in _meta was served as a handshake request even when the server did not list it. It is now -32022.
  • A server whose protocolVersions lists no handshake revision negotiated 2025-11-25 anyway. It now refuses initialize and handshake requests with -32022.
  • Undecodable parameters were reported with the Swift DecodingError text (type names, debug descriptions). The message now names the member path and the problem only, for example Invalid params for tools/call: missing params.name (TypedRequestHandler.problem(in:)). Request and Message decoding decode the parameters again to report where they are wrong.
  • Server.Configuration decoding required the new keys, so a configuration encoded before this PR did not decode. A custom init(from:) gives protocolVersions, cacheHints and defaultCacheHint their defaults when absent.
  • Sources/MCP/Base/Discover.swift: ServerDiscover.Result decodes ttlMs and cacheScope leniently, like the other cacheable results.

StatefulHTTPServerTransport

  • A request whose stateless version was only in _meta, not in the header, reached the server and was served statelessly on the session. It now also gets -32022. The -32022 answer comes after the origin, media type and authentication validators, and the session ID is echoed only to a client that sent it.
  • An initialize refused with an error response (for example by the initialize hook) kept the session it created. The session is now dropped.

StatelessHTTPServerTransport

  • Messages for a slow client were buffered without limit. At most maxBufferedMessages (1024) are buffered per request, on the outgoing queue and on the SSE stream; the oldest notifications are dropped first, never the response.
  • Responses are tagged when routed (Outgoing.response, with the error code read while the ID is rewritten) instead of re-parsed, and the request ID and the _meta version come from one probe (JSONRPCMessageFields.requestFields(in:)).
  • A request whose client went away kept running. When the adapter cancels the task awaiting a pending JSON reply, or the client drops the SSE stream, the transport forgets the exchange and sends the server notifications/cancelled for the internal ID.
  • A client's notifications/cancelled was forwarded with the client's request ID, which the server does not know and which other clients may also use. It is now rewritten to the internal ID and forwarded only when it carries the same Authorization header as exactly one request in flight with that ID; otherwise it is ignored (202).
  • GET and other non-POST methods returned 405 before validation, so ProtectedResourceMetadataValidator could not serve the resource metadata document. They now run the pipeline, return a 2xx answer from a validator, and 405 otherwise.

Fixtures

  • Sources/MCPConformance/Server/HTTPApp.swift: concurrent first stateless requests could each start a server. They now wait for one shared start task.

Docs

  • README.md: the stateless section covers the hooks, strict, the stateful transport's -32022 rule, the dropped session of a refused initialize, and cancellation on the stateless transport.

Diagram

flowchart TD
    R["incoming request"] --> V{"_meta protocolVersion"}
    V -->|"absent or served handshake revision"| H["handshake era"]
    V -->|"empty or not a string"| P["-32602"]
    V -->|"other version"| C{"clientCapabilities and clientInfo valid"}
    C -->|"no"| P
    C -->|"yes"| S{"in Configuration.protocolVersions"}
    S -->|"no"| U["-32022 with data.supported"]
    V -->|"handshake revision not served"| U
    S -->|"yes"| ST["stateless era"]
    H --> HO{"server/discover or subscriptions/listen"}
    HO -->|"yes"| NF["-32601"]
    HO -->|"no"| HH["handler"]
    ST --> K{"initializeHook without statelessRequestHook"}
    K -->|"yes"| U
    K -->|"no"| G{"removed method or capability not declared"}
    G -->|"yes"| NF
    G -->|"no"| SH["statelessRequestHook, handler, then annotate result"]
Loading
sequenceDiagram
    participant C as Client
    participant T as StatelessHTTPServerTransport
    participant S as Server
    C->>T: POST tools/call id 1, MCP-Protocol-Version 2026-07-28
    T->>T: check header against _meta version
    T->>S: request with id mcp-http-uuid
    S->>T: notifications/progress related to mcp-http-uuid
    T-->>C: 200 text/event-stream with the progress event
    S->>T: response for mcp-http-uuid
    T-->>C: response event with id 1, stream ends
Loading

API changes

Added

Symbol Notes
ServerDiscover (Parameters, Result) server/discover. Result conforms to CacheableResult
CacheHint, CacheHint.uncached Default SEP-2549 hints
Server.Configuration.init(strict:protocolVersions:cacheHints:defaultCacheHint:) All parameters have defaults
Server.Configuration.protocolVersions, .cacheHints, .defaultCacheHint Served versions and cache hints
Server.HandlerContext.protocolVersion, .clientCapabilities, .clientInfo, .logLevel, .isStateless, .profile Per-request client context
LogLevel: Comparable Severity order
HTTPRequest.statelessProtocolVersion Routing helper
HTTPResponse.withRequestID(_:) Sets the ID of an error body
Server.StatelessRequestHook (Client.Info?, Client.Capabilities) async throws -> Void
statelessRequestHook: parameter of Server.start(transport:initializeHook:statelessRequestHook:) Defaults to nil
Server.Configuration.init(from:) Decodes configurations without the new keys
StatelessHTTPServerTransport.maxBufferedMessages 1024, per request

Changed

Symbol Change
HTTPResponse.data(_:headers:) Now data(_:statusCode:headers:), statusCode defaults to 200. Pattern matches no longer compile. breaking
HTTPResponse.error(statusCode:_:sessionID:extraHeaders:) Now error(statusCode:_:id:sessionID:extraHeaders:). Pattern matches no longer compile. breaking
HTTPResponse.bodyData for .error Encodes the full MCPError (with data) and the request ID instead of id: null
ProtocolVersionValidator An unsupported version is -32022 with data.supported / data.requested instead of -32600
Server.start(transport:initializeHook:) Gains the defaulted statelessRequestHook: parameter; source compatible. With an initializeHook and no statelessRequestHook, stateless requests are refused with -32022
Server.Configuration Codable New stored properties take their defaults when absent, so JSON saved before this change still decodes
StatelessHTTPServerTransport Server.HandlerContext.id and httpRequestContext(for:) use the internal ID, not the client's ID

Removed: none.

Behavior changes

  • With the default configuration, a Server on any transport serves a request whose _meta names 2026-07-28 statelessly, unless it was started with an initializeHook and no statelessRequestHook. Version.supported and the client still default to the handshake. P4 ([P4] client: connect with server/discover at 2026-07-28 #367) and P9 ([P9] versions: make 2026-07-28 the client default #361) change the client.
  • Handshake-era clients get -32601 for server/discover and subscriptions/listen.
  • Stateless requests:
    • removed methods and methods of capabilities the server did not declare are -32601;
    • results gain resultType: "complete" and _meta.serverInfo;
    • cacheable results gain ttlMs / cacheScope (default 0 / private);
    • log notifications follow the request's logLevel, and there are none without it;
    • server-to-client requests throw;
    • Configuration.strict does not apply; a statelessRequestHook runs before each one.
  • initialize negotiates only among the configured handshake versions, and is -32022 when none is configured. A handshake revision in _meta that the server does not serve is -32022.
  • Undecodable parameters are -32602 for every request; the message names the member, not Swift types.
  • StatelessHTTPServerTransport:
    • stateless errors use HTTP 400/404;
    • related notifications can arrive over SSE; at most 1024 are buffered per request, oldest dropped first;
    • termination before a response is 503 instead of 500;
    • HTTP error bodies carry the request ID and data;
    • a request whose client goes away (cancelled HTTP task or dropped SSE stream) is cancelled in the server;
    • notifications/cancelled is honored only with the same Authorization header as exactly one request in flight with that ID;
    • non-POST requests answered by a validator (resource metadata) are served; others are 405.
  • StatefulHTTPServerTransport answers a non-initialize request with a stateless MCP-Protocol-Version header or _meta version with 400 -32022, after origin, media type and authentication validation. A refused initialize leaves no session.

Conformance

Leg Before (P2) After
2025-11-25 0 / 0 0 / 0
2026-07-28 108 / 47 25 / 47
default 106 / 46 51 / 46

Tier score 2026-07-28 server: 26/37.

The 25 server entries left in the 2026-07-28 leg:

Tests

  • Tests/MCPTests/StatelessServerTests.swift (new), using WireExchange from P2 ([P2] base: protocol profiles, error data, envelope _meta and result types #369).
    • StatelessServerTests:
      • discovery and result annotation; no annotation for legacy results; per-method cache hints;
      • -32602 for invalid _meta, -32022 with the served versions, -32601 for removed methods, for server/discover on handshake connections and for undeclared capabilities;
      • a handshake version in _meta is served as a handshake request;
      • the per-request handler context, log-level gating and the server-request refusal;
      • -32602 for undecodable params, and initialize negotiation among the configured versions.
    • Stateless HTTP Tests:
      • the routing helper;
      • client ID restored and errors mapped to HTTP status; legacy errors stay 200;
      • header and _meta agreement; an unknown header version is -32022 with the request ID;
      • SSE when notifications precede the result;
      • concurrent requests with the same ID;
      • validation errors carry the request ID;
      • the stateful transport rejects stateless requests with -32022.
  • Tests/MCPTests/HTTPServerTransportTests.swift: existing stateless transport and handler-context tests read the internal ID from receive() instead of assuming the client's ID. They also expect 503 on termination.
  • Tests/MCPTests/StatelessGatingTests.swift (new):
    • Stateless request gating: an initialize hook without a stateless hook refuses stateless requests with -32022; a stateless hook runs before each stateless request and can refuse it; without hooks stateless requests are served; an unserved handshake revision in _meta is -32022; a server without handshake revisions refuses initialize and handshake requests; undecodable parameters name the member; a server/discover result with unknown cache hints decodes.
    • Stateful transport and stateless requests: a stateless version in _meta alone is -32022 on a session; the origin check still runs; a refused initialize leaves no session.
    • Stateless transport exchanges: notifications/cancelled reaches the request with the same ID and Authorization; cancelling a pending JSON reply cancels the request in the server; a slow client's stream keeps the newest messages and the response; a GET answered by a validator is served, any other GET is 405.
    • Server configuration coding: a configuration encoded before protocolVersions decodes; a configuration round-trips.
  • 662 tests.

Review notes

Verification

export npm_config_registry=https://registry.npmjs.org
swift test
swift build
scripts/run-conformance.sh --spec-version 2026-07-28 --mode server --bin-path $(swift build --show-bin-path)
scripts/run-conformance.sh --spec-version 2025-11-25 --bin-path $(swift build --show-bin-path)
scripts/run-conformance.sh --bin-path $(swift build --show-bin-path)
scripts/run-conformance.sh --requirements 2026-07-28 --mode server --bin-path $(swift build --show-bin-path)

The --requirements 2026-07-28 leg reports 26/37 at this point and still fails.

Every branch of the stack builds and passes swift test; at this branch, 662 swift-testing tests plus the XCTest cases, all passed. The three conformance legs pass at their baselines.


AI usage disclosure: the changes, the tests, the commit messages and this description were written with Claude Opus 5.5 and reviewed by the authors.

`Server` serves self-contained 2026-07-28 requests (SEP-2575) alongside
`initialize`-based connections. The server classifies each request by
the protocol version in its `_meta`. Requests at 2026-07-28 and later
are validated, gated by method and server capability, and answered with
annotated results (`resultType`, `serverInfo`, SEP-2549 cache hints).
`server/discover` gets a default handler. `StatelessHTTPServerTransport`
is reworked to serve these requests over HTTP, and
`StatefulHTTPServerTransport` rejects them with -32022 so a client can
fall back to the handshake.

A server that gates clients with an `initializeHook` refuses stateless
requests unless it also passes a `statelessRequestHook`, so stateless
requests cannot bypass the gate. `StatelessHTTPServerTransport` bounds
the messages it buffers per request, cancels a request whose client goes
away, and honors `notifications/cancelled` only from the client that
sent the request.
- End a stateless request's HTTP exchange when the transport honors
  its notifications/cancelled: the exchange is forgotten, a response
  not yet decided is 202 Accepted with no body, and an open SSE stream
  ends normally. The POST no longer stays open until the client
  disconnects; the abandon and terminate paths are unchanged.
- Match notifications/cancelled to a request in flight by id value,
  not its text, so integer id 1 and string id "1" are different
  requests.
- Reject an unserved stateless protocol version with -32022 and the
  served versions before checking clientCapabilities and clientInfo,
  so the client can negotiate instead of getting -32602.
- Build the serverInfo of stateless results with Value.preservingStrings,
  so a data: icon src (Server.init takes icons since main's #258) is sent
  as written, not rewritten to base64.
- Read an empty params._meta io.modelcontextprotocol/protocolVersion as
  absent in the HTTP transports' message probe, as a version that is not
  a string already is. StatelessRequests.classify answers "" with
  -32602, but the probe passed it on as a version: the stateless
  transport refused it with -32020 (header mismatch) and the stateful
  transport with -32022 and "requested": "". The same request now gets
  -32602 on both transports and in Server: from the stateless transport
  when the MCP-Protocol-Version header names a stateless revision, and
  from Server otherwise.

Tests: StatelessHTTPTests (empty version with and without the header),
StatefulStatelessBoundaryTests (empty version on a session reaches the
server), StatelessServerTests.testInvalidMeta (empty version in Server).
canarik
canarik previously approved these changes Nov 25, 2026

@canarik canarik left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @jeanmatthieu

Base automatically changed from conformance/p2-foundations to rel/1.0.0 November 25, 2026 12:34
@jeanmatthieu
jeanmatthieu dismissed canarik’s stale review November 25, 2026 12:34

The base branch was changed.

@jeanmatthieu
jeanmatthieu merged commit 94b0c89 into rel/1.0.0 Nov 25, 2026
@jeanmatthieu
jeanmatthieu deleted the conformance/p3-stateless-server branch November 25, 2026 12:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants