Skip to content

MCP Swift SDK 1.0.0 - #372

Open
jeanmatthieu wants to merge 308 commits into
mainfrom
rel/1.0.0
Open

jeanmatthieu wants to merge 308 commits into
mainfrom
rel/1.0.0

Conversation

@jeanmatthieu

Copy link
Copy Markdown
Contributor

This draft PR merges rel/1.0.0 into main and becomes the Swift SDK 1.0.0. It is the overview of the release. The work itself is reviewed in 36 stacked PRs, P0 to P35, each with its own description of the design choices behind it. They merge into rel/1.0.0 in order, then this PR merges into main.

What 1.0.0 brings

  • Both protocol eras on one Server and one Client. The stateless 2026-07-28 revision (per-request _meta, server/discover, subscriptions/listen, multi round-trip requests, standard and custom request headers, cache hints) is served next to the initialize-based revisions, 2024-11-05 through 2025-11-25. Servers serve both by default. Clients connect with server/discover and fall back to initialize for older servers. Code that differs per revision reads ProtocolProfile flags.
  • Conformance. Every leg of the MCP conformance harness (@modelcontextprotocol/[email protected]) passes with an empty baseline: 2025-11-25, 2026-07-28 and the default wire, client and server. The tier score is 100% for clients and servers at 2025-11-25 and at 2026-07-28. A formal verification of the framework against an executable model of the specification found further divergences; P35 fixes them.
  • Interop. A matrix runs the Swift client and server against the Go SDK (v1.8.0), the Python SDK (v2.3.0) and the TypeScript SDK (1.32.2, with ext-apps 1.7.5), over stdio and Streamable HTTP, in both eras. interop/RESULTS.md has the results.
  • Extensions. Tasks (SEP-1686 at 2025-11-25, and the io.modelcontextprotocol/tasks extension of SEP-2663 at 2026-07-28), Skills (SEP-2640), Server Cards (SEP-2127) and MCP Apps views (SEP-1865), on the server and the client.
  • Authorization. Issuer checks (RFC 8414, RFC 9207), application_type, authorization server migration, the JWT bearer grant (RFC 7523), token exchange and enterprise-managed authorization (SEP-990, RFC 8693), workload identity, and DPoP-bound tokens (RFC 9449, SEP-1932).
  • A 1.x stability promise. Semantic versioning as VERSIONING.md defines it: every public enum is frozen, extensible or an open type, and an api-breakage CI job compares the public API with the newest release. CHANGELOG.md lists the breaking changes from 0.12, and docs/migration.md shows the before and after code.
  • Platforms. macOS, iOS (built and tested on a simulator in CI), Mac Catalyst, tvOS, watchOS, visionOS, and Linux (glibc and static musl), with the same HTTP client on Linux and macOS.
  • Documentation. Feature guides in docs/, design notes in design/, and a SEP coverage table in ROADMAP.md that marks each SEP Implemented, Partial, Planned or Not applicable, with the reason.

ROADMAP.md lists what is planned after 1.0.0, such as the MCP Apps View-Host bridge.

The PRs, by area

Each area lists the parts a domain expert may want to read first. Every part builds and passes swift test, and every part after P0 is stacked on the one before it, so its diff shows only its own changes.

2026-07-28 stateless protocol

Part
P2 (#369) Protocol profiles, error data, envelope _meta and result types
P3 (#368) Serving 2026-07-28 stateless requests
P4 (#367) The client connects with server/discover
P5 (#366) Standard and custom request headers (SEP-2243)
P6 (#365) subscriptions/listen notification streams (SEP-2575)
P7 (#364) Input-required results, multi round-trip requests (SEP-2322)
P9 (#361) 2026-07-28 becomes the client default

Transports and reliability

Part
P1 (#370) Related messages travel on their request's stream; client response streams resume (2025-11-25)
P11 (#360) Request lifecycle, server replies, OAuth hardening
P18 (#353) The same HTTP client on Linux and macOS
P33 (#338) A client transport dropped without disconnect() is released

Authorization

Part
P8 (#363) Issuer checks, application_type, authorization server migration (SEP-2468, SEP-837, SEP-2352)
P12 (#359) JWT bearer grant, token exchange, enterprise-managed authorization
P13 (#358) DPoP-bound tokens (RFC 9449, SEP-1932)
P14 (#357) Four client auth findings from testing against independent servers

Extensions

Part
P24 (#347) Tasks (SEP-1686, SEP-2663)
P25 (#346) Skills (SEP-2640)
P31 (#340) Server Cards (SEP-2127)
P32 (#339) MCP Apps views (SEP-1865)

Specification features and deprecations

Part
P27 (#344) Tools in sampling requests (SEP-1577)
P28 (#343) A warning for server requests outside a client request (SEP-2260)
P29 (#342) The tool name format (SEP-986)
P30 (#341) Deprecations: roots, sampling, logging and includeContext (SEP-2577, SEP-2596)

Conformance, interop and verification

Part
P0 (#371) The conformance harness pinned, with one leg per revision
P15 (#356) The interop matrix against the Go and Python SDKs
P23 (#348) Conformance harness 0.2.0-alpha.12
P35 (#336) Fixes from a formal verification of the framework

CI and platforms

Part
P17 (#354) One job list for GitHub Actions and a local Linux container
P34 (#337) iOS builds, and the tests on its simulator

API stability and release

Part
P16 (#355) The version bump, later folded into 1.0.0
P19 (#352) An extensibility promise for every public enum
P20 (#351) The 1.0 rough edges
P21 (#350) Stability tooling for 1.x
P22 (#349) The 1.0.0 release notes

Documentation

Part
P10 (#362) Guides, design notes and process documents
P26 (#345) SEP coverage

How it merges

  • The parts merge into rel/1.0.0 in stack order, bottom up: P0 to P8, P10, P9, P11 to P35. Each part needs one approval from a code owner.
  • Every merge is a merge commit, so the commits reviewed in each part, review fixes included, keep their hashes. When a part merges, GitHub deletes its branch and retargets the next part to rel/1.0.0, so no part has to be rebased.
  • The stack does not change after it is opened. Fixes and follow-ups are new PRs against rel/1.0.0.
  • CI runs on this PR each time a part merges. When the last part is in, this PR leaves draft, merges into main with a merge commit, and main is tagged 1.0.0.

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. Two review-fix commits (in P14 and P35) were also written with Gemini, as their Assisted-by trailers say.

With authentication .none(clientID: "") the authorizer registers the
client dynamically (RFC 7591) or uses a Client ID Metadata Document
(SEP-991). When the authorization server offers neither, because it has
no registration_endpoint and CIMD does not apply, OAuthClientRegistrar
returned nil as if no registration were needed. The flow then went on
with the empty client ID: the authorization request carried client_id=
and the server answered invalid_client, an error that does not say the
client needs pre-registered credentials.

OAuthAuthorizationError.registrationInformationRequired already
describes this case ("No supported client registration mechanism was
available; provide pre-registered client credentials") but nothing
threw it. The registrar now throws it when the client ID is empty and
there is no registration endpoint. A pre-registered client ID is still
used as is, and the jwt-bearer grant, which skips registration, is not
affected.

Found by driving the client against the Inspector test server
oauth-cimd-http.json, which turns dynamic registration off, without a
client ID.
OAuthDiscoveryClient.fetchAuthorizationServerMetadata skips a candidate
authorization server that fails URL validation (not https and not an
allowed loopback host) or whose host is a private address. It skipped
them silently: when every candidate was refused, discovery threw
authorizationServerMetadataDiscoveryFailed ("Failed to discover
authorization server metadata"), which reads as if the server serves no
metadata and hides that the client refused the URL before sending any
request.

When no candidate was fetched, discovery now throws the error that
refused the first one: insecureAuthorizationServerEndpoint with the URL,
or privateIPAddressBlocked. When any candidate was fetched, the errors
are unchanged, so the 2025-03-26 fallback, which keys on
authorizationServerMetadataDiscoveryFailed, still runs. The refusal
itself is unchanged.

Found by driving the client against the Inspector test server
oauth-insecure-token-endpoint-http.json, whose issuer is
http://localhost.:8091.
Streamable HTTP: a server that accepts a JSON-RPC notification or
response "MUST return HTTP status code 202 Accepted with no body"
(basic/transports, Sending Messages to the Server). Such a response has
no Content-Type, so HTTPClientTransport.processResponse fell through to
logger.warning("Unexpected content type: "), and every connection to a
compliant server logged a warning, for example after
notifications/initialized.

A 202 now ends the response quietly. A 202 that does carry JSON or SSE
is still read as before, and any other 2xx with an unexpected content
type still logs the warning.

Noticed in the client logs while driving the auth experiments against
the Inspector test servers.
- A Bearer token for a protected resource whose metadata sets
  dpop_bound_access_tokens_required fails with dpopRequired instead of
  being stored. RFC 9728 §2: such a resource always requires DPoP-bound
  tokens, so it would reject every request and the client would
  re-authorize until maxAuthorizationAttempts. Other Bearer answers stay a
  downgrade (RFC 9449 §5). The dpopRequired docs, its message, the
  troubleshooting row and the protocol guide say so.
- The protocol guide's SSRF section says that discovery follows a
  redirect to a loopback host only from a loopback host, and checks each
  hop against the previous one. The code change is in
  conformance/p11-fixes; this line was last changed here, so the guide
  edit would conflict lower in the stack.
- A refresh that returns a Bearer token for a resource requiring DPoP now
  returns false instead of throwing dpopRequired before tokenStorage.clear(),
  so answerChallenge clears the stale token and tries a full grant.
- Keep the 2025-03-26 defaultEndpoints fallback when a synthesized fallback
  origin is loopback HTTP or a private IP, preserving tokenEndpoint overrides
  with client credentials while still validating default endpoints on use.
- Share OAuthURLValidating private-IP/AS helpers and Authorization.resumeWaiters().
- Widen signInOutlastsDiscoveryTimeout to 1 s / 2 s with per-test hosts and a
  suite time limit, and add tests for failed sign-in past the deadline,
  cancelling connect during sign-in, and two refused AS candidates.
- Sync docs in OAuthTokenExchange, OAuthClientRegistrar, design/auth.md, and
  docs/protocol.md.

Assisted-by: Gemini
- A 202 Accepted without JSON or SSE still logs "Unexpected content
  type" when it answers a request, in both processResponse copies: only
  a notification or a response is accepted with 202 (Streamable HTTP,
  Sending Messages to the Server); a request is owed JSON or SSE, and
  without the warning it waits with no hint.
- OAuthDiscoveryFetching requires the reportRefused variant of
  fetchAuthorizationServerMetadata; the variant without it forwards
  reportRefused: true. The old default dropped the flag, so
  MockDiscoveryClient never saw it.
- cancellingConnectDuringSignIn waits on the transport's waiter count
  instead of a fixed 100 ms, and its sign-in ignores cancellation until
  released, so only the discovery timer's cancellation handler
  (stopWaitingForAuthorization) can end the wait.
  failedSignInAfterDeadlineThrows and timeoutAfterSignIn use the 1 s
  timeout and 2 s sign-in of signInOutlastsDiscoveryTimeout, so a slow
  401 cannot beat the timer.
- Tests: a 202 for a request logs the warning; with the mock, a
  2025-03-26 fallback origin is fetched with reportRefused false and
  falls back to default endpoints, and a listed server's refusal is
  thrown; with OAuthURLValidator, private-address resource_metadata,
  token and authorization endpoints are refused before any request.
- Docs: design/auth.md on refused candidates, the refused-origin
  fallback, Bearer answers for a DPoP-required resource, and
  registration errors thrown without a registration endpoint; the
  refreshAccessToken and tokenEndpoint(issuer:) doc comments; the catch
  comment in maybeRegisterClient; registrationInformationRequired in the
  protocol guide.
Adds an interop matrix that runs real clients and servers of the Swift,
Go and Python MCP SDKs against each other, in both protocol eras, over
Streamable HTTP and stdio. The matrix found two bugs in
`HTTPClientTransport`, a connection-limit deadlock and requests that
waited forever after their response stream ended. Both predate this work
and are fixed earlier in the series. In the recorded run, the Swift SDK
passes every cell in which it is the client or the server. The Python
side is pinned by commit and installed from a lock with hashes; a cell
whose client crashed or reported nothing counts as a failure.
- run-interop.sh: limit() forks and runs the command in its own process
  group; on expiry it sends TERM, then KILL, to the group and to every
  descendant, so a Go client (the Go runtime ignores SIGALRM) is stopped
  and a stdio client's server (Foundation's Process gives it a group of
  its own) does not survive. Exit status stays 142 on expiry and
  128+signal otherwise; signals to the limit reach the command.
- Python driver: an exception after connect but before the profile's
  checks finish is reported as a failed "battery" check with exit status
  1, instead of being printed as shutdown noise with exit status 0.
- report.py: an example client with a non-zero exit status is listed in
  the Failures table, so the report no longer says "No failures.".
- The conformance server's build backend (hatchling and its
  dependencies) is pinned with hashes in the Python lock, and the git
  requirement is installed without build isolation or the index.
- Go driver: concurrent-calls also fails on progress for unknown
  interop-c tokens, as the Swift driver does; the Python driver cannot
  observe such tokens, which a comment now says.
- The unsupported-version expectation of the connect profile passes only
  on -32022 or an error that says the protocol version is unsupported or
  not supported, in all three drivers. A substring match on "unsupported"
  also passed on, for example, HTTP 415 Unsupported Media Type.
- session-expired passes only when the call recovers or fails with an
  error saying the session was not found, expired or terminated; any other
  error fails the check. The recorded outcomes of every SDK still pass.
- cleanup also sends TERM to the children of each tracked process. A
  session cell's tracked PID is its subshell; its child, the limit, stops
  the client's process group and tree, so an aborted run no longer leaves
  the client running until the 300 s limit.
- The connect cells that negotiate against the Swift, Python and Go
  stateless servers expect 2026-07-28 (--expect-era stateless). Without an
  expectation, a fallback to the handshake against a server that serves
  2026-07-28 still passed.
- unknown-tool passes on an isError result or -32602 only, and
  unknown-resource on -32602 or -32002 only, in all three drivers. Any
  MCPError passed before, including -32000 and -32001, and the -32603 the
  HTTP transport synthesizes for HTTP 5xx and dropped streams, so a crashed
  server passed. The codes are the spec's (tools, resources error
  handling, 2025-11-25 and 2026-07-28); every SDK's server returns -32602
  or an isError result in the recorded run.
- The Python discover check sends server/discover with send_discover. In a
  pinned 2026-07-28 mode, discover() returns the locally synthesized result
  without a request. The Python and Swift checks also require a non-empty
  supportedVersions.
Names the release that carries the 2026-07-28 work: 0.13.0. The work
breaks source compatibility (`docs/migration.md`), and under the
package's 0.x rules (`VERSIONING.md`) the minor number plays the role of
the major, so the version after 0.12 is 0.13.0. The installation
snippets depend on it with `.upToNextMinor(from: "0.13.0")`, and the
migration guide, roadmap, design notes and dependency policy name the
version instead of "this major version". The package manifest takes
swift-docc-plugin by version instead of its `main` branch. No library
code changes.
- Lower the swift-docc-plugin floor from 1.4.6 to 1.4.0, the oldest
  release that works with current DocC (1.3.0 and earlier pass
  `--index`, which `docc convert` rejects); Package.resolved stays at
  1.4.6, and the dependency policy notes why 1.4.0 is the floor.
- State in the dependency policy that SwiftPM refuses a version-based
  requirement on a package whose manifest has branch- or
  revision-based dependencies, the binding reason for banning them.
- Record the originHash of the current Package.swift in
  Package.resolved. SwiftPM computes it as the SHA-256 of the root
  manifest, so lowering the swift-docc-plugin floor to 1.4.0 left the
  hash of the 1.4.6 manifest. `swift package resolve` does not rewrite
  the hash while the pins are unchanged, so the value is set to the
  checksum SwiftPM computes; the pins are unchanged.
- Say 0.13.0, not 1.x or 1.0.0, in the design overview, in the
  versioning note on the release that serves 2026-07-28, and in the
  migration guide's entry in the docs index.
Lists every CI job once, in `scripts/ci/jobs`, and runs them through
`scripts/ci/run-jobs.sh`, from GitHub Actions and on a Mac, where
`scripts/ci-linux.sh` runs the Linux CI in a container. The first Linux
runs show where Linux falls short of macOS; that gap is recorded in
`design/linux.md` and left for later. Jobs that Linux fails run as
advisory: they report but do not gate.
- ci-linux.sh: --source runs another worktree (one without scripts/ci
  runs `-- <command>`), --build-volume and --seed-from give each worktree
  its own warm build directory copied from a reference volume, --session
  keeps a container up and re-syncs /w each run (only .build kept), and
  `-- <command>` runs any command. A session run is in its own session
  id, so an interrupted run, or what a run leaves behind, is stopped,
  including the test runner swift test starts in its own process group.
- ci-linux.sh: the package caches are a directory on the Mac instead of
  a volume, because a volume can be attached to one running container at
  a time; Go gets -modcacherw since root in the container cannot write
  into read-only directories there.
- ci-linux.sh: a job id that is also a script name (interop, docs) runs
  the job with its arguments from scripts/ci/jobs unless script options
  follow it; `all` accepts --gate/--advisory/--strict after it and
  refuses anything else instead of dropping it.
- ci-linux.sh: conformance and interop results left in the build volume
  by earlier runs are removed before a run, so only its own are copied.
- run-jobs.sh: jobs read /dev/null, not the job list the loop reads.
- ci.yml: the build-test step runs through run-jobs.sh like the others.
- deps-linux.sh: the Node and Go tarballs are checked against their
  published SHA-256 before they are extracted.
- deps-linux.sh, interop.sh: ps is installed for the interop job. The
  time limit of run-interop.sh stops a client's process tree with it, and
  swift:6.1-rhel-ubi9 has no ps.
- report.py: --expect compares row counts, so a duplicated row differs.
- run-interop.sh: the Python SDK clone is refetched when an earlier
  fetch failed and left a repository without a commit.
- design/linux.md: the noble reproduction runs
  conformance-2026-07-28-client; `conformance-2026-07-28` matches no job,
  since run-jobs.sh anchors the pattern to the whole id, and exited 2.
  The summary table names the jobs it covers as `<leg>-*`.
- ci-linux.sh: --clean --session refuses a session that a live run holds
  (`session <name> is busy`) instead of stopping its container and
  removing its lock. The lock owner check is one helper for both places.
- ci-linux.sh: a run with a --build-volume other than the default copies
  its results to .build/linux/<volume>/, so runs in parallel against one
  tree, which need a volume each, do not remove each other's results.
  The volume name is checked like a session name, since it is now a
  directory.
`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.
The package is built without library evolution, so adding a case to a
public enum breaks every exhaustive `switch` in client code. Before 1.0,
each public enum gets one of three promises, written on the type and in
`VERSIONING.md`:
- Require form elicitation for a form elicitation input request: a
  client that declared only URL elicitation now gets -32021 naming
  elicitation.form, at 2026-07-28 and in the handshake bridge. A
  declaration with neither sub-capability still counts as form, as the
  capability decoder reads it.
- Accept an elicitation of a mode the SDK does not know for any client
  that declares elicitation, instead of always refusing it, and name
  only elicitation, without form, in -32021 for a client without it.
- Decode an input response that has a roots, action, content or model
  key but does not decode as that kind as unknown, so a result of a
  later kind that reuses one of these keys no longer fails the
  parameters that carry it.
- Add BearerTokenValidationResult.tokenInfo, the BearerTokenInfo of a
  valid result and nil otherwise, so a result can be read back without
  making its outcome public.
- Decode unknown content blocks and unknown elicitation modes with
  strings as written (Value.Preserved), so a data: URL string inside
  one is forwarded byte for byte instead of as a base64 data: URL.
- Document on OAuthAuthorizationError's pattern operators and in the
  migration guide that a pattern built with values compiles and
  matches by code only; compare statusCode or oauthError in a where
  clause. Update the MRTR design note for both behavior changes.
- A 408 or 429 from the token endpoint during a refresh fails the request
  and keeps the stored tokens, as a 5xx or a network error does. Before,
  every 4xx counted as a refusal, so a timed-out or rate-limited refresh
  cleared a valid refresh token and started a new grant (a browser
  prompt for authorization_code). Other 4xx still count as a refusal:
  servers often answer an invalid client with 401 and no error member.
- Keep data: URL strings as written in input requests and responses.
  A plain Value decode turns such a string into .data, which encodes as
  a base64 data: URL, and several conversions went through one:
  InputRequest.params() used Value(_:), so a sampling prompt or an
  elicitation message "data:,hello" reached the client's handler
  rewritten; InputResponse.init(from:) decoded [String: Value] and
  re-encoded it, so a sampling text or a roots name was rewritten before
  the typed result was decoded; the params of an unknown input request,
  an unknown input response and the result of a bridged unknown request
  were kept as .data, not as received. params() now uses
  Value.preservingStrings, a known response decodes from the decoder
  itself (a Value field reads a data: URL once, as for any other type),
  unknown params and responses decode as Value.Preserved, and the
  handshake bridge reads an unknown request's result as Value.Preserved.
  A response built from a client handler's result keeps its strings too,
  so it is sent as the handler returned it.
- Correct UnknownBlock.decode's comment: an unknown block encodes back
  to the same JSON value, not byte for byte (key order and number
  formatting can change).
- Run the end-to-end half of the unknown elicitation mode test at both
  2026-07-28 and through the handshake bridge, and test an input request
  of an unknown method end to end, at both, through the client's handler
  for it.
The breaking API fixes listed in `docs/rough_edges.md`, made before 1.0
freezes the API.
- A 405 to a POST no longer cancels the standalone GET stream: a
  handshake-only server that refuses the sessionless server/discover
  with 405 left the session that followed without its GET stream. The
  GET path keeps its own 405 handling.
- Setting configuration.logLevel after init now changes Client.logLevel,
  which the _meta of stateless requests carries; the later of that and
  setLoggingLevel wins.
- A 404 on the GET stream for a request that carried the session ID
  drops the session, reports isSessionExpired and stops reconnecting,
  as a 404 on a POST does, instead of retrying with the expired session.
- A CancellationError from the authorizer (endpoint check, headers,
  challenge, on POST and GET) is thrown as is instead of wrapped in
  transportError; other authorizer errors stay wrapped.
- The migration guide lists the HTTP client error descriptions that
  changed, instead of saying they are the same.
- HTTPStatusError's debugDescription names the response headers without
  their values, so logging an MCPError no longer prints cookies or
  authentication challenges.
- Document that an application Initialize handler replaces the SDK's
  handshake, so initializeHook and version negotiation do not run.
- The logging server sample captures the server weakly; the strong
  capture kept the server alive through its own handler.
- Update three tests that still destructured callTool's result as a
  tuple, which no longer compiled after callTool returned the result.
- ServerTests: the server-metadata test from main's #258 initializes with
  Version.latestHandshake instead of the deprecated Version.latest.
- OAuthAuthorizationError: the doc example catches the error inside
  MCPError.transportError(_:), as HTTPClientTransport throws it; a bare
  `catch OAuthAuthorizationError.dpopRequired` around connect never matched.
  The migration guide points from its OAuthAuthorizationError section to
  HTTP client errors.
- Migration guide: a transportError is sent on the wire when a server
  handler that calls another server through a Client lets it propagate
  (-32001, "Transport error: ..."), so such handlers translate it.
- HTTPClientTransport: a 404 on the standalone GET stream no longer drops
  the session ID. The next request carries it, gets the 404 the server must
  send for it (2025-11-25 transports, session management), and reports
  HTTPStatusError(isSessionExpired: true) to its caller instead of an
  unrelated 400 for a request without a session.
- Client: connect(transport:) resets logLevel to configuration.logLevel, so a
  reconnect does not carry the previous connection's level in _meta, and a
  handshake reconnect does not report a level the new session never got.
- ServerTests.startKeepsHandlers finishes its stream after ping(), so a
  regression fails the expectation instead of hanging.
design/auth.md described the transport as recognizing a use_dpop_nonce
challenge and failing a second one without calling handleChallenge. The
authorizer now reports the nonce retry in its HTTPChallengeResult, and
the transport asks it before failing a second one.
canarik and others added 9 commits November 30, 2026 01:27
On a 2xx response with Content-Type application/json,
`HTTPClientTransport.processResponse` read the body with
`ResponseBody.collect()`, whose limit defaults to `Int.max`. A server
could send a body of any size, or one that never ends, and the client
kept all of it in memory. The SSE path already fails a line or the
data of an event longer than 16 MiB, and the error body of a 4xx reply
is read up to 1 MiB, so answering with application/json instead of
text/event-stream bypassed the transport's limit.
Fix: an application/json body longer than 16 MiB, the limit of one SSE
event, now fails the request with `internalError` and its download is
cancelled. A `Content-Length` over the limit is refused before the body
is read; otherwise the read stops one byte past the limit. A body of at
most 16 MiB is delivered unchanged. The class documentation, the
migration guide and the threat model say so.

Adds four tests to `HTTPClientTransportTests`: a 40 MiB body, a
Content-Length over the limit, a body one byte over the limit, and a
body of exactly 16 MiB. The first three fail without the fix.
`StdioTransport.send(_:)` writes a message in a loop and, when the pipe
is full, waits 10 ms with `Task.sleep` before it tries again. If the
sending task was cancelled during that wait, `Task.sleep` threw
`CancellationError` and the send returned after writing only part of
the message and no newline. `releaseOutput()` then handed the output to
the next queued send, which wrote its message straight after the
partial bytes. The peer read one line that is not valid JSON and lost
both messages, and a request answered by the second one never
completed. This happens when a peer cancels a request whose handler is
writing a large notification or result.
Fix: once a send has written part of its message, wait between retries
with a sleep that does not end on cancellation, so the send finishes
the line. A send that has written nothing still throws
`CancellationError` and passes the output on, and `disconnect()` still
ends a send that is part-way through a message.

A waiting send is handed the output by `releaseOutput()`, while its
cancellation reaches `cancelSendWaiter(_:)` through a separate task. If
the output was handed over first, the cancelled send wrote its message
anyway, although `send(_:)` documents that it throws.
Fix: `acquireOutput()` checks for cancellation after it is handed the
output, and passes the output on unwritten.

Adds three tests to `StdioTransportTests`: a send cancelled part-way
through a message, a send cancelled before it writes anything, and a
disconnect that ends a cancelled send part-way through a message.

Introduced in 1e61f20 ("Add support for Linux with glibc (#61)").
`searchedByteCount` exists only so tests can check how many bytes the
read loop searched for a newline, but it grows by every received byte
for the life of the transport and was updated with trapping `+=`. On
32-bit watchOS (arm64_32) `Int` is 32 bits, so a transport that has
received 2 GiB overflows the counter, and Swift traps on overflow in
release builds too. Both `StdioTransport` and `NetworkTransport` build
for watchOS.

Use `&+=` at the four sites, so test instrumentation can never crash
production code. The tests send far less than 2 GiB, so their exact
counts are unchanged.

Assisted-by: Claude
The HTTP server transports answered a POST that `Server` reads as a
response with 400 and -32600, while still giving it to `Server`, which
completed its pending request with it. The client saw a refusal for an
answer the server had acted on. `JSONRPCMessageKind` now classifies a
message with a `method`, a readable `id` and a `result` or an `error`
as a response when it decodes as `Response<AnyMethod>`, as `Server`
and `Client` read a single message. Both transports then accept it
with 202 through their `.response` path, and `Server.Batch.Item` hands
such a batch item to the pending request instead of answering -32600.
A message that does not read as a response, such as `"error": 5`,
still gets -32600 with its `id`. `readsAsAnswer` is removed.
`HTTPClientTransport.answeredRequestID` reads the same classifier, so
a server answer with an extra `method` now ends the wait on its
stream.
Two tests in ClientReceiveLoopTerminationTests failed on the Ubuntu 24.04
job of #407, a change to StdioTransport only. The 2-second limit of
outcome(within:) ran out in both. Neither found a wrong result. The tests
that ran alongside took 4.4 to 5.0 seconds each, so the overloaded runner
did not get to the client's work within the limit. The reconnect test
also failed the same way on an unrelated branch's iOS job.

Every wait in the suite for something that must finish now uses one
10-second limit. A passing test returns as soon as the operation does, so
the limit only adds time when a test fails, and the suite's one-minute
time limit still applies. The 200 ms check that a request does not fail
early keeps its short limit.

Assisted-by: Claude
"Cancelling connect during sign-in stops waiting promptly" holds the
server/discover sign-in until release(). Cancelling connect can also
send notifications/cancelled for that request. Its POST gets a 401 as
well, which starts a second sign-in while the first one waits.
SlowSignInAuthorizer kept one continuation, so the second sign-in
replaced the first. The dropped continuation was freed without being
resumed, and the runtime printed SWIFT TASK CONTINUATION MISUSE. The
server/discover POST stayed suspended for the rest of the run.

The mock now keeps every waiting sign-in, and release() resumes them all.

The warning appears in the Linux CI logs. On a 2-CPU Linux container it
showed up in 4 of 4 full test runs, each with a second challenge for
notifications/cancelled. After the change it showed up in none of 6.

Assisted-by: Claude
`connect()` retried by restarting the `NWConnection` it had cancelled.
A cancelled `NWConnection` cannot be restarted and reports no further
state, so `attemptConnection()` waited on its state stream forever and
the retry never completed. A `.waiting` connection was not treated as a
failed attempt and had no timeout, so `connect()` to an unreachable peer
blocked indefinitely and `maxAttempts` never applied.

Each retry now dials a fresh connection to the same endpoint, and a
later `connect()` dials fresh whenever the stored connection has been
started. A `.waiting` connection counts as a failed attempt, so
`maxAttempts` and backoff apply. `disconnect()` stops a `connect()` in
progress and releases its connection; a `connect()` cancelled while its
connection is preparing throws instead of returning success, and a
`.ready` delivered after `disconnect()` no longer marks the transport
connected. A second `connect()` while one is in progress throws instead
of replacing the first one's connection, and the loss handlers no
longer cancel the connection themselves before calling `connect()`.

Adds tests for each case to `NetworkTransportTests`, and records the
behavior change in the migration guide and the changelog.

Co-authored-by: Jean-Matthieu Schaffhauser <[email protected]>
fix: Reject an HTTP request that also has a result or an error
canarik and others added 6 commits November 30, 2026 16:02
fix: search only new bytes for a newline and limit message length
fix: limit JSON response bodies to 16 MiB in the HTTP client
…gn-in continuation (#408)

test: fix two Linux CI flakes: receive loop deadlines and a leaked sign-in continuation
fix: retry NetworkTransport.connect() on a fresh connection
…ge (#407)

fix: finish a cancelled stdio send that has written part of its message
jeanmatthieu added a commit that referenced this pull request Nov 30, 2026
…he deadline

The four sign-in tests in "Discovery timeout over HTTP" set
discoveryTimeout to 1 second and assumed that the server/discover POST
reaches the authorizer before the timeout runs out. On a loaded runner
it can take longer: the discovery timer then finds no authorization in
progress, abandons the probe and connect moves on to initialize. Each
test fails its own way:

- "Cancelling connect during sign-in stops waiting promptly": the timer
  never waits, so authorizationWaiterCount stays 0 (#410, RHEL UBI 9;
  earlier on the iOS simulator)
- "Signing in does not count against the discovery timeout": connects
  at 2025-11-25 instead of 2026-07-28 (twice on #372, RHEL and Ubuntu)
- the other two: initialize is challenged as well

In a 2-CPU RHEL UBI 9 container (scripts/ci-linux.sh --cpus 2) the
first one failed in 2 of 4 full test runs, each time with one sign-in
and no authorized request.

The sign-in now lasts until release(), which the tests call once the
discovery timer waits for it, so it outlasts the deadline whatever the
runner's speed. A sign-in that starts before start + timeout belongs to
server/discover, because initialize is sent only after the timer fires;
an attempt where it started later does not test the timer and is run
again with a longer timeout (1, 4, then 12 seconds), and the test
records an issue when even the longest one is missed. The assertions
are unchanged.

In the same container the four tests passed in 12 of 12 full runs.
With the discovery timer changed to give up instead of waiting for a
sign-in, all four fail. On an idle machine they finish in 1 to 2
seconds, as before.

Assisted-by: Claude
varun06 and others added 2 commits November 30, 2026 12:22
A server can request includeContext: allServers, which asks the client
to share context from every connected MCP server with that one server.
The 2025-11-25 specification soft-deprecates thisServer and allServers,
and servers should use them only when the client declares
sampling.context; SEP-2596 deprecates them.

Add Client.Configuration.maxContextInclusion, default .none. Before a
sampling handler runs, the client lowers a higher includeContext to the
cap. The cap applies in withMethodHandler, so it covers requests at
2025-11-25 and input requests at 2026-07-28, and reads the configuration
when the request arrives. A request without includeContext is unchanged.
Sampling.ContextInclusion becomes Comparable
(none < thisServer < allServers).

The configuration saves the cap; a missing key decodes to .none.

Co-authored-by: Alex Bullitt <[email protected]>
feat: cap the includeContext a sampling handler sees
jeanmatthieu added a commit that referenced this pull request Nov 30, 2026
…very test leg finish

The Conformance (ubuntu-latest, swift:6.1-noble) job failed in most CI
runs of #372 although every conformance leg in it passed. The first leg,
conformance-scripts, installs Node with apt, and archive.ubuntu.com and
security.ubuntu.com refused connections: `apt-get update` only warned
("Some index files failed to download"), and the install that followed
failed with "Unable to locate package curl". The next leg in the same job
installed the same packages a few minutes later.

apt_install in scripts/ci/deps-linux.sh now tries the update and the
install again up to four times, after 15, 30, 45 and 60 seconds, and
fails the job after the fifth attempt.

The test matrix in ci.yml also sets fail-fast: false, as the other
matrices do. Without it, one Linux leg that failed cancelled the two
macOS legs and the other Linux leg, so a single flake hid the results of
three platforms.

Assisted-by: Claude
jeanmatthieu added a commit that referenced this pull request Nov 30, 2026
…ulator

Most failures in the CI runs of #372 and #410 came from the tests, not
from the SDK. Each cause:

- offThreadPool ran blocking work, such as a read() on a pipe, on
  DispatchQueue.global(). On Linux the Swift global executor runs on
  libdispatch's global queues, so those reads held the cooperative
  pool's threads: in about one full run in eight on two CPUs the whole
  process froze for about 30 seconds (a thread dump showed five workers
  blocked in read() and one running every async job), and dozens of
  tests failed on their time limits at once, among them the
  HTTPClientTransportTests.swift:2759 and :2888 failures. It now runs
  each work item on a Thread of its own, as do the two streaming mocks
  that block while they wait. OffThreadPoolTests blocks 24 work items
  until all have started: with the Dispatch queue only 23 started within
  10 seconds on Linux.

- The mock URL protocols checked a "stopped" flag and then called their
  client, so a task cancelled in between was called after it had left
  its session ("Trying to access a behaviour for a task that in not in
  the registry", MockURLProtocol.load()). They also called it from a
  Swift task or a Dispatch thread, while every corelibs URLProtocolClient
  method reads the session's task registry, two dictionaries without a
  lock, as the session's work queue changes it ("Bad pointer dereference
  at 0x10" in URLSession.behaviour(for:)). URLProtocolStop now holds a
  lock across the check and the call, and on Linux makes each call on
  the task's work queue, where corelibs makes its own protocols' calls
  and runs stopLoading(); the queue is internal, so the helper finds it
  with Mirror. A stress test that sends 1000 requests, 50 at a time, on
  one session crashed in 8 of 10 runs with the calls made in place, and
  in none of 10 on the work queue.

- The four sign-in tests of "Discovery timeout over HTTP" assumed the
  server/discover POST reaches the authorizer within the 1-second
  discovery timeout. On a loaded runner it can come later, the timer
  abandons the probe, and connect moves on to initialize. The sign-in
  now lasts until release(); an attempt whose sign-in started after the
  deadline does not test the timer and is run again with a longer
  timeout (1, 4, then 12 seconds). With the timer changed to give up
  instead of waiting for a sign-in, all four fail. They also wait at
  most 30 seconds for connect, then record the attempt's state and
  cancel it, instead of holding the suite.

- Limits that only stop a hang are raised: nextIncoming() in
  StatelessGatingTests from 2 to 30 seconds, and the second-response
  test at HTTPClientTransportTests.swift:2888 from 5 to 30. The 2759 and
  2888 failures now print the outcome; 2759 ("fails promptly") keeps its
  2 seconds.

- testRoundtrip() raced each step against a 10-second Task.sleep of its
  own, and failed with that sleep's CancellationError on the iOS
  simulator when a trivial test took 26.7 seconds to finish. The steps
  now await the client's calls directly, the concurrent ones with async
  let, and the test's .timeLimit is the only limit.

- Every .timeLimit in the suite (59 tests) is 2 minutes instead of 1.
  These limits only stop a hang, and a stall of the simulator alone has
  taken 27 seconds of the minute.

With these and the next commit, 60 of 60 full test runs passed in a
2-CPU RHEL UBI 9 container (scripts/ci-linux.sh --cpus 2), against 23 of
27 before, with four 30-second freezes.

Assisted-by: Claude
canarik and others added 2 commits November 30, 2026 23:07
`OAuthRedirectGuard` follows a discovery redirect to a loopback host
only from a loopback host. The URLs a server names directly were
checked for private IP literals only: the `resource_metadata` URL of a
`WWW-Authenticate` challenge, the `authorization_servers` of the
protected resource metadata, the authorization, token and registration
endpoints of the authorization server metadata, and the token endpoint
in an identity provider's metadata. `isPrivateIPHost` leaves loopback
out because the MCP endpoint itself may be on loopback, so these URLs
could name a loopback host whatever the server that named them.
Fix: `rejectPrivateIP` and `validateAuthorizationServerAndHost` take an
`allowingLoopback` flag, and a URL a server names may be on a loopback
host only when that server is (RFC 9728 section 7.7). The challenge URL
and the listed authorization servers follow the MCP endpoint; the
endpoints in authorization server or identity provider metadata follow
that server. URLs in `endpointOverrides` and the URLs an application
passes to `OAuthTokenExchange` are not affected. The loopback check of
`OAuthRedirectGuard` moves to `OAuthURLValidator.isLoopbackHost`, so
both use the same definition.

Adds tests to `OAuthAuthorizerTests`, `OAuthDiscoveryClientTests`,
`OAuthClientRegistrarTests`, `OAuthURLValidatorTests` and
`OAuthJWTBearerTests`, and updates the protocol guide, `design/auth.md`
and `design/threat_model.md`.
…let every test leg finish

The Conformance (ubuntu-latest, swift:6.1-noble) job failed in most CI
runs of #372 although every conformance leg in it passed. The first leg,
conformance-scripts, installs Node with apt, and archive.ubuntu.com and
security.ubuntu.com refused connections: `apt-get update` only warned
("Some index files failed to download"), and the install that followed
failed with "Unable to locate package curl". The next leg in the same job
installed the same packages a few minutes later.

apt_install in scripts/ci/deps-linux.sh now tries the update and the
install again up to four times, after 15, 30, 45 and 60 seconds, and
fails the job after the fifth attempt.

On dnf, Node 22 comes from nodejs.org, checked against its published
SHA-256 as on apt, when the image's repositories cannot install it. The
UBI 9 x86_64 AppStream mirrors listed the nodejs:22 module without its
packages ("Unable to find a match: nodejs npm"), which failed the
Conformance (swift:6.1-rhel-ubi9) and Interop (ubuntu-latest) jobs
before they ran anything; the arm64 mirrors had them. Run in fresh
images, the script installs the dnf package on arm64 UBI 9, falls back
to nodejs.org on x86_64 UBI 9, and installs from nodejs.org on noble as
before.

The test matrix in ci.yml also sets fail-fast: false, as the other
matrices do. Without it, one Linux leg that failed cancelled the two
macOS legs and the other Linux leg, so a single flake hid the results of
three platforms.

Assisted-by: Claude
jeanmatthieu added a commit that referenced this pull request Nov 30, 2026
…ulator

Most failures in the CI runs of #372 and #410 came from the tests, not
from the SDK. Each cause:

- offThreadPool ran blocking work, such as a read() on a pipe, on
  DispatchQueue.global(). On Linux the Swift global executor runs on
  libdispatch's global queues, so those reads held the cooperative
  pool's threads: in about one full run in eight on two CPUs the whole
  process froze for about 30 seconds (a thread dump showed five workers
  blocked in read() and one running every async job), and dozens of
  tests failed on their time limits at once, among them the
  HTTPClientTransportTests.swift:2759 and :2888 failures. It now runs
  each work item on a Thread of its own, as do the two streaming mocks
  that block while they wait. OffThreadPoolTests blocks 24 work items
  until all have started: with the Dispatch queue only 23 started within
  10 seconds on Linux.

- The mock URL protocols checked a "stopped" flag and then called their
  client, so a task cancelled in between was called after it had left
  its session ("Trying to access a behaviour for a task that in not in
  the registry", MockURLProtocol.load()). They also called it from a
  Swift task or a Dispatch thread, while every corelibs URLProtocolClient
  method reads the session's task registry, two dictionaries without a
  lock, as the session's work queue changes it ("Bad pointer dereference
  at 0x10" in URLSession.behaviour(for:)). URLProtocolStop now holds a
  lock across the check and the call, and on Linux makes each call on
  the task's work queue, where corelibs makes its own protocols' calls
  and runs stopLoading(); the queue is internal, so the helper finds it
  with Mirror. A stress test that sends 1000 requests, 50 at a time, on
  one session crashed in 8 of 10 runs with the calls made in place, and
  in none of 10 on the work queue.

- The four sign-in tests of "Discovery timeout over HTTP" assumed the
  server/discover POST reaches the authorizer within the 1-second
  discovery timeout. On a loaded runner it can come later, the timer
  abandons the probe, and connect moves on to initialize. The sign-in
  now lasts until release(); an attempt whose sign-in started after the
  deadline does not test the timer and is run again with a longer
  timeout (1, 4, then 12 seconds). With the timer changed to give up
  instead of waiting for a sign-in, all four fail. They also wait at
  most 30 seconds for connect, then record the attempt's state and
  cancel it, instead of holding the suite.

- Limits that only stop a hang are raised: nextIncoming() in
  StatelessGatingTests from 2 to 30 seconds, and the second-response
  test at HTTPClientTransportTests.swift:2888 from 5 to 30. The 2759 and
  2888 failures now print the outcome; 2759 ("fails promptly") keeps its
  2 seconds.

- testRoundtrip() raced each step against a 10-second Task.sleep of its
  own, and failed with that sleep's CancellationError on the iOS
  simulator when a trivial test took 26.7 seconds to finish. The steps
  now await the client's calls directly, the concurrent ones with async
  let, and the test's .timeLimit is the only limit.

- Every .timeLimit in the suite (59 tests) is 2 minutes instead of 1.
  These limits only stop a hang, and a stall of the simulator alone has
  taken 27 seconds of the minute.

With these and the next commit, 60 of 60 full test runs passed in a
2-CPU RHEL UBI 9 container (scripts/ci-linux.sh --cpus 2), against 23 of
27 before, with four 30-second freezes.

Assisted-by: Claude
The previous commit refuses a loopback URL that a remote server names
(resource_metadata, authorization servers, and the endpoints in
authorization server or identity provider metadata), and
OAuthTokenExchange.tokenEndpoint(issuer:) now checks the endpoint it
returns. Releases up to 0.12.x accepted these setups, so upgraders can
hit privateIPAddressBlocked where they did not before.

Add a bullet to the behavior changes of 1.0.0 in CHANGELOG.md, and a
summary row and two Authorization bullets to the migration guide that
point at endpointOverrides. docs/migration.md is regenerated with
scripts/weave.swift.

Assisted-by: Claude
…#412)

fix: apply the redirect loopback rule to OAuth URLs that servers name
…ulator

Most failures in the CI runs of #372 and #410 came from the tests, not
from the SDK. Each cause:

- offThreadPool ran blocking work, such as a read() on a pipe, on
  DispatchQueue.global(). On Linux the Swift global executor runs on
  libdispatch's global queues, so those reads held the cooperative
  pool's threads: in about one full run in eight on two CPUs the whole
  process froze for about 30 seconds (a thread dump showed five workers
  blocked in read() and one running every async job), and dozens of
  tests failed on their time limits at once, among them the
  HTTPClientTransportTests.swift:2759 and :2888 failures. It now runs
  each work item on a Thread of its own, as do the two streaming mocks
  that block while they wait. OffThreadPoolTests blocks 24 work items
  until all have started: with the Dispatch queue only 23 started within
  10 seconds on Linux.

- The mock URL protocols checked a "stopped" flag and then called their
  client, so a task cancelled in between was called after it had left
  its session ("Trying to access a behaviour for a task that in not in
  the registry", MockURLProtocol.load()). They also called it from a
  Swift task or a Dispatch thread, while every corelibs URLProtocolClient
  method reads the session's task registry, two dictionaries without a
  lock, as the session's work queue changes it ("Bad pointer dereference
  at 0x10" in URLSession.behaviour(for:)). URLProtocolStop now holds a
  lock across the check and the call, and on Linux makes each call on
  the task's work queue, where corelibs makes its own protocols' calls
  and runs stopLoading(); the queue is internal, so the helper finds it
  with Mirror. A stress test that sends 1000 requests, 50 at a time, on
  one session crashed in 8 of 10 runs with the calls made in place, and
  in none of 10 on the work queue.

- The four sign-in tests of "Discovery timeout over HTTP" assumed the
  server/discover POST reaches the authorizer within the 1-second
  discovery timeout. On a loaded runner it can come later, the timer
  abandons the probe, and connect moves on to initialize. The sign-in
  now lasts until release(); an attempt whose sign-in started after the
  deadline does not test the timer and is run again with a longer
  timeout (1, 4, then 12 seconds). With the timer changed to give up
  instead of waiting for a sign-in, all four fail. They also wait at
  most 30 seconds for connect, then record the attempt's state and
  cancel it, instead of holding the suite.

- Limits that only stop a hang are raised: nextIncoming() in
  StatelessGatingTests from 2 to 30 seconds, and the second-response
  test at HTTPClientTransportTests.swift:2888 from 5 to 30. The 2759 and
  2888 failures now print the outcome; 2759 ("fails promptly") keeps its
  2 seconds.

- testRoundtrip() raced each step against a 10-second Task.sleep of its
  own, and failed with that sleep's CancellationError on the iOS
  simulator when a trivial test took 26.7 seconds to finish. The steps
  now await the client's calls directly, the concurrent ones with async
  let, and the test's .timeLimit is the only limit.

- Every .timeLimit in the suite (59 tests) is 2 minutes instead of 1.
  These limits only stop a hang, and a stall of the simulator alone has
  taken 27 seconds of the minute.

With these and the next commit, 60 of 60 full test runs passed in a
2-CPU RHEL UBI 9 container (scripts/ci-linux.sh --cpus 2), against 23 of
27 before, with four 30-second freezes.

Assisted-by: Claude
…reaming

Both crash the process on swift-corelibs-foundation (release/6.1) when
a task is cancelled as it finishes or while it starts.

OAuthAuthorizationCodeFlow, without an OAuthAuthorizationDelegate,
crashed with

  SWIFT TASK CONTINUATION MISUSE: data(for:delegate:) tried to resume
  its continuation more than once, throwing ... Code=-999 "cancelled"
  ... https://localhost:8080/oauth/authorize?response_type=code...

perform sends the authorization request on its own no-redirect session
and ended with `defer { noRedirectSession.invalidateAndCancel() }`. A
task's success path calls the completion handler, which resumes the
data(for:) continuation, and only then sets the task to .completed
(_ProtocolClient.urlProtocolDidFinishLoading). The resumed caller can
run the defer in between: cancel() still sees .running, and its failure
path completes the task a second time. The request has always ended
when the defer runs, so the session is now invalidated with
finishTasksAndInvalidate(), as the guarded session of
URLSession.oauthData(for:redirects:validator:) already is. Cancelling
the caller still cancels the request through data(for:)'s own
cancellation handler. A stress run (40,000 authorizations, 12 busy
threads on 8 CPUs, Swift 6.1 on Ubuntu 24.04) crashed in 2 of 2 runs
before the change and in none of 6 after it; with fewer busy threads it
did not crash in 28 runs, so no test in the suite can show it reliably.

HTTPClientTransport crashed with

  FoundationNetworking/TaskRegistry.swift:118: Fatal error: Trying to
  access a behaviour for a task that in not in the registry
  URLSession.behaviour(for:)
  _ProtocolClient.urlProtocol(task:didFailWithError:)
  closure #1 in closure #2 in closure #1 in URLSessionTask.cancel()

StreamingSession, which streams HTTPClientTransport's responses and
ServerCard.fetch's on Linux, took the configuration as given, and
URLSessionConfiguration.ephemeral has an in-memory URLCache. With a
cache, corelibs first looks each request up in it, and a task cancelled
during that lookup can be failed after it has left its session's
registry. The session now copies the configuration and sets urlCache to
nil. MCP requests are never answered from a cache, and a server card is
revalidated with its ETag through fetch(from:ifNoneMatch:session:); on
Linux ServerCard.fetch therefore no longer reads the session's cache.
Apple platforms do not use this session. In 60 full test runs on two
CPUs, with the test fixes of the previous commit, the crash happened 11
times without the change and never in 60 runs with it.

The short-lived OAuth sessions that
URLSession.oauthData(for:redirects:validator:) and
OAuthAuthorizationCodeFlow.perform make on Linux also took the caller's
configuration, cache included, and data(for:) cancels their task when
the calling task is cancelled, so they were open to the same trap. They
now use the same copy without urlCache
(URLSessionConfiguration.withoutURLCache()); OAuth responses are not
meant to be served from a cache anyway.

The interleaving cannot be forced from a test, so the regression tests
check that each of these sessions has no cache: the streaming session
directly, and the OAuth sessions through a URLProtocol that reads the
session of its task. They fail without the change, and the streaming
test also checks that the caller's configuration keeps its own cache.

Assisted-by: Claude
… resume on Linux, apt retries (#410)

fix: CI failures on rel/1.0.0: a stateless test wait, an OAuth double resume on Linux, apt retries
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.

9 participants