Skip to content

MCP Swift SDK 1.0.0 - #372

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

jeanmatthieu wants to merge 315 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/conformance@0.2.0-alpha.12) 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.

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.
- HTTPClientTransport: a 404 reports isSessionExpired when the request
  carried Mcp-Session-Id, as HTTPStatusError documents, not when the actor
  still has a session ID. The POST records the header it sent before it
  awaits the reply, so every request in flight on an expired session reports
  the expiry, not only the first reply to arrive (2025-11-25 transports,
  session management: a 404 to a request carrying the session ID ends it).
  The GET stream does the same with the header of the GET it sent.
- HTTPClientTransport: a 404 to a POST that ends the session also stops the
  GET stream, with or without a JSON-RPC error body. Before, the stream
  reconnected without a session ID, its 404 no longer counted as an expiry,
  and it retried until disconnect().
- protocol and troubleshooting guides: a 404 on the GET stream keeps the
  session ID, and the next request reports the expiry; a 404 to a POST stops
  the GET stream.
- client and protocol guides, design notes: connect(transport:) returns a
  Client.ConnectionInfo, whose serverInfo is optional, not an
  Initialize.Result.
- Client.Configuration.logLevel: the doc says that only a change to another
  value sets Client.logLevel; setLoggingLevel(_:) does not change the
  configuration, so assigning the value it already has keeps the level
  setLoggingLevel(_:) set. The test pins that.
- design/auth.md: a CancellationError from the authorizer is thrown as is.
What keeps 1.x stable: one manifest at Swift 6.1, a CI job that fails on
a breaking API change within the major, a doc comment on every public
declaration, libFuzzer on the parsers and the HTTP server transports,
and a threat model. Fuzzing found a leak: every started `Server` was
kept alive; fixed here.
- FuzzStatelessHTTP: the tools/call header set carries Mcp-Param-Region,
  so the tools-call seed reaches its handler instead of being refused
  with -32020; a new tools/list header set does the same for the
  tools-list seed, which lacked MCP-Protocol-Version.
- FuzzSSE copies the parser only at up to 8 offsets named by the input's
  first bytes, not at every byte, which made long lines quadratic; the
  header comment now says what the target does.
- fuzz.sh runs every target when one fails and fails at the end, naming
  the failed targets.
- api-breakage.sh unshallows a shallow clone before choosing the
  baseline and fails with a clear message when it cannot fetch the
  history and tags; outside a git checkout it says it skipped.
- Server registers its notifications/cancelled handler once, not on
  every start, so restarting a server no longer stacks handlers.
- Server.stop() cancels the request handlers still running, and those
  about to start, and the shared tools/list schema pass: their
  responses can no longer be sent.
- CONTRIBUTING.md and CLAUDE.md: `scripts/ci-linux.sh fuzz 300` ran the
  `fuzz` job with its default 60 s, because `fuzz` is a job id and `300`
  became a second id pattern. They run the job as is, or
  `scripts/ci-linux.sh -- scripts/ci/fuzz.sh <seconds>` for longer runs.
- api-breakage.sh: the default baseline is the newest release whatever
  major version HEAD develops, so a pull request that starts the next major
  version sets the job line to `api-breakage none` (or a ref) until X.0.0 is
  tagged. The message without a tag no longer says "1.x".
Server.stop() reset the per-connection request state but kept the
handshake: isInitialized, the client info and capabilities, the
negotiated protocol version and whether the connection served a
stateless request. A stopped and restarted server answered the next
handshake client's `initialize` with -32600 "Server is already
initialized", and would otherwise have reported the previous client's
info and capabilities. A handshake is per connection (2025-11-25
lifecycle, "Initialization"), so stop() now clears that state and the
next connection starts from a fresh `initialize`.

The stop() doc comment now says so. The new ServerLifecycleTests test
restarts a server between two handshake clients with different info and
capabilities; it fails without the fix.
Server.stop() set isInitialized to false and marked the requests not yet
registered as cancelled before it awaited the transport's disconnect(),
and cleared `connection` only afterwards. A request task spawned just
before stop() ran its pre-dispatch checks first: with
Configuration.strict it was refused with -32600 "Server is not
initialized", and the error went out on the transport that was
disconnecting, or on the next connection once start(transport:) had
attached one. A request still waiting for its HTTP context lost its
cancelled mark when the next connection reused its id, and then ran and
answered on that connection. A request to the client sent just before
stop() kept its id in unsentRequests, so its registration task, running
during the disconnect or after a restart, registered a continuation that
stop() had already drained and sent the request on the old transport:
requestSampling, requestElicitation and listRoots never returned.

stop() now increments a connection generation where it cancels the
handlers. The receive loop passes the generation of its connection to
handleRequest and handleBatch, and send(_:) records it for a request to
the client. handleRequest returns without answering when the generation
changed: at entry, in reject before any refusal is sent, after the await
for the HTTP context, and after the handler. handleBatch sends nothing
for a stopped connection. The registration task of a request to the
client fails it with -32603 "Server disconnected", the error stop()
gives the requests it drains. stop() clears startingRequests and
unsentRequests, and a stale request no longer removes entries of
startingRequests or pendingRequestTasks that may belong to the next
connection. stop() clears `connection` before it awaits disconnect(), so
nothing is sent on a transport that is disconnecting.

Three ServerLifecycleTests tests fail without the fix: a request held at
its HTTP context while the server restarts and the next connection
reuses its id; a strict batch whose second call is handled while stop()
disconnects; and requestSampling called while stop() disconnects.
- doc-coverage.swift: the `case` alternative of the declaration pattern
  could never match, because an enum case takes no access modifier, so
  enum cases were never checked. The script now finds the bodies of
  public enums by counting braces outside string literals and comments,
  and checks their `case` lines; the cases of private, internal and
  package enums (`CodingKeys`) and of `switch` statements are not
  checked. The 25 undocumented public cases (MCPError, Value,
  ProgressToken, InputResponse, Elicitation.RequestSchema.SchemaType,
  CreateElicitation.Result.Action, PrivateKeyJWTAssertionError) now
  have doc comments. CONTRIBUTING.md says cases are checked.
- doc-coverage.swift: the walk over attributes took any line ending in
  `)` or `,` within 8 lines below an `@` line for the end of a
  multi-line attribute, so a declaration after one with an attribute,
  such as `public static let b = Foo(rawValue: "b")` after an
  `@available` constant, borrowed that constant's doc comment. A line
  now ends an attribute only when its parentheses balance on the `@`
  line above it.
- fuzz: FuzzStatefulHTTP's only `tools/call` seed was a batch, which
  StatefulHTTPServerTransport refuses with 400 before the server reads
  it. The new seed tools-call.json is a single request; batch.json
  stays for the refusal path. FuzzDecode reuses one decoder and one
  encoder instead of creating them for each of its probes.
canarik and others added 2 commits November 30, 2026 15:54
`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 <jeanmatthieu@apple.com>
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 <abullitt@apple.com>
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
…ycle

Freeze the `Transport` protocol for 1.0 and address transport, HTTP
validation, and server lifecycle edge cases:

- `Transport` 1.0 surface: make `logger` `nonisolated`, replace the
  `send(_:)` requirement and prerelease overloads with
  `send(_:options:)` (`TransportSendOptions`), add six defaulted hooks
  (`didNegotiate(protocolVersion:)`, `abandonRequest(_:)`,
  `authorizationEnd(of:)`, `prepare(servingProtocolVersions:)`,
  `isSessionless`, `httpRequest(for:)`), add `TransportWrapper`, remove
  `HTTPContextProviding`, rename `httpRequestContext(for:)` to
  `httpRequest(for:)` and `updateNegotiatedProtocolVersion(_:)` to
  `didNegotiate(protocolVersion:)`, and enforce lifecycle rules on
  `connect()` / `disconnect()` / `send(_:options:)`.
- Async HTTP request validation: remove `HTTPRequestValidationPipeline`
  and `validationPipeline:`, add `validators:` and `defaultValidators`,
  make `HTTPRequestValidator.validate` and
  `BearerTokenValidator.TokenValidator` `async`, and re-validate on
  `stateGeneration` changes.
- Typed `ID` HTTP routing: route HTTP server messages by typed `ID` so
  numeric `1` and string `"1"` do not collide, and require positive
  `Last-Event-ID` counters (`>= 1`).
- `NetworkTransport` and `StdioTransport`: remove
  `HeartbeatConfiguration`, `BufferConfiguration`, and
  `MCPError.isResourceTemporarilyUnavailable(_:)`; add
  `init(connection:maximumMessageLength:connectionTimeout:reconnection:logger:)`
  with reconnection off by default and clamped timeout and backoff
  durations; stop toggling `O_NONBLOCK` or polling in `StdioTransport`,
  finish stdio streams with `MCPError.transportError` on read errors,
  and avoid per-chunk `fcntl` calls.
- `Server` lifecycle: make `Server.waitUntilCompleted()` `async throws`
  so receive stream errors surface (treating `connectionClosed` and
  `stop()` as normal completion), drain queued `start()`/`stop()` calls
  in FIFO order, and throw `MCPError.internalError` on overlapping
  `start()` calls without disrupting the active run.
- Protocol and wire precision: compare `ID`, progress tokens, method
  names, task IDs/owners, subscription URIs, SEP-2243 request headers
  and JSON body keys, and `RequestState` audiences by exact Unicode
  scalar values; saturate wire integers on 32-bit `Int`; ignore
  `Mcp-Session-Id` on `2026-07-28` replies while preserving `initialize`
  fallback; break `InMemoryTransport` retain cycles on disconnect.
- Update `CHANGELOG.md` and `docs/src/migration.src.md` (re-woven into
  `docs/migration.md`).

Assisted-by: Claude
…edirects

Update the OAuth extension interfaces, resource-key handling, and HTTP
redirect behavior for 1.0:

- OAuth extension points: replace `TokenStorage` / `InMemoryTokenStorage`
  with resource-keyed async throwing `OAuthTokenStorage` /
  `InMemoryOAuthTokenStorage`; drop `AnyObject` from
  `HTTPClientAuthorizer`, `OAuthScopeSelecting`, and
  `OAuthWWWAuthenticateParsing`; replace `prepareAuthorization` and
  `handleChallenge(statusCode:...)` with `prepare(for:session:)` and
  `handleChallenge(_: HTTPAuthorizationChallenge, session:) ->
  HTTPChallengeResult`; remove `validateEndpointSecurity(for:)` (always
  enforced by `HTTPClientTransport` before `prepare` and after
  `requestModifier`); make `HTTPClientTransport.requestModifier` an
  async throwing `inout` closure; widen `tokenRequestFailed(statusCode:)`
  to `Int?` and add structured `OAuthAuthorizationError` codes with
  redacted URLs.
- Canonical resource URIs and token validation (RFC 8707, RFC 3986,
  RFC 9449): canonicalize resource URIs (scheme/host case, default port,
  user info, query, dot segments, percent-encoding, trailing slashes),
  use `Int64` JWT `NumericDate` values, normalize DPoP nonce keys by
  origin, publish `protectedResourceMetadata` and
  `pendingKeyChangeResource` atomically, snapshot them before awaiting
  `tokens.load(for:)`, and validate reloaded and superseded tokens
  against issuer and DPoP key requirements across 401/403/nonce paths.
- HTTP redirects (Fetch/HTTP semantics on Apple and Linux): keep
  `Authorization`, `Proxy-Authorization`, `Cookie`, and `Mcp-Session-Id`
  on the initial origin only (separating credentials from
  `URLSessionConfiguration.httpAdditionalHeaders`); mint fresh `DPoP`
  proofs on same-origin hops; refuse non-`http`/`https`, `https` to
  `http`, remote to loopback/unspecified (including non-canonical IP
  literals), and loopback `http` to non-loopback `http` redirects;
  follow 301/302/303/307/308 only (keeping method/body on 307/308,
  20-hop limit on Linux); fail fast on credential-less 401/403 with
  `protectedResourceMismatch`; and scope session expiry and
  `Mcp-Session-Id` recording to same-origin responses.
- Update `CHANGELOG.md`, `docs/src/migration.src.md` (re-woven into
  `docs/migration.md`), `design/auth.md`, and `design/threat_model.md`.

Assisted-by: Claude
Update `Client` and `Server` request lifecycle APIs and limits for 1.0:

- `Client.withBatch(isolation:body:)` and `Client.Batch`: make
  `withBatch` inherit caller actor isolation and return a `Sendable`
  value, replace `actor Batch` with a `Sendable` `Client.Batch` struct
  backed by `openBatches`, and reject late `addRequest` calls after a
  batch returns or across a reconnect.
- Server-to-client request cancellation (2025-11-25
  basic/utilities/cancellation): withdraw `requestSampling`,
  `requestElicitation`, and `listRoots` on task cancellation via a
  unified `outgoingRequestPhases` state machine (`.unsent`, `.sending`,
  `.withdrawnWhileSending`) that preserves originating stream routing
  and sends `notifications/cancelled` before resuming the caller; keep
  `Server.cancelRequest(_:reason:)` as a deprecated 0.12.1 shim with
  the same phase and routing guards.
- Out-of-band server response caps in `Client`: bound in-flight `ping`
  replies (`incomingPingLimit = 64`) and error refusals
  (`incomingRefusalLimit = 64`) in disjoint pools (combined cap 128) so
  refusal bursts cannot starve `ping` liveness checks and a stalled peer
  cannot accumulate unbounded tasks, build responses without retaining
  incoming request payloads, cancel parked tasks on disconnect while
  sparing a reconnecting custom `Ping` handler, and re-arm overflow
  drop warnings with hysteresis.
- Resource subscriptions and decoding: add public `init(uri:)` on
  `ResourceSubscribe.Parameters` and `ResourceUnsubscribe.Parameters`,
  require `resources.subscribe == true` in strict mode, track handshake
  subscriptions by exact Unicode scalar values (`ExactString`), decode
  unrecognized `Icon.Theme` values as `nil`, preserve `DecodingError`
  coding paths in `Response`, and ignore internal wire generation in
  `TaskSnapshot` equality/hashing.
- Update `CHANGELOG.md` and `docs/src/migration.src.md` (re-woven into
  `docs/migration.md`).

Assisted-by: Claude
Update binary content models, `data:` URL handling, duration
serialization, and task timestamp/polling arithmetic for 1.0:

- `Data`-typed binary content: switch `image` and `audio` cases on
  `Tool.Content`, `Prompt.Message.Content`,
  `Sampling.Message.Content.ContentBlock`, and
  `Sampling.ToolResultContent.ContentBlock` (and `Sampling.Message.Content`
  factories) from base64 `String` to unlabeled `Data`, and replace
  `Resource.Content.text`/`.blob` with `body: Resource.Content.Body`
  (`.text(String)` or `.blob(Data)`). Decode base64 with shared WHATWG
  forgiving-base64 rules (RFC 4648 §4, consistent on Darwin and Linux)
  and keep `@available(*, deprecated)` 0.12.1 forwarding shims.
- `DataURL` and `Value.data` removal: remove `Value.data(mimeType:_:)`
  so every JSON string decodes as `Value.string`, and add `DataURL`
  (RFC 2397) with cached unicode-scalar regex matching, ASCII-only case
  folding, MIME type normalization, and round-trip-safe `Codable`
  encoding; keep deprecated 0.12.1 forwarding shims for
  `Value.dataValue` and the `Data` data-URL helpers.
- Millisecond durations and task timestamps: unify whole-millisecond
  `Duration` encoding/decoding with overflow-safe clamping and lenient
  inbound decoding, encode saved `Client.Configuration` /
  `Client.Configuration.Tasks` durations under `...Ms` keys while still
  decoding legacy keys, clamp `TaskTimestamp.string(from:)` to
  `1970-01-01T00:00:00Z`...`9999-12-31T23:59:59Z` with `0...999` ms,
  and avoid `Int(_: Double)` overflow traps in `TaskManager.waitForChange`
  when `maximumTTL` is `nil` or stored dates are out of range.
- Update `CHANGELOG.md`, `VERSIONING.md`, `docs/src/migration.src.md`,
  `docs/src/server.src.md`, and `docs/src/client.src.md` (re-woven into
  `docs/`).

Assisted-by: Claude
Address review findings and CI timing flakiness on top of the Phase A
1.0 commits:

- Extract `Server.tearDownConnection()` and run it under the stop-waiter
  gate when `Server.start` restarts after a receive stream ended
  naturally without `stop()`, tearing down open subscriptions, task
  observer, in-flight handlers, pending server-to-client requests,
  handshake state, and the previous transport before starting the next
  run. Also check `stopped()` between `transport.prepare` and
  `transport.connect`.
- Compute `NetworkTransport.maxTimeoutDuration` with `Int64(100)` so it
  does not overflow 32-bit `Int` on watchOS `arm64_32`.
- Treat `POLLNVAL` as ready in `DescriptorReadiness.readinessNow()` so
  a closed descriptor fails immediately with `EBADF` in `read`/`write`
  instead of hanging indefinitely in `wait`.
- Guard `writer.close()` against double-closing in `testOneBytePerRead`.
- Document the removal of `NetworkTransport.Heartbeat` in `CHANGELOG.md`
  and `docs/src/migration.src.md` (re-woven into `docs/migration.md`),
  and mention `protectedResourceMismatch` in
  `OAuthAuthorizationError.detail`'s doc comment.
- Harden `TaskLifecycleEdgeTests` and `StdioTransportTests` timing
  bounds under loaded CI runners and the iOS simulator: return early in
  `TaskManager.waitForChange` when `timeout <= .zero`, widen task expiry
  test separation, append directly in `StdioTransport.readLoop`, and use
  a 30s idle-progress / 120s overall cap in `StdioTransportTests.write`.

Assisted-by: Gemini
Assisted-by: Claude
Before 1.0, keeping callable `@available(*, deprecated)` compatibility
shims for removed or superseded 0.12.1 APIs commits the SDK to carrying
those 0.x APIs through the entire 1.x line. Use `@available(*,
unavailable)` tombstones instead so migrating callers receive targeted
compiler diagnostics and fix-its without shipping dead 0.x shims in 1.0.

- Update `AGENTS.md` and `VERSIONING.md` to distinguish post-1.0 minor
  releases (deprecated forwarding shims) from pre-1.0 / major breaking
  changes (clean removal with `@available(*, unavailable)` tombstones
  for prior-release symbols where unambiguous).
- Convert the 17 Phase A `@available(*, deprecated)` 0.12.1 shims to
  `@available(*, unavailable)` tombstones: `Resource.Content.text` and
  `.blob`, the 10 `String`-based `image`/`audio` content factories,
  `Server.cancelRequest(_:reason:)`, `Value.dataValue`, and the three
  `Data` data-URL helpers (`isDataURL(string:)`, `parseDataURL(_:)`,
  `dataURLEncoded(mimeType:)`).
- Add `@available(*, unavailable)` tombstones for removed 0.12.1
  transport and OAuth symbols: `HTTPContextProviding`,
  `StatefulHTTPServerTransport.httpRequestContext(for:)`,
  `StatelessHTTPServerTransport.httpRequestContext(for:)`,
  `HTTPClientTransport.updateNegotiatedProtocolVersion(_:)`,
  `HTTPRequestValidationPipeline`, the `validationPipeline:` server
  transport initializers, `NetworkTransport.HeartbeatConfiguration`,
  `NetworkTransport.BufferConfiguration`, the five-parameter
  `NetworkTransport` initializer, `MCPError.isResourceTemporarilyUnavailable`,
  `TokenStorage`, `InMemoryTokenStorage`, and the superseded
  `HTTPClientAuthorizer` methods (`validateEndpointSecurity`,
  `prepareAuthorization`, `authorizationHeader`, and the old
  `handleChallenge` signature).
- Remove the shim-only unit tests and update `CHANGELOG.md` and
  `docs/src/migration.src.md` (re-woven into `docs/migration.md`).

Assisted-by: Claude
…tent APIs (#413)

feat: finalize 1.0 transport, OAuth, client lifecycle, and binary content APIs
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