Repository navigation
feat: finalize 1.0 transport, OAuth, client lifecycle, and binary content APIs - #413
Open
jeanmatthieu wants to merge 5 commits into
Open
jeanmatthieu wants to merge 5 commits into
jeanmatthieu wants to merge 5 commits into
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
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
jeanmatthieu
force-pushed
the
fix/phase-a
branch
from
December 3, 2026 01:35
bc3b5c7 to
fb7bde5
Compare
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.