Repository navigation
feat: finalize 1.0 transport, OAuth, client lifecycle, and binary content APIs - #413
Merged
Merged
Conversation
…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
force-pushed
the
fix/phase-a
branch
from
December 3, 2026 01:35
bc3b5c7 to
fb7bde5
Compare
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
jeanmatthieu
force-pushed
the
fix/phase-a
branch
from
December 3, 2026 07:51
fb7bde5 to
6e7dda6
Compare
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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)Transportprotocol freeze:Transport.loggerisnonisolated;receive()isasync;send(_:options:)takingTransportSendOptions(relatedRequestID,headers) replacessend(_:)as the protocol requirement (removing prereleasesend(_:relatedRequestID:)andsend(_:additionalHeaders:)).didNegotiate(protocolVersion:),abandonRequest(_:),authorizationEnd(of:),prepare(servingProtocolVersions:),isSessionless,httpRequest(for:)) andTransportWrapperso wrapping transports forward every hook automatically.HTTPContextProviding; renameshttpRequestContext(for:)tohttpRequest(for:)on both HTTP server transports andHTTPClientTransport.updateNegotiatedProtocolVersion(_:)todidNegotiate(protocolVersion:).connect()throws when already connected or afterdisconnect(); sends throwconnectionClosedafter disconnect or peer close;InMemoryTransportclearspairedTransporton disconnect).HTTPRequestValidationPipelineandvalidationPipeline:in favor ofvalidators:(defaulting todefaultValidators), makesHTTPRequestValidator.validate,BearerTokenValidator.TokenValidator, andStandardValidationPipeline.validateasync, and re-validates acrossstateGenerationchanges.IDHTTP routing &Last-Event-ID: routes HTTP server messages by typedIDso numeric1and string"1"stay distinct, and requires positiveLast-Event-IDcounters (>= 1).NetworkTransportandStdioTransport: removesHeartbeatConfiguration,BufferConfiguration, the old 5-parameter initializer, andMCPError.isResourceTemporarilyUnavailable(_:); addsinit(connection:maximumMessageLength:connectionTimeout:reconnection:logger:)with reconnection off by default and clamped timeout/backoff durations; stops togglingO_NONBLOCKor polling inStdioTransport, finishes stdio streams withMCPError.transportErroron read errors, and avoids per-chunkfcntlcalls.Serverlifecycle: makesServer.waitUntilCompleted()async throws(treatingconnectionClosedandstop()as normal ends while surfacing transport read errors), drains queuedstart()/stop()calls in FIFO order, and throwsMCPError.internalErroron overlappingstart()calls without disrupting the active run.ID,ProgressToken, method names, task IDs/owners, subscription URIs, SEP-2243 request headers and JSON body keys, andRequestStateaudiences by exact Unicode scalar values (ExactString); saturates wire integers on 32-bitInt; ignoresMcp-Session-Idon2026-07-28replies while preserving handshakeinitializefallback.2. OAuth 1.0 extension points, canonical resource URIs, and HTTP redirects (
fc2ad952)TokenStorage/InMemoryTokenStoragewith resource-keyedasync throwsOAuthTokenStorage/InMemoryOAuthTokenStorage(not class-bound).AnyObjectfromHTTPClientAuthorizer,OAuthScopeSelecting, andOAuthWWWAuthenticateParsing.prepareAuthorization(for:session:)withprepare(for:session:)(default no-op; thrown errors fail the request) andhandleChallenge(statusCode:...)withhandleChallenge(_: HTTPAuthorizationChallenge, session:) -> HTTPChallengeResult; makesdidReceiveResponse(headers:for:)async; removesvalidateEndpointSecurity(for:)becauseHTTPClientTransportalways runs the check beforeprepareand afterrequestModifier.HTTPClientTransport.requestModifierto@Sendable (inout URLRequest) async throws -> Void.OAuthAuthorizationError.tokenRequestFailed(statusCode:oauthError:)toInt?, adds structured authorization/registration error codes, and redacts URLs in descriptions.OAuthMetadataDiscovering).Int64JWTNumericDatevalues, normalizes DPoP nonce keys by origin, publishesprotectedResourceMetadataandpendingKeyChangeResourceatomically, snapshots them before awaitingtokens.load(for:), and validates reloaded and superseded tokens against issuer and DPoP key requirements across 401, 403, and nonce paths.Authorization,Proxy-Authorization,Cookie, andMcp-Session-Idon the initial origin only (separating credentials fromURLSessionConfiguration.httpAdditionalHeaders) and mints freshDPoPproofs per same-origin hop.http/https,httpstohttp, remote to loopback/unspecified (including non-canonical IP literals), and loopbackhttpto non-loopbackhttphops; follows 301/302/303/307/308 only (keeping method/body on 307/308, 20-hop limit on Linux).protectedResourceMismatch, and scopes session expiry andMcp-Session-Idrecording to same-origin responses.3. Client batching, server-request cancellation, and response caps (
2e28d6de)Client.withBatch(isolation:body:)andClient.Batch: inherits caller actor isolation (#isolation), returns aSendablevalue (@discardableResult), replacesactor Batchwith aSendablestruct backed byopenBatches, and rejects lateaddRequest(_:)calls afterwithBatchreturns or across a reconnect.requestSampling,requestElicitation, andlistRootson task cancellation via a unifiedoutgoingRequestPhasesstate machine (.unsent,.sending,.withdrawnWhileSending) that preserves originating stream routing and sendsnotifications/cancelledbefore resuming the awaiting caller. KeepsServer.cancelRequest(_:reason:)as a@available(*, deprecated)0.12.1 shim with the same phase and routing guards.Client: bounds in-flightpingreplies (incomingPingLimit = 64) and error refusals (incomingRefusalLimit = 64) in disjoint pools (combined cap 128) so refusal bursts cannot starvepingliveness 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 customPinghandler; re-arms overflow drop warnings with hysteresis.init(uri:)onResourceSubscribe.ParametersandResourceUnsubscribe.Parameters, enforcesresources.subscribe == truein strict mode, tracks handshake subscriptions viaExactString, decodes unrecognizedIcon.Themevalues asnil, preservesDecodingErrorcoding paths inResponse, and ignores internal wire generation inTaskSnapshotequality/hashing.4.
Data-typed binary content,DataURL, and millisecond/timestamp codecs (fcec8b07)Data-typed binary content &Resource.Content.Body: switchesimageandaudiocases onTool.Content,Prompt.Message.Content,Sampling.Message.Content.ContentBlock, andSampling.ToolResultContent.ContentBlock(andSampling.Message.Contentfactories) from base64Stringto unlabeledData, and replacesResource.Content.text/.blobwithbody: 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.DataURLandValue.dataremoval: removesValue.data(mimeType:_:)so every JSON string decodes asValue.string, addsDataURL(RFC 2397) with cached unicode-scalar regex matching, ASCII-only case folding, MIME type normalization, and round-trip-safeCodableencoding, and preserves deprecated 0.12.1 shims forValue.dataValueand theDatadata-URL helpers.Durationencoding/decoding with overflow-safe clamping and lenient inbound decoding, encodes savedClient.Configuration/Client.Configuration.Tasksdurations under...Mskeys while still decoding legacy keys, clampsTaskTimestamp.string(from:)to1970-01-01T00:00:00Z...9999-12-31T23:59:59Zwith0...999ms, and avoidsInt(_: Double)overflow traps inTaskManager.waitForChangewhenmaximumTTLisnilor stored dates are out of range.CHANGELOG.md,VERSIONING.md,docs/src/migration.src.md,docs/src/server.src.md,docs/src/client.src.md,design/auth.md, anddesign/threat_model.md(with wovendocs/regenerated viascripts/weave.swift).Verification
All checks run on
fix/phase-a(fcec8b07):swift test: 1961 tests in 163 suites passed (2 pre-existing known issues).scripts/ci-linux.sh build-test(Swift 6.1): 1982 tests passed (3 pre-existing known issues).swift package generate-documentation --target MCP --warnings-as-errors,swift scripts/doc-coverage.swift, andswift scripts/weave.swift --checkall passed.2025-11-25: 248 client / 84 server passed, 0 failed.2026-07-28: 408 client / 152 server passed, 0 failed.scripts/run-interop.sh --checkmatchesinterop/RESULTS.md.AI assistance: written by Claude at the author's request, for human review before merge.