Skip to content

[P4] client: connect with server/discover at 2026-07-28 - #367

Merged
jeanmatthieu merged 3 commits into
rel/1.0.0from
conformance/p4-client
Nov 25, 2026
Merged

jeanmatthieu merged 3 commits into
rel/1.0.0from
conformance/p4-client

Conversation

@jeanmatthieu

@jeanmatthieu jeanmatthieu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor
Part P4 of P0–P35, merged into rel/1.0.0 in order (previous: P3 (#368) · next: P5 (#366))
Branch conformance/p4-client
Base conformance/p3-stateless-server (stacked: GitHub retargets this PR to rel/1.0.0 when the previous part merges)
Commits 312076a client: connect with server/discover at 2026-07-28
7043d6e client: review fixes
c2b0abd client: third-pass review fixes
Size 10 files, +1304 / -84

Summary

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; the flip to .automatic happens in P9 (#361) (conformance/p9-flip).

.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.

Motivation

  • SEP-2575 (2026-07-28): connections are stateless. There is no initialize, ping or logging/setLevel; the client names its version, capabilities and identity in each request's _meta, and discovers the server with server/discover.
  • Servers at 2026-07-28 answer protocol errors with HTTP 4xx and a JSON-RPC body. The transport threw a generic error for these (for example MCPError.internalError("Bad request") for 400), so the client could not see -32022 or its data.supported list.
  • Conformance client scenarios request-metadata and json-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.Configuration gains protocolMode (default .handshake), logLevel and discoveryTimeout (default 10 s).
  • New Client.ProtocolMode: .handshake, .automatic, .stateless(String).
  • connect(transport:) dispatches on protocolMode: _initialize() for .handshake, discoverOrInitialize(Version.stateless[0], fallback: true) for .automatic, discoverOrInitialize(version, fallback: false) for .stateless.
  • discoverOrInitialize:
    • sends server/discover with the _meta envelope for the candidate version;
    • with fallback, on MCPError.unsupportedProtocolVersion (-32022), retries once with the first entry of data.supported that is a known stateless revision, even when it equals the requested version;
    • with fallback, calls initialize when 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 within discoveryTimeout;
    • without fallback, uses only the requested version: no retry, and a discover result that does not list it throws -32022;
    • rethrows other errors raised while sending (authorization, 429, 5xx, transport failures).
  • adopt(_:version:) records capabilities, server info, instructions and the version, switches HTTPClientTransport to stateless mode, and synthesizes an Initialize.Result so connect keeps its return type.
  • send(_:) stamps _meta on stateless connections via requestMeta(version:merging:); keys already present in the request's _meta win.
  • ping() sends server/discover on stateless connections.
  • setLoggingLevel(_:) stores the level in configuration.logLevel on stateless connections instead of sending logging/setLevel.
  • notifyRootsChanged() does nothing on stateless connections.
  • serverCapabilities becomes public read-only; new public negotiatedProtocolVersion, serverInfo, isStateless. The private serverVersion is replaced by negotiatedProtocolVersion.

Transports (Sources/MCP/Base/Transports/HTTPClientTransport.swift)

  • MCP-Protocol-Version is taken from the outgoing message's params._meta["io.modelcontextprotocol/protocolVersion"] when present, otherwise from protocolVersion.
  • New useStatelessProtocol(_:): sets the version, clears the session ID, cancels the GET streaming task and releases a pending initial-session-ID wait. Mcp-Session-Id is not sent while stateless.
  • Non-2xx replies other than 401/403 whose JSON body is a JSON-RPC error response for the POSTed request are yielded to the message stream as responses (deliverErrorResponse). On the streaming path the body is read up to 1 MiB first.
  • 2026-07-28 has no stream resumption: a POST response stream that ends before its response fails the request at once with -32603 ("The server closed the response stream without a response"), without the Last-Event-ID GET 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 its MCP-Protocol-Version from the request's _meta.

Fixtures (Sources/MCPConformance/Client/main.swift)

  • conformanceProtocolMode: .handshake when MCP_CONFORMANCE_PROTOCOL_VERSION is a handshake revision, .automatic otherwise (including outside the harness).
  • makeConformanceClient(capabilities:) replaces the direct Client(...) constructions in every scenario.
  • New scenarios: request-metadata (all client capabilities declared, tools/list, tools/call add_numbers) and json-schema-ref-no-deref (tools/list only).

Baselines

  • conformance-baseline.2026-07-28.yml, conformance-baseline.yml regenerated.

Docs

  • README.md: new "Protocol Versions" section with the mode table and a .automatic example.

Review fixes

Client (Sources/MCP/Client/Client.swift)

  • .automatic fell back to initialize on any MCPError from server/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.
  • A server that never answered server/discover left connect waiting forever in .automatic. Configuration.discoveryTimeout (default 10 s, nil waits indefinitely) bounds the wait; on timeout the pending request is removed and the client falls back to initialize. A late answer is ignored. Other requests, and connect as 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. Without fallback, neither happens: it connects at v or throws unsupportedProtocolVersion.
  • Client.Configuration decoding required the new keys, so a configuration encoded before this PR did not decode. Custom init(from:) and encode(to:) give protocolMode, logLevel and discoveryTimeout their defaults when absent and encode a nil timeout explicitly.
  • Fallback decisions are logged at info level.

Transport (Sources/MCP/Base/Transports/HTTPClientTransport.swift)

  • deliverErrorResponse yielded any JSON-RPC response in a non-2xx body, so a result, a placeholder ID, another request's ID or a batch could complete or confuse pending requests. It now delivers only an object with an error, no result, and the POSTed request's ID; anything else, and any reply to a notification, fails with the status error.
  • A 404 with a JSON-RPC error body skipped the session-expiry handling. A 404 now clears the session ID with or without a deliverable error body.
  • A request that named 2026-07-28 in its _meta before useStatelessProtocol(_:) was called (the first server/discover) could be resumed with a GET. Resumption now also checks the request's own _meta version: a revision without sessions fails at once.
  • Each outgoing message is parsed once (OutgoingMessage: request ID, method, _meta version, cancelled request ID) instead of once per field.
  • Status error texts are shared constants (StatusMessage). JSONRPCMessageKind.extractID(from:) becomes package.

Docs

  • README.md: the mode table states that .stateless(version) fails if the server does not serve it, and a paragraph lists when .automatic falls 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"| RE
Loading

API changes

Added

Symbol Notes
Client.ProtocolMode .handshake, .automatic, .stateless(String); Hashable, Codable, Sendable
Client.Configuration.protocolMode default .handshake
Client.Configuration.logLevel LogLevel?, sent in _meta on stateless connections
Client.Configuration.discoveryTimeout Duration?, default 10 s; bounds the .automatic probe
Client.Configuration.init(from:), encode(to:) Decode configurations without the new keys
Client.negotiatedProtocolVersion public private(set) String?
Client.serverInfo public private(set) Server.Info?
Client.isStateless Bool, from Version.profile(for:).usesRequestMeta
HTTPClientTransport.useStatelessProtocol(_:) switches the transport to a stateless revision

Changed

Symbol Change
Client.Configuration.init(strict:protocolMode:logLevel:discoveryTimeout:) three new defaulted parameters; source compatible
Client.Configuration Codable the new keys are optional on decode; JSON saved before this change still decodes
Client.serverCapabilities private to public private(set)

Removed

None.

Behavior changes

  • With the default .handshake mode, Client behaves 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-based MCPError.internalError. Any other body (a result, 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 whose params._meta carries io.modelcontextprotocol/protocolVersion sets the MCP-Protocol-Version header from it. A request whose _meta names a revision without sessions is never resumed.
  • On stateless connections: a response stream that ends early fails its request with -32603 and is not resumed. ping() sends server/discover, setLoggingLevel(_:) sends nothing and changes the _meta log level, notifyRootsChanged() sends nothing, no session ID and no GET stream.
  • .automatic: falls back to initialize on a JSON-RPC error, a handshake-only -32022 list, an HTTP 400/404/405 refusal or a discoveryTimeout expiry; 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 serve v.

Conformance

Baseline entries (server / client), alpha.11:

Leg Before (P3) After (P4)
2025-11-25 0 / 0 0 / 0
2026-07-28 25 / 47 25 / 38
default 51 / 46 51 / 42
  • 2026-07-28 client: request-metadata, json-schema-ref-no-deref, json-schema-2020-12-preservation, http-standard-headers and tools_call pass. In auth/scope-retry-limit and auth/scope-step-up the earlier failures pass and only sep-837-application-type-present remains (OAuth, P8 ([P8] oauth: issuer checks, application_type, AS migration (SEP-2468/837/2352) #363)); auth/authorization-server-migration:sep-837-application-type-present is newly reached and baselined.
  • Tier score 2026-07-28 (stated in the P5 entry as unchanged from this PR): server 26/37, client 11/32.

Tests

  • Tests/MCPTests/ClientStatelessTests.swift:
    • ClientStatelessTests ("Client Stateless Connection Tests"): automatic discovery, fallback to initialize on a handshake-only server, .handshake never sends server/discover, pinned .stateless fails on a server that does not serve it, stateless ping, stateless setLoggingLevel.
    • ClientDiscoveryNegotiationTests: -32022 retried once with a listed stateless version, fallback on method-not-found, fallback when -32022 lists only handshake versions.
    • HTTPClientTransportTests extension: header follows the request _meta version and 4xx JSON-RPC errors are delivered; no session ID in stateless mode. These live in the serialized HTTPClientTransportTests suite because they share MockURLProtocol.
  • 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 on server/discover are rethrown without initialize; HTTP 400, 404 and 405 refusals fall back; an unanswered server/discover falls 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 a nil discovery 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 a result on 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.
  • 691 tests pass.

Review notes

Verification

swift build
swift test
BIN=$(swift build --show-bin-path)
scripts/run-conformance.sh --spec-version 2026-07-28 --mode client --bin-path "$BIN"
scripts/run-conformance.sh --spec-version 2025-11-25 --bin-path "$BIN"
scripts/run-conformance.sh --bin-path "$BIN"
scripts/run-conformance.sh --requirements 2026-07-28 --bin-path "$BIN"

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.

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.
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/p3-stateless-server to rel/1.0.0 November 25, 2026 12:35
@jeanmatthieu
jeanmatthieu dismissed canarik’s stale review November 25, 2026 12:35

The base branch was changed.

@jeanmatthieu
jeanmatthieu merged commit f290e6b into rel/1.0.0 Nov 25, 2026
@jeanmatthieu
jeanmatthieu deleted the conformance/p4-client 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