Repository navigation
[P4] client: connect with server/discover at 2026-07-28 - #367
Merged
Merged
Conversation
Adds a client side to the stateless 2026-07-28 protocol. `Client` can open a connection with `server/discover` instead of `initialize`, retry once on -32022 with a version the server lists, and fall back to the handshake for older servers. On a stateless connection every request carries the `_meta` envelope (protocol version, client capabilities, client info, log level), and `HTTPClientTransport` drops the session ID and the standalone GET stream. The default remains the `initialize` handshake; a later change makes `.automatic` the default. `.automatic` falls back to `initialize` only when the server answers with a JSON-RPC error, lists only handshake revisions, refuses the request with HTTP 400, 404 or 405, or does not answer within `discoveryTimeout`; other transport errors are rethrown. `.stateless(v)` connects at `v` or throws.
- Clear the negotiated version and the server-learned state at connect, so reconnecting after a 2026-07-28 connection no longer stamps the old stateless _meta on its requests and can fall back to initialize. - Keep only the server/discover exchange inside the discovery do/catch, so an error from the initialize fallback is thrown instead of being handled as a discovery error and sending initialize again. - Close the POST of a timed-out server/discover through a new HTTPClientTransport.cancelRequest(_:), without notifications/cancelled; it stayed open until the server answered or the client disconnected.
- Deliver the JSON-RPC error of a non-2xx reply only on a 4xx other than 401, 403, 408 and 429. A 408, 429 or 5xx with the request's JSON-RPC error, such as the 503 and connectionClosed of a terminated StatelessHTTPServerTransport, now fails the request with the status error, so .automatic rethrows it instead of falling back to initialize, as ProtocolMode.automatic documents. Both the Linux and the Apple response paths share the check.
This was referenced Nov 25, 2026
Merged
Base automatically changed from
conformance/p3-stateless-server
to
rel/1.0.0
November 25, 2026 12:35
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: P3 (#368) · next: P5 (#366))conformance/p4-clientconformance/p3-stateless-server(stacked: GitHub retargets this PR torel/1.0.0when the previous part merges)312076aclient: connect with server/discover at 2026-07-287043d6eclient: review fixesc2b0abdclient: third-pass review fixesSummary
Adds a client side to the stateless 2026-07-28 protocol.
Clientcan open a connection withserver/discoverinstead ofinitialize, retry once on -32022 with a version the server lists, and fall back to the handshake for older servers. On a stateless connection every request carries the_metaenvelope (protocol version, client capabilities, client info, log level), andHTTPClientTransportdrops the session ID and the standalone GET stream. The default remains theinitializehandshake; the flip to.automatichappens in P9 (#361) (conformance/p9-flip)..automaticfalls back toinitializeonly when the server answers with a JSON-RPC error, lists only handshake revisions, refuses the request with HTTP 400, 404 or 405, or does not answer withindiscoveryTimeout; other transport errors are rethrown..stateless(v)connects atvor throws.Motivation
initialize,pingorlogging/setLevel; the client names its version, capabilities and identity in each request's_meta, and discovers the server withserver/discover.MCPError.internalError("Bad request")for 400), so the client could not see -32022 or itsdata.supportedlist.request-metadataandjson-schema-ref-no-deref(SEP-2106) had no handler in the fixture client, and the 2026-07-28 client scenarios ran over the handshake.Changes
Client (
Sources/MCP/Client/Client.swift)Client.ConfigurationgainsprotocolMode(default.handshake),logLevelanddiscoveryTimeout(default 10 s).Client.ProtocolMode:.handshake,.automatic,.stateless(String).connect(transport:)dispatches onprotocolMode:_initialize()for.handshake,discoverOrInitialize(Version.stateless[0], fallback: true)for.automatic,discoverOrInitialize(version, fallback: false)for.stateless.discoverOrInitialize:server/discoverwith the_metaenvelope for the candidate version;fallback, onMCPError.unsupportedProtocolVersion(-32022), retries once with the first entry ofdata.supportedthat is a known stateless revision, even when it equals the requested version;fallback, callsinitializewhen the -32022 list is empty or contains a handshake revision, when the server answers with any other JSON-RPC error, when the discover result lists no stateless revision in common, when the POST is refused with HTTP 400, 404 or 405, or when no answer arrives withindiscoveryTimeout;fallback, uses only the requested version: no retry, and a discover result that does not list it throws -32022;adopt(_:version:)records capabilities, server info, instructions and the version, switchesHTTPClientTransportto stateless mode, and synthesizes anInitialize.Resultsoconnectkeeps its return type.send(_:)stamps_metaon stateless connections viarequestMeta(version:merging:); keys already present in the request's_metawin.ping()sendsserver/discoveron stateless connections.setLoggingLevel(_:)stores the level inconfiguration.logLevelon stateless connections instead of sendinglogging/setLevel.notifyRootsChanged()does nothing on stateless connections.serverCapabilitiesbecomes public read-only; new publicnegotiatedProtocolVersion,serverInfo,isStateless. The privateserverVersionis replaced bynegotiatedProtocolVersion.Transports (
Sources/MCP/Base/Transports/HTTPClientTransport.swift)MCP-Protocol-Versionis taken from the outgoing message'sparams._meta["io.modelcontextprotocol/protocolVersion"]when present, otherwise fromprotocolVersion.useStatelessProtocol(_:): sets the version, clears the session ID, cancels the GET streaming task and releases a pending initial-session-ID wait.Mcp-Session-Idis not sent while stateless.deliverErrorResponse). On the streaming path the body is read up to 1 MiB first.Last-Event-IDGET that P1 ([P1] http: deliver related messages on the request's stream; resume client response streams #370) sends on handshake connections. The resumption GET takes itsMCP-Protocol-Versionfrom the request's_meta.Fixtures (
Sources/MCPConformance/Client/main.swift)conformanceProtocolMode:.handshakewhenMCP_CONFORMANCE_PROTOCOL_VERSIONis a handshake revision,.automaticotherwise (including outside the harness).makeConformanceClient(capabilities:)replaces the directClient(...)constructions in every scenario.request-metadata(all client capabilities declared,tools/list,tools/call add_numbers) andjson-schema-ref-no-deref(tools/listonly).Baselines
conformance-baseline.2026-07-28.yml,conformance-baseline.ymlregenerated.Docs
README.md: new "Protocol Versions" section with the mode table and a.automaticexample.Review fixes
Client (
Sources/MCP/Client/Client.swift).automaticfell back toinitializeon anyMCPErrorfromserver/discover, including errors the transport raised (429, 5xx, authorization failures), so a transient failure or an authorization error silently downgraded the connection. Errors raised while sending are now kept apart from the server's answer (send(_:markingSendFailures:),SendFailure): a JSON-RPC error from the server still falls back; a transport error falls back only when it is an HTTP 400, 404 or 405 refusal (HTTPClientTransport.isSessionlessRefusal(_:), how a handshake-only server refuses a request without a session); anything else is rethrown.server/discoverleftconnectwaiting forever in.automatic.Configuration.discoveryTimeout(default 10 s,nilwaits indefinitely) bounds the wait; on timeout the pending request is removed and the client falls back toinitialize. A late answer is ignored. Other requests, andconnectas a whole, have no timeout..stateless(v)retried on -32022 with another listed version and adopted another stateless version from the discover result, contrary to its documentation. Withoutfallback, neither happens: it connects atvor throwsunsupportedProtocolVersion.Client.Configurationdecoding required the new keys, so a configuration encoded before this PR did not decode. Custominit(from:)andencode(to:)giveprotocolMode,logLevelanddiscoveryTimeouttheir defaults when absent and encode aniltimeout explicitly.Transport (
Sources/MCP/Base/Transports/HTTPClientTransport.swift)deliverErrorResponseyielded any JSON-RPC response in a non-2xx body, so aresult, a placeholder ID, another request's ID or a batch could complete or confuse pending requests. It now delivers only an object with anerror, noresult, and the POSTed request's ID; anything else, and any reply to a notification, fails with the status error._metabeforeuseStatelessProtocol(_:)was called (the firstserver/discover) could be resumed with a GET. Resumption now also checks the request's own_metaversion: a revision without sessions fails at once.OutgoingMessage: request ID, method,_metaversion, cancelled request ID) instead of once per field.StatusMessage).JSONRPCMessageKind.extractID(from:)becomespackage.Docs
README.md: the mode table states that.stateless(version)fails if the server does not serve it, and a paragraph lists when.automaticfalls back and which errors it rethrows.Diagram
flowchart TD C["connect(transport:)"] --> M{protocolMode} M -->|handshake| INIT["initialize"] M -->|automatic or stateless| DISC["server/discover with _meta"] DISC -->|result| S{"stateless version in common?"} S -->|yes| ADOPT["adopt: stateless connection"] S -->|no, automatic| INIT S -->|no, stateless| ERR["throw -32022"] DISC -->|"-32022, automatic, first time, stateless version listed"| RETRY["retry with that version"] RETRY --> DISC DISC -->|"-32022, list empty or has handshake"| FB{automatic?} FB -->|yes| INIT FB -->|no| ERR DISC -->|"other JSON-RPC error, HTTP 400/404/405, or timeout"| OE{automatic?} OE -->|yes| INIT OE -->|no| RE["rethrow"] DISC -->|"other transport error"| REAPI changes
Added
Client.ProtocolMode.handshake,.automatic,.stateless(String);Hashable,Codable,SendableClient.Configuration.protocolMode.handshakeClient.Configuration.logLevelLogLevel?, sent in_metaon stateless connectionsClient.Configuration.discoveryTimeoutDuration?, default 10 s; bounds the.automaticprobeClient.Configuration.init(from:),encode(to:)Client.negotiatedProtocolVersionpublic private(set) String?Client.serverInfopublic private(set) Server.Info?Client.isStatelessBool, fromVersion.profile(for:).usesRequestMetaHTTPClientTransport.useStatelessProtocol(_:)Changed
Client.Configuration.init(strict:protocolMode:logLevel:discoveryTimeout:)Client.ConfigurationCodableClient.serverCapabilitiesprivatetopublic private(set)Removed
None.
Behavior changes
.handshakemode,Clientbehaves as before.HTTPClientTransport, all revisions: a non-2xx reply (except 401/403) whose body is a JSON-RPC error for the POSTed request now completes the pending request with the server's error, instead of failing with a status-basedMCPError.internalError. Any other body (aresult, another ID, a batch, a reply to a notification) still fails with the status error. A 404 clears the session ID in both cases.HTTPClientTransport, all revisions: a message whoseparams._metacarriesio.modelcontextprotocol/protocolVersionsets theMCP-Protocol-Versionheader from it. A request whose_metanames a revision without sessions is never resumed.ping()sendsserver/discover,setLoggingLevel(_:)sends nothing and changes the_metalog level,notifyRootsChanged()sends nothing, no session ID and no GET stream..automatic: falls back toinitializeon a JSON-RPC error, a handshake-only -32022 list, an HTTP 400/404/405 refusal or adiscoveryTimeoutexpiry; rethrows authorization errors, 429, 5xx and other transport failures..stateless(v): never retries with another version and never adopts one; throws -32022 when the server does not servev.Conformance
Baseline entries (server / client), alpha.11:
request-metadata,json-schema-ref-no-deref,json-schema-2020-12-preservation,http-standard-headersandtools_callpass. Inauth/scope-retry-limitandauth/scope-step-upthe earlier failures pass and onlysep-837-application-type-presentremains (OAuth, P8 ([P8] oauth: issuer checks, application_type, AS migration (SEP-2468/837/2352) #363));auth/authorization-server-migration:sep-837-application-type-presentis newly reached and baselined.Tests
Tests/MCPTests/ClientStatelessTests.swift:ClientStatelessTests("Client Stateless Connection Tests"): automatic discovery, fallback toinitializeon a handshake-only server,.handshakenever sendsserver/discover, pinned.statelessfails on a server that does not serve it, statelessping, statelesssetLoggingLevel.ClientDiscoveryNegotiationTests: -32022 retried once with a listed stateless version, fallback on method-not-found, fallback when -32022 lists only handshake versions.HTTPClientTransportTestsextension: header follows the request_metaversion and 4xx JSON-RPC errors are delivered; no session ID in stateless mode. These live in the serializedHTTPClientTransportTestssuite because they shareMockURLProtocol.Tests/MCPTests/HTTPClientResumptionTests.swift: "At 2026-07-28 a stream that ends early fails without a GET"; "A request that names 2026-07-28 in _meta is not resumed before the switch".Tests/MCPTests/ClientConnectionFailureTests.swift(new):AutomaticConnectionFailureTests: a transport error and an authorization failure onserver/discoverare rethrown withoutinitialize; HTTP 400, 404 and 405 refusals fall back; an unansweredserver/discoverfalls back after the timeout and its late answer is ignored; a pinned revision is not retried on -32022 and not replaced by another listed one.ClientConfigurationCodingTests: a configuration encoded before protocol modes decodes; a configuration round-trips, including anildiscovery timeout.OutgoingMessageTests: request fields read in one pass; responses, notifications, cancellations and batches are not requests.HTTPErrorBodyTests: an error with another request's ID and aresulton a non-2xx reply fail with the status; an error for the request is delivered; a notification's non-2xx reply fails; a 404 clears the session ID with or without an error body for the request.Review notes
.automaticonly..stateless(v)connects atvor throws; it neither retries nor adopts another version..automaticmode any JSON-RPC error fromserver/discoverfalls back toinitialize, not only -32601. Errors raised while sending fall back only for HTTP 400, 404 and 405, which is how a handshake-only server refuses a request without a session; recognized by the transport's status error text.adoptfills a missingserverInfowithServer.Info(name: "", version: "")so the synthesizedInitialize.Resultis complete.HTTPClientTransportapplies to every revision, not only 2026-07-28. 401/403 still go through the authentication challenge path. Only an error for the POSTed request's ID is delivered.withBatchdoes not go through the_metastamping insend(_:); fixed in P11 ([P11] fix: request lifecycle, server replies, OAuth hardening #360).subscriptions/listen(P6 ([P6] subscriptions/listen: notification streams at 2026-07-28 (SEP-2575) #365)), MRTR client (P7 ([P7] mrtr: input-required results at 2026-07-28 (SEP-2322) #364)), OAuth (P8 ([P8] oauth: issuer checks, application_type, AS migration (SEP-2468/837/2352) #363)).Verification
Every branch of the stack builds and passes
swift test; at this branch, 691 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.