Skip to content

[P18] http: the same client on Linux and macOS - #353

Merged
jeanmatthieu merged 5 commits into
rel/1.0.0from
conformance/p18-linux
Nov 25, 2026
Merged

jeanmatthieu merged 5 commits into
rel/1.0.0from
conformance/p18-linux

Conversation

@jeanmatthieu

@jeanmatthieu jeanmatthieu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor
Part P18 of P0–P35, merged into rel/1.0.0 in order (previous: P17 (#354) · next: P19 (#352))
Branch conformance/p18-linux
Base conformance/p17-ci (stacked: GitHub retargets this PR to rel/1.0.0 when the previous part merges)
Commits 3b23e96 http: the same client on Linux and macOS
0810588 http: review fixes
0cc85d5 http: second-pass review fixes
c3113e4 http: take the GET stream's DPoP nonce retry from the authorizer
3217135 http: third-pass review fixes
Size 39 files, +5036 / -3973

Summary

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.

Motivation

P17 (#354) measured Linux (design/linux.md at that commit). Its HTTP client used data(for:): it
read 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:

  • 6 client scenarios failed at 2025-11-25 (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 the
    Swift client differed in interop;
  • on Ubuntu 24.04 (libcurl 8.5) the 2026-07-28 client hung in json-schema-ref-no-deref;
  • Client.listen(_:) and subscribeToResource(uri:) threw at 2026-07-28 over HTTP;
  • the HTTP and OAuth test suites were skipped on Linux, so none of this was tested there.

Those 4 CI jobs were advisory. The README lists Linux as a supported platform.

Changes

HTTP client

Path What
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; id with NUL ignored; retry only as ASCII digits). Two deliberate differences from a browser: an event without data is returned (a priming event carries only an id), and finish() returns an event cut off by the end of the stream. A line over 16 MiB fails the stream. ServerSentEvents adapts any AsyncSequence of bytes
Sources/MCP/Base/Transports/ResponseBody.swift (new) ResponseBody: a response body as an AsyncSequence of bytes, with collect(limit:) and cancel(). Apple platforms: URLSession.bytes(for:). swift-corelibs-foundation has neither bytes(for:) nor per-task delegates, so there a second session with the same configuration and a StreamingSessionDelegate hands each data task's response to its caller and its chunks to its body
HTTPClientTransport.swift One code path: the POST response, the GET stream and resumption read a ResponseBody and parse it with ServerSentEventParser. The #if os(Linux) branches, the "SSE is not supported on Linux" fallback and streamsResponses are removed. The streaming session is invalidated on disconnect()
Client.swift listen(_:), subscribeToResource(uri:) and the background notification stream no longer check streamsResponses
OAuthRedirectGuard.swift On Linux, OAuth requests copy the configuration's httpAdditionalHeaders into the request, as the transport does (URLRequest.addingAdditionalHeaders(of:))
Package.swift, [email protected], Package.resolved eventsource removed
Tests/MCPTests/ServerSentEventParserTests.swift (new) 11 tests: line endings, BOM, comments, multi-line data, id and retry rules, events without data, finish(), the line cap
DEPENDENCY_POLICY.md, docs/src/{migration,quick_start,protocol,client}.src.md, design/subscriptions.md eventsource gone; the Linux limitations removed; a migration note

Tests on Linux

  • Every !os(Linux) and !canImport(FoundationNetworking) test guard is removed (the HTTP
    client, OAuth, DPoP, jwt-bearer and resumption suites); HTTPClientTransportTests.swift and
    OAuthTestScenarios.swift are dedented, hence the size. Only the NetworkTransport tests
    stay Apple-only.
  • MockURLProtocol and IsolatedMockURLProtocol stop calling their client once
    stopLoading() ran, and do not hold their lock during a callback. On corelibs a callback
    after cancellation traps (TaskRegistry), and stopLoading() can run on the work queue a
    callback waits for.
  • The test fixes for fixed sleeps that were too short on a loaded Linux machine moved down the
    stack: MockTransport.waitForSentMessages(count:timeout:) and the 13 client and server tests
    that use it are in P1 ([P1] http: deliver related messages on the request's stream; resume client response streams #370), and the RequestLifecycleTests concurrency-limit poll is in P11 ([P11] fix: request lifecycle, server replies, OAuth hardening #360).

CI

Path What
scripts/ci/jobs The 4 advisory jobs gate. advisory stays for a future known Linux-only failure
.github/workflows/ci.yml Tests and conformance also on swift:6.1-noble; interop also on Linux (swift:6.1-rhel-ubi9, Go and uv from deps-linux.sh); linux-advisory removed; artifact names unique per matrix entry
design/linux.md Rewritten: the results per platform, how the client reads responses, the corelibs behavior the SDK depends on, what differs by design
CLAUDE.md, CONTRIBUTING.md, interop/README.md, scripts/ci/run-jobs.sh Updated

Diagram

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 --> B
Loading

API changes

None. The new types are internal.

Behavior changes

  • Linux: the transport streams responses, opens the GET stream on handshake connections,
    resumes POST streams, and supports listen(_:) and resource subscriptions at 2026-07-28.
  • All platforms: SSE comes from the SDK's parser instead of eventsource. It follows the
    standard; it fails a stream with a line over 16 MiB, and an app that imported EventSource
    through the SDK must now declare it itself (migration guide).
  • Linux: OAuth requests carry the session configuration's httpAdditionalHeaders on the
    request itself; the headers sent are the same as before.

Conformance

Baselines and interop/RESULTS.md unchanged: 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 NetworkTransport tests, in five
runs in a row (three on ubi9, two on noble) with no failure.

Review notes

  • The timeout semantics were checked with a probe on ubi9 and noble before relying on them:
    URLRequest.timeoutInterval is an idle timeout on corelibs too, and the request's value
    wins over the configuration's (design/linux.md).
  • The noble hang from P17 ([P17] ci: one job list for GitHub Actions and Linux at the desk #354) no longer occurs: noble passes every job, so no libcurl floor is
    needed.
  • Two upstream ClientTests tests ("Ping request", "Initialize sends initialized
    notification") 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.
  • Not verified: an actual GitHub Actions run, and native amd64 (only emulated).

Verification

At 3b23e96:

  • macOS: scripts/ci/run-jobs.sh --strict (every job: build and tests, DocC with warnings as
    errors and weave --check, every conformance leg in both modes, tier 100% at 2025-11-25
    and 2026-07-28, interop --check). The branch builds and passes swift test.
  • Linux, scripts/ci-linux.sh --strict all, every job passes:
    • a RHEL UBI 9 Swift 6.1 builder image, arm64;
    • swift:6.1-noble, arm64;
    • swift:6.1-rhel-ubi9 (the GitHub Linux image), arm64;
    • ubi9 under --platform linux/amd64 (x86_64, emulated).
  • Tier on Linux: client 18/18 and server 30/30 at 2025-11-25, client 32/32 and server 37/37
    at 2026-07-28.
  • ci.yml parses.
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 --strict

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.

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

@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

@varun06 varun06 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice, looking good!!

@jeanmatthieu
jeanmatthieu merged commit 2feef2d into rel/1.0.0 Nov 25, 2026
@jeanmatthieu
jeanmatthieu deleted the conformance/p18-linux branch November 25, 2026 12:44
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.

3 participants