Skip to content

[P1] http: deliver related messages on the request's stream; resume client response streams - #370

Merged
jeanmatthieu merged 4 commits into
rel/1.0.0from
conformance/p1-legacy-reliability
Nov 25, 2026
Merged

jeanmatthieu merged 4 commits into
rel/1.0.0from
conformance/p1-legacy-reliability

Conversation

@jeanmatthieu

@jeanmatthieu jeanmatthieu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor
Part P1 of P0–P35, merged into rel/1.0.0 in order (previous: P0 (#371) · next: P2 (#369))
Branch conformance/p1-legacy-reliability
Base conformance/p0-harness (stacked: GitHub retargets this PR to rel/1.0.0 when the previous part merges)
Commits aeebfef http: deliver related messages on the request's stream; resume client response streams
9fd62f4 transports: release parsed bytes in the stdio and network read buffers
0282e47 tests: wait for sent messages instead of sleeping
e64940b http: third-pass review fixes
Size 22 files, +1706 / -121

Summary

A handler can send notifications (progress, log) and server-to-client requests (elicitation, sampling) while it handles a request. These messages now go to the SSE stream of the request being handled, not to the standalone GET stream. This removes a race at 2025-11-25 and makes the 2025-11-25 conformance baseline empty. The PR also fixes three fixture defects that the stricter alpha.11 harness reports.

It also fixes two HTTPClientTransport bugs that predate this work: a deadlock of concurrent calls that wait for server-to-client requests, and requests that waited forever when their response stream ended early.

It also bounds the client's reconnection behavior (clamped retry, backoff on the GET stream), makes disconnect() and notifications/cancelled end in-flight POSTs, sends GET-stream 401/403 to the authorizer, and makes StatefulHTTPServerTransport release disconnected streams and cancelled requests.

Motivation

At 2025-11-25, StatefulHTTPServerTransport sent every notification and server-initiated request on the standalone GET stream. When a tool called elicitation/create, the client could receive the request on the GET stream before or after it expected it on the POST stream. As a result, elicitation-sep1330-enums:elicitation-sep1330-general was flaky. The other 2025-11-25 baseline entries come from the fixtures:

  • resources-list:wire-schema-valid: the template URI was listed as a concrete resource.
  • json-schema-2020-12-preservation: the client fixture had no handler for this scenario.

On the client side, the interop matrix against the Go and Python SDKs (P15 (#356)) found two HTTPClientTransport bugs, both present on main:

  • URLSessionConfiguration.default allows 6 connections per host on Apple platforms. Over HTTP/1.1 each call in flight holds a connection until its response ends, and the GET stream holds one more. A server-to-client request (sampling, elicitation, roots) arrives on one of those streams, and the reply needs a connection of its own, so five concurrent calls that each wait for a reply deadlock.
  • When a POST response stream ended before its response, the transport restarted the GET session stream with the last event ID of any stream. A request whose stream the server could not replay on the GET stream never completed. SEP-1699 resumes the stream itself: a GET with that stream's Last-Event-ID.

Changes

Base types

  • Sources/MCP/Base/Transport.swift: new requirement send(_ data: Data, relatedRequestID: ID?). A default implementation in a protocol extension ignores the ID and calls send(_:), so existing transports compile unchanged.

Server

  • Sources/MCP/Server/Server.swift: notify(_:) passes Server.currentHandlerContext?.id as relatedRequestID. Server-to-client requests capture the same ID when the request is created and pass it to the transport.

Transports

  • Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift:
    • The transport tracks the IDs of client requests that are not yet answered (openRequestIDs). An ID is added when a POST request opens its stream, removed when the response is routed, and cleared on termination.
    • send(_:relatedRequestID:) routes a notification or request that relates to an open request to that request's stream. All other messages go to the standalone GET stream, as before.
    • send(_:) forwards with a nil related ID.
    • A related message sent after the client closed the request stream (SEP-1699) is stored on that stream, so a client that resumes with Last-Event-ID receives it.

Client transport (aeebfef)

  • Sources/MCP/Base/Transports/HTTPClientTransport.swift:
    • defaultConfiguration (new, public): URLSessionConfiguration.default with httpMaximumConnectionsPerHost set to defaultMaximumConnectionsPerHost (64). It is the default of init(configuration:).
    • Per-stream resumption: when a POST's SSE stream ends before the response to its request, the transport waits the stream's retry interval (clamped, see Review fixes), sends a GET with the stream's own Last-Event-ID, and reads until the response arrives, up to 10 times (maxStreamResumptions). Without an event ID, when the server refuses the GET, or after 10 attempts, the request fails with -32603.
    • processSSE reports event IDs, retry values and response IDs through closures, so the GET stream and each POST stream keep their own state. It stops reading a POST stream once that stream's response is delivered.
    • Removed: the cancellation of the GET stream when a POST stream closed without data (activeGETSessionTask).

Fixtures

  • Sources/MCPConformance/Server/main.swift:
    • test://template/{id} moves from resources/list to a new resources/templates/list handler.
    • An unknown resource URI throws MCPError.invalidParams (-32602) instead of returning a text content.
    • An unknown prompt throws MCPError.invalidParams (-32602) instead of invalidRequest (-32600).
  • Sources/MCPConformance/Client/main.swift: new json-schema-2020-12-preservation scenario. It lists the tools and echoes the json_schema_2020_12_tool input schema back through json_schema_echo.

Docs

  • README.md: the custom transport section documents send(_:relatedRequestID:).

Baselines

  • conformance-baseline.2025-11-25.yml: empty.
  • conformance-baseline.yml: the four entries fixed here are removed.
  • conformance-baseline.2026-07-28.yml: regenerated header comment only.

Review fixes

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

  • A server's SSE retry value was used as is: retry: 1 gave a reconnection loop, a huge value a wait that never ended. It is now clamped to 10 ms ... 60 s (retryIntervalBounds) on the GET stream and on response streams.
  • The GET stream reconnected after a fixed wait however often it failed. The wait now doubles after each consecutive failure past the first (a failed connection, or a stream that ends without an event), up to 60 s (reconnectDelay, maxReconnectDelay). A stream that delivers an event resets the count.
  • A request's POST, including a response stream waiting to resume, outlived disconnect() and the request's cancellation. Each request's POST now runs in a task tracked by JSON-RPC ID (inFlightPosts): disconnect() cancels all of them and an outgoing notifications/cancelled cancels the cancelled request's POST.
  • GET streams (standalone and resumption) skipped the authorizer on 401/403. They now go through one openEventStream(lastEventID:) that runs prepareAuthorization, passes a 401 or 403 to handleChallenge and retries the GET, up to maxAuthorizationAttempts.
  • A GET resume answered with 400 repeated the same Last-Event-ID forever. A 400 now clears the last event ID, so the next connection opens a fresh stream.
  • The wait for the first session ID could not time out (its timer raced a continuation nothing resumed), so without a prior POST the GET stream never opened. A timer now fires the signal after sseInitializationTimeout, and a signal that fires before the wait starts is remembered (initialSessionIDSignalled).
  • SSE messages are parsed for their ID only when the caller needs it (until or onResponse).
  • init(configuration:) logs a warning when httpMaximumConnectionsPerHost is 6 or lower.
  • Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift: JSONRPCMessageKind.cancelledRequestID(in:) reads the requestId of notifications/cancelled.

Server transport (Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift)

  • A stream the client disconnected stayed registered, so a new GET got 409. Streams are now registered with a generation (register(_:streamID:), streamGenerations) and unregistered on client disconnect only while they are still the current stream for their ID. Messages for a disconnected stream are still stored for replay.
  • notifications/cancelled left the cancelled request open, with its stream and HTTP context. It now releases the request: the stream closes and the context and routing entry are removed; later related messages go to the GET stream.
  • Resuming the stream of an answered or cancelled request replayed it and then kept it open. It now replays it and closes it.
  • A stream that a new stream for the same ID replaced, such as a resumption while the earlier stream was still open, stayed open with nothing sent on it. register now finishes it (aeebfef).

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

  • A notifications/cancelled that the server processed before the handler task of the cancelled request was registered was lost. The handler ran to completion; with StatefulHTTPServerTransport it ran without its HTTP context, and its messages went to the GET stream. The receive loop now records each request it dispatches (startingRequests), every early return removes the record, and a cancellation that arrives first cancels the task as it registers. Batched requests are not recorded.

Diagram

sequenceDiagram
    participant C as Client
    participant T as StatefulHTTPServerTransport
    participant S as Server handler
    C->>T: POST tools/call id 7
    T->>S: request 7
    S->>T: elicitation/create, related to 7
    T-->>C: SSE event on the POST 7 stream
    C->>T: POST elicitation response
    T->>S: elicitation result
    S->>T: response 7
    T-->>C: response on the POST 7 stream, stream closes
Loading

Before this change, the elicitation/create event went to the standalone GET stream.

Client: a response stream that ends early.

sequenceDiagram
    participant C as HTTPClientTransport
    participant S as Server
    C->>S: POST tools/call (id 7)
    S-->>C: SSE event id e1 (progress)
    S--xC: stream closed, no response
    Note over C: wait the stream's retry interval
    C->>S: GET, Last-Event-ID e1
    S-->>C: replay after e1, response id 7
    Note over C,S: no event ID, or GET refused: id 7 fails with -32603
Loading

API changes

Added

Symbol Notes
Transport.send(_:relatedRequestID:) Protocol requirement with a default implementation that calls send(_:)
StatefulHTTPServerTransport.send(_:relatedRequestID:) Routes related messages to the request's stream
HTTPClientTransport.defaultConfiguration URLSessionConfiguration with 64 connections per host
HTTPClientTransport.defaultMaximumConnectionsPerHost 64

Changed: the default value of HTTPClientTransport.init(configuration:) is defaultConfiguration instead of .default (source compatible). Removed: none. The review fixes add no public API.

Behavior changes

  • With StatefulHTTPServerTransport, a notification or server-to-client request that a handler sends while its request is unanswered arrives on that request's POST SSE stream. Messages sent outside a handler, or after the response, still arrive on the standalone GET stream.
  • Custom transports that do not implement send(_:relatedRequestID:) behave as before.
  • The default HTTP client allows 64 connections per host. A configuration that the caller passes is used as is; one with 6 or fewer connections per host logs a warning.
  • A POST response stream that ends early is resumed with its own Last-Event-ID. A request whose stream cannot be resumed fails with -32603 ("The server closed the response stream without a response or an event ID to resume from", or "The response stream could not be resumed") instead of waiting forever.
  • HTTPClientTransport:
    • a server's retry is clamped to 10 ms ... 60 s; repeated GET stream failures back off up to 60 s;
    • disconnect() ends every POST in flight, including one waiting to resume; sending notifications/cancelled ends the cancelled request's POST, whose send(_:) throws CancellationError;
    • a 401 or 403 on a GET stream goes to the authorizer and the GET is retried;
    • a GET resume refused with 400 is followed by a GET without Last-Event-ID;
    • without a session ID, the GET stream opens after sseInitializationTimeout instead of never.
  • StatefulHTTPServerTransport:
    • a GET stream the client dropped can be opened again (no 409);
    • notifications/cancelled closes the cancelled request's stream; later related messages go to the GET stream;
    • resuming the stream of an answered or cancelled request replays it and ends;
    • a stream that a new stream for the same ID replaces is finished.
  • Server: a notifications/cancelled that arrives before the cancelled request's handler starts cancels the handler, instead of being lost.

Conformance

Leg Before (P0 (#371)) After
2025-11-25 2 / 2 0 / 0
2026-07-28 108 / 47 108 / 47
default 108 / 48 106 / 46

Tier score 2025-11-25 after this PR: client 18/18, server 30/30 (100%).

Tests

  • Tests/MCPTests/HTTPServerTransportTests.swift, StatefulHTTPServerTransportTests:
    • "Related notification is routed to the request's SSE stream": a progress notification and an elicitation/create request arrive on the POST stream and not on the GET stream.
    • "Message related to an answered request goes to the GET stream".
    • "Related message is replayed after the request stream is closed": the message is delivered when the client resumes with Last-Event-ID.
  • ServerHandlerContextTests, "Handler notifications carry the originating request ID": Server.log inside a handler passes the request ID. Outside a handler it passes nil.
  • Tests/MCPTests/Helpers/MockTransport.swift: records relatedRequestIDs in call order.
  • Tests/MCPTests/HTTPClientResumptionTests.swift (new): the response arrives through a GET with the stream's own Last-Event-ID; a stream that carried a notification is still resumed; resumption repeats while the server closes the stream again; without an event ID the request fails; a refused resumption fails the request.
  • Tests/MCPTests/HTTPClientTransportConfigurationTests.swift (new): the default configuration's connection limit.
  • Tests/MCPTests/HTTPClientReliabilityTests.swift (new):
    • HTTPClientRetryBoundsTests: retry clamping, the backoff schedule, reading requestId from notifications/cancelled.
    • HTTPClientConnectionLimitTests: a configuration at 6 connections per host logs a warning; the default does not.
    • HTTPClientReliabilityTests (serialized): disconnect() ends a response stream waiting a server-chosen delay; notifications/cancelled stops reading and resuming the cancelled request's stream; repeated GET failures back off; a 400 on resume is followed by a fresh GET; a 401 on the GET stream and on a resumption GET goes to the authorizer.
  • StatefulHTTPServerTransportTests, stream cleanup: a disconnected GET stream can be opened again; notifications/cancelled closes and releases the request; resuming an answered request's stream replays it and ends; "Resuming a request's stream finishes the stream it replaces".
  • ServerHandlerContextTests, "Handler requests to the client carry the originating request ID".
  • Tests/MCPTests/CancellationTests.swift, "A cancellation that arrives before the handler is registered cancels it".
  • HTTPClientResumptionTests, "The request fails after the most resumptions" (maxStreamResumptions).
  • The client reliability tests wait for the mock's requests or for the transport's log instead of fixed sleeps.
  • 593 tests.

Review notes

Verification

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

Every branch of the stack builds and passes swift test; at this branch, 593 swift-testing tests, all passed (the package has no XCTest cases). 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.

… response streams

A handler can send notifications (progress, log) and server-to-client
requests (elicitation, sampling) while it handles a request. These
messages now go to the SSE stream of the request being handled, not to
the standalone GET stream. This removes a race at 2025-11-25 and makes
the 2025-11-25 conformance baseline empty. It also fixes three fixture
defects that the stricter alpha.11 harness reports.

It also fixes two `HTTPClientTransport` bugs that predate this work: a
deadlock of concurrent calls that wait for server-to-client requests,
and requests that waited forever when their response stream ended early.

It also bounds the client's reconnection behavior (clamped `retry`,
backoff on the GET stream), makes `disconnect()` and
`notifications/cancelled` end in-flight POSTs, sends GET-stream 401/403
to the authorizer, and makes `StatefulHTTPServerTransport` release
disconnected streams and cancelled requests.

A `notifications/cancelled` that `Server` processes before the handler
task of the cancelled request is registered is no longer lost. The
receive loop records each request it dispatches, and a cancellation that
arrives before registration cancels the task as it registers. Before,
the handler ran to completion: with `StatefulHTTPServerTransport` it ran
without its HTTP context, and its messages went to the GET stream.

`StatefulHTTPServerTransport` finishes a stream that a new stream for the
same ID replaces, such as a resumption while the earlier stream is still
open, instead of leaving it open with nothing sent on it.

The client reliability tests wait for the mock's requests or for the
transport's log instead of fixed sleeps. New tests cover a cancellation
that arrives before handler registration, the replaced stream,
`maxStreamResumptions` running out, and the handler's request ID on
server-to-client requests.
StdioTransport.readLoop and NetworkTransport.receiveLoop split messages
with `buffer = buffer[(newlineIndex + 1)...]`. A Data slice keeps the same
storage and only moves startIndex, and the next append grows that storage
in place, so each buffer held every byte received on the connection
(one __DataStorage of 1184 KB after 10k tools/call, 5792 KB after 50k).

After parsing a read, drop the consumed prefix: an empty buffer becomes
Data(), a partial message is copied into fresh storage. A read that
completes no message leaves the buffer alone, so a large message that
arrives over many reads is not copied per read.

Both transports report the span of their buffer's storage in an internal
receiveBufferSpan, and new tests push 2000 and 5000 messages through
StdioTransport and NetworkTransport and check that it stays bounded. Both
tests fail without the fix.
Ten ClientTests answer the client's initialize from a task that sleeps
10 ms and then reads the last message MockTransport sent. On a loaded
machine connect() has not sent initialize after 10 ms, so the task
finds nothing, no response is queued, and connect() waits until the
suite's one-minute time limit. On Linux, in the full suite, all ten
fail on some runs and none on others; alone, the suite passes. Three
ServerTests sleep 200 or 500 ms for the server's reply in the same way.

MockTransport.waitForSentMessages(count:timeout:) waits until the
message was sent, with a deadline, and the thirteen tests use it
instead of the sleep (AGENTS.md: no fixed sleeps for synchronization).
- A response stream whose last resumption is cancelled returns instead
  of failing the request with "The response stream could not be
  resumed". processSSE ends without an error when it reads an event
  after the task was cancelled, so on the last attempt the loop's
  condition failed before its cancellation check and the request got a
  synthetic -32603. The client asked for the cancellation and ignores
  any later response (2025-11-25 basic/utilities/cancellation), and a
  closed transport has no request to fail: resumeResponseStream now
  checks both before it reports a lost stream.
- Test: a request cancelled while its last resumed stream is read
  delivers no message. It fails without the fix.
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/p0-harness to rel/1.0.0 November 25, 2026 12:17
@jeanmatthieu
jeanmatthieu dismissed canarik’s stale review November 25, 2026 12:17

The base branch was changed.

@jeanmatthieu
jeanmatthieu merged commit a3d05ae into rel/1.0.0 Nov 25, 2026
@jeanmatthieu
jeanmatthieu deleted the conformance/p1-legacy-reliability branch November 25, 2026 12:29
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