Skip to content

feat: finalize 1.0 transport, OAuth, client lifecycle, and binary content APIs - #413

Open
jeanmatthieu wants to merge 5 commits into
rel/1.0.0from
fix/phase-a
Open

jeanmatthieu wants to merge 5 commits into
rel/1.0.0from
fix/phase-a

Conversation

@jeanmatthieu

Copy link
Copy Markdown
Contributor

Summary

Finalizes the core 1.0 API surface and behavior across transports, OAuth, client/server request lifecycle, and wire/content codecs, organized into four commits (each corresponding to one area of the work):


1. Transport 1.0 protocol, async HTTP validation, and server lifecycle (c6338071)

  • Transport protocol freeze:
    • Transport.logger is nonisolated; receive() is async; send(_:options:) taking TransportSendOptions (relatedRequestID, headers) replaces send(_:) as the protocol requirement (removing prerelease send(_:relatedRequestID:) and send(_:additionalHeaders:)).
    • Adds six defaulted protocol hooks (didNegotiate(protocolVersion:), abandonRequest(_:), authorizationEnd(of:), prepare(servingProtocolVersions:), isSessionless, httpRequest(for:)) and TransportWrapper so wrapping transports forward every hook automatically.
    • Removes HTTPContextProviding; renames httpRequestContext(for:) to httpRequest(for:) on both HTTP server transports and HTTPClientTransport.updateNegotiatedProtocolVersion(_:) to didNegotiate(protocolVersion:).
    • Enforces transport lifecycle contracts (connect() throws when already connected or after disconnect(); sends throw connectionClosed after disconnect or peer close; InMemoryTransport clears pairedTransport on disconnect).
  • Async HTTP request validation: removes HTTPRequestValidationPipeline and validationPipeline: in favor of validators: (defaulting to defaultValidators), makes HTTPRequestValidator.validate, BearerTokenValidator.TokenValidator, and StandardValidationPipeline.validate async, and re-validates across stateGeneration changes.
  • Typed ID HTTP routing & Last-Event-ID: routes HTTP server messages by typed ID so numeric 1 and string "1" stay distinct, and requires positive Last-Event-ID counters (>= 1).
  • NetworkTransport and StdioTransport: removes HeartbeatConfiguration, BufferConfiguration, the old 5-parameter initializer, and MCPError.isResourceTemporarilyUnavailable(_:); adds init(connection:maximumMessageLength:connectionTimeout:reconnection:logger:) with reconnection off by default and clamped timeout/backoff durations; stops toggling O_NONBLOCK or polling in StdioTransport, finishes stdio streams with MCPError.transportError on read errors, and avoids per-chunk fcntl calls.
  • Server lifecycle: makes Server.waitUntilCompleted() async throws (treating connectionClosed and stop() as normal ends while surfacing transport read errors), drains queued start()/stop() calls in FIFO order, and throws MCPError.internalError on overlapping start() calls without disrupting the active run.
  • Exact code-point matching & 32-bit safety: compares ID, ProgressToken, method names, task IDs/owners, subscription URIs, SEP-2243 request headers and JSON body keys, and RequestState audiences by exact Unicode scalar values (ExactString); saturates wire integers on 32-bit Int; ignores Mcp-Session-Id on 2026-07-28 replies while preserving handshake initialize fallback.

2. OAuth 1.0 extension points, canonical resource URIs, and HTTP redirects (fc2ad952)

  • OAuth extension interfaces:
    • Replaces TokenStorage / InMemoryTokenStorage with resource-keyed async throws OAuthTokenStorage / InMemoryOAuthTokenStorage (not class-bound).
    • Drops AnyObject from HTTPClientAuthorizer, OAuthScopeSelecting, and OAuthWWWAuthenticateParsing.
    • Replaces prepareAuthorization(for:session:) with prepare(for:session:) (default no-op; thrown errors fail the request) and handleChallenge(statusCode:...) with handleChallenge(_: HTTPAuthorizationChallenge, session:) -> HTTPChallengeResult; makes didReceiveResponse(headers:for:) async; removes validateEndpointSecurity(for:) because HTTPClientTransport always runs the check before prepare and after requestModifier.
    • Changes HTTPClientTransport.requestModifier to @Sendable (inout URLRequest) async throws -> Void.
    • Widens OAuthAuthorizationError.tokenRequestFailed(statusCode:oauthError:) to Int?, adds structured authorization/registration error codes, and redacts URLs in descriptions.
  • Resource canonicalization & token validation (RFC 8707, RFC 3986, RFC 9449):
    • Canonicalizes resource URIs (scheme/host case, default port, user info, query, dot segments, percent-encoding, trailing slashes; opt-out via custom OAuthMetadataDiscovering).
    • Uses Int64 JWT NumericDate values, normalizes DPoP nonce keys by origin, publishes protectedResourceMetadata and pendingKeyChangeResource atomically, snapshots them before awaiting tokens.load(for:), and validates reloaded and superseded tokens against issuer and DPoP key requirements across 401, 403, and nonce paths.
  • HTTP redirects (consistent Apple and Linux behavior):
    • Keeps Authorization, Proxy-Authorization, Cookie, and Mcp-Session-Id on the initial origin only (separating credentials from URLSessionConfiguration.httpAdditionalHeaders) and mints fresh DPoP proofs per same-origin hop.
    • Refuses non-http/https, https to http, remote to loopback/unspecified (including non-canonical IP literals), and loopback http to non-loopback http hops; follows 301/302/303/307/308 only (keeping method/body on 307/308, 20-hop limit on Linux).
    • Fails fast on credential-less 401/403 with protectedResourceMismatch, and scopes session expiry and Mcp-Session-Id recording to same-origin responses.

3. Client batching, server-request cancellation, and response caps (2e28d6de)

  • Client.withBatch(isolation:body:) and Client.Batch: inherits caller actor isolation (#isolation), returns a Sendable value (@discardableResult), replaces actor Batch with a Sendable struct backed by openBatches, and rejects late addRequest(_:) calls after withBatch returns or across a reconnect.
  • Server-to-client request cancellation (2025-11-25 basic/utilities/cancellation): withdraws 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 awaiting caller. Keeps Server.cancelRequest(_:reason:) as a @available(*, deprecated) 0.12.1 shim with the same phase and routing guards.
  • Out-of-band server response caps in Client: bounds 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; constructs responses before spawning tasks so incoming request payloads are not retained while stalled; cancels parked tasks on disconnect while sparing a reconnecting custom Ping handler; re-arms overflow drop warnings with hysteresis.
  • Subscriptions and wire decoding: adds public init(uri:) on ResourceSubscribe.Parameters and ResourceUnsubscribe.Parameters, enforces resources.subscribe == true in strict mode, tracks handshake subscriptions via ExactString, decodes unrecognized Icon.Theme values as nil, preserves DecodingError coding paths in Response, and ignores internal wire generation in TaskSnapshot equality/hashing.

4. Data-typed binary content, DataURL, and millisecond/timestamp codecs (fcec8b07)

  • Data-typed binary content & Resource.Content.Body: switches 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 replaces Resource.Content.text/.blob with body: Resource.Content.Body (.text(String) or .blob(Data)). Decodes base64 using shared WHATWG forgiving-base64 rules (RFC 4648 §4, consistent on Darwin and Linux) and preserves @available(*, deprecated) 0.12.1 forwarding shims.
  • DataURL and Value.data removal: removes Value.data(mimeType:_:) so every JSON string decodes as Value.string, adds DataURL (RFC 2397) with cached unicode-scalar regex matching, ASCII-only case folding, MIME type normalization, and round-trip-safe Codable encoding, and preserves deprecated 0.12.1 shims for Value.dataValue and the Data data-URL helpers.
  • Millisecond durations & task timestamps: unifies whole-millisecond Duration encoding/decoding with overflow-safe clamping and lenient inbound decoding, encodes saved Client.Configuration / Client.Configuration.Tasks durations under ...Ms keys while still decoding legacy keys, clamps TaskTimestamp.string(from:) to 1970-01-01T00:00:00Z...9999-12-31T23:59:59Z with 0...999 ms, and avoids Int(_: Double) overflow traps in TaskManager.waitForChange when maximumTTL is nil or stored dates are out of range.
  • Documentation: updates CHANGELOG.md, VERSIONING.md, docs/src/migration.src.md, docs/src/server.src.md, docs/src/client.src.md, design/auth.md, and design/threat_model.md (with woven docs/ regenerated via scripts/weave.swift).

Verification

All checks run on fix/phase-a (fcec8b07):

  • macOS swift test: 1961 tests in 163 suites passed (2 pre-existing known issues).
  • Linux scripts/ci-linux.sh build-test (Swift 6.1): 1982 tests passed (3 pre-existing known issues).
  • Documentation: swift package generate-documentation --target MCP --warnings-as-errors, swift scripts/doc-coverage.swift, and swift scripts/weave.swift --check all passed.
  • Conformance (client & server, baselines unchanged):
    • 2025-11-25: 248 client / 84 server passed, 0 failed.
    • 2026-07-28: 408 client / 152 server passed, 0 failed.
    • default: 493 client / 276 server passed, 0 failed.
  • Interop: scripts/run-interop.sh --check matches interop/RESULTS.md.

AI assistance: written by Claude at the author's request, for human review before merge.

…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
@jeanmatthieu
jeanmatthieu requested a review from a team as a code owner December 3, 2026 00:38
@jeanmatthieu jeanmatthieu changed the title feat!: finalize 1.0 transport, OAuth, client lifecycle, and binary content APIs feat: finalize 1.0 transport, OAuth, client lifecycle, and binary content APIs Dec 3, 2026
Under parallel execution of ~2,000 tests on 2-4 vCPU CI runners and the
iOS simulator, cooperative thread pool queuing delays single sleeps by
up to ~10-14s (and 16 MiB pipe transfers past 30s), causing tight
wall-clock bounds in TaskLifecycleEdgeTests and StdioTransportTests to
fail.

- Return early in TaskManager.waitForChange when timeout <= .zero
  (checking cancellation) so already-expired tasks do not poll the store
  or schedule a zero-duration timer wakeup.
- Drop the tight < 5s upper bounds in outOfRangeCreationDateWait,
  foreignNonPositivePollIntervalSleeps, and
  foreignZeroConfiguredPollIntervalSleeps in favor of .timeLimit(.minutes(2)),
  and assert zero store reads for already-expired dates via CountingTaskStore.
- Widen the separation in waitEndsAtExpiry and foreignWaitEndsAtExpiry to a
  120s timeout/poll interval with a < 60s upper bound and .timeLimit(.minutes(2)).
- Append bytes directly via `pendingData.append(contentsOf: buffer[..<bytesRead])`
  in `StdioTransport.readLoop`, avoiding 4,096 temporary `Data` allocations
  per 16 MiB message.
- Switch `StdioTransportTests.write` to a 30s idle-progress deadline
  (resetting on every byte written, capped at 120s overall) and widen the
  16 MiB test `outcome`/`eventually` bounds to 120s so active transfers
  under simulator contention do not hit a 30s wall-clock cutoff while
  stalled readers still time out promptly.

Assisted-by: Gemini
Assisted-by: Claude
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.

1 participant