Repository navigation
[P3] server: serve 2026-07-28 stateless requests - #368
Merged
Merged
Conversation
`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).
This was referenced Nov 25, 2026
Merged
canarik
approved these changes
Nov 25, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
rel/1.0.0in order (previous: P2 (#369) · next: P4 (#367))conformance/p3-stateless-serverconformance/p2-foundations(stacked: GitHub retargets this PR torel/1.0.0when the previous part merges)bb7b0a3server: serve 2026-07-28 stateless requests751aab8server: review fixesc39779dserver: third-pass review fixesSummary
Serverserves self-contained 2026-07-28 requests (SEP-2575) alongsideinitialize-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/discovergets a default handler.StatelessHTTPServerTransportis reworked to serve these requests over HTTP, andStatefulHTTPServerTransportrejects them with -32022 so a client can fall back to the handshake.A server that gates clients with an
initializeHookrefuses stateless requests unless it also passes astatelessRequestHook, so stateless requests cannot bypass the gate.StatelessHTTPServerTransportbounds the messages it buffers per request, cancels a request whose client goes away, and honorsnotifications/cancelledonly from the client that sent the request.Motivation
Protocol 2026-07-28 removes
initialize,ping,logging/setLevel,resources/subscribeandresources/unsubscribe. Instead, every request carriesio.modelcontextprotocol/protocolVersion,clientCapabilities, and optionallyclientInfoandlogLevelin_meta. Clients discover a server withserver/discover. Results carryresultType,_meta["io.modelcontextprotocol/serverInfo"]and cache hints. Over HTTP, theMCP-Protocol-Versionheader 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-acceptedfailed because the fixture'sHTTPApprejected sessionless POSTs before validation.Changes
Server
Sources/MCP/Server/StatelessRequests.swift(new, internal):RequestEra(.handshake/.stateless(StatelessRequestInfo)).StatelessRequests.classify(_:served:)assigns the era:protocolVersionkey, or a served handshake revision, is the handshake era. A handshake revision that is not inservedis -32022.clientCapabilities, or an invalidclientInfo, is -32602.servedis -32022 withdata.supportedset to the served versions.removedMethods,statelessOnlyMethods(server/discover,subscriptions/listen) andcacheableMethods.isDeclared(_:in:)gates tools, prompts, resources and completion methods on the server capability.annotate(...)addsresultType,_meta.serverInfoand, for cacheable methods with a complete result,ttlMsandcacheScopewhen the handler did not set them.CacheHint(public):ttlMsandscope..uncachedis 0 ms with.privatescope.Sources/MCP/Server/Server.swift:Server.Configurationgains an explicitinit(strict:protocolVersions:cacheHints:defaultCacheHint:).protocolVersionsdefaults toVersion.stateless + Version.handshake.cacheHintsholds hints per method name.defaultCacheHintdefaults to.uncached.server/discoverandsubscriptions/listenare -32601. The existing strict-modeinitializecheck still applies.annotate.HandlerContextgainsprotocolVersion,clientCapabilities,clientInfo,logLevel,isStatelessandprofile. For handshake requests, the context holds the negotiated version and the capabilities frominitialize.log(...)inside a stateless request sends a notification only when the request set a log level, and only at or above that level.MCPError.invalidRequest, because the profile does not allow server requests.initializenegotiates among the configured handshake versions; with none configured it is -32022.server/discoverhandler: returnssupportedVersions(the configuredprotocolVersions),capabilitiesandinstructions.Sources/MCP/Base/Discover.swift(new):ServerDiscovermethod. ItsResulthassupportedVersions,capabilities,instructions,_meta,ttlMs,cacheScopeandserverInfo(read from_meta).Sources/MCP/Server/Logging.swift:LogLevel: Comparable, in severity order.Sources/MCP/Base/Messages.swift:TypedRequestHandlermaps a parameter decoding failure toMCPError.invalidParams(-32602), with the member path and the kind of problem.Transports
Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift:HTTPRequest.statelessProtocolVersion: theMCP-Protocol-Versionheader 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.datagainsstatusCode:.HTTPResponse.errorgainsid:. The error body is encoded fromMCPError, so it carriesdata, andidis the request ID when known (otherwisenull).HTTPResponse.withRequestID(_:)fills in the ID of an error response that has none.Sources/MCP/Base/Transports/HTTPServer/HTTPRequestValidation.swift:ProtocolVersionValidatorrejects an unknown version withunsupportedProtocolVersion(supported:requested:)(-32022 with data). It used to reject withinvalidRequest.Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift(rewritten):mcp-http-<uuid>, and the client's ID is restored on the response, so concurrent clients may reuse IDs._metachecks:_metaversion is -32602;_metaversion is -32020;_metaversion without a matching header is -32020.JSONRPCErrorStatus. Legacy requests keep 200, except -32022, which is 400.text/event-stream, the response is an SSE stream that carries the notifications and ends with the response. Otherwise those notifications are dropped.connectionClosed. It used to yield 500.JSONRPCMessageFields(internal) reads and rewrites theid, the_metaprotocol version anderror.codeof a message.Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift: a non-initializerequest whose header or_metanames a stateless version gets 400 -32022 withsupported: Version.handshake.Fixtures
Sources/MCPConformance/Server/HTTPApp.swift:Serveron aStatelessHTTPServerTransport, created on first use with its own validation pipeline.ServerFactorynow takes(String?, any Transport).Sources/MCPConformance/Server/main.swift:test_missing_capability(throws -32021 unless the request declares sampling),test_logging_toolandtest_streaming_elicitation.json_schema_2020_12_tooluses more JSON Schema 2020-12 keywords:$anchor,enum,allOf/anyOf,if/then/else.test_tool_with_loggingusesServer.log.test_reconnectioncloses 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 bystatelessProtocolVersion, the per-request handler context, result annotation, log gating, removed methods and per-request capability checks.Baselines
conformance-baseline.2026-07-28.ymlandconformance-baseline.ymlare regenerated.Review fixes
Server (
Sources/MCP/Server/Server.swift,StatelessRequests.swift)initializeHookgated only handshake clients: a request with a 2026-07-28_metanever sendsinitializeand skipped it.start(transport:initializeHook:statelessRequestHook:)takes a newstatelessRequestHook(Server.StatelessRequestHook), which runs before each stateless request with the client info and capabilities from_meta, withServer.currentHandlerContextset. Throwing anMCPErrorrefuses the request with that error, any other error with -32600. A server with aninitializeHookand nostatelessRequestHookrefuses stateless requests with -32022 listing its handshake versions, so clients fall back toinitialize.Configuration.strictis documented as applying to handshake-era clients only._metawas served as a handshake request even when the server did not list it. It is now -32022.protocolVersionslists no handshake revision negotiated 2025-11-25 anyway. It now refusesinitializeand handshake requests with -32022.DecodingErrortext (type names, debug descriptions). The message now names the member path and the problem only, for exampleInvalid params for tools/call: missing params.name(TypedRequestHandler.problem(in:)).RequestandMessagedecoding decode the parameters again to report where they are wrong.Server.Configurationdecoding required the new keys, so a configuration encoded before this PR did not decode. A custominit(from:)givesprotocolVersions,cacheHintsanddefaultCacheHinttheir defaults when absent.Sources/MCP/Base/Discover.swift:ServerDiscover.ResultdecodesttlMsandcacheScopeleniently, like the other cacheable results.StatefulHTTPServerTransport_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.initializerefused with an error response (for example by the initialize hook) kept the session it created. The session is now dropped.StatelessHTTPServerTransportmaxBufferedMessages(1024) are buffered per request, on the outgoing queue and on the SSE stream; the oldest notifications are dropped first, never the response.Outgoing.response, with the error code read while the ID is rewritten) instead of re-parsed, and the request ID and the_metaversion come from one probe (JSONRPCMessageFields.requestFields(in:)).notifications/cancelledfor the internal ID.notifications/cancelledwas 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 sameAuthorizationheader as exactly one request in flight with that ID; otherwise it is ignored (202).ProtectedResourceMetadataValidatorcould 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 refusedinitialize, 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"]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 endsAPI changes
Added
ServerDiscover(Parameters,Result)server/discover.Resultconforms toCacheableResultCacheHint,CacheHint.uncachedServer.Configuration.init(strict:protocolVersions:cacheHints:defaultCacheHint:)Server.Configuration.protocolVersions,.cacheHints,.defaultCacheHintServer.HandlerContext.protocolVersion,.clientCapabilities,.clientInfo,.logLevel,.isStateless,.profileLogLevel: ComparableHTTPRequest.statelessProtocolVersionHTTPResponse.withRequestID(_:)Server.StatelessRequestHook(Client.Info?, Client.Capabilities) async throws -> VoidstatelessRequestHook:parameter ofServer.start(transport:initializeHook:statelessRequestHook:)nilServer.Configuration.init(from:)StatelessHTTPServerTransport.maxBufferedMessages1024, per requestChanged
HTTPResponse.data(_:headers:)data(_:statusCode:headers:),statusCodedefaults to 200. Pattern matches no longer compile. breakingHTTPResponse.error(statusCode:_:sessionID:extraHeaders:)error(statusCode:_:id:sessionID:extraHeaders:). Pattern matches no longer compile. breakingHTTPResponse.bodyDatafor.errorMCPError(withdata) and the request ID instead ofid: nullProtocolVersionValidatordata.supported/data.requestedinstead of -32600Server.start(transport:initializeHook:)statelessRequestHook:parameter; source compatible. With aninitializeHookand nostatelessRequestHook, stateless requests are refused with -32022Server.ConfigurationCodableStatelessHTTPServerTransportServer.HandlerContext.idandhttpRequestContext(for:)use the internal ID, not the client's IDRemoved: none.
Behavior changes
Serveron any transport serves a request whose_metanames 2026-07-28 statelessly, unless it was started with aninitializeHookand nostatelessRequestHook.Version.supportedand 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.server/discoverandsubscriptions/listen.resultType: "complete"and_meta.serverInfo;ttlMs/cacheScope(default 0 /private);logLevel, and there are none without it;Configuration.strictdoes not apply; astatelessRequestHookruns before each one.initializenegotiates only among the configured handshake versions, and is -32022 when none is configured. A handshake revision in_metathat the server does not serve is -32022.StatelessHTTPServerTransport:data;notifications/cancelledis honored only with the sameAuthorizationheader as exactly one request in flight with that ID;StatefulHTTPServerTransportanswers a non-initializerequest with a statelessMCP-Protocol-Versionheader or_metaversion with 400 -32022, after origin, media type and authentication validation. A refusedinitializeleaves no session.Conformance
Tier score 2026-07-28 server: 26/37.
The 25 server entries left in the 2026-07-28 leg:
http-header-validation,http-custom-header-server-validation: SEP-2243 headers, fixed in P5 ([P5] http: standard and custom request headers at 2026-07-28 (SEP-2243) #366).server-statelesssubscription checks:subscriptions/listen, fixed in P6 ([P6] subscriptions/listen: notification streams at 2026-07-28 (SEP-2575) #365).input-required-result-*: SEP-2322 multi round-trip requests, fixed in P7 ([P7] mrtr: input-required results at 2026-07-28 (SEP-2322) #364).Tests
Tests/MCPTests/StatelessServerTests.swift(new), usingWireExchangefrom P2 ([P2] base: protocol profiles, error data, envelope _meta and result types #369).StatelessServerTests:_meta, -32022 with the served versions, -32601 for removed methods, forserver/discoveron handshake connections and for undeclared capabilities;_metais served as a handshake request;initializenegotiation among the configured versions.Stateless HTTP Tests:_metaagreement; an unknown header version is -32022 with the request ID;Tests/MCPTests/HTTPServerTransportTests.swift: existing stateless transport and handler-context tests read the internal ID fromreceive()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_metais -32022; a server without handshake revisions refusesinitializeand handshake requests; undecodable parameters name the member; aserver/discoverresult with unknown cache hints decodes.Stateful transport and stateless requests: a stateless version in_metaalone is -32022 on a session; the origin check still runs; a refusedinitializeleaves no session.Stateless transport exchanges:notifications/cancelledreaches the request with the same ID andAuthorization; 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 beforeprotocolVersionsdecodes; a configuration round-trips.Review notes
StatelessHTTPServerTransport,Server.currentHandlerContext?.idis the internalmcp-http-<uuid>ID. P6 ([P6] subscriptions/listen: notification streams at 2026-07-28 (SEP-2575) #365) must restore the client'ssubscriptions/listenID forsubscriptionIdin the transport.isDeclaredgates only tools, prompts, resources and completions. Other methods are always allowed.annotatenever overwrites members that the handler set. A handler can return its ownttlMs/cacheScopeor a non-completeresultType. Cache hints apply only to complete results.HTTPResponsechanges are listed indocs/migration.md(P10 ([P10] docs: go-sdk layout, feature guides, design notes and process docs #362)).StatelessHTTPServerTransportcancel a request by closing its HTTP request; the adapter must cancel the task awaitinghandleRequest(_:).notifications/cancelledwithout anAuthorizationheader is ignored, because nothing else tells clients with overlapping request IDs apart.subscriptions/listen(P6 ([P6] subscriptions/listen: notification streams at 2026-07-28 (SEP-2575) #365)), input-required results (P7 ([P7] mrtr: input-required results at 2026-07-28 (SEP-2322) #364)), and the client side of 2026-07-28 (P4 ([P4] client: connect with server/discover at 2026-07-28 #367)).Verification
The
--requirements 2026-07-28leg 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.