Repository navigation
[P18] http: the same client on Linux and macOS - #353
Merged
Merged
Conversation
`HTTPClientTransport` now reads responses the same way on Linux as on Apple platforms: as they arrive, with SSE. On Linux this brings the GET stream, POST stream resumption, server-to-client requests over HTTP and `subscriptions/listen`. The SDK parses `text/event-stream` itself, so the eventsource dependency goes away. Every test suite runs on Linux, and every CI job gates on Linux: all conformance legs, tier 100% at both revisions, and interop matching `interop/RESULTS.md`, on RHEL UBI 9 and Ubuntu 24.04, arm64 and amd64.
- The SSE parser appends data lines in place instead of copying the whole event per line, and caps the data of one event at 16 MiB (EventTooLong), so a many-line event costs linear time and bounded memory. - An event the body ends before its blank line is discarded, as the event-stream algorithm requires, so a cut event is neither delivered truncated nor recorded as the Last-Event-ID to resume from. - The parser releases the line buffer after a line longer than 64 KiB instead of keeping up to 16 MiB of capacity for the stream's life. - An empty `id:` field resets the event ID to resume from, so no stale Last-Event-ID is sent. - A line or event over the 16 MiB limits fails the request at once with a named error instead of resuming, up to ten times, a stream that replays it. - post() and openEventStream() recheck the connection after awaiting the authorizer, and task creation is ordered against disconnect(): a task being created holds the sessions' invalidation until it exists, later ones throw instead of trapping (corelibs) or raising (Apple platforms). connect() after disconnect() builds new sessions. - The streaming delegate records a task that completes before it is registered, so a request started from a cancelled task cannot wait forever for its completion. - The streaming delegate fails a task that reports a second response instead of appending both bodies to one stream. - The GET stream retries a use_dpop_nonce challenge once without counting it as an authorization attempt, as POST does. - The discovery-timeout HTTP test runs on Linux too.
- A resumed response stream that delivers a message resets the count of resumptions: a server that polls (SEP-1699) closes streams that carry progress, so only resumptions in a row without a message count. A new event ID alone is no progress, since each resumption is primed. - A resumption GET that fails to connect is retried within the same count; refusals, authorization failures and a closed transport still fail the request. - Document that the client reopens a background listen stream the server ended with its result, with the same backoff as a failed one (client and protocol guides, design note), and that cancelling a waiting subscribeToResource call ends it and drops the URI it added. The code change is in conformance/p6-listen; these guide lines took their current shape here.
The GET stream exempted one DPoP use_dpop_nonce retry (RFC 9449 §9) from maxAuthorizationAttempts by reading the challenge itself with the default WWW-Authenticate parser. Like the POST path, it now uses the isDPoPNonceRetry of the HTTPChallengeResult the authorizer returns, so an OAuthAuthorizer with a custom challengeParser, or a custom authorizer, decides which retry is free. This removes the transport's isDPoPNonceChallenge helper and the internal Bool overload of handleChallenge(statusCode:headers:endpoint:operationKey:sentAuthorization:session:) that kept the GET stream counting every challenge.
- On swift-corelibs-foundation a response body read from a cancelled task throws `CancellationError` instead of ending early. Its chunks come from an `AsyncThrowingStream`, whose iterator returns `nil` when the reading task is cancelled, so `collect()` passed a cut JSON body on as a message, and a cancelled SSE read ended like a closed stream. The body throws only when the stream itself ended by cancellation (its `onTermination` reason), so a body that ended before the reader was cancelled is still whole. Apple platforms already threw there. - Only a resumed stream that delivers a message under an event ID the client has not seen starts the count of resumptions again. A server that ignores Last-Event-ID and replays the same notification before closing the stream no longer keeps the request waiting forever. - The standalone GET stream drops its Last-Event-ID after a line or event over 16 MiB and reconnects with a fresh stream, as POST streams already skip resuming: a resumption would replay the same event. - Tests: the exact-limit case of the SSE event limit asserts that the event was emitted, and the two-responses mock stops calling its client once the task is stopped, as corelibs traps on a call for a cancelled task.
This was referenced 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: P17 (#354) · next: P19 (#352))conformance/p18-linuxconformance/p17-ci(stacked: GitHub retargets this PR torel/1.0.0when the previous part merges)3b23e96http: the same client on Linux and macOS0810588http: review fixes0cc85d5http: second-pass review fixesc3113e4http: take the GET stream's DPoP nonce retry from the authorizer3217135http: third-pass review fixesSummary
HTTPClientTransportnow reads responses the same way on Linux as on Apple platforms: as theyarrive, with SSE. On Linux this brings the GET stream, POST stream resumption, server-to-client
requests over HTTP and
subscriptions/listen. The SDK parsestext/event-streamitself, sothe eventsource dependency goes away. Every test suite runs on Linux, and every CI job gates
on Linux: all conformance legs, tier 100% at both revisions, and interop matching
interop/RESULTS.md, on RHEL UBI 9 and Ubuntu 24.04, arm64 and amd64.Motivation
P17 (#354) measured Linux (
design/linux.mdat that commit). Its HTTP client useddata(for:): itread a response only once the server ended it, passed an SSE body to the client as a single
message (which the client dropped), and never opened the GET stream. As a result:
tools_call,elicitation-sep1034-client-defaults,sse-retry,auth/scope-step-up,auth/scope-retry-limit,json-schema-2020-12-preservation), the client tier was 13/18, and every HTTP row of theSwift client differed in interop;
json-schema-ref-no-deref;Client.listen(_:)andsubscribeToResource(uri:)threw at 2026-07-28 over HTTP;Those 4 CI jobs were advisory. The README lists Linux as a supported platform.
Changes
HTTP client
Sources/MCP/Base/Transports/ServerSentEvents.swift(new)ServerSentEventParser: the HTML standard's parser, byte by byte (CR, LF or CR LF; a BOM only at the start; comments;idwith NUL ignored;retryonly as ASCII digits). Two deliberate differences from a browser: an event withoutdatais returned (a priming event carries only anid), andfinish()returns an event cut off by the end of the stream. A line over 16 MiB fails the stream.ServerSentEventsadapts anyAsyncSequenceof bytesSources/MCP/Base/Transports/ResponseBody.swift(new)ResponseBody: a response body as anAsyncSequenceof bytes, withcollect(limit:)andcancel(). Apple platforms:URLSession.bytes(for:). swift-corelibs-foundation has neitherbytes(for:)nor per-task delegates, so there a second session with the same configuration and aStreamingSessionDelegatehands each data task's response to its caller and its chunks to its bodyHTTPClientTransport.swiftResponseBodyand parse it withServerSentEventParser. The#if os(Linux)branches, the "SSE is not supported on Linux" fallback andstreamsResponsesare removed. The streaming session is invalidated ondisconnect()Client.swiftlisten(_:),subscribeToResource(uri:)and the background notification stream no longer checkstreamsResponsesOAuthRedirectGuard.swifthttpAdditionalHeadersinto the request, as the transport does (URLRequest.addingAdditionalHeaders(of:))Package.swift,[email protected],Package.resolvedTests/MCPTests/ServerSentEventParserTests.swift(new)idandretryrules, events withoutdata,finish(), the line capDEPENDENCY_POLICY.md,docs/src/{migration,quick_start,protocol,client}.src.md,design/subscriptions.mdTests on Linux
!os(Linux)and!canImport(FoundationNetworking)test guard is removed (the HTTPclient, OAuth, DPoP, jwt-bearer and resumption suites);
HTTPClientTransportTests.swiftandOAuthTestScenarios.swiftare dedented, hence the size. Only theNetworkTransporttestsstay Apple-only.
MockURLProtocolandIsolatedMockURLProtocolstop calling their client oncestopLoading()ran, and do not hold their lock during a callback. On corelibs a callbackafter cancellation traps (
TaskRegistry), andstopLoading()can run on the work queue acallback waits for.
stack:
MockTransport.waitForSentMessages(count:timeout:)and the 13 client and server teststhat use it are in P1 ([P1] http: deliver related messages on the request's stream; resume client response streams #370), and the
RequestLifecycleTestsconcurrency-limit poll is in P11 ([P11] fix: request lifecycle, server replies, OAuth hardening #360).CI
scripts/ci/jobsadvisorystays for a future known Linux-only failure.github/workflows/ci.ymlswift:6.1-noble; interop also on Linux (swift:6.1-rhel-ubi9, Go and uv fromdeps-linux.sh);linux-advisoryremoved; artifact names unique per matrix entrydesign/linux.mdCLAUDE.md,CONTRIBUTING.md,interop/README.md,scripts/ci/run-jobs.shDiagram
flowchart LR T["HTTPClientTransport"] --> B["ResponseBody"] B -->|Apple platforms| A["URLSession.bytes(for:)"] B -->|swift-corelibs-foundation| D["StreamingSessionDelegate data task"] T --> P["ServerSentEventParser"] P --> BAPI changes
None. The new types are internal.
Behavior changes
resumes POST streams, and supports
listen(_:)and resource subscriptions at 2026-07-28.standard; it fails a stream with a line over 16 MiB, and an app that imported
EventSourcethrough the SDK must now declare it itself (migration guide).
httpAdditionalHeaderson therequest itself; the headers sent are the same as before.
Conformance
Baselines and
interop/RESULTS.mdunchanged: Linux now produces exactly the macOS results.Tests
macOS: 871 swift-testing tests (11 new) plus 101 XCTest, three runs in a row with no failure.
Linux: 956 tests (839 at P17 (#354)), the same suite less the 16
NetworkTransporttests, in fiveruns in a row (three on ubi9, two on noble) with no failure.
Review notes
URLRequest.timeoutIntervalis an idle timeout on corelibs too, and the request's valuewins over the configuration's (
design/linux.md).needed.
ClientTeststests ("Ping request", "Initialize sends initializednotification") check nothing: the code under test never sends. They keep their sleep;
fixing them is a separate change. About 100 other upstream sleeps remain; they pass on every
platform measured.
Verification
At
3b23e96:scripts/ci/run-jobs.sh --strict(every job: build and tests, DocC with warnings aserrors and
weave --check, every conformance leg in both modes, tier 100% at 2025-11-25and 2026-07-28,
interop --check). The branch builds and passesswift test.scripts/ci-linux.sh --strict all, every job passes:swift:6.1-noble, arm64;swift:6.1-rhel-ubi9(the GitHub Linux image), arm64;--platform linux/amd64(x86_64, emulated).at 2026-07-28.
ci.ymlparses.scripts/ci-linux.sh --strict all scripts/ci-linux.sh --image swift:6.1-noble --strict all scripts/ci-linux.sh --platform linux/amd64 --job-timeout 90 --strict all export npm_config_registry=https://registry.npmjs.org scripts/ci/run-jobs.sh --strictAI usage disclosure: the changes, the tests, the commit messages and this description were written with Claude Opus 5.5 and reviewed by the authors.