Repository navigation
[P1] http: deliver related messages on the request's stream; resume client response streams - #370
Merged
Merged
Conversation
… 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.
This was referenced Nov 25, 2026
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: P0 (#371) · next: P2 (#369))conformance/p1-legacy-reliabilityconformance/p0-harness(stacked: GitHub retargets this PR torel/1.0.0when the previous part merges)aeebfefhttp: deliver related messages on the request's stream; resume client response streams9fd62f4transports: release parsed bytes in the stdio and network read buffers0282e47tests: wait for sent messages instead of sleepinge64940bhttp: third-pass review fixesSummary
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
HTTPClientTransportbugs 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), makesdisconnect()andnotifications/cancelledend in-flight POSTs, sends GET-stream 401/403 to the authorizer, and makesStatefulHTTPServerTransportrelease disconnected streams and cancelled requests.Motivation
At 2025-11-25,
StatefulHTTPServerTransportsent every notification and server-initiated request on the standalone GET stream. When a tool calledelicitation/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-generalwas 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
HTTPClientTransportbugs, both present onmain:URLSessionConfiguration.defaultallows 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.Last-Event-ID.Changes
Base types
Sources/MCP/Base/Transport.swift: new requirementsend(_ data: Data, relatedRequestID: ID?). A default implementation in a protocol extension ignores the ID and callssend(_:), so existing transports compile unchanged.Server
Sources/MCP/Server/Server.swift:notify(_:)passesServer.currentHandlerContext?.idasrelatedRequestID. 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: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 anilrelated ID.Last-Event-IDreceives it.Client transport (
aeebfef)Sources/MCP/Base/Transports/HTTPClientTransport.swift:defaultConfiguration(new, public):URLSessionConfiguration.defaultwithhttpMaximumConnectionsPerHostset todefaultMaximumConnectionsPerHost(64). It is the default ofinit(configuration:).retryinterval (clamped, see Review fixes), sends a GET with the stream's ownLast-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.processSSEreports event IDs,retryvalues 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.activeGETSessionTask).Fixtures
Sources/MCPConformance/Server/main.swift:test://template/{id}moves fromresources/listto a newresources/templates/listhandler.MCPError.invalidParams(-32602) instead of returning a text content.MCPError.invalidParams(-32602) instead ofinvalidRequest(-32600).Sources/MCPConformance/Client/main.swift: newjson-schema-2020-12-preservationscenario. It lists the tools and echoes thejson_schema_2020_12_toolinput schema back throughjson_schema_echo.Docs
README.md: the custom transport section documentssend(_: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)retryvalue was used as is:retry: 1gave 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.reconnectDelay,maxReconnectDelay). A stream that delivers an event resets the count.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 outgoingnotifications/cancelledcancels the cancelled request's POST.openEventStream(lastEventID:)that runsprepareAuthorization, passes a 401 or 403 tohandleChallengeand retries the GET, up tomaxAuthorizationAttempts.Last-Event-IDforever. A 400 now clears the last event ID, so the next connection opens a fresh stream.sseInitializationTimeout, and a signal that fires before the wait starts is remembered (initialSessionIDSignalled).untiloronResponse).init(configuration:)logs a warning whenhttpMaximumConnectionsPerHostis 6 or lower.Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift:JSONRPCMessageKind.cancelledRequestID(in:)reads therequestIdofnotifications/cancelled.Server transport (
Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift)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/cancelledleft 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.registernow finishes it (aeebfef).Server (
Sources/MCP/Server/Server.swift,aeebfef)notifications/cancelledthat the server processed before the handler task of the cancelled request was registered was lost. The handler ran to completion; withStatefulHTTPServerTransportit 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 closesBefore this change, the
elicitation/createevent 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 -32603API changes
Added
Transport.send(_:relatedRequestID:)send(_:)StatefulHTTPServerTransport.send(_:relatedRequestID:)HTTPClientTransport.defaultConfigurationURLSessionConfigurationwith 64 connections per hostHTTPClientTransport.defaultMaximumConnectionsPerHost64Changed: the default value of
HTTPClientTransport.init(configuration:)isdefaultConfigurationinstead of.default(source compatible). Removed: none. The review fixes add no public API.Behavior changes
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.send(_:relatedRequestID:)behave as before.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:retryis 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; sendingnotifications/cancelledends the cancelled request's POST, whosesend(_:)throwsCancellationError;Last-Event-ID;sseInitializationTimeoutinstead of never.StatefulHTTPServerTransport:notifications/cancelledcloses the cancelled request's stream; later related messages go to the GET stream;Server: anotifications/cancelledthat arrives before the cancelled request's handler starts cancels the handler, instead of being lost.Conformance
Tier score 2025-11-25 after this PR: client 18/18, server 30/30 (100%).
Tests
Tests/MCPTests/HTTPServerTransportTests.swift,StatefulHTTPServerTransportTests:elicitation/createrequest arrive on the POST stream and not on the GET stream.Last-Event-ID.ServerHandlerContextTests, "Handler notifications carry the originating request ID":Server.loginside a handler passes the request ID. Outside a handler it passesnil.Tests/MCPTests/Helpers/MockTransport.swift: recordsrelatedRequestIDsin call order.Tests/MCPTests/HTTPClientResumptionTests.swift(new): the response arrives through a GET with the stream's ownLast-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:retryclamping, the backoff schedule, readingrequestIdfromnotifications/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/cancelledstops 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/cancelledcloses 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).Review notes
Server.currentHandlerContext. For the stateful transport, that is the client's JSON-RPC ID.Taskstarts, so it reflects the handler that created the request.StatelessHTTPServerTransportkeeps the default implementation in this PR. P3 ([P3] server: serve 2026-07-28 stateless requests #368) adds related-message delivery over SSE to it.auth/2025-03-26-oauth-endpoint-fallbackin the default leg. P8 ([P8] oauth: issuer checks, application_type, AS migration (SEP-2468/837/2352) #363) fixes it.MCP-Protocol-Version,Mcp-Session-Id, the authorization header and the request modifier like the session GET stream; both are built byopenEventStream(lastEventID:)and handle 401/403 challenges like a POST.Verification
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.