diff --git a/AGENTS.md b/AGENTS.md index 88c716fe..1403bafa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -64,7 +64,7 @@ swift-sdk/ │ │ └── Authorization/ # OAuth 2.1 client support for `HTTPClientTransport` │ ├── Client/ # `Client` actor; client features (sampling, elicitation, roots) │ ├── Server/ # `Server` actor; server features (tools, resources, prompts, ...) -│ ├── Extensions/ # Extensions on Foundation types (e.g. `Data` data URL encoding) +│ ├── Extensions/ # Extensions on Foundation types (e.g. the base64 coding of binary fields) │ └── MCP.docc/ # DocC catalog ├── Tests/MCPTests/ # Swift Testing suites │ └── Helpers/ # MockTransport, WireExchange (`expectWire`), RawPeer, ... @@ -270,7 +270,8 @@ public struct WidgetListChangedNotification: Notification { `OAuthAuthorizer`). - Don't block threads. Don't use `DispatchSemaphore` or busy-waiting in library code. - New transports conform to `Transport` (`public actor`) with `public nonisolated let logger: Logger`. - They must finish their `receive()` stream on disconnect. + They follow the contract in `Transport`'s doc comment: they must finish their `receive()` stream + on disconnect. A wrapping transport adopts `TransportWrapper`. ### 5. Platform Compatibility diff --git a/CHANGELOG.md b/CHANGELOG.md index cca4dad5..13b301fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,9 +25,62 @@ fixes merged to `main` after it (up to `234e412`), with before and after code: `RequestContext` overload of `callTool`; `Client.initialize()` is removed. - `Client.connect(transport:)` returns `Client.ConnectionInfo`. - The deprecated `Tool.Content` short forms are removed. +- Binary `image` and `audio` cases on `Tool.Content`, `Prompt.Message.Content`, + `Sampling.Message.Content.ContentBlock` and `Sampling.ToolResultContent.ContentBlock`, along + with `Sampling.Message.Content.image(_:mimeType:)` and `.audio(_:mimeType:)`, now take + unlabeled `Data` instead of a base64 `String` (`data:`). Deprecated `data: String` forwarding + factories remain for 0.12.1 construction call sites; pattern matches bind `Data`. +- `Resource.Content` replaces its stored `text: String?` and `blob: String?` properties with + `body: Resource.Content.Body` (`.text(String)` or `.blob(Data)`). Deprecated `text` and `blob` + computed properties remain as forwarding shims. +- `Value.data(mimeType:_:)` is removed: every JSON string, including `data:` URLs, decodes as + `Value.string`. Parse and format `data:` URLs explicitly with `DataURL`; deprecated + `Value.dataValue`, `Data.isDataURL(string:)`, `Data.parseDataURL(_:)` and + `Data.dataURLEncoded(mimeType:)` shims forward to `DataURL`. - `HTTPClientTransport` throws `transportError(HTTPStatusError)` and `transportError(OAuthAuthorizationError)` instead of `internalError` with a message. -- `HTTPClientAuthorizer.authorizationHeader(for:)` is `authorizationHeaders(for:method:)`. +- `HTTPClientAuthorizer` is no longer class-bound (`Sendable`, not `AnyObject`): + `authorizationHeader(for:)` is `authorizationHeaders(for:method:) async throws`; + `prepareAuthorization(for:session:)` is renamed `prepare(for:session:)` (with an empty default — + custom authorizers that still define `prepareAuthorization` compile without it being called — + and its thrown errors now fail the request rather than being ignored); + `handleChallenge(_:session:)` takes `HTTPAuthorizationChallenge` and returns + `HTTPChallengeResult`; `didReceiveResponse(headers:for:)` is `async`; and + `validateEndpointSecurity(for:)` is removed from `HTTPClientAuthorizer` and `OAuthAuthorizer` + because the transport always runs the check ([details](docs/migration.md#httpclientauthorizer)). +- `TokenStorage` and `InMemoryTokenStorage` are replaced by `OAuthTokenStorage` (not class-bound, + keyed by canonical resource `URL`, with `async throws` `load(for:)`, `save(_:for:)`, and + `clear(for:)`) and `InMemoryOAuthTokenStorage` ([details](docs/migration.md#oauthtokenstorage)). +- `OAuthScopeSelecting` and `OAuthWWWAuthenticateParsing` refine `Sendable`. +- `OAuthAuthorizationError.tokenRequestFailed(statusCode:oauthError:)` takes `statusCode: Int?` + (`nil` when the response is not HTTP), and four error codes are added: + `authorizationEndpointMissing`, `authorizationEndpointInvalid`, `registrationRequestFailed`, and + `registrationResponseInvalid` ([details](docs/migration.md#oauthauthorizationerror)). +- `HTTPClientTransport`'s `requestModifier` is `@Sendable (inout URLRequest) async throws -> Void` + instead of `(URLRequest) -> URLRequest` + ([details](docs/migration.md#httpclienttransport-requestmodifier)). +- `Transport`: `logger` is `nonisolated`; `send(_:options:)` with `TransportSendOptions` replaces + `send(_:)` as the requirement; `receive()` is `async`; six defaulted protocol hooks replace + concrete transport downcasts; `HTTPContextProviding` is removed (`httpRequestContext(for:)` is + renamed `httpRequest(for:)`); `HTTPClientTransport.updateNegotiatedProtocolVersion(_:)` is + renamed `didNegotiate(protocolVersion:)` + ([details](docs/migration.md#transport-protocol)). +- `HTTPRequestValidationPipeline` and `validationPipeline:` are removed in favor of + `validators:` (defaulting to `defaultValidators`), and `HTTPRequestValidator.validate`, + `BearerTokenValidator.TokenValidator` and `StandardValidationPipeline.validate` are `async` + ([details](docs/migration.md#async-http-request-validation)). +- `NetworkTransport.HeartbeatConfiguration`, `BufferConfiguration` and the old five-parameter + initializer are removed in favor of + `init(connection:maximumMessageLength:connectionTimeout:reconnection:logger:)`; reconnection is + off by default and heartbeats are no longer sent. `MCPError.isResourceTemporarilyUnavailable(_:)` + is removed ([details](docs/migration.md#networktransport-and-mcperrorisresourcetemporarilyunavailable)). +- `Server.waitUntilCompleted()` is now `async throws` (add `try`); `Server.start` throws + `MCPError.internalError` on overlapping starts or when `stop()` is called while connecting + ([details](docs/migration.md#serverwaituntilcompleted)). +- `Client.withBatch(body:)` is now `@discardableResult withBatch(isolation:body:)`, generic over + `R: Sendable`, and `Client.Batch` is a `Sendable` struct whose `addRequest(_:)` throws + `internalError` after `withBatch` returns; trailing-closure call sites compile unchanged + ([details](docs/migration.md#clientwithbatchisolationbody-and-clientbatch)). - Clients connect with `ProtocolMode.automatic`: `server/discover` at 2026-07-28, then `initialize` for older servers. Servers serve both eras by default. - `Version.supported` lists 2026-07-28; `Version.handshake` lists the `initialize` revisions @@ -69,11 +122,52 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha that server is, and fails with `privateIPAddressBlocked` otherwise. Set `endpointOverrides` for a local authorization server used with a remote MCP endpoint ([details](docs/migration.md#authorization)). -- `HTTPClientTransport.connect()` after `disconnect()` throws `internalError`: create a new - transport to reconnect. +- `DefaultOAuthMetadataDiscovery.canonicalResourceURI(from:)` normalizes resource URIs per RFC + 3986 §6 (lowercase scheme and host, dot segments collapsed, trailing slash stripped, hostless + URLs such as `https:///` rejected), including `endpointOverrides.resource`; servers where a + trailing slash is significant can pass a custom `OAuthMetadataDiscovering`. Reloaded tokens + after a resource key change are checked against the listed authorization servers and DPoP + requirements, and DPoP nonce keys normalize host case and omit default ports `443`/`80` + ([details](docs/migration.md#authorization)). +- `HTTPClientTransport` sends `Authorization`, `Proxy-Authorization`, `Cookie`, and + `Mcp-Session-Id` only on same-origin redirects (also separating credentials from + `URLSessionConfiguration.httpAdditionalHeaders` so they never reach cross-origin redirects or + the authorizer's own requests), re-authorizes same-origin hops (fresh DPoP proofs; no stale + `Authorization` when empty), refuses non-HTTP(S), `https`→`http`, and remote↔loopback/unspecified + redirects, fails credential-less `401`/`403` after a cross-origin redirect with + `protectedResourceMismatch`, and does not mark a live session expired on a `404` from a + redirected hop that did not send `Mcp-Session-Id` + ([details](docs/migration.md#http-client-transport)). +- `connect()` after `disconnect()` throws `internalError` on all SDK transports + (`HTTPClientTransport`, `StdioTransport`, `NetworkTransport`, `InMemoryTransport`): create a + new transport to reconnect. Sends after `disconnect()` or peer close throw `connectionClosed`. +- `StdioTransport` read errors finish the receive stream with `MCPError.transportError` instead + of ending it like end of input, and `StdioTransport` no longer mutates `O_NONBLOCK` on its + descriptors. +- `StatefulHTTPServerTransport` rejects `Last-Event-ID` counter `0` (emitted counters start at 1). +- `HTTPClientTransport` ignores `Mcp-Session-Id` on replies to 2026-07-28 requests and on + transports configured for 2026-07-28 (handshake `initialize` fallback still records it). +- `ID`, `ProgressToken`, task IDs and owners, method names, SEP-2243 request headers and + argument keys, resource subscription URIs and `RequestState` audiences compare by exact Unicode + scalars rather than Swift canonical equivalence + ([details](docs/migration.md#exact-code-point-matching-and-32-bit-safety)). - `Client.connect(transport:)` disconnects and throws `internalError` when the server answers `initialize` with a version that is not in `Version.handshake`. The client used that version before. +- In strict mode, `Client.subscribeToResource(uri:)` and handshake `unsubscribeFromResource(uri:)` + now require `resources.subscribe: true` and throw `methodNotFound` (-32601) when `subscribe` is + `false` or omitted. +- `Server.requestSampling`, `requestElicitation`, and `listRoots` withdraw the request + (`notifications/cancelled`) and throw `CancellationError` when their awaiting task is cancelled + ([details](docs/migration.md#server-to-client-request-cancellation)). +- Binary image/audio `data` and resource `blob` fields decode as standard RFC 4648 §4 base64 + (accepting ASCII whitespace and omitted trailing `=` padding). Non-standard URL-safe base64 + (`-`, `_`), invalid base64, or a `Resource.Content` item with both or neither of `text` and + `blob` fails decoding of the containing result with `DecodingError.dataCorrupted`. +- `Client.Configuration` and `Client.Configuration.Tasks` encode durations as whole-millisecond + JSON keys (`discoveryTimeoutMs`, `minimumPollIntervalMs`, `maximumPollIntervalMs`, + `defaultPollIntervalMs`, `requestedTimeToLiveMs`) instead of Swift `Duration`'s `[high, low]` + attosecond form; the prerelease form under the old keys still decodes. ### Features @@ -125,15 +219,19 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha a repeated `MCP-Protocol-Version`, `Mcp-Method`, `Mcp-Name` or `Mcp-Param-*` header at 2026-07-28 (-32020) without guessing from commas. A repeated `MCP-Protocol-Version` that names only handshake revisions keeps -32022. Adapters should switch to it; the SwiftNIO example does. -- `statelessRequestHook` on `Server.start`, `HTTPClientTransport.cancelRequest(_:)`, - `BearerTokenValidationResult.tokenInfo`, and the `HTTPClientAuthorizer` requirement - `handleChallenge(statusCode:headers:endpoint:operationKey:sentAuthorization:session:)`, with a - default, which receives the `Authorization` header of the challenged request and returns an - `HTTPChallengeResult` that says whether the retry is a DPoP nonce retry. -- The `Transport` requirement `send(_:additionalHeaders:)`, with a default that ignores the - headers, through which the client hands the `Mcp-Param-*` headers of a `tools/call` to any - transport. A custom Streamable HTTP transport sends them on the request's POST, and a wrapping - transport forwards them; `HTTPClientTransport` implements it. +- `statelessRequestHook` on `Server.start`, `BearerTokenValidationResult.tokenInfo`, and + `HTTPClientAuthorizer.handleChallenge(_:session:)`, which receives an `HTTPAuthorizationChallenge` + (carrying status, headers, endpoint, operation key, and the `Authorization` header the request + sent) and returns an `HTTPChallengeResult` (`.retry`, `.retryWithDPoPNonce`, or `.unhandled`). +- `TransportSendOptions` (`relatedRequestID`, `headers`), `Transport.send(_:options:)`, six + defaulted transport protocol hooks, and `TransportWrapper`, through which the client hands + `Mcp-Param-*` headers and per-request routing to any transport and wrapping transports forward + every hook automatically. +- `ResourceSubscribe.Parameters.init(uri:)` and `ResourceUnsubscribe.Parameters.init(uri:)` are + public, and `Client.subscribedResourceURIs` lists active handshake subscriptions in addition to + 2026-07-28 listen streams. +- `DataURL`: explicit RFC 2397 `data:` URL value type (`Codable`, `Hashable`, `Sendable`) with + strict RFC 2045 token header validation and MIME type normalization. - From `main` after 0.12.1: `Server.init` takes `description`, `websiteUrl` and `icons`, sent in `serverInfo` and, at 2026-07-28, in the `_meta` server info of every result, with `data:` icon URLs as written (#258); `Value.numberValue` reads `.int` and `.double` as `Double` (#226); `Value.init(_:)` @@ -158,7 +256,13 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha - A decoded standard error equals the error that was sent, without its message text repeated. - OAuth: a challenge keeps the stored tokens when the authorization server metadata cannot be read, proactive renewal tries each token once, a failed client registration is tried again, - `http://[::1]` counts as loopback, and more private address forms are blocked. + `http://[::1]` counts as loopback, more private address forms are blocked, error descriptions + redact URL userinfo, query, and fragment, and `makePrivateKeyJWTAssertion` uses `Int64` + `NumericDate`s and rejects non-finite lifetimes or dates. +- HTTP redirects: `HTTPClientTransport`, OAuth discovery/token requests, and `ServerCard.fetch` + separate credentials from `URLSessionConfiguration.httpAdditionalHeaders` and keep them + same-origin; on Linux `HTTPClientTransport` follows up to 20 redirects itself, preserving + 307/308 bodies and stripping representation headers and `Host` when 301/302/303 rewrite to `GET`. - `HTTPStatusError`'s `debugDescription` names the response headers without their values. - An `HTTPClientTransport` dropped without `disconnect()` is released and stops its GET stream; before, it was never released and, with `streaming: true`, kept reconnecting. @@ -228,9 +332,15 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha - A response the client cannot decode (an error `code` that is a string, no `jsonrpc`) fails the request it names with `internalError("The server sent an invalid response")` instead of leaving it to wait for its timeout, and the warning logs a sanitized prefix, not the whole message. -- `Data.isDataURL(string:)` and `Data.parseDataURL(_:)` accept only an empty or `type/subtype` - media type made of RFC 2045 tokens (RFC 2397 §3), so text such as `data: 3 rows, 2 columns` - decodes as `Value.string`, not `.data`. +- `DataURL` (and the deprecated `Data.isDataURL(string:)` and `Data.parseDataURL(_:)` shims) + accepts only an empty or `type/subtype` media type made of RFC 2045 tokens (RFC 2397 §3), so + prose such as `data: 3 rows, 2 columns` is rejected. +- Outbound millisecond duration conversions (`ttl`, `ttlMs`, `pollInterval`, `pollIntervalMs`) clamp + negative durations to `0` and saturate at `Int.max` instead of trapping on overflow, while lenient + decoding returns `nil` for negative or out-of-range values and clamps values above `Int.max` on + 32-bit platforms; `TaskRecord` and `CacheHint` pin their `CodingKeys`; task RFC 3339 timestamps + (`createdAt`, `lastUpdatedAt`) clamp store dates outside `1970-01-01T00:00:00Z...9999-12-31T23:59:59Z` + (and `NaN` to the epoch) so encoded timestamps are always valid four-digit-year dates. - `Server` answers a request whose `id` is already in flight with -32600 and runs no handler for it, also for a batch item, including a second item of one batch with the same `id`. Before, the duplicate replaced the first request's entry, so `notifications/cancelled` stopped the wrong @@ -242,9 +352,8 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha was searched about 8 GiB in all. A received message longer than 16 MiB, the limit of an SSE line on `HTTPClientTransport`, now ends the receive stream with `internalError` instead of being buffered however long it grows. That closes the connection: a `Client` fails its pending - requests with the error, and `NetworkTransport` also cancels its `NWConnection`. A - `NetworkTransport` whose `BufferConfiguration.maxReceiveBufferSize` is larger than 16 MiB accepts - messages up to that size, and one with `BufferConfiguration.unlimited` keeps no limit. + requests with the error, and `NetworkTransport` also cancels its `NWConnection`. On + `NetworkTransport`, pass `maximumMessageLength:` to raise the limit (`Int.max` removes it). `StdioTransport` has no setting that raises or removes the limit. - Concurrent `StdioTransport.send(_:)` calls write their messages one at a time, in the order they were called. A send that waited for room in a full pipe let another send write into the @@ -254,20 +363,31 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha the peer stops reading but keeps the pipe open, only `disconnect()` ends such a send. A send cancelled while it waits for an earlier send or for room in the pipe, before it writes anything, throws `CancellationError`, also when it was handed its turn as it was cancelled. -- `NetworkTransport` finds the peer's heartbeats in the received byte stream, where a message - would start, instead of in the first bytes of each read. Before, a message that arrived in the - same read after a heartbeat was dropped, a heartbeat at the end of a read or split across two - reads left its bytes at the start of the next message, and a read that started at U+1F493 - inside a message was discarded. A receiver on an earlier release still mishandles heartbeats; - set `HeartbeatConfiguration.disabled` on the peer that sends to it. -- `NetworkTransport.connect()` retries on a fresh connection to the same endpoint instead of - restarting the cancelled `NWConnection`, which reported no further state, so a retry never - completed. `connect()` to an unreachable peer now fails within the retry budget rather than - blocking forever: a `.waiting` connection counts as a failed attempt, so `maxAttempts` and - backoff apply. `disconnect()` stops a `connect()` in progress and releases its connection. A - second `connect()` while one is in progress throws instead of replacing the first one's - connection, and that includes a `connect()` stopped by `disconnect()` until it has returned, - which can take the rest of its backoff. A `connect()` after that dials a fresh connection. +- `NetworkTransport` no longer sends heartbeats, and skips incoming heartbeats from 0.12 peers + where a message would start instead of in the first bytes of each read. Before, a message that + arrived in the same read after a heartbeat was dropped, a heartbeat at the end of a read or + split across two reads left its bytes at the start of the next message, and a read that started + at U+1F493 inside a message was discarded. +- `NetworkTransport.connect()` retries (when reconnection is enabled) on a fresh connection to + the same endpoint instead of restarting the cancelled `NWConnection`, which reported no further + state, so a retry never completed. `connectionTimeout` (30 seconds by default) bounds + `connect()` and reconnections while `.waiting` connections wait without consuming retry + attempts. `disconnect()` stops a `connect()` in progress and releases its connection, and + `connect()` after `disconnect()` throws `internalError` (create a new transport to reconnect). + A second `connect()` while one is in progress throws instead of replacing the first one's + connection. +- Disconnected `InMemoryTransport` pairs clear their peer references so both actors deallocate + instead of leaking in a retain cycle. +- Wire-controlled integers that exceed `Int` bounds on 32-bit platforms saturate instead of + trapping. +- `Server` drains queued `start()` and `stop()` calls in FIFO order, clears `connection` when + `start()` fails without a concurrent `stop()`, and waits for `stop()` to disconnect before + settling `waitUntilCompleted()`. +- `Icon` decodes unrecognized `theme` strings as `nil` instead of failing the enclosing listing + (`Icon.Theme` remains frozen in 1.x; unrecognized themes are not re-encoded). +- `Response.init(from:)` reports the failing coding path when `result` or `error` fails to decode + instead of throwing a generic root `"Invalid response"` error. +- `TaskSnapshot` equality and hashing ignore its internal wire-generation field. - On Linux, an OAuth authorization code flow without an `OAuthAuthorizationDelegate` no longer crashes the process with `SWIFT TASK CONTINUATION MISUSE` after the authorization request. `OAuthAuthorizationCodeFlow` cancelled its session's request once the request had returned, and @@ -279,16 +399,16 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha cache, nor do the sessions the OAuth requests run in. `ServerCard.fetch(from:session:)` on Linux therefore no longer answers from the session's cache; `fetch(from:ifNoneMatch:session:)` revalidates a card the caller kept. -- From `main` after 0.12.1: `Data.parseDataURL(_:)` reads `;base64` from the header only and - decodes any percent-escaped byte (#309, #310); `client_secret_basic` percent-encodes the client +- From `main` after 0.12.1: `DataURL` (and the deprecated `Data.parseDataURL(_:)` shim) reads + `;base64` from the header only and decodes any percent-escaped byte (#309, #310); `client_secret_basic` percent-encodes the client credentials (RFC 6749 §2.3.1, #300); PKCE verifier characters are uniformly distributed (#303); `WWW-Authenticate` parameter values unescape every quoted pair, not only `\"` (#305); `NetworkTransport` without reconnection cancels its connection when the receive loop gives up, so the socket no longer stays in `CLOSE_WAIT`, and finishes the receive stream with - `connectionClosed` after repeated empty reads (#283), and then stops its heartbeats (#326); + `connectionClosed` after repeated empty reads (#283); heartbeats are no longer sent (#326); `NetworkTransport` clears the connection's state update handler only on the actor's executor, which removes a data race (#301); `StdioTransport.disconnect()` waits for - sends in progress and restores the blocking mode of the descriptors (#297). + sends in progress, and `StdioTransport` leaves descriptor blocking flags unchanged (#297). - The other behavior changes: [docs/migration.md](docs/migration.md#behavior-changes). ### Dependencies @@ -314,3 +434,13 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha [docs/rough_edges.md](docs/rough_edges.md#deprecated-by-the-specification). - `CreateSamplingMessage.ToolChoice.init(mode:)` with an optional mode: pass a `Mode`. With an optional parameter, `.none` is `nil`, which is `auto`. +- `Server.cancelRequest(_:reason:)`: cancel the task awaiting `requestSampling`, + `requestElicitation`, or `listRoots` instead. +- `Resource.Content.text` and `Resource.Content.blob`: switch on `body` (`.text(String)` or + `.blob(Data)`). +- `Value.dataValue`, `Data.isDataURL(string:)`, `Data.parseDataURL(_:)` and + `Data.dataURLEncoded(mimeType:)`: use `DataURL`. +- String-based `.image(data:mimeType:...)` and `.audio(data:mimeType:...)` factories on + `Tool.Content`, `Prompt.Message.Content`, `Sampling.Message.Content`, + `Sampling.Message.Content.ContentBlock` and `Sampling.ToolResultContent.ContentBlock`: pass + `Data` directly with `.image(_:mimeType:...)` or `.audio(_:mimeType:...)`. diff --git a/CLAUDE.md b/CLAUDE.md index ef60a1e7..5e701fba 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -46,7 +46,7 @@ scripts/ci-linux.sh fuzz - `Value.swift` is the dynamic JSON value type used wherever the spec allows arbitrary JSON (tool arguments, resource metadata, etc). - `Transport.swift` defines the `Transport` protocol — implementations must be `Actor`s and - expose `connect()`/`disconnect()`/`send(_:)`/`receive()` (an `AsyncThrowingStream`). + expose `connect()`/`disconnect()`/`send(_:options:)`/`receive()` (an `AsyncThrowingStream`). - `Transports/` holds the concrete transports: `StdioTransport`, `HTTPClientTransport`, `HTTPServer/{Stateless,Stateful}HTTPServerTransport` (with a request validation pipeline in `HTTPRequestValidation.swift`), `InMemoryTransport` (same-process, used heavily in tests), and @@ -56,9 +56,25 @@ scripts/ci-linux.sh fuzz client registration (RFC 7591), PKCE, token endpoint calls, `private_key_jwt` assertions, the RFC 7523 jwt-bearer grant (`assertionProvider`, no DCR, no retry), RFC 8693 token exchange (`OAuthTokenExchange`), `OAuthConfiguration.enterpriseManaged(...)` (SEP-990) and DPoP - (`OAuthConfiguration.dpop`, `OAuthDPoP.swift`, any `DPoPSigningKey`). The transport sets - `authorizationHeaders(for:method:)` after `requestModifier` and passes every response to - `didReceiveResponse(headers:for:)` (DPoP nonces). + (`OAuthConfiguration.dpop`, `OAuthDPoP.swift`, any `DPoPSigningKey`). For each POST and GET the + transport checks the endpoint itself (`https` or loopback `http`), awaits + `prepare(for:session:)` (proactive renewal; an error fails the request), runs the async + `requestModifier`, checks the final URL the same way, awaits + `authorizationHeaders(for:method:)`, then + sets `Mcp-Session-Id` from its state after those awaits. It passes every response to + `didReceiveResponse(headers:for:)` (DPoP nonces), and a 401 or 403 to + `handleChallenge(_:session:)` as an `HTTPAuthorizationChallenge`. `OAuthAuthorizer` keeps its + state in a `Mutex`, runs challenges through `gate` and storage writes through + `TokenStore.writes` (`gate` may wait for `writes`, never the reverse), and keys + `OAuthTokenStorage` by the canonical RFC 8707 resource. Redirects + (`Transports/HTTPRedirects.swift`): credentials (`Authorization`, `Proxy-Authorization`, + `Cookie`, `Mcp-Session-Id`) follow a redirect only while the chain stays on the first origin, + `DPoP` never; with an authorizer a same-origin hop's `Authorization` is the authorizer's or none. + MCP requests follow only `http`/`https` targets, never remote to loopback, never `https` to + `http`, and never loopback to non-loopback `http`. On + Apple platforms each request gets an `HTTPRedirectTaskDelegate`, which the caller cancels; on + Linux `responseBody(for:streaming:)` follows redirects itself, since corelibs drops the body and + traps on a late delegate answer. This is opt-in — wired in via an `OAuthAuthorizer` passed to `HTTPClientTransport`. - `Utilities/` holds cross-cutting concerns used by both Client and Server: `Cancellation`, `Progress`, `Ping`, and `RequestContext` (the client's handle on a pending request: id and @@ -115,8 +131,9 @@ Client: `Client.Configuration.protocolMode` (`.automatic` default, `.handshake`, other MCP errors; `.stateless(v)` never retries. Tests that exercise the handshake pin `.handshake` (`Tests/MCPTests/Helpers/HandshakeConfiguration.swift`). `send` stamps the `_meta` envelope when `isStateless`. Request lifecycle: `register` puts a `ResponseSlot` in `pendingRequests` before -`send` returns and `transmit` sends from a task (`unsentRequests`); `withBatch` uses the same -path. Handlers run off the receive loop: notification handlers run one at a time on the +`send` returns and `transmit` sends from a task (`unsentRequests`); `withBatch(isolation:body:)` +uses the same path, and its `Batch` registers only while the body runs (`openBatches`). +Handlers run off the receive loop: notification handlers run one at a time on the inbound queue; responses are delivered at once, except that a response waits for queued progress notifications of its own request (`progressTokens`, `parkedResponses`; requests sent from a notification handler never wait, via the `isHandlingNotification` task-local). The @@ -124,8 +141,10 @@ client handles `notifications/cancelled` and the listen acknowledgement itself i loop (`handleBuiltIn`). Server-to-client requests run in `incomingRequests` tasks, at most `maxConcurrentServerRequests` at once (64 more queued), refused at 2026-07-28 and for a duplicate id. Cancelling the task that awaits `RequestContext.value` cancels the request. `HTTPClientTransport` takes `MCP-Protocol-Version` from the message `_meta`, -delivers JSON-RPC error bodies of non-2xx replies, and `useStatelessProtocol(_:)` drops the -session and GET stream. A handshake POST stream that ends before its response is resumed +delivers JSON-RPC error bodies of non-2xx replies, and `didNegotiate(protocolVersion:)` at +2026-07-28 drops the session and GET stream. `Client` and `Server` reach transport features only +through `Transport` hooks (`didNegotiate`, `abandonRequest`, `authorizationEnd`, `prepare`, +`isSessionless`, `httpRequest`), never by downcasting; wrappers adopt `TransportWrapper`. A handshake POST stream that ends before its response is resumed with a GET carrying that stream's own `Last-Event-ID` (-32603 when it cannot be); at 2026-07-28 it fails at once. `HTTPClientTransport.defaultConfiguration` allows 64 connections per host: server-to-client replies need a connection while each call holds diff --git a/Examples/Snippets/Client/Notifications.swift b/Examples/Snippets/Client/Notifications.swift index 1fa12dec..c4dbf7b7 100644 --- a/Examples/Snippets/Client/Notifications.swift +++ b/Examples/Snippets/Client/Notifications.swift @@ -55,13 +55,18 @@ func watchNotes(_ client: Client) async throws -> Set { } // resources/subscribe at 2025-11-25; a listen stream per URI at 2026-07-28. try await client.subscribeToResource(uri: "file:///notes.txt") - let subscribed = await client.subscribedResourceURIs // 2026-07-28 streams only + let subscribed = await client.subscribedResourceURIs // ["file:///notes.txt"] // ... try await client.unsubscribeFromResource(uri: "file:///notes.txt") // endsnippet return subscribed } +/// Builds the subscription requests by hand, as a proxy that forwards them does. +func subscriptionRequests(uri: String) -> (Request, Request) { + (ResourceSubscribe.request(.init(uri: uri)), ResourceUnsubscribe.request(.init(uri: uri))) +} + // MARK: - Logging /// Receives server log messages at `info` and above. @@ -133,33 +138,26 @@ actor ProgressInbox { // MARK: - Batching -/// Sends three tool calls in one JSON-RPC batch (2025-03-26 and earlier peers). +/// Sends three tool calls in one JSON-RPC batch (peers at 2025-03-26). func callInBatch(_ client: Client) async throws -> [CallTool.Result] { // snippet: batch - // withBatch's closure is @Sendable, so collect the tasks in an actor. - let collected = TaskCollector() - try await client.withBatch { batch in + let tasks = try await client.withBatch { batch in + var tasks: [Task] = [] for word in ["one", "two", "three"] { - let task = try await batch.addRequest( - CallTool.request(.init(name: "echo", arguments: ["text": .string(word)]))) - await collected.append(task) + tasks.append(try await batch.addRequest( + CallTool.request(.init(name: "echo", arguments: ["text": .string(word)])))) } + return tasks } // The batch is sent when the closure returns; await each result. var results: [CallTool.Result] = [] - for task in await collected.tasks { + for task in tasks { results.append(try await task.value) } // endsnippet return results } -/// Tasks collected inside a `withBatch` closure. -actor TaskCollector { - private(set) var tasks: [Task] = [] - func append(_ task: Task) { tasks.append(task) } -} - // MARK: - Capabilities and extensions /// Declares capabilities and an extension, then reads the server's. diff --git a/Examples/Snippets/Client/Tools.swift b/Examples/Snippets/Client/Tools.swift index b60378fc..8b1383f7 100644 --- a/Examples/Snippets/Client/Tools.swift +++ b/Examples/Snippets/Client/Tools.swift @@ -118,14 +118,16 @@ func readNotes(_ client: Client) async throws -> String? { let contents = try await client.readResource(uri: "file:///notes.txt").contents for content in contents { - if let text = content.text { + switch content.body { + case .text(let text): print("\(content.uri): \(text)") - } else if let blob = content.blob, let data = Data(base64Encoded: blob) { + case .blob(let data): print("\(content.uri): \(data.count) bytes") } } // endsnippet - return contents.first?.text + guard case .text(let text) = contents.first?.body else { return nil } + return text } /// Asks for completions of a prompt argument. diff --git a/Examples/Snippets/Guides/Migration.swift b/Examples/Snippets/Guides/Migration.swift index 4ddeca53..056f399c 100644 --- a/Examples/Snippets/Guides/Migration.swift +++ b/Examples/Snippets/Guides/Migration.swift @@ -119,10 +119,23 @@ func describeServer(_ client: Client, transport: any Transport) async throws -> /// `annotations` and `_meta` default to `nil`. let greeting: [Tool.Content] = [ .text(text: "Hello"), - .image(data: "iVBORw0KGgo=", mimeType: "image/png"), + .image(Data([0x89, 0x50, 0x4E, 0x47]), mimeType: "image/png"), ] // endsnippet +// snippet: migration-data-url +/// Reads the bytes of a `data:` URL argument, which is now a `.string`. +func imageBytes(_ arguments: [String: Value]?) -> (mimeType: String, data: Data)? { + guard let string = arguments?["image"]?.stringValue, let url = DataURL(string) else { return nil } + return (url.mimeType, url.data) +} + +/// Builds a `data:` URL from bytes. +func dataURLString(_ data: Data, mimeType: String) -> String { + DataURL(data: data, mimeType: mimeType).description +} +// endsnippet + // snippet: migration-http-errors /// HTTP and OAuth failures are typed errors inside `transportError`. func describeFailure(_ error: any Error) -> String { diff --git a/Examples/Snippets/Guides/Troubleshooting.swift b/Examples/Snippets/Guides/Troubleshooting.swift index c850bec1..2571b37b 100644 --- a/Examples/Snippets/Guides/Troubleshooting.swift +++ b/Examples/Snippets/Guides/Troubleshooting.swift @@ -23,51 +23,46 @@ func makeLoggedTransports() async -> (StdioTransport, InMemoryTransport, InMemor // snippet: logging-wire /// Wraps a transport and records every message it sends and receives. -actor WireLog: Transport { +/// +/// `TransportWrapper` forwards everything else to `wrapped`, so the wrapped +/// transport keeps its behavior, such as the headers of an HTTP transport. +actor WireLog: TransportWrapper { + nonisolated let wrapped: any Transport nonisolated let logger: Logger - private let base: any Transport private(set) var lines: [String] = [] + /// The stream `receive()` returns, made by its first call. + private var tapped: AsyncThrowingStream? - init(_ base: any Transport, logger: Logger) { - self.base = base + init(_ wrapped: any Transport, logger: Logger) { + self.wrapped = wrapped self.logger = logger } - func connect() async throws { try await base.connect() } - func disconnect() async { await base.disconnect() } - - func send(_ data: Data) async throws { - record("send", data) - try await base.send(data) - } - - func send(_ data: Data, relatedRequestID: ID?) async throws { - record("send", data) - try await base.send(data, relatedRequestID: relatedRequestID) - } - - /// Forwards the `Mcp-Param-*` headers of a `tools/call` at 2026-07-28. - func send(_ data: Data, additionalHeaders: [String: String]) async throws { + func send(_ data: Data, options: TransportSendOptions) async throws { record("send", data) - try await base.send(data, additionalHeaders: additionalHeaders) + try await wrapped.send(data, options: options) } - func receive() -> AsyncThrowingStream { - let base = self.base - return AsyncThrowingStream { continuation in - let task = Task { - do { - for try await data in await base.receive() { - self.record("receive", data) - continuation.yield(data) - } - continuation.finish() - } catch { - continuation.finish(throwing: error) + /// Returns the same stream on every call, as `Transport` requires. + func receive() async -> AsyncThrowingStream { + if let tapped { return tapped } + let (stream, continuation) = AsyncThrowingStream.makeStream() + // Stored before the await, so a concurrent call gets the same stream. + tapped = stream + let messages = await wrapped.receive() + let task = Task { + do { + for try await data in messages { + self.record("receive", data) + continuation.yield(data) } + continuation.finish() + } catch { + continuation.finish(throwing: error) } - continuation.onTermination = { _ in task.cancel() } } + continuation.onTermination = { _ in task.cancel() } + return stream } private func record(_ direction: String, _ data: Data) { diff --git a/Examples/Snippets/Protocol/Authorization.swift b/Examples/Snippets/Protocol/Authorization.swift index 2d4ac0e9..8fb26e41 100644 --- a/Examples/Snippets/Protocol/Authorization.swift +++ b/Examples/Snippets/Protocol/Authorization.swift @@ -101,21 +101,21 @@ func workloadConfiguration(readToken: @escaping @Sendable () throws -> String) - } // snippet: auth-token-storage -/// Keeps the access token across launches. Replace the dictionary with the Keychain. -final class PersistentTokenStorage: TokenStorage, @unchecked Sendable { - private let lock = NSLock() - private var stored: Data? +/// Keeps access tokens across launches, one per server. Replace the dictionary +/// with the Keychain, under the resource's `absoluteString`. +actor PersistentTokenStorage: OAuthTokenStorage { + private var stored: [URL: Data] = [:] - func save(_ token: OAuthAccessToken) { - lock.withLock { stored = try? JSONEncoder().encode(token) } + func save(_ token: OAuthAccessToken, for resource: URL) throws { + stored[resource] = try JSONEncoder().encode(token) } - func load() -> OAuthAccessToken? { - lock.withLock { stored.flatMap { try? JSONDecoder().decode(OAuthAccessToken.self, from: $0) } } + func load(for resource: URL) throws -> OAuthAccessToken? { + try stored[resource].map { try JSONDecoder().decode(OAuthAccessToken.self, from: $0) } } - func clear() { - lock.withLock { stored = nil } + func clear(for resource: URL) { + stored[resource] = nil } } // endsnippet @@ -136,8 +136,15 @@ func verifyToken(_ token: String) -> (subject: String, audience: [String], expir return ("user-1", ["https://mcp.example.com/mcp"], Date().addingTimeInterval(3600), ["tools:read"]) } -/// A validation pipeline for a protected stateful transport. -func protectedPipeline() -> StandardValidationPipeline { +/// Asks the authorization server about a token (RFC 7662 introspection). A stub that +/// suspends like the network call it stands for. +func introspectToken(_ token: String) async -> (subject: String, audience: [String], expiresAt: Date, scopes: Set)? { + await Task.yield() + return verifyToken(token) +} + +/// The validators of a protected stateful transport. +func protectedValidators() -> [any HTTPRequestValidator] { // snippet: auth-server-pipeline let resource = URL(string: "https://mcp.example.com/mcp")! let metadataURL = URL(string: "https://mcp.example.com/.well-known/oauth-protected-resource")! @@ -152,7 +159,8 @@ func protectedPipeline() -> StandardValidationPipeline { resourceMetadataURL: metadataURL, resourceIdentifier: resource, tokenValidator: { token, request, context in - guard let claims = verifyToken(token) else { + // The closure may suspend; the transport serves other requests meanwhile. + guard let claims = await introspectToken(token) else { return .invalidToken(errorDescription: "Unknown token") } guard claims.scopes.contains("tools:read") else { @@ -163,7 +171,7 @@ func protectedPipeline() -> StandardValidationPipeline { audience: claims.audience, scopes: claims.scopes, expiresAt: claims.expiresAt)) }) - let pipeline = StandardValidationPipeline(validators: [ + let validators: [any HTTPRequestValidator] = [ metadata, // before the bearer check: discovery is unauthenticated bearer, OriginValidator(allowedHosts: ["mcp.example.com"], allowedOrigins: ["https://app.example.com"]), @@ -171,15 +179,15 @@ func protectedPipeline() -> StandardValidationPipeline { ContentTypeValidator(), ProtocolVersionValidator(), SessionValidator(), - ]) + ] // endsnippet - return pipeline + return validators } /// A protected stateful transport. func protectedTransport() -> StatefulHTTPServerTransport { // snippet: auth-server-transport - let transport = StatefulHTTPServerTransport(validationPipeline: protectedPipeline()) + let transport = StatefulHTTPServerTransport(validators: protectedValidators()) // endsnippet return transport } diff --git a/Examples/Snippets/Protocol/Transports.swift b/Examples/Snippets/Protocol/Transports.swift index 69b71b9d..3c4ace82 100644 --- a/Examples/Snippets/Protocol/Transports.swift +++ b/Examples/Snippets/Protocol/Transports.swift @@ -9,12 +9,13 @@ import MCP // Snippets for docs/protocol.md, section "Transports". #if canImport(System) - /// Serves a server over the process's stdin and stdout until the client goes away. + /// Serves a server over the process's stdin and stdout until the client goes away, and + /// throws when reading stdin fails. func runStdioServer() async throws { // snippet: transport-stdio-server let server = Server(name: "example", version: "1.0.0", capabilities: .init(tools: .init())) try await server.start(transport: StdioTransport()) - await server.waitUntilCompleted() + try await server.waitUntilCompleted() // endsnippet } #endif @@ -48,9 +49,7 @@ func connectOverHTTP(endpoint: URL) async throws -> Client { endpoint: endpoint, // for example http://localhost:3000/mcp streaming: true, // open the GET stream on handshake connections requestModifier: { request in - var request = request request.setValue("example/1.0", forHTTPHeaderField: "User-Agent") - return request }) let client = Client(name: "example-client", version: "1.0.0") try await client.connect(transport: transport) @@ -191,24 +190,51 @@ func connectInMemory() async throws -> (Client, Server) { } // snippet: transport-custom -/// A transport over a pair of `AsyncStream`s, for example a WebSocket bridge. +/// A transport over a message channel, for example a WebSocket bridge. The bridge +/// passes each message from the peer to `deliver(_:)`, reads `outgoing`, and calls +/// `disconnect()` when the channel closes. actor StreamTransport: Transport { nonisolated let logger = Logger(label: "example.stream-transport") private let outgoing: AsyncStream.Continuation private let incoming: AsyncThrowingStream + private let incomingContinuation: AsyncThrowingStream.Continuation + private var state = State.idle - init(incoming: AsyncThrowingStream, outgoing: AsyncStream.Continuation) { - self.incoming = incoming + private enum State { case idle, connected, closed } + + init(outgoing: AsyncStream.Continuation) { self.outgoing = outgoing + (incoming, incomingContinuation) = AsyncThrowingStream.makeStream() } - func connect() async throws {} + /// Hands a message from the peer to the client or server. + func deliver(_ data: Data) { incomingContinuation.yield(data) } + + /// A transport serves one connection: it can't connect twice, or after `disconnect()`. + func connect() async throws { + guard state == .idle else { throw MCPError.internalError("Transport already used") } + state = .connected + } - func disconnect() async { outgoing.finish() } + /// Finishes the stream `receive()` returns; calling it again does nothing more. + func disconnect() async { + state = .closed + outgoing.finish() + incomingContinuation.finish() + } /// `data` is one JSON-RPC message or batch, without a trailing newline. - func send(_ data: Data) async throws { outgoing.yield(data) } + /// `options` carry a related request ID and HTTP headers, which only HTTP + /// transports use. + func send(_ data: Data, options: TransportSendOptions) async throws { + switch state { + case .idle: throw MCPError.internalError("Transport not connected") + case .connected: outgoing.yield(data) + case .closed: throw MCPError.connectionClosed + } + } + /// Returns the same stream on every call. func receive() -> AsyncThrowingStream { incoming } } // endsnippet diff --git a/Examples/Snippets/Server/Prompts.swift b/Examples/Snippets/Server/Prompts.swift index 61c3f07b..6372cc15 100644 --- a/Examples/Snippets/Server/Prompts.swift +++ b/Examples/Snippets/Server/Prompts.swift @@ -41,7 +41,7 @@ func reviewMessages(diff: String, screenshot: Data) -> [Prompt.Message] { [ .user(.text(text: "Review the change below.")), .user(.resource(resource: .text(diff, uri: "repo://changes/42.diff", mimeType: "text/x-diff"))), - .user(.image(data: screenshot.base64EncodedString(), mimeType: "image/png")), + .user(.image(screenshot, mimeType: "image/png")), .user(.resourceLink(uri: "repo://files/README.md", name: "README.md", mimeType: "text/markdown")), ] } diff --git a/Examples/Snippets/Server/Server.swift b/Examples/Snippets/Server/Server.swift index 176f769a..af37379a 100644 --- a/Examples/Snippets/Server/Server.swift +++ b/Examples/Snippets/Server/Server.swift @@ -33,7 +33,8 @@ func makeHandshakeOnlyServer() -> Server { // endsnippet // snippet: lifecycle-run -/// Serves until the transport closes or the calling task is cancelled. +/// Serves until the transport closes or, when the calling task is cancelled, until the +/// server is stopped. Throws the transport's error when its receive stream fails. func serve(_ server: Server, on transport: any Transport) async throws { try await server.start(transport: transport) { clientInfo, capabilities in // Runs for `initialize` only. 2026-07-28 clients never send it. @@ -41,8 +42,8 @@ func serve(_ server: Server, on transport: any Transport) async throws { throw MCPError.invalidRequest("This client is not allowed") } } - await withTaskCancellationHandler { - await server.waitUntilCompleted() + try await withTaskCancellationHandler { + try await server.waitUntilCompleted() } onCancel: { Task { await server.stop() } } diff --git a/Examples/Snippets/Server/Tools.swift b/Examples/Snippets/Server/Tools.swift index b2b67718..8bd6eb2f 100644 --- a/Examples/Snippets/Server/Tools.swift +++ b/Examples/Snippets/Server/Tools.swift @@ -54,7 +54,7 @@ func registerToolCall(on server: Server) async { func chartResult(png: Data) -> CallTool.Result { CallTool.Result(content: [ .text(text: "Temperature over 24 hours"), - .image(data: png.base64EncodedString(), mimeType: "image/png"), + .image(png, mimeType: "image/png"), .resource( resource: .text("time,celsius\n00:00,12\n", uri: "weather://paris/today.csv", mimeType: "text/csv")), .resourceLink( diff --git a/Examples/Tests/ClientSnippetTests.swift b/Examples/Tests/ClientSnippetTests.swift index e9b79dd0..9d53cd7a 100644 --- a/Examples/Tests/ClientSnippetTests.swift +++ b/Examples/Tests/ClientSnippetTests.swift @@ -455,7 +455,7 @@ struct ClientSnippetTests { func subscribeResource(mode: Client.ProtocolMode) async throws { let (server, client) = try await connected(mode) let subscribed = try await watchNotes(client) - #expect(subscribed == (mode == .handshake ? [] : ["file:///notes.txt"])) + #expect(subscribed == ["file:///notes.txt"]) #expect(await client.subscribedResourceURIs.isEmpty) await client.disconnect() await server.stop() diff --git a/Examples/Tests/GuidesSnippetTests.swift b/Examples/Tests/GuidesSnippetTests.swift index 0ffe17a9..9f965614 100644 --- a/Examples/Tests/GuidesSnippetTests.swift +++ b/Examples/Tests/GuidesSnippetTests.swift @@ -256,6 +256,16 @@ struct GuidesSnippetTests { #expect(client.strict) } + @Test("Migrated data: URL handling") + func migratedDataURLs() throws { + let image = try #require(imageBytes(["image": "data:image/png;base64,iVBORw=="])) + #expect(image.mimeType == "image/png") + #expect(image.data == Data([0x89, 0x50, 0x4E, 0x47])) + #expect(imageBytes(["image": "data: 3 rows"]) == nil) + #expect(imageBytes(nil) == nil) + #expect(dataURLString(Data("hi".utf8), mimeType: "TEXT/plain") == "data:text/plain;base64,aGk=") + } + @Test("Migrated servers and clients") func migratedEndpoints() async throws { let server = makeHandshakeOnlyServer() @@ -388,6 +398,27 @@ struct GuidesSnippetTests { _ = await makeLoggedTransports() } + @Test("WireLog's receive() returns one stream") + func wireLogReceivesOnce() async throws { + let (clientEnd, serverEnd) = await InMemoryTransport.createConnectedPair() + let log = WireLog(clientEnd, logger: makeDebugLogger()) + let first = await log.receive() + _ = await log.receive() + try await log.connect() + try await serverEnd.connect() + try await serverEnd.send(Data(#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#.utf8)) + + // The message reaches the stream of the first call, and is recorded once. + var messages = first.makeAsyncIterator() + let message = try #require(try await messages.next()) + #expect(String(decoding: message, as: UTF8.self).contains("notifications/initialized")) + #expect(await log.lines.filter { $0.hasPrefix("receive: ") }.count == 1) + + await log.disconnect() + #expect(try await messages.next() == nil) + await serverEnd.disconnect() + } + @Test("Undeclared capabilities give -32601 in both eras", arguments: [ (Client.ProtocolMode.handshake, "Unknown method: prompts/list"), (Client.ProtocolMode.automatic, "capability not declared by the server"), diff --git a/Examples/Tests/ProtocolSnippetTests.swift b/Examples/Tests/ProtocolSnippetTests.swift index 0bc0a8f6..57fdd199 100644 --- a/Examples/Tests/ProtocolSnippetTests.swift +++ b/Examples/Tests/ProtocolSnippetTests.swift @@ -105,16 +105,14 @@ struct ProtocolSnippetTests { @Test func customTransportCarriesAConnection() async throws { let (toServer, toServerContinuation) = AsyncStream.makeStream() let (toClient, toClientContinuation) = AsyncStream.makeStream() - func throwing(_ stream: AsyncStream) -> AsyncThrowingStream { - AsyncThrowingStream { continuation in - Task { - for await data in stream { continuation.yield(data) } - continuation.finish() - } - } - } - let serverTransport = StreamTransport(incoming: throwing(toServer), outgoing: toClientContinuation) - let clientTransport = StreamTransport(incoming: throwing(toClient), outgoing: toServerContinuation) + let serverTransport = StreamTransport(outgoing: toClientContinuation) + let clientTransport = StreamTransport(outgoing: toServerContinuation) + // The bridge: each side's outgoing messages reach the other side. + let bridges = [ + Task { for await data in toServer { await serverTransport.deliver(data) } }, + Task { for await data in toClient { await clientTransport.deliver(data) } }, + ] + defer { bridges.forEach { $0.cancel() } } let server = Server(name: "example", version: "1.0.0") let client = Client(name: "example-client", version: "1.0.0") try await server.start(transport: serverTransport) @@ -158,29 +156,45 @@ struct ProtocolSnippetTests { await server.stop() } - @Test func protectedPipelineChallengesAndServesMetadata() throws { - let pipeline = protectedPipeline() + @Test func protectedValidatorsChallengeAndServeMetadata() async throws { + let pipeline = StandardValidationPipeline(validators: protectedValidators()) let post = HTTPRequest( method: "POST", headers: ["Content-Type": "application/json", "Accept": "application/json, text/event-stream"], body: Data("{}".utf8), path: "/mcp") let context = HTTPValidationContext( httpMethod: "POST", sessionID: nil, isInitializationRequest: true) - let challenge = try #require(pipeline.validate(post, context: context)) + let challenge = try #require(await pipeline.validate(post, context: context)) #expect(challenge.statusCode == 401) #expect(challenge.headers[HTTPHeaderName.wwwAuthenticate]?.contains("resource_metadata=") == true) var authorized = post.headers authorized["Authorization"] = "Bearer valid-token" authorized["Host"] = "mcp.example.com" - let accepted = pipeline.validate( + let accepted = await pipeline.validate( HTTPRequest(method: "POST", headers: authorized, body: post.body, path: "/mcp"), context: context) #expect(accepted == nil) let get = HTTPRequest(method: "GET", path: "/.well-known/oauth-protected-resource") let getContext = HTTPValidationContext( httpMethod: "GET", sessionID: nil, isInitializationRequest: false) - #expect(pipeline.validate(get, context: getContext)?.statusCode == 200) + #expect(await pipeline.validate(get, context: getContext)?.statusCode == 200) + } + + @Test func protectedTransportRejectsAnUnknownToken() async throws { + let transport = protectedTransport() + try await transport.connect() + let initialize = HTTPRequest( + method: "POST", + headers: [ + "Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "Host": "mcp.example.com", "Authorization": "Bearer unknown-token", + ], + body: Data(#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#.utf8), path: "/mcp") + let response = await transport.handleRequest(initialize) + #expect(response.statusCode == 401) + #expect(response.headers[HTTPHeaderName.wwwAuthenticate]?.contains("invalid_token") == true) + await transport.disconnect() } @Test func enterpriseAndWorkloadConfigurations() { diff --git a/Examples/Tests/ServerSnippetTests.swift b/Examples/Tests/ServerSnippetTests.swift index 94a45db1..c4beaa6d 100644 --- a/Examples/Tests/ServerSnippetTests.swift +++ b/Examples/Tests/ServerSnippetTests.swift @@ -133,11 +133,11 @@ struct ServerSnippetTests { #expect(try await client.listResources().resources.count == 2) #expect(try await client.listResourceTemplates().templates.first?.uriTemplate == "file:///project/{path}") let readme = try await client.readResource(uri: "file:///project/README.md").contents - #expect(readme.first?.text == "# Project\n") + #expect(readme.first?.body == .text("# Project\n")) let logo = try await client.readResource(uri: "file:///project/logo.png").contents - #expect(logo.first?.blob == Data([0x89, 0x50, 0x4E, 0x47]).base64EncodedString()) + #expect(logo.first?.body == .blob(Data([0x89, 0x50, 0x4E, 0x47]))) let file = try await client.readResource(uri: "file:///project/notes.txt").contents - #expect(file.first?.text == "Contents of notes.txt") + #expect(file.first?.body == .text("Contents of notes.txt")) do { _ = try await client.readResource(uri: "other://x") Issue.record("Expected resourceNotFound") @@ -459,18 +459,36 @@ struct ServerSnippetTests { #expect(await code { _ = try await client.listTools(cursor: "bogus") } == -32602) } - @Test("Lifecycle: initialize hook, strict handshake-only server") + @Test("Lifecycle: initialize hook, cancelled serve, strict handshake-only server") func lifecycle() async throws { let blockedServer = makeServer() let (blockedClientTransport, blockedServerTransport) = await InMemoryTransport.createConnectedPair() let running = Task { try await serve(blockedServer, on: blockedServerTransport) } - try await Task.sleep(for: .milliseconds(50)) + #expect(await eventually { await blockedServer.completionWaiterCount == 1 }) let blocked = Client( name: "blocked-client", version: "1.0", configuration: .init(protocolMode: .handshake)) #expect(await code { _ = try await blocked.connect(transport: blockedClientTransport) } == -32600) running.cancel() _ = await running.result + // Cancelling serve returns once the server is stopped: its transport is disconnected, + // so the client's sends fail. (With an initialize hook and no stateless hook the + // server serves handshake clients only.) + let server = makeServer() + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + let serving = Task { try await serve(server, on: serverTransport) } + #expect(await eventually { await server.completionWaiterCount == 1 }) + let connected = Client(name: "client", version: "1.0", configuration: .init(protocolMode: .handshake)) + try await connected.connect(transport: clientTransport) + serving.cancel() + if case .failure(let error) = await serving.result { + Issue.record("serve threw \(error)") + } + await #expect(throws: MCPError.connectionClosed) { + try await clientTransport.send(Data("{}".utf8)) + } + await connected.disconnect() + // A handshake-only server: an automatic client falls back to initialize. let legacy = makeHandshakeOnlyServer() await registerToolList(on: legacy) diff --git a/Examples/foundation-models/main.swift b/Examples/foundation-models/main.swift index 0ebf3471..7a2b6aaf 100644 --- a/Examples/foundation-models/main.swift +++ b/Examples/foundation-models/main.swift @@ -444,7 +444,7 @@ import MCP #if os(macOS) let server = try await toolset.makeMCPServer() try await server.start(transport: StdioTransport()) - await server.waitUntilCompleted() + try await server.waitUntilCompleted() #else FileHandle.standardError.write( Data("Stdio MCP server mode requires macOS.\n".utf8)) diff --git a/Examples/hello-server/main.swift b/Examples/hello-server/main.swift index fb3bb262..f5ca747b 100644 --- a/Examples/hello-server/main.swift +++ b/Examples/hello-server/main.swift @@ -1,7 +1,8 @@ // HelloServer: an MCP server with one tool, `greet`, served over stdio. // // The server reads JSON-RPC messages from standard input and writes them to -// standard output, one per line. It exits when standard input closes. +// standard output, one per line. It exits when standard input closes, and +// with status 1 when reading it fails. // Run it through the HelloClient example, which starts it as a subprocess: // // swift build --product HelloServer @@ -9,6 +10,7 @@ // $(swift build --show-bin-path)/HelloClient $(swift build --show-bin-path)/HelloServer // snippet: hello-server +import Foundation import MCP let server = Server( @@ -38,5 +40,11 @@ await server.withMethodHandler(CallTool.self) { params in } try await server.start(transport: StdioTransport()) -await server.waitUntilCompleted() +do { + // Returns when standard input closes; throws when reading it fails. + try await server.waitUntilCompleted() +} catch { + FileHandle.standardError.write(Data("hello-server: \(error)\n".utf8)) + exit(1) +} // endsnippet diff --git a/Examples/http-server/main.swift b/Examples/http-server/main.swift index c11c0db4..8ee04b05 100644 --- a/Examples/http-server/main.swift +++ b/Examples/http-server/main.swift @@ -97,12 +97,12 @@ actor Router { description: "Echoes its input, for clients of both protocol eras."), endpointPath: "/mcp") stateless = StatelessHTTPServerTransport( - validationPipeline: StandardValidationPipeline(validators: [ + validators: [ OriginValidator.localhost(port: port), AcceptHeaderValidator(mode: .jsonOnly), ContentTypeValidator(), ProtocolVersionValidator(), - ])) + ]) } /// Starts the shared stateless server and the idle-session reaper. @@ -140,13 +140,13 @@ actor Router { pendingSessions += 1 defer { pendingSessions -= 1 } let transport = StatefulHTTPServerTransport( - validationPipeline: StandardValidationPipeline(validators: [ + validators: [ OriginValidator.localhost(port: port), AcceptHeaderValidator(mode: .sseRequired), ContentTypeValidator(), ProtocolVersionValidator(), SessionValidator(), - ])) + ]) let server = await makeServer() do { try await server.start(transport: transport) diff --git a/README.md b/README.md index 6f276044..c1d71fba 100644 --- a/README.md +++ b/README.md @@ -54,12 +54,13 @@ targets: [ ] ``` -## A server in 30 lines +## A server in 40 lines This server has one tool and runs over stdio ([Examples/hello-server/main.swift](Examples/hello-server/main.swift)): ```swift +import Foundation import MCP let server = Server( @@ -89,7 +90,13 @@ await server.withMethodHandler(CallTool.self) { params in } try await server.start(transport: StdioTransport()) -await server.waitUntilCompleted() +do { + // Returns when standard input closes; throws when reading it fails. + try await server.waitUntilCompleted() +} catch { + FileHandle.standardError.write(Data("hello-server: \(error)\n".utf8)) + exit(1) +} ``` A client calls it the same way in either era: diff --git a/README.src.md b/README.src.md index 146f2c53..ac8b5df3 100644 --- a/README.src.md +++ b/README.src.md @@ -52,7 +52,7 @@ targets: [ ] ``` -## A server in 30 lines +## A server in 40 lines This server has one tool and runs over stdio ([Examples/hello-server/main.swift](Examples/hello-server/main.swift)): diff --git a/ROADMAP.md b/ROADMAP.md index 2ae15af7..5beb7bf7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -100,7 +100,7 @@ Details: [design/auth.md](design/auth.md). ### 2025-11-25 reliability - Notifications and server-to-client requests from a handler travel on the stream of the request - that caused them (`Transport.send(_:relatedRequestID:)`). + that caused them (`TransportSendOptions.relatedRequestID`). ## Planned diff --git a/Sources/MCP/Base/AppTypes.swift b/Sources/MCP/Base/AppTypes.swift index 5f0769c8..79f36242 100644 --- a/Sources/MCP/Base/AppTypes.swift +++ b/Sources/MCP/Base/AppTypes.swift @@ -200,10 +200,9 @@ public struct UIResourceMeta: Hashable, Codable, Sendable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - // As written: a `data:` URL stays a string. func strings(_ key: CodingKeys) -> [String]? { - ((try? container.decodeIfPresent([Value.Preserved].self, forKey: key)) ?? nil)? - .compactMap(\.value.stringValue) + ((try? container.decodeIfPresent([Value].self, forKey: key)) ?? nil)? + .compactMap(\.stringValue) } connectDomains = strings(.connectDomains) resourceDomains = strings(.resourceDomains) @@ -348,9 +347,8 @@ public struct ToolUIMeta: Hashable, Codable, Sendable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) resourceUri = (try? container.decodeIfPresent(String.self, forKey: .resourceUri)) ?? nil - // As written: a `data:` URL stays a string. - visibility = ((try? container.decodeIfPresent([Value.Preserved].self, forKey: .visibility)) ?? nil)? - .compactMap(\.value.stringValue).map(Visibility.init(rawValue:)) + visibility = ((try? container.decodeIfPresent([Value].self, forKey: .visibility)) ?? nil)? + .compactMap(\.stringValue).map(Visibility.init(rawValue:)) } public func encode(to encoder: Encoder) throws { @@ -441,7 +439,7 @@ private enum UIMetaField { static func write(_ newValue: T?, keys: [String], into meta: inout Metadata?) { var fields = meta?.fields ?? [:] - if let newValue, let encoded = (try? Value.preservingStrings(newValue))?.objectValue { + if let newValue, let encoded = (try? Value(newValue))?.objectValue { var ui = fields[key]?.objectValue ?? [:] for known in keys { ui[known] = nil } ui.merge(encoded) { _, new in new } diff --git a/Sources/MCP/Base/Authorization/AsyncGate.swift b/Sources/MCP/Base/Authorization/AsyncGate.swift new file mode 100644 index 00000000..bdc3e8fe --- /dev/null +++ b/Sources/MCP/Base/Authorization/AsyncGate.swift @@ -0,0 +1,115 @@ +import Synchronization + +/// Runs async operations one at a time, in arrival order. +/// +/// A `Mutex` can't be held across `await`, so the gate holds its lock only to +/// change its state; the operation runs outside it. A waiting task that is +/// cancelled stops waiting and throws `CancellationError`, unless it waits +/// with `ignoringCancellation`. +/// +/// Call `run(ignoringCancellation:_:)` from a nonisolated context: its +/// operation is not `Sendable`, so an actor-isolated caller can't pass one. +final class AsyncGate: Sendable { + private struct Waiter { + let id: Int + let continuation: CheckedContinuation + } + + private struct State { + var isBusy = false + var nextWaiterID = 0 + var waiters: [Waiter] = [] + } + + private let state = Mutex(State()) + + /// The number of tasks waiting for the gate. + var waiterCount: Int { state.withLock { $0.waiters.count } } + + /// Runs `body` once every earlier caller has finished. + /// + /// - Parameters: + /// - ignoringCancellation: Whether to keep waiting when the task is + /// cancelled. Use it for short operations that must not be skipped, + /// such as saving a token the authorization server has already issued. + /// The body itself still sees the cancellation. + /// - body: The operation to run while holding the gate. + /// - Returns: The value `body` returns. + /// - Throws: `CancellationError` when the task is cancelled while it + /// waits (unless `ignoringCancellation`), or the error of `body`. + func run(ignoringCancellation: Bool = false, _ body: () async throws -> T) async throws -> T { + if ignoringCancellation { + try await acquireIgnoringCancellation() + } else { + try await acquire() + } + defer { release() } + return try await body() + } + + /// Takes the gate when it is free, or returns an ID to wait under. + private func enter() -> Int? { + state.withLock { state in + guard state.isBusy else { + state.isBusy = true + return nil + } + state.nextWaiterID += 1 + return state.nextWaiterID + } + } + + private func acquire() async throws { + guard let id = enter() else { return } + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + let resumeNow: Result? = state.withLock { state in + // Checked under the lock: a cancellation either finds + // this waiter or is seen here. + if Task.isCancelled { return .failure(CancellationError()) } + guard state.isBusy else { + state.isBusy = true + return .success(()) + } + state.waiters.append(Waiter(id: id, continuation: continuation)) + return nil + } + if let resumeNow { continuation.resume(with: resumeNow) } + } + } onCancel: { + let cancelled: CheckedContinuation? = state.withLock { state in + guard let index = state.waiters.firstIndex(where: { $0.id == id }) else { return nil } + return state.waiters.remove(at: index).continuation + } + cancelled?.resume(throwing: CancellationError()) + } + } + + /// Waits without a cancellation handler, so only `release()` resumes + /// the waiter, and never with an error. + private func acquireIgnoringCancellation() async throws { + guard let id = enter() else { return } + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + let isFree: Bool = state.withLock { state in + guard state.isBusy else { + state.isBusy = true + return true + } + state.waiters.append(Waiter(id: id, continuation: continuation)) + return false + } + if isFree { continuation.resume() } + } + } + + private func release() { + let next: CheckedContinuation? = state.withLock { state in + if state.waiters.isEmpty { + state.isBusy = false + return nil + } + return state.waiters.removeFirst().continuation + } + next?.resume() + } +} diff --git a/Sources/MCP/Base/Authorization/HTTPAuthorizationChallenge.swift b/Sources/MCP/Base/Authorization/HTTPAuthorizationChallenge.swift new file mode 100644 index 00000000..62f30455 --- /dev/null +++ b/Sources/MCP/Base/Authorization/HTTPAuthorizationChallenge.swift @@ -0,0 +1,101 @@ +import Foundation + +/// A `401 Unauthorized` or `403 Forbidden` response to a request that +/// ``HTTPClientTransport`` sent, passed to ``HTTPClientAuthorizer/handleChallenge(_:session:)``. +/// +/// Its description, and the mirror that `dump(_:)` and debuggers read, name the +/// header fields without their values and leave out ``sentAuthorization``, so +/// logging a challenge reveals no token. +/// +/// - SeeAlso: https://www.rfc-editor.org/rfc/rfc6750#section-3 +/// - SeeAlso: https://www.rfc-editor.org/rfc/rfc9449#section-7.1 +/// - SeeAlso: https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#error-handling +public struct HTTPAuthorizationChallenge: Hashable, Sendable { + /// The HTTP status code, `401` or `403`. + public let statusCode: Int + + /// The response headers, among them `WWW-Authenticate` and, with DPoP, `DPoP-Nonce`. + public let headers: [String: String] + + /// The MCP endpoint the challenged request was sent to. + public let endpoint: URL + + /// The JSON-RPC method of the challenged request, such as `tools/call`, or `nil` + /// for a request that carries none, such as the GET stream. + /// + /// ``OAuthAuthorizer`` counts scope step-ups per resource, method and scope set. + public let operationKey: String? + + /// The `Authorization` header the challenged request carried, or `nil`. + /// + /// Compare it with the current token to tell a challenge for a token another + /// request has already replaced from one for the current token. + public let sentAuthorization: String? + + /// Creates a challenge. + /// + /// - Parameters: + /// - statusCode: The HTTP status code, `401` or `403`. + /// - headers: The response headers. + /// - endpoint: The MCP endpoint the challenged request was sent to. + /// - operationKey: The JSON-RPC method of the challenged request, if any. + /// - sentAuthorization: The `Authorization` header the request carried, if any. + public init( + statusCode: Int, headers: [String: String], endpoint: URL, + operationKey: String? = nil, sentAuthorization: String? = nil + ) { + self.statusCode = statusCode + self.headers = headers + self.endpoint = endpoint + self.operationKey = operationKey + self.sentAuthorization = sentAuthorization + } + + /// The value of the header `name`, compared case-insensitively. + /// + /// - Parameter name: The header name, such as `WWW-Authenticate`. + /// - Returns: The header's value, or `nil` when the response has none. + public func value(forHeader name: String) -> String? { + headers.first { $0.key.caseInsensitiveCompare(name) == .orderedSame }?.value + } +} + +// MARK: - Descriptions + +extension HTTPAuthorizationChallenge: CustomStringConvertible, CustomDebugStringConvertible { + /// The status code, the endpoint, the operation and the names of the headers. + /// + /// Header values, such as `WWW-Authenticate`, and ``sentAuthorization`` are + /// left out, so the challenge can be logged; read them from the properties. + /// The endpoint is shown without user information, query and fragment. + public var description: String { + "HTTPAuthorizationChallenge(statusCode: \(statusCode), endpoint: \(redactedEndpoint), " + + "operationKey: \(operationKey ?? "nil"), headers: \(headerNames))" + } + + /// The same as ``description``. + public var debugDescription: String { description } + + /// The names of the headers, without their values. + private var headerNames: [String] { + headers.keys.sorted { $0.lowercased() < $1.lowercased() } + } + + /// The endpoint without user information, query and fragment, which can carry secrets. + private var redactedEndpoint: String { OAuthURLValidator.redacted(endpoint) } +} + +extension HTTPAuthorizationChallenge: CustomReflectable { + /// A mirror with the same redactions as ``description``, for `dump(_:)` and debuggers. + public var customMirror: Mirror { + Mirror( + self, + children: [ + "statusCode": statusCode, + "endpoint": redactedEndpoint, + "operationKey": operationKey as Any, + "headers": headerNames, + ], + displayStyle: .struct) + } +} diff --git a/Sources/MCP/Base/Authorization/HTTPChallengeResult.swift b/Sources/MCP/Base/Authorization/HTTPChallengeResult.swift index f54587de..d1b2c067 100644 --- a/Sources/MCP/Base/Authorization/HTTPChallengeResult.swift +++ b/Sources/MCP/Base/Authorization/HTTPChallengeResult.swift @@ -1,12 +1,12 @@ import Foundation -/// How ``HTTPClientTransport`` answers an authorization challenge: the result -/// of ``HTTPClientAuthorizer/handleChallenge(statusCode:headers:endpoint:operationKey:sentAuthorization:session:)``. +/// How ``HTTPClientTransport`` answers an authorization challenge: the result of +/// ``HTTPClientAuthorizer/handleChallenge(_:session:)``. /// /// - SeeAlso: https://www.rfc-editor.org/rfc/rfc9449#section-9 public struct HTTPChallengeResult: Hashable, Sendable { - /// Whether to send the challenged request again. - public var retry: Bool + /// Whether to send the challenged request again, with the authorizer's new headers. + public var shouldRetry: Bool /// Whether the retry only answers a resource server's DPoP `use_dpop_nonce` /// challenge with the nonce it sent, keeping the token (RFC 9449 §9). @@ -14,33 +14,32 @@ public struct HTTPChallengeResult: Hashable, Sendable { /// ``HTTPClientTransport`` allows one such retry per request without /// counting it against ``HTTPClientAuthorizer/maxAuthorizationAttempts``; /// a second one fails the request. The transport ignores this value when - /// ``retry`` is `false`. + /// ``shouldRetry`` is `false`. public var isDPoPNonceRetry: Bool /// Creates a challenge result. /// + /// When `shouldRetry` is `false`, ``isDPoPNonceRetry`` is set to `false`. + /// /// - Parameters: - /// - retry: Whether to send the challenged request again. + /// - shouldRetry: Whether to send the challenged request again. /// - isDPoPNonceRetry: Whether the retry only answers a DPoP nonce challenge. - public init(retry: Bool, isDPoPNonceRetry: Bool = false) { - self.retry = retry - self.isDPoPNonceRetry = isDPoPNonceRetry + public init(shouldRetry: Bool, isDPoPNonceRetry: Bool = false) { + self.shouldRetry = shouldRetry + self.isDPoPNonceRetry = shouldRetry && isDPoPNonceRetry } -} -extension HTTPChallengeResult { - /// Whether a challenge is a resource server's `use_dpop_nonce`, read with - /// ``DefaultOAuthWWWAuthenticateParser``, with the `DPoP-Nonce` header it - /// requires (RFC 9449 §9). Without the header no retry can carry a nonce, - /// so the challenge is an ordinary one. - static func isDPoPNonceChallenge(statusCode: Int, headers: [String: String]) -> Bool { - statusCode == 401 - && DefaultOAuthWWWAuthenticateParser() - .parseChallenge(scheme: OAuthTokenType.dpop, from: headers)?.error - == OAuthErrorCode.useDPoPNonce - && headers.contains { - $0.key.caseInsensitiveCompare(HTTPHeaderName.dpopNonce) == .orderedSame - && !$0.value.trimmingCharacters(in: .whitespaces).isEmpty - } - } + /// A result that sends the request again, because the authorizer has a token for it. + public static let retry = HTTPChallengeResult(shouldRetry: true) + + /// A result that sends the request again with the resource server's DPoP + /// nonce, keeping the token (RFC 9449 §9). + /// + /// The transport allows one such retry per request, not counted against + /// ``HTTPClientAuthorizer/maxAuthorizationAttempts``. + public static let retryWithDPoPNonce = HTTPChallengeResult(shouldRetry: true, isDPoPNonceRetry: true) + + /// A result that doesn't send the request again: the request fails with the + /// challenge's ``HTTPStatusError``. + public static let unhandled = HTTPChallengeResult(shouldRetry: false) } diff --git a/Sources/MCP/Base/Authorization/OAuthAuthorizationCodeFlow.swift b/Sources/MCP/Base/Authorization/OAuthAuthorizationCodeFlow.swift index 97ccc2eb..99c8bb6a 100644 --- a/Sources/MCP/Base/Authorization/OAuthAuthorizationCodeFlow.swift +++ b/Sources/MCP/Base/Authorization/OAuthAuthorizationCodeFlow.swift @@ -84,6 +84,8 @@ public struct OAuthAuthorizationCodeFlow: Sendable { /// - state: The CSRF state nonce. /// - scopeSerializer: Serializes the scope set to a space-separated string. /// - Returns: The full authorization request URL with all query parameters. + /// - Throws: ``OAuthAuthorizationError/authorizationEndpointInvalid(url:)`` when + /// `authorizationEndpoint` can't be made into a URL with these query parameters. public func buildURL( authorizationEndpoint: URL, resource: URL, @@ -98,7 +100,8 @@ public struct OAuthAuthorizationCodeFlow: Sendable { url: authorizationEndpoint, resolvingAgainstBaseURL: false ) else { - throw OAuthAuthorizationError.authorizationServerMetadataDiscoveryFailed + throw OAuthAuthorizationError.authorizationEndpointInvalid( + url: OAuthURLValidator.redacted(authorizationEndpoint)) } var queryItems: [URLQueryItem] = [ @@ -118,7 +121,8 @@ public struct OAuthAuthorizationCodeFlow: Sendable { components.queryItems = queryItems guard let url = components.url else { - throw OAuthAuthorizationError.authorizationServerMetadataDiscoveryFailed + throw OAuthAuthorizationError.authorizationEndpointInvalid( + url: OAuthURLValidator.redacted(authorizationEndpoint)) } return url } @@ -227,15 +231,15 @@ public struct OAuthAuthorizationCodeFlow: Sendable { url: expectedRedirectURI, resolvingAgainstBaseURL: false) else { throw OAuthAuthorizationError.authorizationResponseRedirectMismatch( - expected: expectedRedirectURI.absoluteString, - actual: redirectURL.absoluteString + expected: OAuthURLValidator.redacted(expectedRedirectURI), + actual: OAuthURLValidator.redacted(redirectURL) ) } if normalizedRedirectBase(redirectComponents) != normalizedRedirectBase(expectedComponents) { throw OAuthAuthorizationError.authorizationResponseRedirectMismatch( - expected: expectedRedirectURI.absoluteString, - actual: redirectURL.absoluteString + expected: OAuthURLValidator.redacted(expectedRedirectURI), + actual: OAuthURLValidator.redacted(redirectURL) ) } diff --git a/Sources/MCP/Base/Authorization/OAuthAuthorizer.swift b/Sources/MCP/Base/Authorization/OAuthAuthorizer.swift index 1ba46f66..da0227dd 100644 --- a/Sources/MCP/Base/Authorization/OAuthAuthorizer.swift +++ b/Sources/MCP/Base/Authorization/OAuthAuthorizer.swift @@ -1,154 +1,137 @@ import Foundation +import Synchronization #if canImport(FoundationNetworking) import FoundationNetworking #endif - // MARK: - HTTPClientAuthorizer Protocol -/// Abstraction used by ``HTTPClientTransport`` to handle OAuth authorization challenges. +/// The authorization that ``HTTPClientTransport`` applies to its requests. +/// +/// Use the built-in ``OAuthAuthorizer`` for MCP authorization (OAuth 2.1), or +/// implement this protocol for another token source. A class, a struct or an actor +/// can conform; an actor declares ``maxAuthorizationAttempts`` `nonisolated`. +/// +/// For each POST and each GET stream, the transport requires its endpoint to be +/// `https`, or `http` on a loopback host, without a fragment, and otherwise fails +/// the request with ``MCPError/transportError(_:)`` wrapping +/// ``OAuthAuthorizationError/insecureOAuthEndpoint(context:url:)`` +/// (``OAuthAuthorizationError/invalidResourceURI(_:)`` for a fragment) before it +/// calls the authorizer. Then it calls ``prepare(for:session:)``, builds the +/// request, runs its `requestModifier`, checks the final URL in the same way, and +/// sets the headers of +/// ``authorizationHeaders(for:method:)``. It passes the headers of every response to +/// ``didReceiveResponse(headers:for:)``. On a `401` or `403` it calls +/// ``handleChallenge(_:session:)`` and retries the request while the result says +/// so, up to ``maxAuthorizationAttempts`` total attempts (the initial request plus +/// up to `maxAuthorizationAttempts - 1` retries). +/// +/// The transport follows redirects. For a redirect to the same origin (scheme, host +/// and port) it calls ``authorizationHeaders(for:method:)`` again, with the target URL +/// and the method of the redirected request, while the request is in flight; the +/// redirected request has no `Authorization` when that call returns none. That call +/// is part of the request: its time counts against +/// ``Client/Configuration/discoveryTimeout``, and cancelling the request cancels it. +/// An error it throws stops the redirect and fails the request like any other error +/// of the authorizer. A redirect to another origin gets no credentials, and neither +/// does any later hop, one back to the origin included; a `401` or `403` it leads to +/// is not passed to ``handleChallenge(_:session:)``: the request fails with +/// ``OAuthAuthorizationError/protectedResourceMismatch(expected:actual:)``. /// -/// Implement this protocol to provide custom token acquisition strategies, -/// or use the built-in ``OAuthAuthorizer`` for a full OAuth 2.1 implementation. +/// Requests of one transport run concurrently, so these methods are called from +/// several tasks at once. An error thrown by any of them fails the request with +/// ``MCPError/transportError(_:)``; a `CancellationError` is thrown as is. /// -/// ``HTTPClientTransport`` calls these methods automatically when it receives -/// `401 Unauthorized` or `403 Forbidden` responses from the server. -public protocol HTTPClientAuthorizer: AnyObject, Sendable { - /// The maximum number of authorization retries permitted for a single request. +/// - SeeAlso: https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization +public protocol HTTPClientAuthorizer: Sendable { + /// The maximum number of total attempts ``HTTPClientTransport`` makes for one + /// request, including the initial attempt (`1` allows no non-nonce retry; `3` + /// allows the initial attempt plus up to `2` retries). /// - /// ``HTTPClientTransport`` will not call ``handleChallenge(statusCode:headers:endpoint:operationKey:session:)`` - /// more than this many times for a single outgoing request. + /// A retry that ``HTTPChallengeResult/isDPoPNonceRetry`` marks is not counted. var maxAuthorizationAttempts: Int { get } - /// Validates that the MCP endpoint URL satisfies the security requirements for OAuth. - /// - /// Called once before the first request is sent. Throw ``OAuthAuthorizationError/insecureOAuthEndpoint(context:url:)`` - /// if the URL does not meet the requirements (e.g., non-HTTPS non-loopback). - /// - Parameter endpoint: The MCP endpoint URL to validate. - func validateEndpointSecurity(for endpoint: URL) throws - - /// Returns the headers that authorize a request, if a valid token is available. - /// - /// ``HTTPClientTransport`` calls this for every request, after its - /// `requestModifier`, with the final URL and method; the returned headers - /// replace any of the same name. + /// Prepares the authorization of a request to `endpoint`, before the request is built. /// - /// - Parameters: - /// - url: The request URL. - /// - method: The HTTP method, such as `POST` or `GET`. - /// - Returns: `Authorization` (`Bearer ` or `DPoP `) and, for - /// a DPoP-bound token, a `DPoP` proof; empty if no valid token is cached. - func authorizationHeaders(for url: URL, method: String) throws -> [String: String] - - /// Handles an authorization challenge received from the server and attempts to acquire a new token. + /// Renew a token here that is about to expire. The request fails with an error + /// thrown here; an implementation that renews ahead of time ignores a failed + /// renewal, and the `401` path recovers. /// - /// Called by ``HTTPClientTransport`` when a `401` or `403` response is received. - /// The implementation should attempt to obtain a valid access token and store it - /// so that a subsequent call to ``authorizationHeaders(for:method:)`` returns it. + /// The transport checks `endpoint` first: it refuses to authorize requests to an + /// endpoint that is neither `https` nor `http` on a loopback host, or that has a + /// fragment, and fails them without calling this method, so an implementation + /// doesn't repeat the check. The default does nothing. /// /// - Parameters: - /// - statusCode: The HTTP status code (401 or 403). - /// - headers: All response headers from the challenge response. - /// - endpoint: The MCP endpoint that returned the challenge. - /// - operationKey: An optional identifier for the MCP operation (e.g., the JSON-RPC method), - /// used to track step-up attempts per operation. - /// - session: The `URLSession` to use for discovery and token requests. - /// - Returns: `true` if a new token was acquired and the original request should be retried; - /// `false` if the challenge cannot be handled. - func handleChallenge( - statusCode: Int, - headers: [String: String], - endpoint: URL, - operationKey: String?, - session: URLSession - ) async throws -> Bool + /// - endpoint: The MCP endpoint the request goes to. + /// - session: The `URLSession` for token requests. + /// - Throws: An error of the implementation, which fails the request. + func prepare(for endpoint: URL, session: URLSession) async throws - /// Handles an authorization challenge, knowing the `Authorization` value - /// the challenged request carried. - /// - /// ``HTTPClientTransport`` calls this method. With the sent value, an - /// implementation can tell a challenge for a token that another request - /// has already replaced from a challenge for the current token. The - /// result also says whether the retry only answers a DPoP `use_dpop_nonce` - /// challenge (RFC 9449 §9), which the transport allows once per request - /// without counting it against ``maxAuthorizationAttempts``. + /// Returns the headers that authorize a request, empty when no valid token is available. /// - /// The default implementation calls - /// ``handleChallenge(statusCode:headers:endpoint:operationKey:session:)`` - /// and reports a DPoP nonce retry when it returns `true` for a `401` - /// whose `DPoP` challenge, read with ``DefaultOAuthWWWAuthenticateParser``, - /// has the error `use_dpop_nonce`, and that carries a `DPoP-Nonce` header. + /// Called for every request, after the `requestModifier`, with the final URL and + /// method, and for each redirect of it to the same origin, with the target URL and + /// the method of the redirected request. The returned headers replace any of the + /// same name. /// /// - Parameters: - /// - statusCode: The HTTP status code (401 or 403). - /// - headers: All response headers from the challenge response. - /// - endpoint: The MCP endpoint that returned the challenge. - /// - operationKey: An optional identifier for the MCP operation (e.g., the JSON-RPC method). - /// - sentAuthorization: The `Authorization` header of the challenged request, - /// or `nil` when it had none. - /// - session: The `URLSession` to use for discovery and token requests. - /// - Returns: Whether to retry the original request, and whether that - /// retry is a DPoP nonce retry. - func handleChallenge( - statusCode: Int, - headers: [String: String], - endpoint: URL, - operationKey: String?, - sentAuthorization: String?, - session: URLSession - ) async throws -> HTTPChallengeResult + /// - url: The request URL. + /// - method: The HTTP method, such as `POST` or `GET`. + /// - Returns: `Authorization` (`Bearer ` or `DPoP `) and, for a + /// DPoP-bound token, a `DPoP` proof (RFC 9449 §4, §7.1). + /// - Throws: An error of the implementation, such as one of its token storage or + /// its signing key, which fails the request. + func authorizationHeaders(for url: URL, method: String) async throws -> [String: String] - /// Proactively refreshes the access token if it is close to expiry. + /// Answers an authorization challenge, and says whether to send the request again. /// - /// Called by ``HTTPClientTransport`` before sending each request and before opening - /// an SSE stream, allowing the token to be silently renewed without a 401 round-trip. - /// Implementations should swallow refresh errors — if refresh fails, the normal - /// ``handleChallenge(statusCode:headers:endpoint:operationKey:session:)`` path recovers. + /// Obtain a token here so that the next ``authorizationHeaders(for:method:)`` + /// returns it. Compare ``HTTPAuthorizationChallenge/sentAuthorization`` with the + /// current token: when another challenge has replaced the token meanwhile, return + /// ``HTTPChallengeResult/retry`` without another flow. Return + /// ``HTTPChallengeResult/retryWithDPoPNonce`` for a `use_dpop_nonce` challenge + /// that only needs the server's nonce (RFC 9449 §9), and + /// ``HTTPChallengeResult/unhandled`` for a challenge you don't answer. /// /// - Parameters: - /// - endpoint: The MCP endpoint about to be contacted. - /// - session: The `URLSession` to use for token refresh requests. - func prepareAuthorization(for endpoint: URL, session: URLSession) async throws + /// - challenge: The `401` or `403` response. + /// - session: The `URLSession` for discovery and token requests. + /// - Returns: Whether to send the request again. + /// - Throws: An error of the implementation, such as a refused grant or a user + /// who cancelled the sign-in, which fails the request instead of the challenge's + /// ``HTTPStatusError``. + func handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) async throws + -> HTTPChallengeResult /// Inspects the headers of a response, before any challenge handling. /// - /// ``HTTPClientTransport`` calls this for every response with the URL the - /// request was sent to. ``OAuthAuthorizer`` records a `DPoP-Nonce` here - /// (RFC 9449 §8). The default does nothing. + /// ``OAuthAuthorizer`` records a `DPoP-Nonce` here (RFC 9449 §8). The default does nothing. /// /// - Parameters: /// - headers: The response headers. - /// - url: The request URL. - func didReceiveResponse(headers: [String: String], for url: URL) + /// - url: The URL that answered, after any redirects. + func didReceiveResponse(headers: [String: String], for url: URL) async } extension HTTPClientAuthorizer { /// Does nothing. - public func prepareAuthorization(for endpoint: URL, session: URLSession) async throws {} - - /// Calls ``handleChallenge(statusCode:headers:endpoint:operationKey:session:)``, - /// ignoring `sentAuthorization`, and reports a DPoP nonce retry for a - /// retried `401` `use_dpop_nonce` challenge with a `DPoP-Nonce` header. - public func handleChallenge( - statusCode: Int, - headers: [String: String], - endpoint: URL, - operationKey: String?, - sentAuthorization: String?, - session: URLSession - ) async throws -> HTTPChallengeResult { - let retry = try await handleChallenge( - statusCode: statusCode, headers: headers, endpoint: endpoint, operationKey: operationKey, - session: session) - return HTTPChallengeResult( - retry: retry, - isDPoPNonceRetry: retry - && HTTPChallengeResult.isDPoPNonceChallenge(statusCode: statusCode, headers: headers)) - } + /// + /// ``HTTPClientTransport`` has already refused an endpoint that is neither + /// `https` nor `http` on a loopback host. + /// + /// - Parameters: + /// - endpoint: The MCP endpoint the request goes to. + /// - session: Not used. + public func prepare(for endpoint: URL, session: URLSession) async throws {} /// Does nothing. - public func didReceiveResponse(headers: [String: String], for url: URL) {} + /// + /// - Parameters: + /// - headers: The response headers. + /// - url: The URL that answered, after any redirects. + public func didReceiveResponse(headers: [String: String], for url: URL) async {} } // MARK: - OAuthAuthorizer @@ -183,111 +166,119 @@ extension HTTPClientAuthorizer { /// let transport = HTTPClientTransport(endpoint: serverURL, authorizer: authorizer) /// ``` /// -/// - Important: Requests of one transport run concurrently. `handleChallenge` -/// and `prepareAuthorization` run one at a time: a challenge that arrives -/// while another is handled waits for it, and retries with the token it -/// obtained instead of starting another flow. Each piece of state is read -/// and written under a lock. One authorizer serves one resource; do not -/// share it between transports for different servers. -public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { +/// - Important: Requests of one transport run concurrently. Challenges and +/// proactive renewals run one at a time: a challenge that arrives while +/// another is handled waits for it, and retries with the token it obtained +/// instead of starting another flow. Storage writes run one at a time too, +/// and a token is cleared only while it is still the stored one. Tokens are +/// kept per resource (see ``OAuthTokenStorage``), so one storage can serve +/// authorizers for several servers. One authorizer serves one MCP server: use +/// one per server, and the same one for every transport to that server. +public final class OAuthAuthorizer: HTTPClientAuthorizer, Sendable { // MARK: - Mutable State - /// Guards every stored property below that has an underscore. - private let stateLock = NSLock() - /// Runs `handleChallenge` and `prepareAuthorization` one at a time. - let gate = AsyncGate() + /// The authorizer's mutable state. Each access takes the lock once; a + /// read-modify-write that must be atomic uses one `withLock`. + private struct State { + var configuration: OAuthConfiguration + var selectedAuthorizationServer: URL? + var protectedResourceMetadata: OAuthProtectedResourceMetadata? + var authorizationServerMetadata: OAuthAuthorizationServerMetadata? + var cachedProtectedResourceMetadataURL: URL? + var stepUpAttempts: [String: Int] = [:] + var clientRegistrationAttempted = false + var clientSecretExpiresAt: Date? + /// The authorization server that issued registered credentials (SEP-2352). + var registrationIssuer: URL? + /// The authorization server of the last registration attempt. + var registrationAttemptIssuer: URL? + var refreshedTokenValue: String? + var completedChallenges = 0 + var lastChallengeError: (any Error)? + var storedTokenLifetime: (value: String, seconds: TimeInterval)? + var proactivelyRenewedToken: String? + /// The MCP endpoint of the last `prepare(for:session:)` or challenge. + var servedEndpoint: URL? + /// A token left under a previous storage key when a resource key change + /// failed transiently before migration completed. + var pendingSuperseded: (key: URL, token: OAuthAccessToken)? + /// The newly discovered resource key whose pre-existing token has not + /// yet been validated or replaced after a resource key change. + var pendingKeyChangeResource: URL? + } - private var _configuration: OAuthConfiguration - private var _selectedAuthorizationServer: URL? - private var _protectedResourceMetadata: OAuthProtectedResourceMetadata? - private var _authorizationServerMetadata: OAuthAuthorizationServerMetadata? - private var _cachedProtectedResourceMetadataURL: URL? - private var _stepUpAttempts: [String: Int] = [:] - private var _clientRegistrationAttempted = false - private var _clientSecretExpiresAt: Date? - private var _registrationIssuer: URL? - private var _registrationAttemptIssuer: URL? - private var _refreshedTokenValue: String? - private var _completedChallenges = 0 - private var _lastChallengeError: (any Error)? - private var _storedTokenLifetime: (value: String, seconds: TimeInterval)? - private var _proactivelyRenewedToken: String? + private let state: Mutex + /// Runs challenges and proactive renewals one at a time. + let gate = AsyncGate() + /// The token storage; its writes run one at a time (see `TokenStore`). + let tokens: TokenStore private var configuration: OAuthConfiguration { - get { stateLock.withLock { _configuration } } - set { stateLock.withLock { _configuration = newValue } } + get { state.withLock { $0.configuration } } + set { state.withLock { $0.configuration = newValue } } } private var selectedAuthorizationServer: URL? { - get { stateLock.withLock { _selectedAuthorizationServer } } - set { stateLock.withLock { _selectedAuthorizationServer = newValue } } + get { state.withLock { $0.selectedAuthorizationServer } } + set { state.withLock { $0.selectedAuthorizationServer = newValue } } } private var protectedResourceMetadata: OAuthProtectedResourceMetadata? { - get { stateLock.withLock { _protectedResourceMetadata } } - set { stateLock.withLock { _protectedResourceMetadata = newValue } } + get { state.withLock { $0.protectedResourceMetadata } } + set { state.withLock { $0.protectedResourceMetadata = newValue } } } private var authorizationServerMetadata: OAuthAuthorizationServerMetadata? { - get { stateLock.withLock { _authorizationServerMetadata } } - set { stateLock.withLock { _authorizationServerMetadata = newValue } } + get { state.withLock { $0.authorizationServerMetadata } } + set { state.withLock { $0.authorizationServerMetadata = newValue } } } private var cachedProtectedResourceMetadataURL: URL? { - get { stateLock.withLock { _cachedProtectedResourceMetadataURL } } - set { stateLock.withLock { _cachedProtectedResourceMetadataURL = newValue } } - } - private var stepUpAttempts: [String: Int] { - get { stateLock.withLock { _stepUpAttempts } } - set { stateLock.withLock { _stepUpAttempts = newValue } } - } - private var clientRegistrationAttempted: Bool { - get { stateLock.withLock { _clientRegistrationAttempted } } - set { stateLock.withLock { _clientRegistrationAttempted = newValue } } - } - private var clientSecretExpiresAt: Date? { - get { stateLock.withLock { _clientSecretExpiresAt } } - set { stateLock.withLock { _clientSecretExpiresAt = newValue } } - } - /// The authorization server that issued registered credentials (SEP-2352). - private var registrationIssuer: URL? { - get { stateLock.withLock { _registrationIssuer } } - set { stateLock.withLock { _registrationIssuer = newValue } } - } - /// The authorization server of the last registration attempt. - private var registrationAttemptIssuer: URL? { - get { stateLock.withLock { _registrationAttemptIssuer } } - set { stateLock.withLock { _registrationAttemptIssuer = newValue } } + get { state.withLock { $0.cachedProtectedResourceMetadataURL } } + set { state.withLock { $0.cachedProtectedResourceMetadataURL = newValue } } } /// The access token the last refresh returned. When the resource rejects /// it, the next challenge reads the resource metadata again before /// refreshing at the same server. private var refreshedTokenValue: String? { - get { stateLock.withLock { _refreshedTokenValue } } - set { stateLock.withLock { _refreshedTokenValue = newValue } } + get { state.withLock { $0.refreshedTokenValue } } + set { state.withLock { $0.refreshedTokenValue = newValue } } } /// The number of challenges handled to the end, and the error the last /// one ended with (`nil` when it succeeded). Cancelled ones are not /// counted. private var lastChallenge: (count: Int, error: (any Error)?) { - stateLock.withLock { (_completedChallenges, _lastChallengeError) } + state.withLock { ($0.completedChallenges, $0.lastChallengeError) } } private func recordChallenge(error: (any Error)?) { - stateLock.withLock { - _completedChallenges += 1 - _lastChallengeError = error + state.withLock { + $0.completedChallenges += 1 + $0.lastChallengeError = error } } /// The `expires_in` of the token this authorizer stored last. private var storedTokenLifetime: (value: String, seconds: TimeInterval)? { - get { stateLock.withLock { _storedTokenLifetime } } - set { stateLock.withLock { _storedTokenLifetime = newValue } } + get { state.withLock { $0.storedTokenLifetime } } + set { state.withLock { $0.storedTokenLifetime = newValue } } + } + /// The MCP endpoint the authorizer serves: the resource when neither the + /// configuration nor the metadata names one. + private var servedEndpoint: URL? { + get { state.withLock { $0.servedEndpoint } } + set { state.withLock { $0.servedEndpoint = newValue } } + } + private var pendingSuperseded: (key: URL, token: OAuthAccessToken)? { + get { state.withLock { $0.pendingSuperseded } } + set { state.withLock { $0.pendingSuperseded = newValue } } } - /// The access token `prepareAuthorization` last tried to replace. It is + private var pendingKeyChangeResource: URL? { + get { state.withLock { $0.pendingKeyChangeResource } } + set { state.withLock { $0.pendingKeyChangeResource = newValue } } + } + /// The access token `prepare(for:session:)` last tried to replace. It is /// tried once: a failed renewal is left to the 401 path. private var proactivelyRenewedToken: String? { - get { stateLock.withLock { _proactivelyRenewedToken } } - set { stateLock.withLock { _proactivelyRenewedToken = newValue } } + get { state.withLock { $0.proactivelyRenewedToken } } + set { state.withLock { $0.proactivelyRenewedToken = newValue } } } - private let tokenStorage: TokenStorage /// The authentication configured at creation, restored when registered /// credentials no longer apply. private let configuredAuthentication: OAuthConfiguration.TokenEndpointAuthentication @@ -309,9 +300,9 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { /// - Parameters: /// - configuration: OAuth 2.1 configuration controlling the grant type, authentication method, /// endpoint discovery overrides, and retry policy. - /// - tokenStorage: Stores acquired access tokens. Defaults to ``InMemoryTokenStorage``, - /// which loses tokens when the process exits. Supply a Keychain-backed implementation - /// to persist tokens across sessions. + /// - tokenStorage: Stores acquired access tokens, one per resource. Defaults to + /// ``InMemoryOAuthTokenStorage``, which loses tokens when the process exits. Supply a + /// Keychain-backed implementation to persist tokens across sessions. /// - scopeSelector: Strategy for selecting OAuth scopes from challenge and metadata hints. /// Defaults to ``DefaultOAuthScopeSelector``. /// - challengeParser: Parses `WWW-Authenticate: Bearer` challenge headers. @@ -320,7 +311,7 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { /// Defaults to ``DefaultOAuthMetadataDiscovery``. public convenience init( configuration: OAuthConfiguration, - tokenStorage: TokenStorage = InMemoryTokenStorage(), + tokenStorage: any OAuthTokenStorage = InMemoryOAuthTokenStorage(), scopeSelector: any OAuthScopeSelecting = DefaultOAuthScopeSelector(), challengeParser: any OAuthWWWAuthenticateParsing = DefaultOAuthWWWAuthenticateParser(), metadataDiscovery: any OAuthMetadataDiscovering = DefaultOAuthMetadataDiscovery() @@ -347,7 +338,7 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { init( configuration: OAuthConfiguration, - tokenStorage: TokenStorage = InMemoryTokenStorage(), + tokenStorage: any OAuthTokenStorage = InMemoryOAuthTokenStorage(), scopeSelector: any OAuthScopeSelecting = DefaultOAuthScopeSelector(), challengeParser: any OAuthWWWAuthenticateParsing = DefaultOAuthWWWAuthenticateParser(), urlValidator: any OAuthURLValidating, @@ -356,9 +347,9 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { clientRegistrar: any OAuthClientRegistering, authCodeFlow: any OAuthAuthorizationCodeFlowing ) { - self._configuration = configuration + self.state = Mutex(State(configuration: configuration)) self.configuredAuthentication = configuration.authentication - self.tokenStorage = tokenStorage + self.tokens = TokenStore(storage: tokenStorage) self.scopeSelector = scopeSelector self.challengeParser = challengeParser self.urlValidator = urlValidator @@ -377,44 +368,199 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { } /// Requires the MCP endpoint to use HTTPS, or HTTP on a loopback host, without a fragment. - public func validateEndpointSecurity(for endpoint: URL) throws { + private func validateEndpoint(_ endpoint: URL) throws { try urlValidator.validateHTTPSOrLoopback(endpoint, context: "MCP endpoint") } - /// Returns the `Authorization` header for the stored access token, with a - /// `DPoP` proof when the token is DPoP-bound. + /// Returns the `Authorization` header for the token stored for the + /// resource of `url`, with a `DPoP` proof when the token is DPoP-bound. /// /// Returns no headers when the token has expired. A token from another /// authorization server than the selected one, or bound to another DPoP /// key, is cleared. - public func authorizationHeaders(for url: URL, method: String) throws -> [String: String] { - guard let accessToken = tokenStorage.load() else { return [:] } - if let tokenAuthorizationServer = accessToken.authorizationServer, - let selectedAuthorizationServer, - !authorizationServersMatch(tokenAuthorizationServer, selectedAuthorizationServer) - { - clearStoredToken(accessToken) - return [:] + /// + /// - Parameters: + /// - url: The request URL. + /// - method: The HTTP method, such as `POST` or `GET`. + /// - Returns: The headers, or none without a valid token. + /// - Throws: ``OAuthAuthorizationError/protectedResourceMismatch(expected:actual:)`` + /// for a URL the named resource doesn't cover, or, when nothing names a + /// resource, a URL on another origin than the endpoint, once the metadata + /// has been read; an error of the token storage; or an error of the DPoP key. + public func authorizationHeaders(for url: URL, method: String) async throws -> [String: String] { + // Snapshot metadata and pending key-change state together before + // awaiting tokens.load(for:) so a pre-existing unvalidated token loaded + // while a migration finishes cannot slip through once the migration + // clears pendingKeyChangeResource. + let (metadata, pendingResource) = state.withLock { + ($0.protectedResourceMetadata, $0.pendingKeyChangeResource) } + let resource = try canonicalResource(for: url, using: metadata) + guard let accessToken = try await tokens.load(for: resource) else { return [:] } // A DPoP-bound token, expired or not, is usable only with the key it // is bound to, and so is its refresh token (RFC 9449 §5). - if isBoundToAnotherKey(accessToken) { - clearStoredToken(accessToken) + if isFromAnotherAuthorizationServer(accessToken) || isBoundToAnotherKey(accessToken) { + try await tokens.clear(accessToken, for: resource) { [self] current in + isFromAnotherAuthorizationServer(current) || isBoundToAnotherKey(current) + } + return [:] + } + let unvalidatedBeforeLoad = + pendingResource == resource + && (metadata.map { !isUsableAfterKeyChange(accessToken, metadata: $0) } ?? false) + if unvalidatedBeforeLoad || isUnvalidatedAfterKeyChange(accessToken, for: resource) { return [:] } if accessToken.isExpired() { return [:] } + // RFC 9449 §5.2: do not send a Bearer token to a resource requiring + // DPoP-bound tokens, while keeping any refresh token for the 401 path. + if protectedResourceMetadata?.dpopBoundAccessTokensRequired == true, !accessToken.isDPoPBound { + return [:] + } guard let dpopSigner, accessToken.isDPoPBound else { return [HTTPHeaderName.authorization: "\(OAuthTokenType.bearer) \(accessToken.value)"] } return [ HTTPHeaderName.authorization: "\(OAuthTokenType.dpop) \(accessToken.value)", - HTTPHeaderName.dpop: try dpopSigner.proof( + HTTPHeaderName.dpop: try await dpopSigner.proof( method: method, url: url, accessToken: accessToken.value, server: .resourceServer), ] } + /// Whether `token` records another authorization server than the active + /// constraint (selected server, configured override, or discovered + /// protected resource metadata). + private func isFromAnotherAuthorizationServer(_ token: OAuthAccessToken) -> Bool { + guard let issuer = token.authorizationServer else { return false } + let (selected, configured, metadata) = state.withLock { + ( + $0.selectedAuthorizationServer, + $0.configuration.endpointOverrides.authorizationServerURL, + $0.protectedResourceMetadata + ) + } + if let selected { return !authorizationServersMatch(issuer, selected) } + if let configured { return !authorizationServersMatch(issuer, configured) } + if let metadata { return !metadata.authorizationServers.contains { authorizationServersMatch(issuer, $0) } } + return false + } + + /// Whether a server that `metadata` lists issued `token`, or, with + /// `endpointOverrides.authorizationServerURL`, the configured server. A + /// token that records no server was issued by none. + private func isIssued(_ token: OAuthAccessToken, byServerOf metadata: OAuthProtectedResourceMetadata) -> Bool { + guard let issuer = token.authorizationServer else { return false } + if let configured = configuration.endpointOverrides.authorizationServerURL { + return authorizationServersMatch(issuer, configured) + } + return metadata.authorizationServers.contains { authorizationServersMatch(issuer, $0) } + } + + /// Whether `token`, found under the key the resource metadata names, may be + /// used: a server the metadata lists issued it, it is not from another + /// server than the active constraint, it is not bound to another DPoP key, + /// and it is DPoP-bound when the resource requires DPoP. + private func isUsableAfterKeyChange(_ token: OAuthAccessToken, metadata: OAuthProtectedResourceMetadata) -> Bool { + isIssued(token, byServerOf: metadata) && !isFromAnotherAuthorizationServer(token) + && !isBoundToAnotherKey(token) + && (metadata.dpopBoundAccessTokensRequired != true || token.isDPoPBound) + } + + /// Whether `token` can be sent as-is given the authorizer's current state. + private func isUsableToken(_ token: OAuthAccessToken) -> Bool { + let requiresDPoP = state.withLock { $0.protectedResourceMetadata?.dpopBoundAccessTokensRequired == true } + return !isFromAnotherAuthorizationServer(token) && !isBoundToAnotherKey(token) + && (!requiresDPoP || token.isDPoPBound) + } + + /// Whether a token stored under a superseded key may be kept for refresh + /// or scope union after a resource key change. + private func isEligibleSuperseded(_ token: OAuthAccessToken) -> Bool { + !isFromAnotherAuthorizationServer(token) && !isBoundToAnotherKey(token) + } + + /// Whether `token` loaded under `resource` must be ignored because a + /// resource key change to `resource` has not yet validated or replaced + /// pre-existing tokens under that key. + func isUnvalidatedAfterKeyChange(_ token: OAuthAccessToken, for resource: URL) -> Bool { + let (pendingResource, metadata) = state.withLock { + ($0.pendingKeyChangeResource, $0.protectedResourceMetadata) + } + guard pendingResource == resource, let metadata else { return false } + return !isUsableAfterKeyChange(token, metadata: metadata) + } + + /// Marks any unfinished resource key migration to `resource` complete. + private func clearPendingKeyChange(for resource: URL) { + state.withLock { state in + if state.pendingKeyChangeResource == resource { + state.pendingKeyChangeResource = nil + } + } + } + + /// Reloads the pending superseded token recorded before a transient + /// failure, if its key differs from `resource`, it is still stored, and it + /// remains eligible for the current authorization server and DPoP key. + /// + /// Best effort, like ``clearSuperseded(_:for:)``: a non-cancellation + /// storage error reading the old key drops the pending record and returns + /// `nil` instead of failing every later challenge. + private func loadPendingSuperseded(excluding resource: URL) async throws -> (key: URL, token: OAuthAccessToken)? { + guard let pending = pendingSuperseded, pending.key != resource else { return nil } + let stillStored: OAuthAccessToken? + do { + stillStored = try await tokens.load(for: pending.key) + } catch is CancellationError { + throw CancellationError() + } catch { + // A storage error on the old key must not break every later challenge. + state.withLock { state in + if state.pendingSuperseded?.key == pending.key, + state.pendingSuperseded?.token.value == pending.token.value + { + state.pendingSuperseded = nil + } + } + return nil + } + if let stillStored, stillStored.value == pending.token.value, isEligibleSuperseded(stillStored) { + return (pending.key, stillStored) + } + state.withLock { state in + if state.pendingSuperseded?.key == pending.key, + state.pendingSuperseded?.token.value == pending.token.value + { + state.pendingSuperseded = nil + } + } + return nil + } + + /// Clears `token` under `resource`, the key it was stored under before the + /// resource metadata named another resource, if it is still stored there. + /// + /// Best effort: no request reads the old key any more, so a storage error + /// here must not fail a request that has a usable token. The token stays + /// behind until a challenge after the next launch, which starts from the + /// old key again, clears it. + private func clearSuperseded(_ token: OAuthAccessToken?, for resource: URL) async { + guard let token else { return } + let value = token.value + state.withLock { state in + if state.pendingSuperseded?.key == resource, state.pendingSuperseded?.token.value == value { + state.pendingSuperseded = nil + } + } + do { + try await tokens.clear(token, for: resource) { $0.value == value } + } catch { + // Left for a later challenge; see above. + } + } + /// Whether `token` is DPoP-bound to another key than the configured one, /// or DPoP-bound while ``OAuthConfiguration/dpop`` is not set. private func isBoundToAnotherKey(_ token: OAuthAccessToken) -> Bool { @@ -423,26 +569,50 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { return token.keyThumbprint != dpopSigner.thumbprint } - /// Clears the stored token if it is still `token`. Runs outside the gate: - /// a challenge may have saved a new token since `token` was loaded. - private func clearStoredToken(_ token: OAuthAccessToken) { - guard tokenStorage.load()?.value == token.value else { return } - tokenStorage.clear() - } - /// Records the `DPoP-Nonce` of a resource server response (RFC 9449 §8) /// when ``OAuthConfiguration/dpop`` is set. - public func didReceiveResponse(headers: [String: String], for url: URL) { + /// + /// - Parameters: + /// - headers: The response headers. + /// - url: The URL that answered, after any redirects. + public func didReceiveResponse(headers: [String: String], for url: URL) async { dpopSigner?.recordNonce(from: headers, for: url, server: .resourceServer) } /// Answers a `401` by refreshing or acquiring an access token, and a `403` /// `insufficient_scope` by requesting the union of the granted and required - /// scopes; returns `false` for any other challenge. + /// scopes. + /// + /// A challenge for a token that another challenge has already replaced + /// retries with the new token. The result is + /// ``HTTPChallengeResult/retryWithDPoPNonce`` when the challenge, read with + /// the authorizer's challenge parser, is a `401` with a `use_dpop_nonce` + /// error and a `DPoP-Nonce` header, and a valid token bound to the + /// configured DPoP key is stored (RFC 9449 §9). Of a `Bearer` and a `DPoP` + /// challenge, the one for the scheme of + /// ``HTTPAuthorizationChallenge/sentAuthorization`` is answered (RFC 9449 §7.2). /// /// Step-up attempts per resource, operation and scope set are limited by /// ``OAuthConfiguration/RetryPolicy/maxScopeUpgradeAttempts``. - public func handleChallenge( + /// + /// - Parameters: + /// - challenge: The `401` or `403` response. + /// - session: The `URLSession` for discovery and token requests. + /// - Returns: Whether to send the request again, and whether that retry only + /// answers a DPoP nonce challenge; ``HTTPChallengeResult/unhandled`` for any + /// other challenge. + /// - Throws: An ``OAuthAuthorizationError``, an error of the token storage or + /// of the authorization delegate, or `CancellationError`. + public func handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) async throws + -> HTTPChallengeResult + { + try await handleChallenge( + statusCode: challenge.statusCode, headers: challenge.headers, endpoint: challenge.endpoint, + operationKey: challenge.operationKey, sentAuthorization: challenge.sentAuthorization, session: session) + } + + /// Handles a challenge, taking the stored token as the one the request sent. + func handleChallenge( statusCode: Int, headers: [String: String], endpoint: URL, @@ -451,24 +621,15 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { ) async throws -> Bool { // The sent token is not known: take the stored one, before waiting // for a challenge in progress. - let stored = tokenStorage.load() + let stored = try await tokens.load(for: canonicalResource(for: endpoint)) return try await handleChallenge( statusCode: statusCode, headers: headers, endpoint: endpoint, operationKey: operationKey, sentToken: stored?.value, sentDPoP: stored?.isDPoPBound == true, session: session - ).retry + ).shouldRetry } /// Handles a challenge for the request that carried `sentAuthorization`. - /// A challenge for a token that another challenge has already replaced - /// retries with the new token. - /// - /// The result is a DPoP nonce retry when the challenge, read with the - /// authorizer's `challengeParser`, is a `401` with a `use_dpop_nonce` - /// error and a `DPoP-Nonce` header, and a valid token bound to the - /// configured DPoP key is stored (RFC 9449 §9). Of a `Bearer` and a - /// `DPoP` challenge, the one for the scheme of `sentAuthorization` is - /// answered (RFC 9449 §7.2). - public func handleChallenge( + func handleChallenge( statusCode: Int, headers: [String: String], endpoint: URL, @@ -498,7 +659,8 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { sentDPoP: Bool, session: URLSession ) async throws -> HTTPChallengeResult { - try validateEndpointSecurity(for: endpoint) + try validateEndpoint(endpoint) + servedEndpoint = endpoint let completedBefore = lastChallenge.count return try await gate.run { // A challenge that ended while this one waited failed (a user who @@ -507,10 +669,14 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { // resource rejected: fail with it instead of starting the same // flow again. let last = lastChallenge - if last.count > completedBefore, let error = last.error, - tokenStorage.load().map({ $0.isExpired() || $0.value == sentToken }) ?? true - { - throw error + if last.count > completedBefore, let error = last.error { + let resource = try canonicalResource(for: endpoint) + if try await tokens.load(for: resource) + .map({ $0.isExpired() || $0.value == sentToken || isUnvalidatedAfterKeyChange($0, for: resource) }) + ?? true + { + throw error + } } do { let handled = try await handleChallengeAlone( @@ -547,18 +713,21 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { if let dpopSigner { let nonce = dpopSigner.recordNonce(from: headers, for: endpoint, server: .resourceServer) // RFC 9449 §9: the token is valid; retry with the server's nonce. - if statusCode == 401, dpopChallenge?.error == OAuthErrorCode.useDPoPNonce, nonce != nil, - let token = tokenStorage.load(), token.isDPoPBound, - token.keyThumbprint == dpopSigner.thumbprint, !token.isExpired() - { - return HTTPChallengeResult(retry: true, isDPoPNonceRetry: true) + if statusCode == 401, dpopChallenge?.error == OAuthErrorCode.useDPoPNonce, nonce != nil { + let resource = try canonicalResource(for: endpoint) + if let token = try await tokens.load(for: resource), token.isDPoPBound, + token.keyThumbprint == dpopSigner.thumbprint, !token.isExpired(), + !isFromAnotherAuthorizationServer(token), !isUnvalidatedAfterKeyChange(token, for: resource) + { + return .retryWithDPoPNonce + } } } - return HTTPChallengeResult( - retry: try await answerChallenge( - statusCode: statusCode, challenge: challenge, endpoint: endpoint, operationKey: operationKey, - sentToken: sentToken, session: session)) + let handled = try await answerChallenge( + statusCode: statusCode, challenge: challenge, endpoint: endpoint, operationKey: operationKey, + sentToken: sentToken, session: session) + return handled ? .retry : .unhandled } /// The `preferred` challenge, or `other` when there is none. The @@ -588,27 +757,31 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { ) async throws -> Bool { switch statusCode { case 401: + let keyBefore = try canonicalResource(for: endpoint) // Another challenge replaced the token meanwhile: retry with it. - if let current = tokenStorage.load(), current.value != sentToken, !current.isExpired() { + if let current = try await tokens.load(for: keyBefore), current.value != sentToken, !current.isExpired(), + isUsableToken(current), !isUnvalidatedAfterKeyChange(current, for: keyBefore) + { return true } let movedMetadata = challenge?.resourceMetadataURL.map { $0 != cachedProtectedResourceMetadataURL } ?? false - var triedRefresh = false - if let rejected = tokenStorage.load(), let refreshToken = rejected.refreshToken, + // The token and resource whose refresh this challenge has tried. + var triedRefresh: (value: String, resource: URL)? + if let rejected = try await tokens.load(for: keyBefore), let refreshToken = rejected.refreshToken, !movedMetadata, rejected.value != refreshedTokenValue, + !isUnvalidatedAfterKeyChange(rejected, for: keyBefore), let asMetadata = authorizationServerMetadata { - triedRefresh = true + triedRefresh = (rejected.value, keyBefore) // Refresh first, at the server that issued the token; read the // resource metadata again only when that does not help. - let resource = try canonicalResource(for: endpoint) let requestedScopes = scopeSelector.selectScopes( challengeScope: challenge?.scope, scopesSupported: protectedResourceMetadata?.scopesSupported ) if try await refreshAccessToken( - rejected, refreshToken: refreshToken, resource: resource, requestedScopes: requestedScopes, + rejected, refreshToken: refreshToken, resource: keyBefore, requestedScopes: requestedScopes, asMetadata: asMetadata, session: session) { return true @@ -619,10 +792,49 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { // A failed read falls back to the cached copy; with none, it // throws and the token is kept. A refreshed token is refreshed // again only after this read. - let rejected = tokenStorage.load() + var rejected = try await tokens.load(for: keyBefore) let current = try await discoverProtectedResourceMetadata( endpoint: endpoint, challenge: challenge, refresh: rejected != nil, session: session) - if !triedRefresh, let rejected, let refreshToken = rejected.refreshToken { + // The metadata can name another resource than the endpoint, and so + // another storage key: a token saved under it, for example in an + // earlier launch, is used before a new sign-in, if a server the + // metadata lists issued it. The token under the old key, which no + // request reads any more, is cleared once the challenge is + // answered; its refresh token is tried when the new key has none. + let resource = try canonicalResource(for: endpoint) + var supersededKey = keyBefore + var superseded: OAuthAccessToken? + if resource != keyBefore { + pendingKeyChangeResource = resource + if let rejected, isEligibleSuperseded(rejected) { + superseded = rejected + pendingSuperseded = (keyBefore, rejected) + } + } else if let pending = try await loadPendingSuperseded(excluding: resource) { + supersededKey = pending.key + superseded = pending.token + } + if resource != keyBefore || superseded != nil || pendingKeyChangeResource == resource { + let stored = try await tokens.load(for: resource) + let usableStored = stored.flatMap { isUsableAfterKeyChange($0, metadata: current) ? $0 : nil } + if let usableStored, usableStored.value != sentToken, !usableStored.isExpired() { + clearPendingKeyChange(for: resource) + await clearSuperseded(superseded, for: supersededKey) + return true + } + // Refresh the usable token under the new key, or the superseded one + // when only it has a refresh token; either is saved under the + // new key. + rejected = + usableStored?.refreshToken == nil && superseded?.refreshToken != nil ? superseded : usableStored + } + // A refresh this challenge tried already for the same resource is + // not tried again; a different token or a newly discovered resource + // is tried. + if let rejected, + triedRefresh.map({ $0.value != rejected.value || $0.resource != resource }) ?? true, + let refreshToken = rejected.refreshToken + { let asMetadata: OAuthAuthorizationServerMetadata? do { asMetadata = try await resolveAuthorizationServerMetadata( @@ -635,15 +847,17 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { } if let asMetadata, try await refreshAccessToken( - rejected, refreshToken: refreshToken, resource: try canonicalResource(for: endpoint), + rejected, refreshToken: refreshToken, resource: resource, requestedScopes: scopeSelector.selectScopes( challengeScope: challenge?.scope, scopesSupported: current.scopesSupported), asMetadata: asMetadata, session: session) { + await clearSuperseded(superseded, for: supersededKey) return true } } - tokenStorage.clear() + await clearSuperseded(superseded, for: supersededKey) + try await tokens.clear(for: canonicalResource(for: endpoint)) let metadata = try await discoverProtectedResourceMetadata( endpoint: endpoint, @@ -667,10 +881,11 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { context: providerContext, session: session ) { - storeExternalAccessToken( + try await storeExternalAccessToken( externalToken, requestedScopes: providerContext.requestedScopes, - authorizationServer: providerContext.authorizationServer + authorizationServer: providerContext.authorizationServer, + for: providerContext.resource ) return true } @@ -686,6 +901,7 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { case 403: guard challenge?.error?.lowercased() == "insufficient_scope" else { return false } + let keyBefore = try canonicalResource(for: endpoint) let metadata = try await discoverProtectedResourceMetadata( endpoint: endpoint, challenge: challenge, @@ -697,14 +913,43 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { scopesSupported: metadata.scopesSupported ) ?? [] + // As for a 401: when the metadata, read for the first time, names + // another resource, a token under the new key is used only if a + // server the metadata lists issued it, and the token under the old + // key gives its scopes to the step-up and is then cleared. + let resource = try canonicalResource(for: endpoint) + let keyChanged = resource != keyBefore + var supersededKey = keyBefore + var superseded: OAuthAccessToken? + if keyChanged { + pendingKeyChangeResource = resource + if let previous = try await tokens.load(for: keyBefore), isEligibleSuperseded(previous) { + superseded = previous + pendingSuperseded = (keyBefore, previous) + } + } else if let pending = try await loadPendingSuperseded(excluding: resource) { + supersededKey = pending.key + superseded = pending.token + } + let pendingKeyChange = keyChanged || superseded != nil || pendingKeyChangeResource == resource + let stored = try await tokens.load(for: resource).flatMap { token in + if pendingKeyChange { + return isUsableAfterKeyChange(token, metadata: metadata) ? token : nil + } + return isFromAnotherAuthorizationServer(token) || isBoundToAnotherKey(token) ? nil : token + } + // Another challenge obtained a token with these scopes meanwhile: retry with it. - if let current = tokenStorage.load(), current.value != sentToken, !current.isExpired(), - current.scopes.isSuperset(of: requiredScopes) + if let current = stored, current.value != sentToken, !current.isExpired(), + current.scopes.isSuperset(of: requiredScopes), + isUsableToken(current) { + clearPendingKeyChange(for: resource) + await clearSuperseded(superseded, for: supersededKey) return true } - let existingScopes = tokenStorage.load()?.scopes ?? [] + let existingScopes = (stored ?? superseded)?.scopes ?? [] let upgradedScopes = existingScopes.union(requiredScopes) let resourceKey = try discoveryClient.metadataDiscovery.canonicalResourceURI( from: endpoint @@ -712,11 +957,13 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { let operationAttemptKey = normalizedOperationKey(operationKey) let attemptKey = "\(resourceKey)|\(operationAttemptKey)|\(upgradedScopes.sorted().joined(separator: " "))" - let attempts = stepUpAttempts[attemptKey, default: 0] - guard attempts < configuration.retryPolicy.maxScopeUpgradeAttempts else { - return false + let allowed = state.withLock { state in + let attempts = state.stepUpAttempts[attemptKey, default: 0] + guard attempts < state.configuration.retryPolicy.maxScopeUpgradeAttempts else { return false } + state.stepUpAttempts[attemptKey] = attempts + 1 + return true } - stepUpAttempts[attemptKey] = attempts + 1 + guard allowed else { return false } let providerRequestedScopes = upgradedScopes.isEmpty ? nil : upgradedScopes let providerContext = try await makeAccessTokenProviderContext( @@ -731,11 +978,13 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { context: providerContext, session: session ) { - storeExternalAccessToken( + try await storeExternalAccessToken( externalToken, requestedScopes: providerContext.requestedScopes, - authorizationServer: providerContext.authorizationServer + authorizationServer: providerContext.authorizationServer, + for: providerContext.resource ) + await clearSuperseded(superseded, for: supersededKey) return true } @@ -745,6 +994,7 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { requestedScopes: upgradedScopes, session: session ) + await clearSuperseded(superseded, for: supersededKey) return true default: @@ -752,17 +1002,35 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { } } - /// Renews the access token when it expires within - /// ``OAuthConfiguration/proactiveRefreshWindowSeconds``: with its refresh - /// token, or with a new `client_credentials` or `jwt-bearer` grant. + /// Requires the MCP endpoint to use HTTPS, or HTTP on a loopback host, + /// without a fragment, then renews the access token when it expires + /// within ``OAuthConfiguration/proactiveRefreshWindowSeconds``: with its + /// refresh token, or with a new `client_credentials` or `jwt-bearer` grant. + /// + /// A failed renewal is ignored; the `401` path recovers. /// - /// Failures are ignored; the `401` path recovers. - public func prepareAuthorization(for endpoint: URL, session: URLSession) async throws { + /// - Parameters: + /// - endpoint: The MCP endpoint the request goes to. + /// - session: The `URLSession` for token requests. + /// - Throws: ``OAuthAuthorizationError/insecureOAuthEndpoint(context:url:)`` for an + /// insecure endpoint, an error of the token storage when it can't load the + /// token, or `CancellationError`. + public func prepare(for endpoint: URL, session: URLSession) async throws { + try validateEndpoint(endpoint) + servedEndpoint = endpoint guard configuration.proactiveRefreshWindowSeconds > 0 else { return } - guard let token = tokenStorage.load(), isDueForRenewal(token) else { return } + // A resource the endpoint doesn't match has no token to renew; the + // request reports the mismatch. + guard let resource = try? canonicalResource(for: endpoint) else { return } + guard let token = try await tokens.load(for: resource), !isUnvalidatedAfterKeyChange(token, for: resource), + isDueForRenewal(token) + else { return } try await gate.run { - // Read again: a refresh may have run while this one waited. - guard let token = tokenStorage.load(), isDueForRenewal(token) else { return } + // Read again: a challenge may have changed the resource or refreshed the token while this one waited. + guard let resource = try? canonicalResource(for: endpoint) else { return } + guard let token = try await tokens.load(for: resource), !isUnvalidatedAfterKeyChange(token, for: resource), + isDueForRenewal(token) + else { return } guard let asMeta = authorizationServerMetadata, configuration.endpointOverrides.tokenEndpoint != nil || asMeta.tokenEndpoint != nil else { return } @@ -773,36 +1041,43 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { let metadata = protectedResourceMetadata else { return } proactivelyRenewedToken = token.value - try? await acquireToken( - endpoint: endpoint, metadata: metadata, - requestedScopes: token.scopes.isEmpty ? nil : token.scopes, session: session) - // A cancelled attempt is not a try: the next request makes it. - if Task.isCancelled { proactivelyRenewedToken = nil } - return - } - - let resource: URL - do { - resource = try canonicalResource(for: endpoint) - } catch { + try await ignoringRenewalFailure { + try await acquireToken( + endpoint: endpoint, metadata: metadata, + requestedScopes: token.scopes.isEmpty ? nil : token.scopes, session: session) + } return } let requestedScopes = token.scopes.isEmpty ? nil : token.scopes proactivelyRenewedToken = token.value - _ = try? await refreshAccessToken( - token, - refreshToken: refreshToken, - resource: resource, - requestedScopes: requestedScopes, - asMetadata: asMeta, - session: session - ) - if Task.isCancelled { proactivelyRenewedToken = nil } + try await ignoringRenewalFailure { + _ = try await refreshAccessToken( + token, + refreshToken: refreshToken, + resource: resource, + requestedScopes: requestedScopes, + asMetadata: asMeta, + session: session + ) + } } } - /// Whether `prepareAuthorization` replaces `token`: it expires within + /// Runs a proactive renewal, ignoring its failure: the `401` path + /// recovers. A renewal that fails because the task is cancelled is not a + /// try, so the next request makes it, and the cancellation is thrown. + private func ignoringRenewalFailure(_ renewal: () async throws -> Void) async throws { + do { + try await renewal() + } catch { + guard error is CancellationError || Task.isCancelled else { return } + proactivelyRenewedToken = nil + throw CancellationError() + } + } + + /// Whether `prepare(for:session:)` replaces `token`: it expires within /// `proactiveRefreshWindowSeconds`, and it was not tried already. For a /// token this authorizer stored with a lifetime shorter than the window, /// the window shrinks to half the time the token is sent (until @@ -879,19 +1154,39 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { } try validateProtectedResource(metadata: metadata, endpoint: endpoint) + let resourceBefore = try canonicalResource(for: endpoint) + let resourceAfter = try canonicalResource(for: endpoint, using: metadata) + // A configured authorization server is used whatever the resource // lists, so the resource cannot move away from it. + var switchedServer = false if configuration.endpointOverrides.authorizationServerURL == nil, let selected = selectedAuthorizationServer, !metadata.authorizationServers.contains(where: { authorizationServersMatch($0, selected) }) { - // Another server: the token, and its refresh token, belong to the old one. - selectedAuthorizationServer = nil - authorizationServerMetadata = nil - tokenStorage.clear() + // Another server: the token, and its refresh token, belong to the + // old one. Cleared under the key in use before the metadata + // changes, and before the selection is dropped: until the clear + // has finished, authorizationHeaders still checks tokens against + // the old server, and a clear that fails leaves the state as it + // was, so the next challenge makes the switch again. + try await tokens.clear(for: resourceBefore) + switchedServer = true + } + // Publish metadata and any resource-key change atomically so no + // concurrent authorizationHeaders(for:method:) call can resolve to + // resourceAfter before pendingKeyChangeResource guards it. + state.withLock { state in + if switchedServer { + state.selectedAuthorizationServer = nil + state.authorizationServerMetadata = nil + } + state.protectedResourceMetadata = metadata + state.cachedProtectedResourceMetadataURL = candidates.first + if resourceAfter != resourceBefore { + state.pendingKeyChangeResource = resourceAfter + } } - self.protectedResourceMetadata = metadata - self.cachedProtectedResourceMetadataURL = candidates.first return metadata } @@ -979,7 +1274,7 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { (server, asMetadata) = (origin, .defaultEndpoints(issuer: origin)) } if let previous = selectedAuthorizationServer, !authorizationServersMatch(previous, server) { - tokenStorage.clear() + try await tokens.clear(for: canonicalResource(for: endpoint)) } self.selectedAuthorizationServer = server self.authorizationServerMetadata = asMetadata @@ -1083,7 +1378,7 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { dpop: dpopSigner, session: session ) - try storeTokenResponse(decoded, requestedScopes: requestedScopes) + try await storeTokenResponse(decoded, requestedScopes: requestedScopes, for: resource) } /// The `aud` claim of a JWT (the strings of an array), or `nil` when @@ -1121,7 +1416,7 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { dpop: dpopSigner, session: session ) - try storeTokenResponse(decoded, requestedScopes: requestedScopes) + try await storeTokenResponse(decoded, requestedScopes: requestedScopes, for: resource) } private func acquireTokenViaAuthorizationCode( @@ -1131,7 +1426,7 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { session: URLSession ) async throws { guard let authorizationEndpoint = asMetadata.authorizationEndpoint else { - throw OAuthAuthorizationError.tokenEndpointMissing + throw OAuthAuthorizationError.authorizationEndpointMissing } try urlValidator.validateAuthorizationServerAndHost( authorizationEndpoint, context: "Authorization endpoint", allowingLoopback: authorizationServerIsLoopback) @@ -1186,7 +1481,7 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { dpop: dpopSigner, session: session ) - try storeTokenResponse(decoded, requestedScopes: requestedScopes) + try await storeTokenResponse(decoded, requestedScopes: requestedScopes, for: resource) } /// RFC 9449 §5.1, §5.2: the resource may require DPoP, and the @@ -1257,7 +1552,10 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { dpop: dpopSigner, session: session ) - guard try storeTokenResponse(decoded, requestedScopes: requestedScopes, refreshing: token) else { + guard + try await storeTokenResponse( + decoded, requestedScopes: requestedScopes, refreshing: token, for: resource) + else { return false } refreshedTokenValue = decoded.accessToken @@ -1280,35 +1578,40 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { asMetadata: OAuthAuthorizationServerMetadata, session: URLSession ) async throws { - if let expiry = clientSecretExpiresAt, Date() >= expiry { - clientSecretExpiresAt = nil - clientRegistrationAttempted = false - // Register again: the expired client ID is not reused. - configuration.authentication = .none(clientID: "") - } - // Registered credentials belong to the server that issued them (SEP-2352). - if let registrationIssuer, let selectedAuthorizationServer, - !authorizationServersMatch(registrationIssuer, selectedAuthorizationServer) - { - self.registrationIssuer = nil - clientSecretExpiresAt = nil - clientRegistrationAttempted = false - configuration.authentication = configuredAuthentication - } else if clientRegistrationAttempted, registrationIssuer == nil, let selectedAuthorizationServer, - let attempted = registrationAttemptIssuer, - !authorizationServersMatch(attempted, selectedAuthorizationServer) - { - // Registration was not possible at the previous server; try the new one. - clientRegistrationAttempted = false - } + let configuredAuthentication = configuredAuthentication + let shouldRegister: Bool = state.withLock { state in + if let expiry = state.clientSecretExpiresAt, Date() >= expiry { + state.clientSecretExpiresAt = nil + state.clientRegistrationAttempted = false + // Register again: the expired client ID is not reused. + state.configuration.authentication = .none(clientID: "") + } + // Registered credentials belong to the server that issued them (SEP-2352). + if let registrationIssuer = state.registrationIssuer, let selected = state.selectedAuthorizationServer, + !authorizationServersMatch(registrationIssuer, selected) + { + state.registrationIssuer = nil + state.clientSecretExpiresAt = nil + state.clientRegistrationAttempted = false + state.configuration.authentication = configuredAuthentication + } else if state.clientRegistrationAttempted, state.registrationIssuer == nil, + let selected = state.selectedAuthorizationServer, let attempted = state.registrationAttemptIssuer, + !authorizationServersMatch(attempted, selected) + { + // Registration was not possible at the previous server; try the new one. + state.clientRegistrationAttempted = false + } - guard !clientRegistrationAttempted else { return } - guard case .none = configuration.authentication.method else { return } - // The assertion identifies the client: nothing to register. - guard configuration.grantType != .jwtBearer else { return } + guard !state.clientRegistrationAttempted else { return false } + guard case .none = state.configuration.authentication.method else { return false } + // The assertion identifies the client: nothing to register. + guard state.configuration.grantType != .jwtBearer else { return false } - clientRegistrationAttempted = true - registrationAttemptIssuer = selectedAuthorizationServer + state.clientRegistrationAttempted = true + state.registrationAttemptIssuer = state.selectedAuthorizationServer + return true + } + guard shouldRegister else { return } let result: (OAuthClientRegistrationResponse, OAuthConfiguration.TokenEndpointAuthentication)? do { @@ -1322,22 +1625,27 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { // Nothing is remembered when registration failed, or when the // server cannot register this client (`registrationInformationRequired`, // `cimdNotSupported`, `invalidClientIDMetadataURL`): the next flow checks again. - clientRegistrationAttempted = false - registrationAttemptIssuer = nil + state.withLock { state in + state.clientRegistrationAttempted = false + state.registrationAttemptIssuer = nil + } throw error } if let (registration, updatedAuth) = result { - configuration.authentication = updatedAuth - registrationIssuer = selectedAuthorizationServer - if let expiresAt = registration.clientSecretExpiresAt, expiresAt > 0 { - clientSecretExpiresAt = Date(timeIntervalSince1970: Double(expiresAt)) + state.withLock { state in + state.configuration.authentication = updatedAuth + state.registrationIssuer = state.selectedAuthorizationServer + if let expiresAt = registration.clientSecretExpiresAt, expiresAt > 0 { + state.clientSecretExpiresAt = Date(timeIntervalSince1970: Double(expiresAt)) + } } } } // MARK: - State Helpers - /// Stores a token response. `previous` is the token a refresh replaces. + /// Stores a token response under `resource`, the `resource` the token + /// request named. `previous` is the token a refresh replaces. /// A Bearer token for a resource whose metadata requires DPoP-bound tokens /// returns `false` during a refresh (so a full grant can try) and throws /// `dpopRequired` otherwise, as the resource would reject it. @@ -1345,8 +1653,9 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { private func storeTokenResponse( _ decoded: OAuthTokenResponse, requestedScopes: Set?, - refreshing previous: OAuthAccessToken? = nil - ) throws -> Bool { + refreshing previous: OAuthAccessToken? = nil, + for resource: URL + ) async throws -> Bool { // A Bearer answer to a DPoP request is a downgrade (RFC 9449 §5): use it as Bearer. let boundKey = decoded.tokenType.caseInsensitiveCompare(OAuthTokenType.dpop) == .orderedSame @@ -1365,10 +1674,7 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { scopeSet = requestedScopes ?? previous?.scopes ?? [] } let expiresAt = decoded.expiresIn.map { Date().addingTimeInterval(TimeInterval($0)) } - storedTokenLifetime = decoded.expiresIn.map { (decoded.accessToken, TimeInterval($0)) } - // A stored token is new, even with the value of the one tried. - proactivelyRenewedToken = nil - tokenStorage.save(OAuthAccessToken( + let token = OAuthAccessToken( value: decoded.accessToken, tokenType: boundKey == nil ? OAuthTokenType.bearer : OAuthTokenType.dpop, expiresAt: expiresAt, @@ -1378,7 +1684,16 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { refreshToken: decoded.refreshToken ?? previous?.refreshToken, clientID: nonEmptyClientID(), keyThumbprint: boundKey - )) + ) + try await tokens.save(token, for: resource) + state.withLock { state in + state.storedTokenLifetime = decoded.expiresIn.map { (decoded.accessToken, TimeInterval($0)) } + // A stored token is new, even with the value of the one tried. + state.proactivelyRenewedToken = nil + if state.pendingKeyChangeResource == resource { + state.pendingKeyChangeResource = nil + } + } return true } @@ -1406,6 +1721,12 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { } private func canonicalResource(for endpoint: URL) throws -> URL { + try canonicalResource(for: endpoint, using: protectedResourceMetadata) + } + + private func canonicalResource( + for endpoint: URL, using metadata: OAuthProtectedResourceMetadata? + ) throws -> URL { let endpointCanonical = try discoveryClient.metadataDiscovery.canonicalResourceURI( from: endpoint) @@ -1423,7 +1744,9 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { return configuredCanonical } - if let prmResourceString = protectedResourceMetadata?.resource, + if let prmResourceString = metadata?.resource? + .trimmingCharacters(in: .whitespacesAndNewlines), + !prmResourceString.isEmpty, let prmResourceURL = URL(string: prmResourceString) { let prmCanonical = try discoveryClient.metadataDiscovery.canonicalResourceURI( @@ -1439,17 +1762,40 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { return prmCanonical } + // Nothing names a resource: the resource is the endpoint the + // authorizer serves, the `resource` its token requests sent + // (RFC 8707 §2), so a request that the requestModifier moves to + // another path of that origin finds the token saved for it. A URL + // on another origin is another server: after discovery it fails as + // a URL outside a named resource does, before it has no token. + guard let servedEndpoint else { return endpointCanonical } + let servedCanonical = try discoveryClient.metadataDiscovery.canonicalResourceURI(from: servedEndpoint) + if DefaultOAuthMetadataDiscovery.haveSameOrigin(servedCanonical, endpointCanonical) { + return servedCanonical + } + guard metadata == nil else { + throw OAuthAuthorizationError.protectedResourceMismatch( + expected: endpointCanonical.absoluteString, + actual: servedCanonical.absoluteString + ) + } return endpointCanonical } private func authorizationServersMatch(_ lhs: URL, _ rhs: URL) -> Bool { - normalizedAuthorizationServer(lhs) == normalizedAuthorizationServer(rhs) + guard let lhs = normalizedAuthorizationServer(lhs), + let rhs = normalizedAuthorizationServer(rhs) + else { + return false + } + return lhs == rhs } private func normalizedAuthorizationServer(_ url: URL) -> URL? { guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false), let scheme = components.scheme?.lowercased(), let host = components.host?.lowercased(), + !host.isEmpty, scheme == OAuthURLScheme.http || scheme == OAuthURLScheme.https else { return nil @@ -1476,10 +1822,10 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { private func storeExternalAccessToken( _ token: String, requestedScopes: Set?, - authorizationServer: URL? - ) { - proactivelyRenewedToken = nil - tokenStorage.save(OAuthAccessToken( + authorizationServer: URL?, + for resource: URL + ) async throws { + let accessToken = OAuthAccessToken( value: token, tokenType: OAuthTokenType.bearer, expiresAt: nil, @@ -1487,7 +1833,14 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { authorizationServer: authorizationServer, refreshToken: nil, clientID: nonEmptyClientID() - )) + ) + try await tokens.save(accessToken, for: resource) + state.withLock { state in + state.proactivelyRenewedToken = nil + if state.pendingKeyChangeResource == resource { + state.pendingKeyChangeResource = nil + } + } } private func makeAccessTokenProviderContext( @@ -1533,65 +1886,47 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { } } -/// Runs async operations one at a time, in arrival order. A waiting task -/// that is cancelled stops waiting and throws `CancellationError`. -final class AsyncGate: @unchecked Sendable { - private let lock = NSLock() - private var busy = false - private var nextWaiter = 0 - private var waiters: [(id: Int, continuation: CheckedContinuation)] = [] +// MARK: - Token Store - /// The number of tasks waiting for the gate. - var waiterCount: Int { lock.withLock { waiters.count } } - - func run(_ body: () async throws -> T) async throws -> T { - try await acquire() - defer { release() } - return try await body() +/// The authorizer's access to its ``OAuthTokenStorage``: loads run concurrently, +/// writes one at a time. +/// +/// Lock order: `OAuthAuthorizer.gate` may be held while waiting for `writes`, +/// never the reverse, and a `writes` body only calls the storage. So the two +/// gates can't deadlock. Internal, not private, so tests can read `writes`. +struct TokenStore: Sendable { + let storage: any OAuthTokenStorage + let writes = AsyncGate() + + func load(for resource: URL) async throws -> OAuthAccessToken? { + try await storage.load(for: resource) } - private func acquire() async throws { - let id: Int? = lock.withLock { - if busy { - nextWaiter += 1 - return nextWaiter - } - busy = true - return nil - } - guard let id else { return } - try await withTaskCancellationHandler { - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - let resumeNow: Result? = lock.withLock { - // Checked under the lock: a cancellation either finds - // this waiter or is seen here. - if Task.isCancelled { return .failure(CancellationError()) } - if busy { - waiters.append((id, continuation)) - return nil - } - busy = true - return .success(()) - } - if let resumeNow { continuation.resume(with: resumeNow) } - } - } onCancel: { - let cancelled: CheckedContinuation? = lock.withLock { - guard let index = waiters.firstIndex(where: { $0.id == id }) else { return nil } - return waiters.remove(at: index).continuation - } - cancelled?.resume(throwing: CancellationError()) + /// Saves `token`. Waits for the gate even when the task is cancelled: the + /// token endpoint has issued the token, and may have rotated the refresh + /// token it replaces (OAuth 2.1 §4.3.1). + func save(_ token: OAuthAccessToken, for resource: URL) async throws { + try await writes.run(ignoringCancellation: true) { + try await storage.save(token, for: resource) } } - private func release() { - let next: CheckedContinuation? = lock.withLock { - if waiters.isEmpty { - busy = false - return nil - } - return waiters.removeFirst().continuation + func clear(for resource: URL) async throws { + try await writes.run { try await storage.clear(for: resource) } + } + + /// Clears the token stored for `resource` if it is still `token` and + /// `shouldClear` still holds for it: compare-then-clear, with no write + /// between the compare and the clear. + func clear( + _ token: OAuthAccessToken, for resource: URL, + if shouldClear: @Sendable (OAuthAccessToken) -> Bool + ) async throws { + try await writes.run { + guard let current = try await storage.load(for: resource), + current.value == token.value, shouldClear(current) + else { return } + try await storage.clear(for: resource) } - next?.resume() } } diff --git a/Sources/MCP/Base/Authorization/OAuthClientRegistrar.swift b/Sources/MCP/Base/Authorization/OAuthClientRegistrar.swift index 83f799fd..f75229a1 100644 --- a/Sources/MCP/Base/Authorization/OAuthClientRegistrar.swift +++ b/Sources/MCP/Base/Authorization/OAuthClientRegistrar.swift @@ -41,7 +41,10 @@ struct OAuthClientRegistrar: Sendable { /// Throws ``OAuthAuthorizationError/privateIPAddressBlocked(context:url:)`` /// before a request when the registration endpoint is on a private /// address, or on a loopback host unless `allowingLoopback`. - /// Throws if registration was attempted but failed (4xx, 5xx, or unexpected response). + /// Throws ``OAuthAuthorizationError/registrationRequestFailed(statusCode:oauthError:)`` + /// for a non-2xx or non-HTTP response, and + /// ``OAuthAuthorizationError/registrationResponseInvalid`` for a 2xx response that is + /// not a client information response. func register( configuration: OAuthConfiguration, asMetadata: OAuthAuthorizationServerMetadata, @@ -125,29 +128,24 @@ struct OAuthClientRegistrar: Sendable { let (data, response) = try await session.oauthData( for: request, redirects: .none, validator: urlValidator) - if let httpResponse = response as? HTTPURLResponse, - (400..<500).contains(httpResponse.statusCode) - { - let oauthError = - (try? JSONDecoder().decode(OAuthTokenErrorResponse.self, from: data))?.error - throw OAuthAuthorizationError.tokenRequestFailed( - statusCode: httpResponse.statusCode, - oauthError: oauthError - ) - } + // RFC 7591 §3.2.2: an error response carries an OAuth `error` code. guard let httpResponse = response as? HTTPURLResponse, (200..<300).contains(httpResponse.statusCode) else { - let statusCode = (response as? HTTPURLResponse)?.statusCode ?? 0 let oauthError = (try? JSONDecoder().decode(OAuthTokenErrorResponse.self, from: data))?.error - throw OAuthAuthorizationError.tokenRequestFailed( - statusCode: statusCode, + throw OAuthAuthorizationError.registrationRequestFailed( + statusCode: (response as? HTTPURLResponse)?.statusCode, oauthError: oauthError ) } - let registration = try JSONDecoder().decode(OAuthClientRegistrationResponse.self, from: data) + let registration: OAuthClientRegistrationResponse + do { + registration = try JSONDecoder().decode(OAuthClientRegistrationResponse.self, from: data) + } catch { + throw OAuthAuthorizationError.registrationResponseInvalid + } let updatedAuth = OAuthClientRegistrar.updatedAuthentication( from: registration, current: configuration.authentication) diff --git a/Sources/MCP/Base/Authorization/OAuthConfiguration.swift b/Sources/MCP/Base/Authorization/OAuthConfiguration.swift index 73a734b5..e557153b 100644 --- a/Sources/MCP/Base/Authorization/OAuthConfiguration.swift +++ b/Sources/MCP/Base/Authorization/OAuthConfiguration.swift @@ -183,7 +183,8 @@ public struct OAuthConfiguration: Sendable { /// /// Frozen: no case is added in 1.x (the two ways the helper can fail). public enum PrivateKeyJWTAssertionError: LocalizedError, Sendable { - /// The requested lifetime, in seconds, is not greater than zero. + /// The requested lifetime, in seconds, is not a finite number greater + /// than zero, or the expiration time it gives can't be represented. case invalidLifetime(TimeInterval) /// Not thrown: signing uses swift-crypto on every platform. case cryptographyUnavailable @@ -191,7 +192,8 @@ public struct OAuthConfiguration: Sendable { public var errorDescription: String? { switch self { case .invalidLifetime(let lifetime): - return "private_key_jwt assertion lifetime must be greater than zero seconds, got \(lifetime)" + return "private_key_jwt assertion lifetime must be a finite number of seconds greater than zero" + + " with a representable expiration time, got \(lifetime)" case .cryptographyUnavailable: return "private_key_jwt assertion signing is unavailable" } @@ -227,8 +229,12 @@ public struct OAuthConfiguration: Sendable { /// - issuedAt: The `iat` claim. Defaults to `Date()`. /// - expiresIn: Lifetime of the assertion in seconds. Defaults to 300 (5 minutes). Must be > 0. /// - Returns: A compact-serialized JWT string (`header.payload.signature`). - /// - Throws: ``PrivateKeyJWTAssertionError/invalidLifetime(_:)`` if `expiresIn` ≤ 0, - /// or the error of `P256.Signing.PrivateKey(pemRepresentation:)` for an invalid key. + /// - Throws: ``PrivateKeyJWTAssertionError/invalidLifetime(_:)`` if `expiresIn` is not a + /// finite number greater than zero, or if the `exp` claim it gives is outside the range + /// of `Int64`; `EncodingError.invalidValue(_:_:)`, with the `timeIntervalSince1970` + /// of `issuedAt` as its value, if `issuedAt` is not finite or its `iat` claim is + /// outside the range of `Int64`; or the error of + /// `P256.Signing.PrivateKey(pemRepresentation:)` for an invalid key. public static func makePrivateKeyJWTAssertion( clientID: String, tokenEndpoint: URL, @@ -238,7 +244,15 @@ public struct OAuthConfiguration: Sendable { issuedAt: Date = Date(), expiresIn: TimeInterval = 300 ) throws -> String { - guard expiresIn > 0 else { + // `iat` and `exp` are NumericDates (RFC 7519 §2), computed as Int64: + // `Int` is 32 bits on watchOS, too small after 2038-01-19. + guard expiresIn > 0, let wholeSeconds = Int64(exactly: expiresIn.rounded(.down)) else { + throw PrivateKeyJWTAssertionError.invalidLifetime(expiresIn) + } + let lifetimeSeconds = max(1, wholeSeconds) + let issuedAtSeconds = try issuedAt.jwtNumericDate() + let (expirationSeconds, overflow) = issuedAtSeconds.addingReportingOverflow(lifetimeSeconds) + guard !overflow else { throw PrivateKeyJWTAssertionError.invalidLifetime(expiresIn) } @@ -247,14 +261,12 @@ public struct OAuthConfiguration: Sendable { JWTClaimName.type: JWTClaimName.typeValue, ]) - let issuedAtUnix = Int(issuedAt.timeIntervalSince1970) - let lifetimeSeconds = max(1, Int(expiresIn.rounded(.down))) let payload = try JSONSerialization.data(withJSONObject: [ JWTClaimName.issuer: clientID, JWTClaimName.subject: clientID, JWTClaimName.audience: audience ?? tokenEndpoint.absoluteString, - JWTClaimName.issuedAt: issuedAtUnix, - JWTClaimName.expiration: issuedAtUnix + lifetimeSeconds, + JWTClaimName.issuedAt: issuedAtSeconds, + JWTClaimName.expiration: expirationSeconds, JWTClaimName.jwtID: UUID().uuidString, ]) @@ -282,7 +294,9 @@ public struct OAuthConfiguration: Sendable { /// Controls retry behavior for authorization challenges. public struct RetryPolicy: Sendable { - /// Maximum number of authentication retries for a single MCP request. + /// Maximum number of total attempts for a single MCP request, including + /// the initial attempt (`1` allows no non-nonce retry; the default `3` + /// allows up to `2` retries). public let maxAuthorizationAttempts: Int /// Maximum number of scope step-up attempts for a resource and operation. @@ -290,11 +304,10 @@ public struct OAuthConfiguration: Sendable { /// Creates a retry policy. /// - /// Both values are clamped to a minimum of `1` to prevent infinite loops - /// or zero-retry configurations. + /// Both values are clamped to a minimum of `1`. /// /// - Parameters: - /// - maxAuthorizationAttempts: Maximum authorization retries per request. Defaults to 3. + /// - maxAuthorizationAttempts: Maximum total attempts per request (initial attempt plus retries). Defaults to 3. /// - maxScopeUpgradeAttempts: Maximum scope step-up attempts per resource+operation. Defaults to 2. public init( maxAuthorizationAttempts: Int = 3, @@ -335,7 +348,13 @@ public struct OAuthConfiguration: Sendable { /// set ``authorizationServerURL`` too to fix both. public let tokenEndpoint: URL? - /// Optional override for the resource indicator used in token requests. + /// Optional override for the resource indicator used in token requests (RFC 8707 §2). + /// + /// It must cover the MCP endpoint. ``OAuthAuthorizer`` also stores tokens in its + /// ``OAuthTokenStorage`` under it. Without it, the key is the endpoint until the + /// authorizer has read the protected resource metadata, and the metadata's `resource` + /// after. For a storage that keeps tokens across launches, set it to the server's + /// resource, so the first request after a launch finds its token. public let resource: URL? /// Creates endpoint overrides. A `nil` value is not overridden. @@ -534,7 +553,7 @@ public struct OAuthConfiguration: Sendable { public let authorizationDelegate: (any OAuthAuthorizationDelegate)? /// How many seconds before token expiry ``OAuthAuthorizer`` proactively refreshes a token - /// when `prepareAuthorization(for:session:)` is called. + /// when ``OAuthAuthorizer/prepare(for:session:)`` is called. /// /// Set to `0` to disable proactive refresh. Defaults to 60 seconds. A token /// issued with a shorter lifetime is refreshed halfway between its issue @@ -628,3 +647,26 @@ extension String { return addingPercentEncoding(withAllowedCharacters: allowed) ?? self } } + +// MARK: - JWT NumericDate + +extension Date { + /// Returns the JWT NumericDate of the date (RFC 7519 §2): whole seconds + /// since 1970-01-01T00:00:00Z UTC, truncated toward zero. + /// + /// - Throws: `EncodingError.invalidValue` when the date is not finite or + /// the seconds are outside the range of `Int64`. Its value is the + /// date's `timeIntervalSince1970`, not the date: describing a NaN date + /// traps on Linux. + func jwtNumericDate() throws -> Int64 { + let seconds = timeIntervalSince1970 + guard let numericDate = Int64(exactly: seconds.rounded(.towardZero)) else { + throw EncodingError.invalidValue( + seconds, + .init( + codingPath: [], + debugDescription: "\(seconds) seconds since 1970 is not an Int64 NumericDate (RFC 7519 §2)")) + } + return numericDate + } +} diff --git a/Sources/MCP/Base/Authorization/OAuthDPoP.swift b/Sources/MCP/Base/Authorization/OAuthDPoP.swift index a30571f0..3354737a 100644 --- a/Sources/MCP/Base/Authorization/OAuthDPoP.swift +++ b/Sources/MCP/Base/Authorization/OAuthDPoP.swift @@ -5,6 +5,7 @@ import Foundation #endif import Crypto +import Synchronization /// A P-256 key that signs DPoP proofs (ES256). /// @@ -12,20 +13,19 @@ import Crypto /// `SecureEnclave.P256.Signing.PrivateKey`. Conform another type to sign with /// a key held elsewhere, such as a hardware security module. /// -/// The SDK signs synchronously, once for every MCP request and every token -/// request. ``HTTPClientTransport`` handles no other request or response -/// while it signs one of its requests, so a key that is slow to use, such as -/// one behind a network call, delays every request. Use a key that signs -/// locally, such as one in the Secure Enclave. +/// The SDK signs once for every MCP request and every token request, and the +/// request waits for the signature. A key behind a network call delays every +/// request; prefer one that signs locally, such as one in the Secure Enclave. public protocol DPoPSigningKey: Sendable { /// The public key, published in each proof's `jwk` header. var publicKey: P256.Signing.PublicKey { get } - /// An ECDSA signature of `data` with SHA-256. + /// Returns an ECDSA signature of `data` with SHA-256. /// - /// Called synchronously for each proof; it should return in - /// milliseconds. See ``DPoPSigningKey``. - func signature(for data: Data) throws -> P256.Signing.ECDSASignature + /// - Parameter data: The JWS signing input of a proof. + /// - Returns: The signature. + /// - Throws: An error of the key, which fails the request. + func signature(for data: Data) async throws -> P256.Signing.ECDSASignature } extension P256.Signing.PrivateKey: DPoPSigningKey {} @@ -46,7 +46,7 @@ extension OAuthConfiguration { /// support DPoP answers with a Bearer token, which is then used as one. /// /// Only ES256 is supported. Tokens are bound to the key: a token in - /// ``TokenStorage`` bound to another key is discarded, so persist the key + /// ``OAuthTokenStorage`` bound to another key is discarded, so persist the key /// together with the tokens. public struct DPoP: Sendable { let key: any DPoPSigningKey @@ -79,7 +79,7 @@ extension OAuthConfiguration { /// /// Nonces are kept per origin, separately for authorization servers and /// resource servers. -final class DPoPProofSigner: @unchecked Sendable { +final class DPoPProofSigner: Sendable { enum ServerKind: String { case authorizationServer = "as" case resourceServer = "rs" @@ -92,8 +92,8 @@ final class DPoPProofSigner: @unchecked Sendable { private let jwk: [String: String] let thumbprint: String - private let lock = NSLock() - private var nonces: [String: String] = [:] + /// The last nonce of each server, keyed by `nonceKey(_:_:)`. + private let nonces = Mutex<[String: String]>([:]) init(configuration: OAuthConfiguration.DPoP) { key = configuration.key @@ -108,13 +108,19 @@ final class DPoPProofSigner: @unchecked Sendable { /// - url: The request URL; `htu` drops its query and fragment. /// - accessToken: The token the request presents (`ath`), if any. /// - server: Which nonce to include. + /// - now: The `iat` claim. + /// - Throws: An error of the key, `invalidResourceURI` for a URL + /// without a target URI, or `EncodingError.invalidValue` for a `now` + /// that has no NumericDate. func proof( method: String, url: URL, accessToken: String?, server: ServerKind, now: Date = Date() - ) throws -> String { + ) async throws -> String { + // NumericDate (RFC 7519 §2) as Int64: `Int` is 32 bits on watchOS. + let issuedAt = try now.jwtNumericDate() let header: [String: Any] = [ JWTClaimName.type: Self.proofType, JWTClaimName.algorithm: Self.algorithm, @@ -124,7 +130,7 @@ final class DPoPProofSigner: @unchecked Sendable { JWTClaimName.jwtID: Self.randomIdentifier(), "htm": method.uppercased(), "htu": try Self.targetURI(url), - JWTClaimName.issuedAt: Int(now.timeIntervalSince1970), + JWTClaimName.issuedAt: issuedAt, ] if let accessToken { claims["ath"] = Data(SHA256.hash(data: Data(accessToken.utf8))).base64URLEncodedString() @@ -136,22 +142,18 @@ final class DPoPProofSigner: @unchecked Sendable { let claimsData = try JSONSerialization.data(withJSONObject: claims, options: [.sortedKeys]) let signingInput = "\(headerData.base64URLEncodedString()).\(claimsData.base64URLEncodedString())" - let signature = try key.signature(for: Data(signingInput.utf8)).rawRepresentation + let signature = try await key.signature(for: Data(signingInput.utf8)).rawRepresentation return "\(signingInput).\(signature.base64URLEncodedString())" } func nonce(for url: URL, server: ServerKind) -> String? { guard let key = Self.nonceKey(url, server) else { return nil } - lock.lock() - defer { lock.unlock() } - return nonces[key] + return nonces.withLock { $0[key] } } func setNonce(_ nonce: String, for url: URL, server: ServerKind) { guard let key = Self.nonceKey(url, server) else { return } - lock.lock() - defer { lock.unlock() } - nonces[key] = nonce + nonces.withLock { $0[key] = nonce } } /// Records the `DPoP-Nonce` response header, if present. Returns the nonce. @@ -207,10 +209,11 @@ final class DPoPProofSigner: @unchecked Sendable { private static func nonceKey(_ url: URL, _ server: ServerKind) -> String? { guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false), - let scheme = components.scheme?.lowercased(), - let host = components.host?.lowercased() + let scheme = components.scheme?.lowercased(), !scheme.isEmpty, + let host = components.encodedHost.map(DefaultOAuthMetadataDiscovery.asciiLowercased), !host.isEmpty else { return nil } - let port = components.port.map { ":\($0)" } ?? "" + let defaultPort = DefaultOAuthMetadataDiscovery.defaultPort(for: scheme) + let port = components.port.flatMap { $0 == defaultPort ? nil : ":\($0)" } ?? "" return "\(server.rawValue)|\(scheme)://\(host)\(port)" } diff --git a/Sources/MCP/Base/Authorization/OAuthDiscovery.swift b/Sources/MCP/Base/Authorization/OAuthDiscovery.swift index e7c5e9fc..d49134b5 100644 --- a/Sources/MCP/Base/Authorization/OAuthDiscovery.swift +++ b/Sources/MCP/Base/Authorization/OAuthDiscovery.swift @@ -14,7 +14,9 @@ import Foundation /// /// Override the default ``DefaultOAuthScopeSelector`` to apply custom scope /// filtering or transformation logic. -public protocol OAuthScopeSelecting { +/// +/// ``OAuthAuthorizer`` calls it from several tasks at once, so a conforming type is `Sendable`. +public protocol OAuthScopeSelecting: Sendable { /// Selects the scope set to request for a token. /// /// Priority order (highest first): @@ -114,13 +116,38 @@ public protocol OAuthMetadataDiscovering: Sendable { /// Derives the canonical RFC 8707 resource URI from an endpoint URL. /// - /// The canonical form strips the query string, fragment, and trailing slash - /// while preserving the scheme, host, port, and path. + /// ``OAuthAuthorizer`` sends the canonical URI as the `resource` parameter of its + /// authorization and token requests, stores tokens under it (see + /// ``OAuthTokenStorage``), and canonicalizes both sides before it compares the + /// `resource` of protected resource metadata (RFC 9728 §3.3) with the endpoint. + /// + /// ``DefaultOAuthMetadataDiscovery`` uses the form the MCP specification's + /// "Canonical Server URI" prefers, normalized as RFC 3986 §6.2.2 and §6.2.3 + /// describe. It lowercases the scheme, and the ASCII letters of the host in its + /// encoded form (an internationalized host is punycode, so its Unicode and + /// punycode spellings give one URI); drops user information, the scheme's + /// default port (`443` for `https`, `80` for `http`), the query, and every + /// trailing `/`, also after a path; writes percent-encodings with uppercase hex + /// digits, decoding those of unreserved characters; and removes `.` and `..` + /// segments (RFC 3986 §5.2.4). So `https://MCP.Example.com:443/mcp/` becomes + /// `https://mcp.example.com/mcp`, `https://example.com/` becomes + /// `https://example.com`, `https://example.com/mcp/../admin` becomes + /// `https://example.com/admin`, and `https://example.com:8443/mcp` keeps its port. + /// The result is its own canonical form. It rejects a URL with a fragment, which + /// a resource indicator must not have (RFC 8707 §2). + /// + /// For a server whose trailing slash is significant, pass + /// ``OAuthAuthorizer/init(configuration:tokenStorage:scopeSelector:challengeParser:metadataDiscovery:)`` + /// a `metadataDiscovery` that wraps the default and puts the slash back in the + /// URIs it returns here. ``protectedResourceMatches(resource:endpoint:)`` of the + /// default ignores trailing slashes, so the wrapper changes only the `resource` + /// the authorizer sends and the key it stores tokens under. /// /// - Parameter endpoint: The MCP endpoint URL. /// - Returns: The canonical resource URI. - /// - Throws: ``OAuthAuthorizationError/invalidResourceURI(_:)`` if the URL does not - /// satisfy the HTTPS-or-loopback-HTTP requirement. + /// - Throws: ``OAuthAuthorizationError/invalidResourceURI(_:)`` if the URL has a fragment + /// or does not satisfy the HTTPS-or-loopback-HTTP requirement. + /// - SeeAlso: https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#canonical-server-uri func canonicalResourceURI(from endpoint: URL) throws -> URL /// Derives a fallback authorization server issuer URL from an endpoint URL. @@ -151,7 +178,9 @@ public protocol OAuthMetadataDiscovering: Sendable { /// /// - Builds `/.well-known/oauth-protected-resource` URLs with and without the endpoint path suffix. /// - Builds RFC 8414 and OIDC discovery URLs with path-inserted and path-appended variants. -/// - Canonicalises resource URIs by stripping query, fragment, and trailing slash. +/// - Canonicalises resource URIs: lowercases the scheme and host; drops user information, a +/// default port, the query and a trailing slash; normalizes percent-encodings; rejects a +/// fragment (see ``OAuthMetadataDiscovering/canonicalResourceURI(from:)``). /// - Matches resources using scheme/host/port equality and path prefix rules. public struct DefaultOAuthMetadataDiscovery: OAuthMetadataDiscovering { /// Creates the default metadata discovery. @@ -170,16 +199,19 @@ public struct DefaultOAuthMetadataDiscovery: OAuthMetadataDiscovering { return [] } + // User information is a credential: discovery requests don't carry it. + components.user = nil + components.password = nil components.query = nil components.fragment = nil - let endpointPath = components.path + let endpointPath = components.percentEncodedPath let normalizedPath = endpointPath == "/" ? "" : endpointPath var urls: [URL] = [] var pathSpecific = components - pathSpecific.path = "\(OAuthWellKnownPath.protectedResource)\(normalizedPath)" + pathSpecific.percentEncodedPath = "\(OAuthWellKnownPath.protectedResource)\(normalizedPath)" if let url = pathSpecific.url { urls.append(url) } @@ -211,6 +243,9 @@ public struct DefaultOAuthMetadataDiscovery: OAuthMetadataDiscovering { return [] } + // User information is a credential: discovery requests don't carry it. + components.user = nil + components.password = nil components.query = nil components.fragment = nil @@ -254,8 +289,9 @@ public struct DefaultOAuthMetadataDiscovery: OAuthMetadataDiscovering { return urls } - /// Lowercases the scheme and host, removes the query, and drops a root - /// path of `/`. + /// Lowercases the scheme and the ASCII letters of the host, drops user + /// information, a default port, the query and trailing slashes, normalizes + /// percent-encodings and removes dot segments. /// /// Throws ``OAuthAuthorizationError/invalidResourceURI(_:)`` for a fragment /// or for a URL that is neither HTTPS nor loopback HTTP. @@ -275,13 +311,35 @@ public struct DefaultOAuthMetadataDiscovery: OAuthMetadataDiscovering { } components.scheme = scheme - components.host = host + // RFC 3986 §6.2.2.1: the host in its encoded (IDNA) form, with only + // its ASCII letters lowercased, so a Unicode and a punycode spelling + // of one host give one key. + if let encodedHost = components.encodedHost { + components.encodedHost = Self.asciiLowercased(encodedHost) + } + // User information is credentials, not part of the resource's + // identity (RFC 3986 §3.2.1, §7.5): it must not reach the + // authorization server, a storage key or an error message. + components.user = nil + components.password = nil + // RFC 3986 §6.2.3: the scheme's default port is the same as none. + if components.port == Self.defaultPort(for: scheme) { + components.port = nil + } components.query = nil components.fragment = nil - if components.path == "/" { - components.path = "" + // RFC 3986 §6.2.2.1, §6.2.2.2, §6.2.2.3 (dot segments, so that + // `/mcp/../admin` is `/admin` and no resource `/mcp` covers it); + // then MCP 2025-11-25 "Canonical Server URI": the form without a + // trailing slash. Every trailing slash goes, so that the canonical + // form of a canonical URI is itself. + var path = Self.removingDotSegments( + from: Self.normalizingPercentEncodings(in: components.percentEncodedPath)) + while path.hasSuffix("/") { + path.removeLast() } + components.percentEncodedPath = path guard let url = components.url else { throw OAuthAuthorizationError.invalidResourceURI("Failed to normalize resource URI") @@ -290,6 +348,97 @@ public struct DefaultOAuthMetadataDiscovery: OAuthMetadataDiscovering { return url } + /// `path` with the hex digits of each percent-encoding in uppercase, and the + /// percent-encodings of unreserved characters decoded (RFC 3986 §6.2.2.1, + /// §6.2.2.2). A `%` without two hex digits after it is kept as is. + static func normalizingPercentEncodings(in path: String) -> String { + guard path.contains("%") else { return path } + var bytes = Array(path.utf8)[...] + var result: [UInt8] = [] + result.reserveCapacity(bytes.count) + while let byte = bytes.popFirst() { + guard byte == UInt8(ascii: "%"), bytes.count >= 2, + let high = Self.hexValue(bytes[bytes.startIndex]), + let low = Self.hexValue(bytes[bytes.startIndex + 1]) + else { + result.append(byte) + continue + } + bytes.removeFirst(2) + let decoded = high << 4 | low + if Self.isUnreserved(decoded) { + result.append(decoded) + } else { + let digits = Array("0123456789ABCDEF".utf8) + result += [UInt8(ascii: "%"), digits[Int(high)], digits[Int(low)]] + } + } + return String(decoding: result, as: UTF8.self) + } + + /// `path` without `.` and `..` segments, as RFC 3986 §5.2.4 removes them. + static func removingDotSegments(from path: String) -> String { + guard path.contains(".") else { return path } + var input = Substring(path) + var output: [Substring] = [] + while !input.isEmpty { + if input.hasPrefix("../") { + input = input.dropFirst(3) + } else if input.hasPrefix("./") { + input = input.dropFirst(2) + } else if input.hasPrefix("/./") { + input = input.dropFirst(2) + } else if input == "/." { + input = "/" + } else if input.hasPrefix("/../") { + input = input.dropFirst(3) + _ = output.popLast() + } else if input == "/.." { + input = "/" + _ = output.popLast() + } else if input == "." || input == ".." { + input = "" + } else { + // The first segment, with its leading `/`, up to the next `/`. + let start = input.hasPrefix("/") ? input.index(after: input.startIndex) : input.startIndex + let end = input[start...].firstIndex(of: "/") ?? input.endIndex + output.append(input[.. String { + String( + decoding: string.utf8.map { (UInt8(ascii: "A")...UInt8(ascii: "Z")).contains($0) ? $0 + 32 : $0 }, + as: UTF8.self) + } + + /// The value of an ASCII hex digit, or `nil` for another byte. + private static func hexValue(_ byte: UInt8) -> UInt8? { + switch byte { + case UInt8(ascii: "0")...UInt8(ascii: "9"): byte - UInt8(ascii: "0") + case UInt8(ascii: "A")...UInt8(ascii: "F"): byte - UInt8(ascii: "A") + 10 + case UInt8(ascii: "a")...UInt8(ascii: "f"): byte - UInt8(ascii: "a") + 10 + default: nil + } + } + + /// Whether `byte` is an unreserved character: ALPHA, DIGIT, `-`, `.`, `_` + /// or `~` (RFC 3986 §2.3). + private static func isUnreserved(_ byte: UInt8) -> Bool { + switch byte { + case UInt8(ascii: "A")...UInt8(ascii: "Z"), UInt8(ascii: "a")...UInt8(ascii: "z"), + UInt8(ascii: "0")...UInt8(ascii: "9"), UInt8(ascii: "-"), UInt8(ascii: "."), UInt8(ascii: "_"), + UInt8(ascii: "~"): + true + default: + false + } + } + /// Returns the endpoint's scheme, host and port, without a path. public func authorizationServerFallbackIssuer(from endpoint: URL) throws -> URL { guard var components = URLComponents(url: endpoint, resolvingAgainstBaseURL: false), @@ -304,6 +453,9 @@ public struct DefaultOAuthMetadataDiscovery: OAuthMetadataDiscovering { components.scheme = scheme components.host = host + // User information is a credential, not part of an issuer. + components.user = nil + components.password = nil components.path = "" components.query = nil components.fragment = nil @@ -317,8 +469,10 @@ public struct DefaultOAuthMetadataDiscovery: OAuthMetadataDiscovering { /// Compares scheme, host and port (with the scheme's default port), then /// requires the endpoint path to equal the resource path or lie under it. /// - /// A trailing slash is ignored, and a resource without a path matches every - /// endpoint on its origin. + /// The paths are compared percent-encoded, so `%2F` is not a `/`: `/a%2Fb` + /// doesn't cover `/a/b/mcp`. Trailing slashes are ignored, and a resource + /// without a path matches every endpoint on its origin. Pass canonical URIs + /// (``canonicalResourceURI(from:)``), whose dot segments are removed. public func protectedResourceMatches(resource: URL, endpoint: URL) -> Bool { guard let resourceComponents = URLComponents( url: resource, @@ -332,10 +486,13 @@ public struct DefaultOAuthMetadataDiscovery: OAuthMetadataDiscovering { return false } - let resourceScheme = resourceComponents.scheme?.lowercased() - let endpointScheme = endpointComponents.scheme?.lowercased() - let resourceHost = resourceComponents.host?.lowercased() - let endpointHost = endpointComponents.host?.lowercased() + guard let resourceScheme = resourceComponents.scheme?.lowercased(), !resourceScheme.isEmpty, + let endpointScheme = endpointComponents.scheme?.lowercased(), !endpointScheme.isEmpty, + let resourceHost = resourceComponents.encodedHost.map(Self.asciiLowercased), !resourceHost.isEmpty, + let endpointHost = endpointComponents.encodedHost.map(Self.asciiLowercased), !endpointHost.isEmpty + else { + return false + } let resourcePort = resourceComponents.port ?? Self.defaultPort(for: resourceScheme) let endpointPort = endpointComponents.port ?? Self.defaultPort(for: endpointScheme) @@ -346,8 +503,8 @@ public struct DefaultOAuthMetadataDiscovery: OAuthMetadataDiscovering { return false } - let resourcePath = Self.normalizedResourcePath(resourceComponents.path) - let endpointPath = Self.normalizedResourcePath(endpointComponents.path) + let resourcePath = Self.normalizedResourcePath(resourceComponents.percentEncodedPath) + let endpointPath = Self.normalizedResourcePath(endpointComponents.percentEncodedPath) if resourcePath.isEmpty { return true } @@ -357,17 +514,34 @@ public struct DefaultOAuthMetadataDiscovery: OAuthMetadataDiscovering { return endpointPath.hasPrefix(resourcePath + "/") } - private static func normalizedResourcePath(_ rawPath: String) -> String { - if rawPath.isEmpty || rawPath == "/" { - return "" - } - if rawPath.count > 1 && rawPath.hasSuffix("/") { - return String(rawPath.dropLast()) + /// Whether `lhs` and `rhs` have the same origin (RFC 6454 §4): the same + /// scheme, host and port, compared as ``canonicalResourceURI(from:)`` + /// writes them (lowercase, a default port written or not). `http` and + /// `https` on one host are two origins. + static func haveSameOrigin(_ lhs: URL, _ rhs: URL) -> Bool { + guard let lhs = URLComponents(url: lhs, resolvingAgainstBaseURL: false), + let rhs = URLComponents(url: rhs, resolvingAgainstBaseURL: false) + else { return false } + let lhsScheme = lhs.scheme?.lowercased() + let rhsScheme = rhs.scheme?.lowercased() + guard let lhsScheme, lhsScheme == rhsScheme, + let lhsHost = lhs.encodedHost.map(asciiLowercased), !lhsHost.isEmpty, + lhsHost == rhs.encodedHost.map(asciiLowercased) + else { return false } + return (lhs.port ?? defaultPort(for: lhsScheme)) == (rhs.port ?? defaultPort(for: rhsScheme)) + } + + /// `encodedPath` with its percent-encodings normalized, dot segments + /// collapsed, and without trailing slashes; a root path is empty. + private static func normalizedResourcePath(_ encodedPath: String) -> String { + var path = removingDotSegments(from: normalizingPercentEncodings(in: encodedPath)) + while path.hasSuffix("/") { + path.removeLast() } - return rawPath + return path } - private static func defaultPort(for scheme: String?) -> Int? { + static func defaultPort(for scheme: String?) -> Int? { switch scheme?.lowercased() { case OAuthURLScheme.http: return OAuthDefaultPort.http @@ -379,6 +553,7 @@ public struct DefaultOAuthMetadataDiscovery: OAuthMetadataDiscovering { } static func isSecureOAuthScheme(scheme: String, host: String) -> Bool { + guard !host.isEmpty else { return false } if scheme == OAuthURLScheme.https { return true } diff --git a/Sources/MCP/Base/Authorization/OAuthErrors.swift b/Sources/MCP/Base/Authorization/OAuthErrors.swift index fabbb88a..83f002dc 100644 --- a/Sources/MCP/Base/Authorization/OAuthErrors.swift +++ b/Sources/MCP/Base/Authorization/OAuthErrors.swift @@ -43,22 +43,38 @@ public struct OAuthAuthorizationError: LocalizedError, Hashable, Sendable { rawValue: "authorizationServerMetadataDiscoveryFailed") /// The authorization server metadata does not include a `token_endpoint`. public static let tokenEndpointMissing = Code(rawValue: "tokenEndpointMissing") - /// The token endpoint returned a non-2xx HTTP response: ``statusCode``, ``oauthError``. + /// The authorization server metadata does not include an `authorization_endpoint`, + /// which the authorization code grant needs (RFC 8414 §2). + public static let authorizationEndpointMissing = Code(rawValue: "authorizationEndpointMissing") + /// The `authorization_endpoint` of the authorization server metadata can't be made into + /// an authorization request URL: ``url``, without user information, query or fragment. + public static let authorizationEndpointInvalid = Code(rawValue: "authorizationEndpointInvalid") + /// The token endpoint returned a non-2xx HTTP response, or a response that is not + /// HTTP: ``statusCode`` (`nil` without an HTTP response), ``oauthError``. public static let tokenRequestFailed = Code(rawValue: "tokenRequestFailed") - /// The token response has an empty `access_token`, or a token type other than `Bearer` - /// (or `DPoP`, when the request carried a proof). + /// The token response is not a token response (RFC 6749 §5.1), has an empty + /// `access_token`, or has a token type other than `Bearer` (or `DPoP`, when the request + /// carried a proof). public static let tokenResponseInvalid = Code(rawValue: "tokenResponseInvalid") /// A URL that must be a valid resource identifier (RFC 8707) failed validation: ``detail``. public static let invalidResourceURI = Code(rawValue: "invalidResourceURI") /// The client ID looks like a URL but is not an HTTPS URL with a path, as Client ID /// Metadata Documents require: ``clientID``. public static let invalidClientIDMetadataURL = Code(rawValue: "invalidClientIDMetadataURL") - /// The `resource` of the Protected Resource Metadata is not the requested endpoint: - /// ``expected``, ``actual``. + /// The `resource` of the Protected Resource Metadata is not the requested endpoint, or + /// a request went to a URL outside the resource: ``expected``, ``actual``, and a + /// ``detail`` when ``HTTPClientTransport`` was redirected to another origin. public static let protectedResourceMismatch = Code(rawValue: "protectedResourceMismatch") /// The authorization server does not support dynamic registration and no pre-registered /// credentials were supplied. public static let registrationInformationRequired = Code(rawValue: "registrationInformationRequired") + /// The client registration endpoint returned a non-2xx HTTP response (RFC 7591 §3.2.2), + /// or a response that is not HTTP: ``statusCode`` (`nil` without an HTTP response), + /// ``oauthError``. + public static let registrationRequestFailed = Code(rawValue: "registrationRequestFailed") + /// The client registration endpoint answered with a 2xx response that is not a client + /// information response (RFC 7591 §3.2.1). + public static let registrationResponseInvalid = Code(rawValue: "registrationResponseInvalid") /// The authorization server supports neither Client ID Metadata Documents nor dynamic /// registration: ``clientID``. public static let cimdNotSupported = Code(rawValue: "cimdNotSupported") @@ -136,11 +152,13 @@ public struct OAuthAuthorizationError: LocalizedError, Hashable, Sendable { /// What failed. public let code: Code - /// The HTTP status code of the response that failed, for ``Code/tokenRequestFailed`` and - /// ``Code/authorizationRequestFailed``. + /// The HTTP status code of the response that failed, for ``Code/tokenRequestFailed``, + /// ``Code/registrationRequestFailed`` and ``Code/authorizationRequestFailed``; `nil` when + /// the response was not an HTTP response. public let statusCode: Int? - /// The `error` field of the OAuth error response, for ``Code/tokenRequestFailed``. + /// The `error` field of the OAuth error response, for ``Code/tokenRequestFailed`` and + /// ``Code/registrationRequestFailed``. public let oauthError: String? /// Which URL or endpoint failed, for example `"Token endpoint"`. @@ -217,6 +235,10 @@ public struct OAuthAuthorizationError: LocalizedError, Hashable, Sendable { return "Failed to discover authorization server metadata" case .tokenEndpointMissing: return "Authorization server metadata is missing token_endpoint" + case .authorizationEndpointMissing: + return "Authorization server metadata is missing authorization_endpoint" + case .authorizationEndpointInvalid: + return "Authorization endpoint cannot be made into an authorization request URL: \(url)" case .tokenRequestFailed: let status = statusCode.map(String.init) ?? "unknown" if let oauthError, !oauthError.isEmpty { @@ -230,10 +252,19 @@ public struct OAuthAuthorizationError: LocalizedError, Hashable, Sendable { case .invalidClientIDMetadataURL: return "Client ID metadata document URL must use https and include a path: \(clientID ?? "")" case .protectedResourceMismatch: - return "Protected resource metadata resource mismatch. Expected \(expected), got \(actual)" + let mismatch = "Protected resource metadata resource mismatch. Expected \(expected), got \(actual)" + return detail.map { "\(mismatch). \($0)" } ?? mismatch case .registrationInformationRequired: return "No supported client registration mechanism was available; provide pre-registered client credentials" + case .registrationRequestFailed: + let status = statusCode.map(String.init) ?? "unknown" + if let oauthError, !oauthError.isEmpty { + return "Client registration failed with status \(status) (oauth_error: \(oauthError))" + } + return "Client registration failed with status \(status)" + case .registrationResponseInvalid: + return "Client registration response is invalid" case .cimdNotSupported: return "Authorization server does not support Client ID Metadata Documents; configure pre-registered credentials or ensure the server advertises client_id_metadata_document_supported: \(clientID ?? "")" @@ -305,10 +336,14 @@ extension OAuthAuthorizationError { code: .authorizationServerMetadataDiscoveryFailed) /// See ``Code/tokenEndpointMissing``. public static let tokenEndpointMissing = Self(code: .tokenEndpointMissing) + /// See ``Code/authorizationEndpointMissing``. + public static let authorizationEndpointMissing = Self(code: .authorizationEndpointMissing) /// See ``Code/tokenResponseInvalid``. public static let tokenResponseInvalid = Self(code: .tokenResponseInvalid) /// See ``Code/registrationInformationRequired``. public static let registrationInformationRequired = Self(code: .registrationInformationRequired) + /// See ``Code/registrationResponseInvalid``. + public static let registrationResponseInvalid = Self(code: .registrationResponseInvalid) /// See ``Code/authorizationResponseMissingRedirectLocation``. public static let authorizationResponseMissingRedirectLocation = Self( code: .authorizationResponseMissingRedirectLocation) @@ -333,10 +368,26 @@ extension OAuthAuthorizationError { public static let tokenRequestFailed = Self(code: .tokenRequestFailed) /// See ``Code/tokenRequestFailed``. - public static func tokenRequestFailed(statusCode: Int, oauthError: String?) -> Self { + public static func tokenRequestFailed(statusCode: Int?, oauthError: String?) -> Self { Self(code: .tokenRequestFailed, statusCode: statusCode, oauthError: oauthError) } + /// Every error with code ``Code/registrationRequestFailed``, for `catch` and `case` patterns. + public static let registrationRequestFailed = Self(code: .registrationRequestFailed) + + /// See ``Code/registrationRequestFailed``. + public static func registrationRequestFailed(statusCode: Int?, oauthError: String?) -> Self { + Self(code: .registrationRequestFailed, statusCode: statusCode, oauthError: oauthError) + } + + /// Every error with code ``Code/authorizationEndpointInvalid``, for `catch` and `case` patterns. + public static let authorizationEndpointInvalid = Self(code: .authorizationEndpointInvalid) + + /// See ``Code/authorizationEndpointInvalid``. + public static func authorizationEndpointInvalid(url: String) -> Self { + Self(code: .authorizationEndpointInvalid, url: url) + } + /// Every error with code ``Code/invalidResourceURI``, for `catch` and `case` patterns. public static let invalidResourceURI = Self(code: .invalidResourceURI) diff --git a/Sources/MCP/Base/Authorization/OAuthModels.swift b/Sources/MCP/Base/Authorization/OAuthModels.swift index db6d83bb..1ad88792 100644 --- a/Sources/MCP/Base/Authorization/OAuthModels.swift +++ b/Sources/MCP/Base/Authorization/OAuthModels.swift @@ -170,7 +170,7 @@ struct OAuthTokenErrorResponse: Decodable { /// An OAuth 2.1 access token and its associated metadata. /// -/// Stored by ``TokenStorage`` and produced by ``OAuthAuthorizer`` after a successful +/// Stored by ``OAuthTokenStorage`` and produced by ``OAuthAuthorizer`` after a successful /// token request. Use ``isExpired(now:skewSeconds:)`` to check validity before use. public struct OAuthAccessToken: Sendable, Codable { /// The raw bearer token string for use in the `Authorization` header. diff --git a/Sources/MCP/Base/Authorization/OAuthRedirectGuard.swift b/Sources/MCP/Base/Authorization/OAuthRedirectGuard.swift index e98f7657..a330e08b 100644 --- a/Sources/MCP/Base/Authorization/OAuthRedirectGuard.swift +++ b/Sources/MCP/Base/Authorization/OAuthRedirectGuard.swift @@ -1,16 +1,21 @@ import Foundation +import Synchronization #if canImport(FoundationNetworking) import FoundationNetworking #endif -/// Checks the HTTP redirects of OAuth requests (SSRF protection). +/// Checks the HTTP redirects of OAuth and server card requests (SSRF +/// protection). /// /// Discovery requests may follow a redirect to an `https` URL (or a loopback /// `http` URL, when the previous hop was loopback `http`) whose host is not /// a private IP literal, and to a loopback host only from a loopback host. /// Token and registration requests carry credentials and follow no redirects. -final class OAuthRedirectGuard: NSObject, URLSessionTaskDelegate, @unchecked Sendable { +/// A followed redirect keeps credentials as ``HTTPRedirect`` says. +/// `@unchecked Sendable`: `NSObject` is not `Sendable` on Linux; `policy` +/// and `validator` are immutable `Sendable`, and `chains` is guarded by a `Mutex`. +final class OAuthRedirectGuard: NSObject, URLSessionTaskDelegate, HTTPRedirectDeciding, @unchecked Sendable { enum Policy: Sendable { /// Follow redirects that pass the URL checks. case validated @@ -20,8 +25,10 @@ final class OAuthRedirectGuard: NSObject, URLSessionTaskDelegate, @unchecked Sen private let policy: Policy private let validator: OAuthURLValidator + /// The redirect chain of each task it is the delegate of. + private let chains = Mutex<[Int: HTTPRedirectChain]>([:]) - init(policy: Policy, validator: OAuthURLValidator) { + init(policy: Policy, validator: OAuthURLValidator = OAuthURLValidator()) { self.policy = policy self.validator = validator } @@ -35,7 +42,35 @@ final class OAuthRedirectGuard: NSObject, URLSessionTaskDelegate, @unchecked Sen ) { // The previous hop, not the first URL of the chain. let source = response.url ?? task.currentRequest?.url - completionHandler(allows(from: source, to: request.url) ? request : nil) + let next = chains.withLock { chains in + var chain = chains[task.taskIdentifier, default: HTTPRedirectChain()] + defer { chains[task.taskIdentifier] = chain } + return self.request(redirectedTo: request, original: task.originalRequest, from: source, chain: &chain) + } + completionHandler(next) + } + + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: (any Error)?) { + chains.withLock { $0[task.taskIdentifier] = nil } + } + + func request( + redirectedTo proposed: URLRequest, by response: HTTPURLResponse, original: URLRequest?, + chain: inout HTTPRedirectChain + ) async -> URLRequest? { + request(redirectedTo: proposed, original: original, from: response.url, chain: &chain) + } + + /// The request to send for the redirect URLSession proposes, `proposed`, + /// from the URL `source` that answered with it, in a chain that started + /// with `original`: `proposed` with the credentials ``HTTPRedirect`` + /// keeps, or `nil` when the policy doesn't follow it. + func request( + redirectedTo proposed: URLRequest, original: URLRequest?, from source: URL?, + chain: inout HTTPRedirectChain + ) -> URLRequest? { + guard allows(from: source, to: proposed.url) else { return nil } + return HTTPRedirect.request(redirectedTo: proposed, original: original, from: source, chain: &chain).request } /// Whether a redirect from `source` to `target` may be followed. @@ -69,16 +104,32 @@ extension URLSession { for request: URLRequest, redirects policy: OAuthRedirectGuard.Policy, validator: OAuthURLValidator ) async throws -> (Data, URLResponse) { + var request = request + let (strippedConfiguration, credentials) = HTTPRedirect.separatingCredentials(of: configuration) + HTTPRedirect.addingCredentials(credentials, to: &request) #if canImport(FoundationNetworking) let guarded = URLSession( - configuration: configuration.withoutURLCache(), + configuration: strippedConfiguration.withoutURLCache(), delegate: OAuthRedirectGuard(policy: policy, validator: validator), delegateQueue: nil) defer { guarded.finishTasksAndInvalidate() } - return try await guarded.data(for: request.addingAdditionalHeaders(of: configuration)) + return try await guarded.data(for: request.addingAdditionalHeaders(of: strippedConfiguration)) #else let guardDelegate = OAuthRedirectGuard(policy: policy, validator: validator) - return try await data(for: request, delegate: guardDelegate) + guard !credentials.isEmpty else { + return try await data(for: request, delegate: guardDelegate) + } + let sessionDelegate = ForwardingSessionDelegate(forwardingTo: delegate) + let fetchSession = URLSession( + configuration: strippedConfiguration, delegate: sessionDelegate, delegateQueue: delegateQueue) + let result: Result<(Data, URLResponse), any Error> + do { + result = .success(try await fetchSession.data(for: request, delegate: guardDelegate)) + } catch { + result = .failure(error) + } + await sessionDelegate.invalidate(fetchSession) + return try result.get() #endif } } diff --git a/Sources/MCP/Base/Authorization/OAuthTokenEndpointClient.swift b/Sources/MCP/Base/Authorization/OAuthTokenEndpointClient.swift index d6c52c6d..cc0cd58f 100644 --- a/Sources/MCP/Base/Authorization/OAuthTokenEndpointClient.swift +++ b/Sources/MCP/Base/Authorization/OAuthTokenEndpointClient.swift @@ -52,7 +52,7 @@ struct OAuthTokenEndpointClient: Sendable { urlRequest.httpBody = OAuthFormEncoding.encode(parameters) if let dpop { urlRequest.setValue( - try dpop.proof( + try await dpop.proof( method: "POST", url: endpoint, accessToken: nil, server: .authorizationServer), forHTTPHeaderField: HTTPHeaderName.dpop) @@ -61,7 +61,7 @@ struct OAuthTokenEndpointClient: Sendable { let (data, response) = try await session.oauthData( for: urlRequest, redirects: .none, validator: urlValidator) guard let httpResponse = response as? HTTPURLResponse else { - throw OAuthAuthorizationError.tokenRequestFailed(statusCode: -1, oauthError: nil) + throw OAuthAuthorizationError(code: .tokenRequestFailed) } let nonce = dpop?.recordNonce( from: Self.headers(of: httpResponse), for: endpoint, server: .authorizationServer) @@ -81,8 +81,9 @@ struct OAuthTokenEndpointClient: Sendable { ) } - let decoded = try JSONDecoder().decode(OAuthTokenResponse.self, from: data) - guard !decoded.accessToken.isEmpty else { + guard let decoded = try? JSONDecoder().decode(OAuthTokenResponse.self, from: data), + !decoded.accessToken.isEmpty + else { throw OAuthAuthorizationError.tokenResponseInvalid } let tokenType = decoded.tokenType diff --git a/Sources/MCP/Base/Authorization/OAuthTokenExchange.swift b/Sources/MCP/Base/Authorization/OAuthTokenExchange.swift index 40f31a5d..39130b43 100644 --- a/Sources/MCP/Base/Authorization/OAuthTokenExchange.swift +++ b/Sources/MCP/Base/Authorization/OAuthTokenExchange.swift @@ -156,7 +156,7 @@ public enum OAuthTokenExchange { let (data, response) = try await session.oauthData( for: urlRequest, redirects: .none, validator: urlValidator) guard let httpResponse = response as? HTTPURLResponse else { - throw OAuthAuthorizationError.tokenRequestFailed(statusCode: -1, oauthError: nil) + throw OAuthAuthorizationError(code: .tokenRequestFailed) } guard (200..<300).contains(httpResponse.statusCode) else { let oauthError = (try? JSONDecoder().decode(OAuthTokenErrorResponse.self, from: data))?.error diff --git a/Sources/MCP/Base/Authorization/OAuthTokenStorage.swift b/Sources/MCP/Base/Authorization/OAuthTokenStorage.swift new file mode 100644 index 00000000..3dc78a2c --- /dev/null +++ b/Sources/MCP/Base/Authorization/OAuthTokenStorage.swift @@ -0,0 +1,123 @@ +import Foundation +import Synchronization + +// MARK: - Token Storage Protocol + +/// Keeps the OAuth access tokens of ``OAuthAuthorizer``, one per protected resource. +/// +/// ``OAuthAuthorizer`` stores each token under the canonical URI of the resource it +/// requested the token for, the value it sends as the `resource` parameter +/// (RFC 8707 §2): the configured ``OAuthConfiguration/EndpointOverrides/resource``, +/// else the `resource` of the server's protected resource metadata when it covers +/// the endpoint, else the endpoint itself, each canonicalized by +/// ``OAuthMetadataDiscovering/canonicalResourceURI(from:)``. So one storage can serve +/// authorizers for several servers, and a token is loaded only for the resource it +/// was issued for. Compare keys with `==`; they are already canonical. With +/// ``DefaultOAuthMetadataDiscovery``, a key has a lowercase scheme and host, no user +/// information, no default port, no query, fragment, dot segments or trailing `/`, +/// and percent-encodings in uppercase: `https://mcp.example.com/mcp`, also for an endpoint +/// `https://MCP.example.com:443/mcp/`, while `https://mcp.example.com:8443/mcp` is +/// another key. +/// +/// The key can change once the authorizer has read the server's protected +/// resource metadata, for example from `https://mcp.example.com/mcp` to +/// `https://mcp.example.com`. The authorizer looks the token up again under the +/// new key before it starts a sign-in, and uses it when an authorization server +/// that the metadata lists issued it. It clears the token under the old key, +/// after trying its refresh token when the new key has none. For a store that +/// keeps tokens across launches, set ``OAuthConfiguration/EndpointOverrides/resource`` +/// to the server's resource, so the first request after a launch finds its token. +/// +/// The key follows the URL of each request. When the configuration or the metadata +/// names a resource, a URL that resource covers uses its key, and after discovery a +/// URL it doesn't cover fails with +/// ``OAuthAuthorizationError/protectedResourceMismatch(expected:actual:)``. When +/// nothing names one, the resource is the MCP endpoint the authorizer serves, and +/// every URL on the endpoint's origin, such as one a `requestModifier` gives another +/// path, uses the endpoint's key; after discovery a URL on another origin fails with +/// the same error. Before discovery, a request to another server's URL uses that +/// server's key. Two endpoints whose metadata names the same `resource` share one +/// token, since the token was issued for that resource (RFC 8707 §2). +/// +/// A stored token carries its refresh token. Keep it where your platform keeps +/// secrets, such as the Keychain (`kSecClassGenericPassword`, with +/// `resource.absoluteString` as the account and an explicit `kSecAttrAccessible`), +/// never in `UserDefaults` or a plain file. With DPoP, persist the signing key with +/// the tokens (see ``OAuthConfiguration/DPoP``). +/// +/// An authorizer calls the storage from several tasks at once, for every request. +/// It writes one token at a time, but loads concurrently with its writes. Two +/// authorizers that share a store and a resource don't coordinate their writes; +/// use one authorizer per server. Don't block the calling thread: run a +/// synchronous store, such as `SecItemCopyMatching`, off the cooperative pool. +/// Don't call the authorizer or its transport from the storage: the authorizer +/// may be waiting for the storage. +/// +/// Throw when the store fails, for example when the Keychain is locked: the +/// request that needed the token fails with the error. Finish a +/// ``save(_:for:)`` even when the calling task is cancelled: the authorization +/// server may already have replaced the refresh token it supersedes, so a token +/// that isn't saved can cost the user another sign-in. +/// +/// The default ``InMemoryOAuthTokenStorage`` loses its tokens when the process exits. +/// +/// - SeeAlso: https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#resource-parameter-implementation +public protocol OAuthTokenStorage: Sendable { + /// Returns the token stored for `resource`, or `nil` when there is none. + /// + /// - Parameter resource: The canonical resource URI the token was requested for. + /// - Returns: The stored token, with its refresh token. + /// - Throws: An error of the underlying store. + func load(for resource: URL) async throws -> OAuthAccessToken? + + /// Stores `token` for `resource`, replacing any token stored for it. + /// + /// - Parameters: + /// - token: The token to store, with its refresh token. + /// - resource: The canonical resource URI the token was requested for. + /// - Throws: An error of the underlying store. + func save(_ token: OAuthAccessToken, for resource: URL) async throws + + /// Removes the token stored for `resource`, if any. Tokens of other resources stay. + /// + /// - Parameter resource: The canonical resource URI whose token to remove. + /// - Throws: An error of the underlying store; removing a missing token is not one. + func clear(for resource: URL) async throws +} + +// MARK: - In-Memory Implementation + +/// An ``OAuthTokenStorage`` that keeps tokens in memory, one per resource. +/// +/// The tokens are lost when the process exits. Its methods are synchronous and +/// never throw; they can be called from several tasks at once. +public final class InMemoryOAuthTokenStorage: OAuthTokenStorage { + private let tokens = Mutex<[URL: OAuthAccessToken]>([:]) + + /// Creates an empty storage. + public init() {} + + /// Returns the token stored for `resource`, if any. + /// + /// - Parameter resource: The canonical resource URI the token was requested for. + /// - Returns: The stored token, or `nil`. + public func load(for resource: URL) -> OAuthAccessToken? { + tokens.withLock { $0[resource] } + } + + /// Stores `token` for `resource`, replacing any token stored for it. + /// + /// - Parameters: + /// - token: The token to store. + /// - resource: The canonical resource URI the token was requested for. + public func save(_ token: OAuthAccessToken, for resource: URL) { + tokens.withLock { $0[resource] = token } + } + + /// Removes the token stored for `resource`, if any. + /// + /// - Parameter resource: The canonical resource URI whose token to remove. + public func clear(for resource: URL) { + tokens.withLock { _ = $0.removeValue(forKey: resource) } + } +} diff --git a/Sources/MCP/Base/Authorization/OAuthURLValidator.swift b/Sources/MCP/Base/Authorization/OAuthURLValidator.swift index 5694f074..7b88f1e2 100644 --- a/Sources/MCP/Base/Authorization/OAuthURLValidator.swift +++ b/Sources/MCP/Base/Authorization/OAuthURLValidator.swift @@ -32,7 +32,7 @@ extension OAuthURLValidating { isPrivateIPHost(host) || (!allowingLoopback && OAuthURLValidator.isLoopbackHost(host)) { throw OAuthAuthorizationError.privateIPAddressBlocked( - context: context, url: url.absoluteString) + context: context, url: OAuthURLValidator.redacted(url)) } } @@ -60,6 +60,20 @@ public struct OAuthURLValidator: Sendable { self.allowLoopbackHTTPForAuthorizationServer = allowLoopbackHTTPForAuthorizationServer } + /// `url` as an error describes it: without user information, a query or a + /// fragment, which can carry a password or a token. Errors are logged, for + /// example by ``HTTPClientTransport``'s GET stream. + static func redacted(_ url: URL) -> String { + guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { + return "" + } + components.user = nil + components.password = nil + components.query = nil + components.fragment = nil + return components.string ?? "" + } + /// Validates that the URL uses HTTPS or loopback HTTP, and has no fragment. /// /// Used for MCP endpoints and protected resource metadata URLs. @@ -71,7 +85,7 @@ public struct OAuthURLValidator: Sendable { components.fragment == nil else { throw OAuthAuthorizationError.invalidResourceURI( - "Invalid \(context): \(url.absoluteString)" + "Invalid \(context): \(OAuthURLValidator.redacted(url))" ) } @@ -80,7 +94,7 @@ public struct OAuthURLValidator: Sendable { else { throw OAuthAuthorizationError.insecureOAuthEndpoint( context: context, - url: url.absoluteString + url: OAuthURLValidator.redacted(url) ) } } @@ -96,7 +110,7 @@ public struct OAuthURLValidator: Sendable { components.fragment == nil else { throw OAuthAuthorizationError.invalidResourceURI( - "Invalid \(context): \(url.absoluteString)" + "Invalid \(context): \(OAuthURLValidator.redacted(url))" ) } @@ -110,7 +124,7 @@ public struct OAuthURLValidator: Sendable { guard scheme == OAuthURLScheme.https else { throw OAuthAuthorizationError.insecureAuthorizationServerEndpoint( context: context, - url: url.absoluteString + url: OAuthURLValidator.redacted(url) ) } } @@ -123,7 +137,7 @@ public struct OAuthURLValidator: Sendable { let scheme = components.scheme?.lowercased(), components.fragment == nil else { - throw OAuthAuthorizationError.invalidRedirectURI(url.absoluteString) + throw OAuthAuthorizationError.invalidRedirectURI(OAuthURLValidator.redacted(url)) } if scheme == OAuthURLScheme.https { return } @@ -135,7 +149,7 @@ public struct OAuthURLValidator: Sendable { return } - throw OAuthAuthorizationError.invalidRedirectURI(url.absoluteString) + throw OAuthAuthorizationError.invalidRedirectURI(OAuthURLValidator.redacted(url)) } /// Returns `true` if `host` is a literal IPv4 or IPv6 address in a private or reserved range. @@ -211,6 +225,93 @@ public struct OAuthURLValidator: Sendable { return validator.isPrivateIPHost(host, includingLoopback: true) && !validator.isPrivateIPHost(host) } + /// Whether `host` names this machine (`localhost`, `*.localhost`, + /// `127.0.0.0/8`, `::1`) or an unspecified address (`0.0.0.0/8`, `::`), + /// including non-canonical numeric IPv4 spellings (`127.1`, `2130706433`, + /// `0177.0.0.1`, `0x7f000001`), trailing-dot forms (`127.0.0.1.`), and + /// IPv4-embedded IPv6 literals (including non-canonical IPv4 tails). + static func isLoopbackOrUnspecifiedHost(_ host: String) -> Bool { + var literal = host.lowercased() + if literal.hasPrefix("[") || literal.hasSuffix("]") { + guard literal.hasPrefix("["), literal.hasSuffix("]"), literal.contains(":") else { + return false + } + literal = String(literal.dropFirst().dropLast()) + } + if let zone = literal.firstIndex(of: "%") { + literal = String(literal[.. [UInt8]? { + let trimmed = host.hasSuffix(".") ? String(host.dropLast()) : host + guard !trimmed.isEmpty, trimmed.first?.isNumber == true, + trimmed.allSatisfy({ $0.isHexDigit || $0 == "." || $0 == "x" }) + else { return nil } + var address = in_addr() + guard inet_aton(trimmed, &address) != 0 else { return nil } + let value = UInt32(bigEndian: address.s_addr) + return [ + UInt8((value >> 24) & 0xff), + UInt8((value >> 16) & 0xff), + UInt8((value >> 8) & 0xff), + UInt8(value & 0xff), + ] + } + + private static func isLoopbackOrUnspecifiedIPv6(_ bytes: [UInt8]) -> Bool { + let prefix96 = bytes.prefix(12) + let embedded = Array(bytes.suffix(4)) + if bytes.allSatisfy({ $0 == 0 }) { return true } // :: + if prefix96.allSatisfy({ $0 == 0 }) { + if embedded == [0, 0, 0, 1] { return true } // ::1 + return embedded[0] == 127 || embedded[0] == 0 // ::/96 (IPv4-compatible) + } + if prefix96.elementsEqual([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff]) // ::ffff:0:0/96 + || prefix96.elementsEqual([0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0]) // ::ffff:0:0:0/96 + || prefix96.elementsEqual([0x00, 0x64, 0xff, 0x9b, 0, 0, 0, 0, 0, 0, 0, 0]) // 64:ff9b::/96 + { + return embedded[0] == 127 || embedded[0] == 0 + } + if bytes[0] == 0x20 && bytes[1] == 0x02 { // 2002::/16 (6to4) + return bytes[2] == 127 || bytes[2] == 0 + } + return false + } + /// Whether the host of `url` names this machine (``isLoopbackHost(_:)``). static func isLoopback(_ url: URL?) -> Bool { guard let url, let host = URLComponents(url: url, resolvingAgainstBaseURL: false)?.host else { diff --git a/Sources/MCP/Base/Authorization/OAuthWWWAuthenticateParser.swift b/Sources/MCP/Base/Authorization/OAuthWWWAuthenticateParser.swift index eeb028a4..114542e4 100644 --- a/Sources/MCP/Base/Authorization/OAuthWWWAuthenticateParser.swift +++ b/Sources/MCP/Base/Authorization/OAuthWWWAuthenticateParser.swift @@ -6,7 +6,10 @@ import Foundation /// /// ``OAuthAuthorizer`` uses this protocol to inspect 401 and 403 responses from the server. /// Override the default ``DefaultOAuthWWWAuthenticateParser`` to handle custom challenge formats. -public protocol OAuthWWWAuthenticateParsing { +/// Conforming types are `Sendable`: ``OAuthAuthorizer`` calls them from several tasks at once. +/// +/// - SeeAlso: https://www.rfc-editor.org/rfc/rfc6750#section-3 +public protocol OAuthWWWAuthenticateParsing: Sendable { /// Parses the `WWW-Authenticate` header from a response header dictionary. /// /// - Parameter headers: The full set of HTTP response headers (case-insensitive lookup is expected). diff --git a/Sources/MCP/Base/Authorization/TokenStorage.swift b/Sources/MCP/Base/Authorization/TokenStorage.swift deleted file mode 100644 index 49142397..00000000 --- a/Sources/MCP/Base/Authorization/TokenStorage.swift +++ /dev/null @@ -1,44 +0,0 @@ -import Foundation - -// MARK: - Token Storage Protocol - -/// Abstraction for persisting OAuth access tokens. -/// -/// Implement this protocol to provide custom token storage (e.g., Keychain-backed). -/// The default ``InMemoryTokenStorage`` stores tokens in memory only. -/// Implementations must be safe to call from several tasks at once. -public protocol TokenStorage: AnyObject, Sendable { - func save(_ token: OAuthAccessToken) - func load() -> OAuthAccessToken? - func clear() -} - -// MARK: - In-Memory Implementation - -/// Default ``TokenStorage`` that stores the access token in memory only. -/// -/// The token is lost when the process exits. For persistent storage -/// (e.g., system Keychain), implement ``TokenStorage`` directly. Its methods -/// may be called from several tasks at once. -public final class InMemoryTokenStorage: TokenStorage, @unchecked Sendable { - private let lock = NSLock() - private var token: OAuthAccessToken? - - /// Creates an empty token storage. - public init() {} - - /// Replaces the stored token. - public func save(_ token: OAuthAccessToken) { - lock.withLock { self.token = token } - } - - /// Returns the stored token, if any. - public func load() -> OAuthAccessToken? { - lock.withLock { token } - } - - /// Removes the stored token. - public func clear() { - lock.withLock { token = nil } - } -} diff --git a/Sources/MCP/Base/DataURL.swift b/Sources/MCP/Base/DataURL.swift new file mode 100644 index 00000000..08682aa0 --- /dev/null +++ b/Sources/MCP/Base/DataURL.swift @@ -0,0 +1,294 @@ +import Foundation +import RegexBuilder + +/// A `data:` URL (RFC 2397): bytes with their media type. +/// +/// MCP carries binary content in typed fields (image and audio `data`, a resource's `blob`), +/// so the SDK never turns a string into a `DataURL` by itself: a `data:` URL in a tool +/// argument or in `structuredContent` is a ``Value/string(_:)``. Parse it with ``init(_:)``, +/// or declare a `DataURL` property in a `Codable` type, which decodes and validates the string: +/// +/// ```swift +/// struct Arguments: Codable { +/// var image: DataURL +/// } +/// ``` +/// +/// ``init(_:)`` accepts `data:` in lowercase, then an optional media type `type/subtype`, +/// then an optional `;charset=`, then an optional `;base64`, then `,` and the payload. +/// The type, the subtype and the charset value are RFC 2045 tokens: printable ASCII without +/// space or `()<>@,;:\"/[]?=`. So prose such as `data: 3 rows, 2 columns` is not a `data:` +/// URL, and neither is one with another parameter, such as `;name=`. The names `charset` and +/// `base64` are matched without regard to ASCII case. A base64 payload may contain ASCII whitespace +/// and lack its `=` padding, but not `%XX` escapes; any other payload must have a well-formed +/// `%XX` after every `%`. +/// +/// The MIME type rules: +/// +/// - ``mimeType`` is `text/plain` for an empty media type, including when only parameters +/// are given (such as `;charset=utf-8`, which becomes `text/plain;charset=utf-8`). +/// - `;charset=` is kept only for a `text/` type or an empty media type, as in +/// `text/plain;charset=utf-8`; for other types it is dropped. +/// - The type, the subtype and the parameter names are lowercase (ASCII only). +/// ``init(data:mimeType:)`` and the ``mimeType`` setter also remove ASCII whitespace at +/// either end of the media type, around each `;`, and around the first `=` of each +/// parameter, so `text/html; charset=utf-8` becomes `text/html;charset=utf-8`; ``init(_:)`` +/// rejects whitespace in the URL header and normalizes case and the default `text/plain` +/// (see ``mimeType``). +/// +/// A media type that this grammar can't carry, set with ``init(data:mimeType:)`` or +/// ``mimeType``, doesn't parse back from ``description``, or parses to another value: another +/// parameter, or a space inside the type, the subtype or the charset, makes ``init(_:)`` +/// return `nil`, a charset on a type that is not `text/` is dropped, and a `,` ends the media +/// type early, so the rest of it is read as the payload and the bytes change. ``encode(to:)`` +/// throws for such a value instead of writing it, so a `Codable` round trip never changes a +/// `DataURL`. +/// +/// - SeeAlso: [RFC 2397](https://www.rfc-editor.org/rfc/rfc2397.html) +public struct DataURL: Hashable, Sendable { + /// The media type of ``data``, such as `image/png` or `text/plain;charset=utf-8`. + /// + /// The type, the subtype and the parameter names are lowercase, as RFC 2045 §5.1 makes + /// them case-insensitive; parameter values keep their case. ASCII whitespace (tab, line + /// feed, form feed, carriage return and space) is removed at either end of the value, + /// around each `;`, and around the first `=` of each parameter: RFC 2045 §5.1 allows + /// whitespace between tokens, as in the common `text/html; charset=utf-8`, and the URL + /// form of RFC 2397 §3 has none. An empty type part after that becomes `text/plain`, + /// whether the whole value is empty or starts with a parameter such as `;charset=utf-8`. + /// + /// ``init(data:mimeType:)`` and this setter apply all of this normalization, including + /// whitespace trimming; ``init(_:)`` rejects whitespace in the header and applies the + /// case and `text/plain` normalization, so `TEXT/PLAIN` and `text/plain` are equal and + /// hash the same. + public var mimeType: String { + get { normalizedMIMEType } + set { normalizedMIMEType = Self.normalized(newValue) } + } + + /// The bytes. + public var data: Data + + private var normalizedMIMEType: String + + /// Creates a `data:` URL of `data` with the media type `mimeType`. + /// + /// `mimeType` is normalized as ``mimeType`` describes; an empty or whitespace-only type + /// part becomes `text/plain` (so `""` becomes `text/plain` and `;charset=utf-8` becomes + /// `text/plain;charset=utf-8`). For ``description`` to parse back to an equal value, pass + /// `type/subtype` (or omit it for `text/plain`), optionally with `;charset=` for a `text/` + /// type. + /// + /// - Parameters: + /// - data: The bytes. + /// - mimeType: The media type of the bytes, such as `image/png`. + public init(data: Data, mimeType: String) { + self.data = data + self.normalizedMIMEType = Self.normalized(mimeType) + } + + private static let asciiWhitespace = CharacterSet(charactersIn: "\t\n\u{0C}\r ") + + /// `mimeType` with a lowercase type, subtype and parameter names (ASCII only), without + /// ASCII whitespace at either end, around each `;` or around the first `=` of each + /// parameter, and with an empty type part replaced by `text/plain`. + private static func normalized(_ mimeType: String) -> String { + var parts = mimeType.split(separator: ";", omittingEmptySubsequences: false).map { trimmed($0) } + parts[0] = parts[0].isEmpty ? "text/plain" : asciiLowercased(parts[0]) + for index in parts.indices.dropFirst() { + guard let equals = parts[index].firstIndex(of: "=") else { continue } + let name = asciiLowercased(trimmed(parts[index][.. String { + String( + decoding: string.utf8.map { byte in + (UInt8(ascii: "A")...UInt8(ascii: "Z")).contains(byte) ? byte &+ 32 : byte + }, + as: UTF8.self) + } + + /// `string` without leading and trailing ASCII whitespace (tab, line feed, form feed, + /// carriage return and space). + private static func trimmed(_ string: Substring) -> String { + string.trimmingCharacters(in: asciiWhitespace) + } +} + +// MARK: - Parsing + +extension DataURL: CustomStringConvertible { + /// Parses a `data:` URL; `nil` when `description` is not one. + /// + /// The type's documentation gives the grammar and the MIME type rules. + /// + /// - Parameter description: The string to parse, such as `data:image/png;base64,iVBORw==`. + public init?(_ description: String) { + guard let match = description.wholeMatch(of: Self.regex) else { return nil } + let (_, mediaType, charset, base64Marker, payload) = match.output + // A base64 payload is read with the forgiving-base64 rules (whitespace, missing + // padding), but, unlike the WHATWG Fetch `data:` URL processor, it is not + // percent-decoded first: `data:;base64,aGk%3D` is not a `data:` URL here. + let bytes = base64Marker != nil ? Data(lenientBase64Encoded: payload) : Self.percentDecoded(payload) + guard let bytes else { return nil } + var type = mediaType.isEmpty ? "text/plain" : String(mediaType) + if let charset, !charset.isEmpty, Self.asciiLowercased(type).hasPrefix("text/") { + type += ";charset=\(charset)" + } + self.init(data: bytes, mimeType: type) + } + + /// The URL in base64 form, `data:;base64,`. + /// + /// It is not always the spelling that was parsed: the media type is normalized and the + /// payload is always base64, so `data:TEXT/Plain,hi` is `data:text/plain;base64,aGk=`. + /// The media type is written as it is, so one that the grammar can't carry doesn't parse + /// back to this value (see the type's documentation). + public var description: String { + "data:\(mimeType);base64,\(data.base64EncodedString())" + } + + /// The grammar of the type's documentation: the media type, the charset, the base64 + /// marker and the payload. + /// + /// `Regex` does not conform to `Sendable` because a pattern can capture non-`Sendable` + /// transform closures. This pattern has no transform closures, and its bytecode is warmed + /// once inside static initialization before concurrent read-only matching. + private nonisolated(unsafe) static let regex: Regex<(Substring, Substring, Substring?, Substring?, Substring)> = { + // A `token` character of RFC 2045 §5.1: printable US-ASCII without + // space and `tspecials`. + let mediaTypeTokenCharacter = CharacterClass( + .anyOf("!#$%&'*+-.^_`{|}~"), "a"..."z", "A"..."Z", "0"..."9") + let compiled: Regex<(Substring, Substring, Substring?, Substring?, Substring)> = Regex { + "data:" + // RFC 2397 §3: `[ type "/" subtype ]`, so prose such as + // `data: 3 rows, 2 columns` is not a data URL. + Capture { + Optionally { + OneOrMore(mediaTypeTokenCharacter) + "/" + OneOrMore(mediaTypeTokenCharacter) + } + } + // RFC 2045 §5.1: parameter names are case-insensitive (ASCII only). + Optionally { + #/;[cC][hH][aA][rR][sS][eE][tT]=/# + Capture { + OneOrMore(mediaTypeTokenCharacter) + } + } + Optionally { + Capture { #/;[bB][aA][sS][eE]64/# } + } + "," + Capture { + ZeroOrMore { .any } + } + }.matchingSemantics(.unicodeScalar) + _ = "data:,".wholeMatch(of: compiled) + return compiled + }() + + /// Decodes `%XX` escapes directly into bytes, so any byte value is accepted. + /// + /// - Parameter string: The percent-encoded string. + /// - Returns: The decoded bytes, or `nil` if an escape is malformed. + private static func percentDecoded(_ string: Substring) -> Data? { + var bytes = Data(capacity: string.utf8.count) + var iterator = string.utf8.makeIterator() + while let byte = iterator.next() { + guard byte == UInt8(ascii: "%") else { + bytes.append(byte) + continue + } + guard let high = iterator.next().flatMap(hexValue), + let low = iterator.next().flatMap(hexValue) + else { return nil } + bytes.append(high << 4 | low) + } + return bytes + } + + private static func hexValue(_ byte: UInt8) -> UInt8? { + switch byte { + case UInt8(ascii: "0")...UInt8(ascii: "9"): return byte - UInt8(ascii: "0") + case UInt8(ascii: "a")...UInt8(ascii: "f"): return byte - UInt8(ascii: "a") + 10 + case UInt8(ascii: "A")...UInt8(ascii: "F"): return byte - UInt8(ascii: "A") + 10 + default: return nil + } + } +} + +// MARK: - Codable + +extension DataURL: Codable { + /// Decodes a `data:` URL from a JSON string. + /// + /// - Throws: `DecodingError.typeMismatch` when the value is not a string, and + /// `DecodingError.dataCorrupted` when the string is not a `data:` URL. + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + guard let url = DataURL(try container.decode(String.self)) else { + throw DecodingError.dataCorruptedError(in: container, debugDescription: "The string is not a data: URL") + } + self = url + } + + /// Encodes the URL as a JSON string, its ``description``. + /// + /// - Throws: `EncodingError.invalidValue` when ``init(_:)`` can't read the media type + /// back from ``description`` (see the type's documentation), so that decoding never + /// gives another value. The error holds the media type, not the bytes. + public func encode(to encoder: any Encoder) throws { + guard DataURL("data:\(mimeType);base64,")?.mimeType == mimeType else { + throw EncodingError.invalidValue( + mimeType, + .init( + codingPath: encoder.codingPath, + debugDescription: "The media type can't be written in a data: URL that reads back as it")) + } + var container = encoder.singleValueContainer() + try container.encode(description) + } +} + +// MARK: - Deprecated Data helpers + +extension Data { + /// Returns whether `string` is a valid `data:` URL (RFC 2397). + /// + /// - Parameter string: The string to check. + /// - Returns: `true` if `string` parses as a ``DataURL``, otherwise `false`. + /// - SeeAlso: ``DataURL`` + @available(*, deprecated, message: "Use DataURL(_:) != nil instead") + public static func isDataURL(string: String) -> Bool { + DataURL(string) != nil + } + + /// Parses a `data:` URL string into its normalized MIME type and decoded bytes. + /// + /// - Parameter string: The `data:` URL string to parse. + /// - Returns: A tuple of the normalized MIME type and decoded bytes, or `nil` if `string` + /// is not a valid `data:` URL. + /// - SeeAlso: ``DataURL`` + @available(*, deprecated, message: "Use DataURL(_:) instead") + public static func parseDataURL(_ string: String) -> (mimeType: String, data: Data)? { + guard let url = DataURL(string) else { return nil } + return (mimeType: url.mimeType, data: url.data) + } + + /// Encodes the bytes as a base64 `data:` URL string with an optional MIME type. + /// + /// - Parameter mimeType: The MIME type of the bytes; defaults to `text/plain` when `nil`. + /// - Returns: A `data:` URL string representation of the bytes. + /// - SeeAlso: ``DataURL`` + @available(*, deprecated, message: "Use DataURL(data:mimeType:).description instead") + public func dataURLEncoded(mimeType: String? = nil) -> String { + DataURL(data: self, mimeType: mimeType ?? "text/plain").description + } +} diff --git a/Sources/MCP/Base/Discover.swift b/Sources/MCP/Base/Discover.swift index 17bcd9e2..4c4f5cd5 100644 --- a/Sources/MCP/Base/Discover.swift +++ b/Sources/MCP/Base/Discover.swift @@ -52,7 +52,7 @@ public enum ServerDiscover: Method { capabilities = try container.decode(Server.Capabilities.self, forKey: .capabilities) instructions = try container.decodeIfPresent(String.self, forKey: .instructions) _meta = try container.decodeIfPresent(Metadata.self, forKey: ._meta) - ttlMs = container.decodeTTL(forKey: .ttlMs) + ttlMs = container.decodeMilliseconds(forKey: .ttlMs) cacheScope = container.decodeCacheScope(forKey: .cacheScope) } diff --git a/Sources/MCP/Base/Error.swift b/Sources/MCP/Base/Error.swift index a0358060..6ed32df9 100644 --- a/Sources/MCP/Base/Error.swift +++ b/Sources/MCP/Base/Error.swift @@ -1,11 +1,5 @@ import Foundation -#if canImport(System) - import System -#else - @preconcurrency import SystemPackage -#endif - /// Information about a required URL elicitation public struct URLElicitationInfo: Codable, Hashable, Sendable { /// Elicitation mode (must be "url") @@ -108,13 +102,13 @@ public enum MCPError: Swift.Error, Sendable { case .resourceNotFound(let uri, _): return ["uri": .string(uri)] case .missingRequiredClientCapabilities(let capabilities, _): - return ["requiredCapabilities": (try? Value.preservingStrings(capabilities)) ?? [:]] + return ["requiredCapabilities": (try? Value(capabilities)) ?? [:]] case .unsupportedProtocolVersion(let supported, let requested): var data: [String: Value] = ["supported": .array(supported.map { .string($0) })] if let requested { data["requested"] = .string(requested) } return .object(data) case .urlElicitationRequired(_, let elicitations): - let items = elicitations.map { (try? Value.preservingStrings($0)) ?? .null } + let items = elicitations.map { (try? Value($0)) ?? .null } return ["elicitations": .array(items)] case .connectionClosed: return nil @@ -122,20 +116,6 @@ public enum MCPError: Swift.Error, Sendable { return ["error": .string(error.localizedDescription)] } } - - /// Check if an error represents a "resource temporarily unavailable" condition - public static func isResourceTemporarilyUnavailable(_ error: Swift.Error) -> Bool { - #if canImport(System) - if let errno = error as? System.Errno, errno == .resourceTemporarilyUnavailable { - return true - } - #else - if let errno = error as? SystemPackage.Errno, errno == .resourceTemporarilyUnavailable { - return true - } - #endif - return false - } } // MARK: LocalizedError @@ -360,9 +340,6 @@ extension MCPError: Codable { } // A message equal to the case's own text for `message: nil` is `nil`. let customMessage: (String) -> String? = { text in message == text ? nil : message } - // An application sees `.data` for a `data:` URL in `data`, as in any - // other decoded `Value`. - let serverData = data?.decodingDataURLs switch code { case -32700: @@ -378,7 +355,7 @@ extension MCPError: Codable { } else if code == -32602 { self = .invalidParams(detailOrMessage("Invalid params")) } else { - self = .serverError(code: code, message: message, data: serverData) + self = .serverError(code: code, message: message, data: data) } case -32603: self = .internalError(detailOrMessage("Internal error")) @@ -393,7 +370,7 @@ extension MCPError: Codable { self = .missingRequiredClientCapabilities( required, message: customMessage("Missing required client capabilities")) } else { - self = .serverError(code: code, message: message, data: serverData) + self = .serverError(code: code, message: message, data: data) } case -32022: let supported = fields?["supported"]?.arrayValue?.compactMap(\.stringValue) ?? [] @@ -413,12 +390,12 @@ extension MCPError: Codable { { self = .urlElicitationRequired(message: message, elicitations: elicitations) } else { - self = .serverError(code: code, message: message, data: serverData) + self = .serverError(code: code, message: message, data: data) } default: // -32000 and -32001 are used by the SDK for local transport errors // only; on the wire they are implementation-defined server errors. - self = .serverError(code: code, message: message, data: serverData) + self = .serverError(code: code, message: message, data: data) } } } diff --git a/Sources/MCP/Base/ExactString.swift b/Sources/MCP/Base/ExactString.swift new file mode 100644 index 00000000..b6e2561a --- /dev/null +++ b/Sources/MCP/Base/ExactString.swift @@ -0,0 +1,64 @@ +// Matching of strings a peer chose: ids, tokens, method names, keys. +// +// Swift `String` equality is Unicode canonical equivalence: "\u{E9}" equals +// "e\u{301}", and U+212A KELVIN SIGN equals "K". JSON-RPC peers in other +// languages compare a string's code points, so a string that selects a +// request, a task or a handler matches only the same code points here too. + +extension StringProtocol { + /// Whether the two strings have the same Unicode scalars. + /// + /// Unlike `==`, a canonically equivalent but different spelling does not + /// match. A valid string has one UTF-8 encoding per scalar sequence, + /// which a native string stores, so the bytes are compared without + /// decoding. + /// + /// - Complexity: O(*n*), where *n* is the length of the strings in UTF-8. + func isExactly(_ other: some StringProtocol) -> Bool { + utf8.count == other.utf8.count && utf8.elementsEqual(other.utf8) + } +} + +extension String { + /// Hashes the string's UTF-8 bytes, which agrees with `isExactly(_:)`. + /// + /// The bytes are the same for every representation of the string, + /// including one bridged from Objective-C. + func hashExactly(into hasher: inout Hasher) { + var string = self + string.withUTF8 { bytes in + hasher.combine(bytes.count) + hasher.combine(bytes: UnsafeRawBufferPointer(bytes)) + } + } +} + +/// A string that matches only the same Unicode scalars, as the key of a +/// table that a peer's string selects from. +struct ExactString: Hashable, Sendable, CustomStringConvertible { + /// The string. + let value: String + + init(_ value: String) { + self.value = value + } + + var description: String { value } + + static func == (lhs: ExactString, rhs: ExactString) -> Bool { + lhs.value.isExactly(rhs.value) + } + + func hash(into hasher: inout Hasher) { + value.hashExactly(into: &hasher) + } +} + +extension Dictionary where Key == String { + /// The value for `key` when the stored key has the same Unicode scalars; + /// `nil` for a key that is only canonically equivalent. + func exactValue(forKey key: String) -> Value? { + guard let index = index(forKey: key), self[index].key.isExactly(key) else { return nil } + return self[index].value + } +} diff --git a/Sources/MCP/Base/ID.swift b/Sources/MCP/Base/ID.swift index 41c0acec..8844d2d5 100644 --- a/Sources/MCP/Base/ID.swift +++ b/Sources/MCP/Base/ID.swift @@ -2,7 +2,17 @@ import struct Foundation.UUID /// A unique identifier for a request. /// +/// A JSON-RPC 2.0 id is a JSON string or number (§4), and two ids are the +/// same id when their JSON values are: `.string("1")` and `.number(1)` are +/// different ids, and so are two strings with different Unicode scalars. +/// Equality and hashing compare a string's scalars exactly, unlike Swift +/// `String` equality, which treats canonically equivalent spellings such as +/// `"\u{E9}"` and `"e\u{301}"` as equal. Peers in other languages compare +/// the scalars, and so do the transports' routing keys. +/// /// Frozen: no case is added in 1.x (a JSON-RPC 2.0 ID is a string or a number). +/// +/// - SeeAlso: https://www.jsonrpc.org/specification#request_object public enum ID: Hashable, Sendable { /// A string ID. case string(String) @@ -16,6 +26,38 @@ public enum ID: Hashable, Sendable { } } +// MARK: - Equatable and Hashable + +extension ID { + /// Returns whether two IDs are the same JSON-RPC id: numbers that are + /// equal, or strings with the same Unicode scalars. + /// + /// - Complexity: O(*n*), where *n* is the length of the strings in UTF-8. + public static func == (lhs: ID, rhs: ID) -> Bool { + switch (lhs, rhs) { + case (.number(let lhs), .number(let rhs)): + return lhs == rhs + case (.string(let lhs), .string(let rhs)): + return lhs.isExactly(rhs) + case (.number, .string), (.string, .number): + return false + } + } + + /// Hashes the case and the number, or the string's UTF-8 bytes, so IDs + /// that are equal hash alike. + public func hash(into hasher: inout Hasher) { + switch self { + case .number(let number): + hasher.combine(0) + hasher.combine(number) + case .string(let string): + hasher.combine(1) + string.hashExactly(into: &hasher) + } + } +} + // MARK: - ExpressibleByStringLiteral extension ID: ExpressibleByStringLiteral { diff --git a/Sources/MCP/Base/Icon.swift b/Sources/MCP/Base/Icon.swift index 670fd429..a3f35b74 100644 --- a/Sources/MCP/Base/Icon.swift +++ b/Sources/MCP/Base/Icon.swift @@ -9,7 +9,13 @@ import Foundation public struct Icon: Hashable, Codable, Sendable { /// The theme this icon is designed for. /// - /// Frozen: no case is added in 1.x (the values of CSS `prefers-color-scheme`). + /// Frozen in 1.x: no case is added in a 1.x release, so switches over + /// `Theme` stay exhaustive (the 2025-11-25 schema defines `"light"` and + /// `"dark"`, matching CSS `prefers-color-scheme`). If a peer sends another + /// string, ``Icon/init(from:)`` decodes ``Icon/theme`` as `nil` instead of + /// failing the enclosing listing; the icon then reads as usable with any + /// theme, compares equal to one with no theme, and omits `theme` if encoded + /// again. public enum Theme: String, Hashable, Codable, Sendable { /// Icon is designed for light backgrounds case light @@ -45,7 +51,12 @@ public struct Icon: Hashable, Codable, Sendable { /// - `light`: Icon is designed to be used with a light background /// - `dark`: Icon is designed to be used with a dark background /// - /// If not provided, the client should assume the icon can be used with any theme. + /// `nil` means either that the icon omitted `theme` or that the peer sent a + /// string outside ``Theme`` (for example from a newer protocol revision or + /// a custom value). Either way, treat the icon as usable with any theme, as + /// the specification says for an icon without a theme. Because unrecognized + /// strings decode to `nil`, such an icon compares equal to one with no + /// theme and omits `theme` if encoded again. public let theme: Theme? /// Creates a new icon. @@ -66,4 +77,17 @@ public struct Icon: Hashable, Codable, Sendable { self.sizes = sizes self.theme = theme } + + private enum CodingKeys: String, CodingKey { + case src, mimeType, sizes, theme + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + src = try container.decode(String.self, forKey: .src) + mimeType = try container.decodeIfPresent(String.self, forKey: .mimeType) + sizes = try container.decodeIfPresent([String].self, forKey: .sizes) + // A theme from a later revision reads as no theme, so one icon can't fail a listing. + theme = try container.decodeIfPresent(String.self, forKey: .theme).flatMap(Theme.init(rawValue:)) + } } diff --git a/Sources/MCP/Base/Messages.swift b/Sources/MCP/Base/Messages.swift index db632ead..3093b4bc 100644 --- a/Sources/MCP/Base/Messages.swift +++ b/Sources/MCP/Base/Messages.swift @@ -150,9 +150,7 @@ private struct MetaProbe: Decodable { /// keys already present in the encoded `_meta` win. private func mergingMeta(_ meta: Metadata, into params: P) throws -> Value { var object: [String: Value] - // Through `Value`, but strings stay strings: a `data:` URL argument is - // sent as given. - switch try Value.preservingStrings(params) { + switch try Value(params) { case .object(let fields): object = fields case .null: object = [:] default: @@ -226,7 +224,6 @@ extension AnyRequest { init(_ request: Request) throws { let encoder = JSONEncoder() let decoder = JSONDecoder() - decoder.userInfo[.valuePreservesStrings] = true let data = try encoder.encode(request) self = try decoder.decode(AnyRequest.self, from: data) @@ -276,8 +273,7 @@ final class TypedRequestHandler: RequestHandlerBox, @unchecked Sendab let encoder = JSONEncoder() let decoder = JSONDecoder() - // Create a concrete request from the type-erased one; here `data:` - // URL strings in `Value` fields become `.data`. + // Create a concrete request from the type-erased one. let data = try encoder.encode(request) let request: Request do { @@ -292,8 +288,7 @@ final class TypedRequestHandler: RequestHandlerBox, @unchecked Sendab // Convert result to AnyMethod response switch response.result { case .success(let result): - // Strings as written: the result is sent as the handler made it. - return Response(id: response.id, result: try Value.preservingStrings(result)) + return Response(id: response.id, result: try Value(result)) case .failure(let error): return Response(id: response.id, error: error) } @@ -364,6 +359,12 @@ public struct Response: Hashable, Identifiable, Codable, Sendable { } else if let error = try? container.decode(MCPError.self, forKey: .error) { self.result = .failure(error) } else { + // Decode again to report where the result or the error is wrong. + if container.contains(.result) { + _ = try container.decode(M.Result.self, forKey: .result) + } else if container.contains(.error) { + _ = try container.decode(MCPError.self, forKey: .error) + } throw DecodingError.dataCorrupted( DecodingError.Context( codingPath: container.codingPath, @@ -381,7 +382,7 @@ extension AnyResponse { case .success(let result): self = Response( id: response.id, - result: .success(try Value.preservingStrings(result)) + result: .success(try Value(result)) ) case .failure(let error): self = Response( diff --git a/Sources/MCP/Base/MetaKeys.swift b/Sources/MCP/Base/MetaKeys.swift index 1dba8f46..04e2d94b 100644 --- a/Sources/MCP/Base/MetaKeys.swift +++ b/Sources/MCP/Base/MetaKeys.swift @@ -69,6 +69,6 @@ extension Metadata { } private mutating func encodeField(_ value: T?, _ key: String) { - fields[key] = value.flatMap { try? Value.preservingStrings($0) } + fields[key] = value.flatMap { try? Value($0) } } } diff --git a/Sources/MCP/Base/Milliseconds.swift b/Sources/MCP/Base/Milliseconds.swift new file mode 100644 index 00000000..1de9c1bf --- /dev/null +++ b/Sources/MCP/Base/Milliseconds.swift @@ -0,0 +1,96 @@ +// Durations travel as whole milliseconds: `ttlMs` and `pollIntervalMs` +// (2026-07-28), the task `ttl` and `pollInterval` and `TaskMetadata.ttl` +// (2025-11-25), and the `...Ms` keys of a saved `Client.Configuration`. +// This file converts between those wire milliseconds and `Duration`, and +// reads them leniently. Code that works on the numbers themselves, such as +// a task record's expiry date or the clamp of a configured cache hint, does +// not go through it. + +extension Duration { + /// Creates a duration of `milliseconds` read from the wire. + init(wireMilliseconds milliseconds: Int) { + self = .milliseconds(milliseconds) + } + + /// The duration in whole milliseconds, for the wire: rounded down, at + /// least 1 for a positive duration (so a short lifetime is not sent as + /// "stale at once"), 0 for a negative one (the fields have no negative + /// values), and `Int.max` for one longer than that. + var wholeMilliseconds: Int { + let (seconds, attoseconds) = components + guard seconds >= 0, attoseconds >= 0 else { return 0 } + let (milliseconds, overflow) = seconds.multipliedReportingOverflow(by: 1000) + let (total, carry) = milliseconds.addingReportingOverflow(attoseconds / 1_000_000_000_000_000) + if overflow || carry { return .max } + if total == 0, seconds > 0 || attoseconds > 0 { return 1 } + // `Int` is 32 bits on watchOS (arm64_32). + return Int(clamping: total) + } +} + +extension KeyedDecodingContainer { + /// The milliseconds at `key`, read leniently: a fractional value is + /// rounded down, and on 32-bit platforms a value past `Int.max` is + /// `Int.max`, as encoding clamps; a negative, non-numeric or non-finite + /// value, one past `Int64.max`, `null` and an absent key are `nil`, so a + /// hint from a peer never fails its result. + func decodeMilliseconds(forKey key: Key) -> Int? { + decodeMilliseconds(Int.self, forKey: key) + } + + /// The milliseconds at `key` as `T`, read as + /// ``decodeMilliseconds(forKey:)`` describes, with a value past `T.max` + /// clamped to `T.max`. + /// + /// The value is read in 64 bits on every platform, so `Int32` gives on a + /// 64-bit platform what `Int` gives on watchOS (arm64_32). + func decodeMilliseconds(_ type: T.Type, forKey key: Key) -> T? { + if let value = try? decodeIfPresent(Int64.self, forKey: key) { + return value >= 0 ? T(clamping: value) : nil + } + // `Double(Int64.max)` is 2^63, so a smaller value converts. + guard let value = try? decodeIfPresent(Double.self, forKey: key), + value.isFinite, value >= 0, value < Double(Int64.max) + else { return nil } + return T(clamping: Int64(value)) + } + + /// The milliseconds at `key` as a duration; `nil` as + /// ``decodeMilliseconds(forKey:)`` describes. + /// + /// A fractional value is rounded down to whole milliseconds first, so + /// `0.4` is zero. + func decodeDuration(forKey key: Key) -> Duration? { + decodeMilliseconds(forKey: key).map(Duration.init(wireMilliseconds:)) + } + + /// The milliseconds at `key` as a duration or, when `key` is absent, the + /// duration at `legacyKey` in `Duration`'s own `Codable` form + /// (`[high, low]` attoseconds), which configurations saved by + /// prereleases of 1.0 use. + /// + /// - Throws: The errors of `decodeIfPresent(Duration.self, forKey:)` + /// for `legacyKey`. + func decodeDuration(forKey key: Key, legacyKey: Key) throws -> Duration? { + if contains(key) { return decodeDuration(forKey: key) } + return try decodeIfPresent(Duration.self, forKey: legacyKey) + } +} + +extension KeyedEncodingContainer { + /// Encodes `duration` in whole milliseconds (see + /// `Duration.wholeMilliseconds`); nothing when it is `nil`. + mutating func encodeMilliseconds(_ duration: Duration?, forKey key: Key) throws { + try encodeIfPresent(duration?.wholeMilliseconds, forKey: key) + } + + /// Encodes `duration` in whole milliseconds, or `null` when it is `nil` + /// (no limit, such as a task's unlimited lifetime). + mutating func encodeMillisecondsOrNull(_ duration: Duration?, forKey key: Key) throws { + if let duration { + try encode(duration.wholeMilliseconds, forKey: key) + } else { + try encodeNil(forKey: key) + } + } +} diff --git a/Sources/MCP/Base/MultiRoundTrip.swift b/Sources/MCP/Base/MultiRoundTrip.swift index 8e934880..c245f9d5 100644 --- a/Sources/MCP/Base/MultiRoundTrip.swift +++ b/Sources/MCP/Base/MultiRoundTrip.swift @@ -96,11 +96,11 @@ public enum InputRequest: Hashable, Sendable { } } - /// The `params` of the request, with strings as written. + /// The `params` of the request. func params() throws -> Value { switch self { - case .elicitation(let params): return try Value.preservingStrings(params) - case .sampling(let params): return try Value.preservingStrings(params) + case .elicitation(let params): return try Value(params) + case .sampling(let params): return try Value(params) case .listRoots: return [:] case .unknown(_, let params): return params } @@ -123,8 +123,8 @@ extension InputRequest: Codable { case ListRoots.name: self = .listRoots default: - let params = try container.decodeIfPresent(Value.Preserved.self, forKey: .params) - self = .unknown(method: method, params: params?.value ?? [:]) + let params = try container.decodeIfPresent(Value.self, forKey: .params) + self = .unknown(method: method, params: params ?? [:]) } } @@ -186,15 +186,13 @@ public enum InputResponse: Hashable, Sendable { return nil } - /// Decodes the result of a request of `method`, with strings as - /// written: the response is sent on as the handler returned it. + /// Decodes the result of a request of `method`: the response is sent on + /// as the handler returned it. init(method: String, result: Value) throws { switch method { - case CreateElicitation.name: - self = .elicitation(try CreateElicitation.Result(decoding: result, preservingStrings: true)) - case CreateSamplingMessage.name: - self = .sampling(try CreateSamplingMessage.Result(decoding: result, preservingStrings: true)) - case ListRoots.name: self = .roots(try ListRoots.Result(decoding: result, preservingStrings: true)) + case CreateElicitation.name: self = .elicitation(try CreateElicitation.Result(decoding: result)) + case CreateSamplingMessage.name: self = .sampling(try CreateSamplingMessage.Result(decoding: result)) + case ListRoots.name: self = .roots(try ListRoots.Result(decoding: result)) default: self = .unknown(result) } } @@ -207,9 +205,7 @@ extension InputResponse: Codable { public init(from decoder: Decoder) throws { let shape = try decoder.container(keyedBy: ShapeKeys.self) - // A known kind decodes from `decoder` itself, not through a `Value`, - // so a `data:` URL string is read once, as for any other type. A - // result of a later kind may share a key with a known one: it is + // A result of a later kind may share a key with a known one: it is // unknown when it does not decode as the kind its shape suggests. if shape.contains(.roots), let result = try? ListRoots.Result(from: decoder) { self = .roots(result) @@ -220,7 +216,7 @@ extension InputResponse: Codable { { self = .sampling(result) } else { - self = .unknown(try Value.Preserved(from: decoder).value) + self = .unknown(try Value(from: decoder)) } } @@ -301,12 +297,8 @@ enum MRTR { } extension Decodable { - /// Decodes a value from its JSON `Value`. With `preservingStrings`, a - /// `data:` URL string in a `Value` field stays a string. - init(decoding value: Value, preservingStrings: Bool = false) throws { - let data = try JSONEncoder().encode(value) - let decoder = JSONDecoder() - if preservingStrings { decoder.userInfo[.valuePreservesStrings] = true } - self = try decoder.decode(Self.self, from: data) + /// Decodes a value from its JSON `Value`. + init(decoding value: Value) throws { + self = try JSONDecoder().decode(Self.self, from: JSONEncoder().encode(value)) } } diff --git a/Sources/MCP/Base/PendingRequest.swift b/Sources/MCP/Base/PendingRequest.swift index 0341cd6e..a5e65570 100644 --- a/Sources/MCP/Base/PendingRequest.swift +++ b/Sources/MCP/Base/PendingRequest.swift @@ -136,8 +136,6 @@ struct AnyPendingRequest: Sendable { _resume = { result in switch result { case .success(let value): - // A result decoded from the wire keeps `data:` URL strings; - // the typed decode turns those in `Value` fields into `.data`. if let value = value as? Value { do { return deliver(.success(try decodeResponseResult(value, as: T.self))) diff --git a/Sources/MCP/Base/Results.swift b/Sources/MCP/Base/Results.swift index ee90d9f0..578393a5 100644 --- a/Sources/MCP/Base/Results.swift +++ b/Sources/MCP/Base/Results.swift @@ -72,19 +72,6 @@ public struct CacheScope: RawRepresentable, Hashable, Codable, Sendable, } extension KeyedDecodingContainer { - /// A caching hint's `ttlMs`, read leniently: a fractional value is - /// rounded down; a negative, non-numeric or out-of-range value is - /// ignored instead of failing the result. - func decodeTTL(forKey key: Key) -> Int? { - if let value = try? decodeIfPresent(Int.self, forKey: key) { - return value >= 0 ? value : nil - } - guard let value = try? decodeIfPresent(Double.self, forKey: key), - value.isFinite, value >= 0, value < Double(Int.max) - else { return nil } - return Int(value) - } - /// A caching hint's `cacheScope`; a non-string value is ignored. func decodeCacheScope(forKey key: Key) -> CacheScope? { try? decodeIfPresent(CacheScope.self, forKey: key) diff --git a/Sources/MCP/Base/ServerCard.swift b/Sources/MCP/Base/ServerCard.swift index 768008aa..ff83be05 100644 --- a/Sources/MCP/Base/ServerCard.swift +++ b/Sources/MCP/Base/ServerCard.swift @@ -506,6 +506,16 @@ extension ServerCard { /// names are not resolved: a name whose address is private is fetched. The /// body is read up to ``maximumSize``. /// + /// An `Authorization`, `Proxy-Authorization`, `Cookie`, `Mcp-Session-Id` or + /// `DPoP` in the `httpAdditionalHeaders` of `session`'s configuration is + /// sent as a header of the request, so a redirect keeps it on the same + /// origin only, as ``HTTPClientTransport`` does. On Apple platforms the + /// request then runs in a session with that configuration without them, on + /// `session`'s delegate queue. The delegate of `session` gets that + /// session's calls, such as a server trust challenge, with it as their + /// `session`, except `urlSession(_:didBecomeInvalidWithError:)`: the fetch + /// invalidates the session it made before it returns. + /// /// - Throws: ``ServerCardError``, or the error of the session. public static func fetch(from url: URL, session: URLSession = .shared) async throws -> ServerCard { switch try await fetch(from: url, ifNoneMatch: nil, session: session) { @@ -532,9 +542,43 @@ extension ServerCard { if let etag { request.setValue(etag, forHTTPHeaderField: HTTPHeaderName.ifNoneMatch) } + // The configuration's credentials are the request's, so that a + // redirect to another origin drops them. + let (configuration, credentials) = HTTPRedirect.separatingCredentials(of: session.configuration) + HTTPRedirect.addingCredentials(credentials, to: &request) + #if canImport(FoundationNetworking) + // The streaming session, on `configuration`, sends the request. + return try await load(request, from: url, ifNoneMatch: etag, session: session, configuration: configuration) + #else + guard !credentials.isEmpty else { + return try await load( + request, from: url, ifNoneMatch: etag, session: session, configuration: configuration) + } + let delegate = ForwardingSessionDelegate(forwardingTo: session.delegate) + let fetchSession = URLSession( + configuration: configuration, delegate: delegate, delegateQueue: session.delegateQueue) + let result: Result + do { + result = .success( + try await load( + request, from: url, ifNoneMatch: etag, session: fetchSession, configuration: configuration)) + } catch { + result = .failure(error) + } + await delegate.invalidate(fetchSession) + return try result.get() + #endif + } + + /// The card of `request` to `url`, sent through `session`, whose + /// configuration's credentials are in `configuration` no longer. + private static func load( + _ request: URLRequest, from url: URL, ifNoneMatch etag: String?, session: URLSession, + configuration: URLSessionConfiguration + ) async throws -> FetchResult { // Each hop is checked before it is requested, as for OAuth discovery. let redirects = OAuthRedirectGuard(policy: .validated, validator: OAuthURLValidator()) - let streaming = StreamingSession(configuration: session.configuration, redirects: redirects) + let streaming = StreamingSession(configuration: configuration, redirects: redirects) defer { streaming.invalidate() } let (body, response) = try await session.responseBody(for: request, streaming: streaming) defer { body.cancel() } diff --git a/Sources/MCP/Base/SkillFrontmatter.swift b/Sources/MCP/Base/SkillFrontmatter.swift index 3c5beb22..0041dab3 100644 --- a/Sources/MCP/Base/SkillFrontmatter.swift +++ b/Sources/MCP/Base/SkillFrontmatter.swift @@ -547,8 +547,7 @@ enum SkillFrontmatter { /// Whether two frontmatter objects have the same JSON content: numbers /// compare by value (`1` and `1.0` are equal), key order does not matter, - /// and a `data:` URL string equals the ``Value/data(mimeType:_:)`` it - /// decodes to. + /// and strings compare as strings. static func matches(_ lhs: [String: Value], _ rhs: [String: Value]) -> Bool { equivalent(.object(lhs), .object(rhs)) } @@ -561,10 +560,6 @@ enum SkillFrontmatter { case (.double(let a), .double(let b)): return a == b case (.int(let a), .double(let b)), (.double(let b), .int(let a)): return Double(a) == b case (.string(let a), .string(let b)): return a == b - case (.data(let m1, let d1), .data(let m2, let d2)): return m1 == m2 && d1 == d2 - case (.data(let mimeType, let data), .string(let string)), (.string(let string), .data(let mimeType, let data)): - guard let (parsedType, parsedData) = Data.parseDataURL(string) else { return false } - return parsedType == mimeType && parsedData == data case (.array(let a), .array(let b)): return a.count == b.count && zip(a, b).allSatisfy { equivalent($0, $1) } case (.object(let a), .object(let b)): diff --git a/Sources/MCP/Base/SkillTypes.swift b/Sources/MCP/Base/SkillTypes.swift index 29c36675..f072b1b2 100644 --- a/Sources/MCP/Base/SkillTypes.swift +++ b/Sources/MCP/Base/SkillTypes.swift @@ -99,12 +99,10 @@ public struct Skill: Hashable, Codable, Sendable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) uri = try container.decode(String.self, forKey: .uri) - // As written: a `data:` URL in the frontmatter stays a string. - frontmatter = try container.decode([String: Value.Preserved].self, forKey: .frontmatter) - .mapValues(\.value) + frontmatter = try container.decode([String: Value].self, forKey: .frontmatter) if let manifest = try? container.decode([SkillResource].self, forKey: .resources) { resources = .manifest(manifest) - } else if let value = try container.decodeIfPresent(Value.Preserved.self, forKey: .resources)?.value { + } else if let value = try container.decodeIfPresent(Value.self, forKey: .resources) { resources = value == "dynamic" ? .dynamic : .unrecognized(value) } else { resources = .unrecognized(.null) @@ -209,7 +207,7 @@ public enum ListSkills: Method { skills = try container.decode([Skill].self, forKey: .skills) nextCursor = try container.decodeIfPresent(String.self, forKey: .nextCursor) _meta = try container.decodeIfPresent(Metadata.self, forKey: ._meta) - ttlMs = container.decodeTTL(forKey: .ttlMs) + ttlMs = container.decodeMilliseconds(forKey: .ttlMs) cacheScope = container.decodeCacheScope(forKey: .cacheScope) } @@ -267,7 +265,7 @@ public enum GetSkill: Method { let container = try decoder.container(keyedBy: CodingKeys.self) skill = try container.decode(Skill.self, forKey: .skill) _meta = try container.decodeIfPresent(Metadata.self, forKey: ._meta) - ttlMs = container.decodeTTL(forKey: .ttlMs) + ttlMs = container.decodeMilliseconds(forKey: .ttlMs) cacheScope = container.decodeCacheScope(forKey: .cacheScope) } diff --git a/Sources/MCP/Base/Subscriptions.swift b/Sources/MCP/Base/Subscriptions.swift index 41e238d5..5f174944 100644 --- a/Sources/MCP/Base/Subscriptions.swift +++ b/Sources/MCP/Base/Subscriptions.swift @@ -29,6 +29,16 @@ public struct SubscriptionFilter: Hashable, Codable, Sendable { self.resourceSubscriptions = resourceSubscriptions self.taskIds = taskIds } + + /// Whether the two filters ask for the same flags and the exact same URI + /// and task ID spellings (by Unicode scalars). + func isExactly(_ other: SubscriptionFilter) -> Bool { + toolsListChanged == other.toolsListChanged + && promptsListChanged == other.promptsListChanged + && resourcesListChanged == other.resourcesListChanged + && resourceSubscriptions?.map(ExactString.init) == other.resourceSubscriptions?.map(ExactString.init) + && taskIds?.map(ExactString.init) == other.taskIds?.map(ExactString.init) + } } /// Opens a stream for notifications that do not belong to a request @@ -143,22 +153,26 @@ enum SubscriptionEvent: Hashable, Sendable { } } + /// Whether a stream with `filter` receives this event. Resource URIs and + /// task ids match by the same code points. func matches(_ filter: SubscriptionFilter) -> Bool { switch self { case .toolsListChanged: return filter.toolsListChanged == true case .promptsListChanged: return filter.promptsListChanged == true case .resourcesListChanged: return filter.resourcesListChanged == true - case .resourceUpdated(let uri): return filter.resourceSubscriptions?.contains(uri) == true - case .task(let id, _): return filter.taskIds?.contains(id) == true + case .resourceUpdated(let uri): return filter.resourceSubscriptions?.contains { $0.isExactly(uri) } == true + case .task(let id, _): return filter.taskIds?.contains { $0.isExactly(id) } == true } } /// Whether a stream with `filter`, whose resource URIs are `resources` /// and task ids `tasks`, receives this event. - func matches(_ filter: SubscriptionFilter, resources: Set, tasks: Set = []) -> Bool { + func matches( + _ filter: SubscriptionFilter, resources: Set, tasks: Set = [] + ) -> Bool { switch self { - case .resourceUpdated(let uri): return resources.contains(uri) - case .task(let id, _): return tasks.contains(id) + case .resourceUpdated(let uri): return resources.contains(ExactString(uri)) + case .task(let id, _): return tasks.contains(ExactString(id)) default: return matches(filter) } } diff --git a/Sources/MCP/Base/TaskTypes.swift b/Sources/MCP/Base/TaskTypes.swift index 7ba1363a..e1b4ce09 100644 --- a/Sources/MCP/Base/TaskTypes.swift +++ b/Sources/MCP/Base/TaskTypes.swift @@ -27,6 +27,18 @@ enum TaskGeneration: Hashable, Sendable { case v2 } +/// Stores a value that takes no part in the equality and hash of the type +/// that holds it. +@propertyWrapper +struct EqualityIgnored: Hashable, Sendable { + var wrappedValue: Value + + init(wrappedValue: Value) { self.wrappedValue = wrappedValue } + + static func == (lhs: Self, rhs: Self) -> Bool { true } + func hash(into hasher: inout Hasher) {} +} + /// The state of a task. /// /// Open to values this SDK does not know, so a peer's new status does not @@ -133,7 +145,7 @@ public struct TaskMetadata: Hashable, Codable, Sendable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - ttl = container.decodeTTL(forKey: .ttl) + ttl = container.decodeMilliseconds(forKey: .ttl) } public func encode(to encoder: Encoder) throws { @@ -177,8 +189,9 @@ public struct TaskSnapshot: Hashable, Sendable { /// Metadata. public var _meta: Metadata? - /// The form the task is encoded in. - var generation: TaskGeneration + /// The form the task is encoded in. Not part of equality: it doesn't + /// change what the task is. + @EqualityIgnored var generation: TaskGeneration /// Creates a task in its 2026-07-28 form. public init( @@ -266,9 +279,8 @@ extension TaskSnapshot: Codable { !container.contains(.ttlMs) && !container.contains(.pollIntervalMs) && (container.contains(.ttl) || container.contains(.pollInterval)) generation = isV1 ? .v1 : .v2 - ttlMs = isV1 ? container.decodeTTL(forKey: .ttl) : container.decodeTTL(forKey: .ttlMs) - pollIntervalMs = - isV1 ? container.decodeTTL(forKey: .pollInterval) : container.decodeTTL(forKey: .pollIntervalMs) + ttlMs = container.decodeMilliseconds(forKey: isV1 ? .ttl : .ttlMs) + pollIntervalMs = container.decodeMilliseconds(forKey: isV1 ? .pollInterval : .pollIntervalMs) inputRequests = try container.decodeIfPresent([String: InputRequest].self, forKey: .inputRequests) result = try container.decodeIfPresent(Value.self, forKey: .result) error = try container.decodeIfPresent(MCPError.self, forKey: .error) @@ -519,17 +531,28 @@ enum TaskTimestamp { return calendar }() + /// 1970-01-01T00:00:00Z and 9999-12-31T23:59:59Z, the dates written (the last whole + /// second: a `Date` this late can't hold `.999` exactly, and is written as `.998`). + private static let earliest = Date(timeIntervalSince1970: 0) + private static let latest = Date(timeIntervalSince1970: 253_402_300_799) + /// `date` as `YYYY-MM-DDTHH:MM:SS.sssZ`. + /// + /// A task's dates are moments the server recorded, so one before `earliest` or after + /// `latest`, or NaN, is bad store data. It is written as the nearer bound, and NaN as + /// `earliest`: a valid timestamp beats a trap or an invalid string. static func string(from date: Date) -> String { + let date = date.timeIntervalSince1970.isNaN ? earliest : min(max(date, earliest), latest) let components = calendar.dateComponents( [.year, .month, .day, .hour, .minute, .second, .nanosecond], from: date) func pad(_ value: Int?, _ width: Int) -> String { let digits = String(value ?? 0) return String(repeating: "0", count: max(0, width - digits.count)) + digits } + let milliseconds = min(max((components.nanosecond ?? 0) / 1_000_000, 0), 999) return "\(pad(components.year, 4))-\(pad(components.month, 2))-\(pad(components.day, 2))" + "T\(pad(components.hour, 2)):\(pad(components.minute, 2)):\(pad(components.second, 2))" - + ".\(pad((components.nanosecond ?? 0) / 1_000_000, 3))Z" + + ".\(pad(milliseconds, 3))Z" } /// Parses an ISO 8601 timestamp with or without fractional seconds. @@ -553,14 +576,3 @@ enum TaskIdentifier { .replacingOccurrences(of: "=", with: "") } } - -extension Duration { - /// The duration in whole milliseconds, rounded down; at least 1 for a - /// positive duration. - var wholeMilliseconds: Int { - let (seconds, attoseconds) = components - let total = seconds * 1000 + attoseconds / 1_000_000_000_000_000 - if total == 0, seconds > 0 || attoseconds > 0 { return 1 } - return Int(clamping: total) - } -} diff --git a/Sources/MCP/Base/Transport.swift b/Sources/MCP/Base/Transport.swift index 79dce4ea..f31869b0 100644 --- a/Sources/MCP/Base/Transport.swift +++ b/Sources/MCP/Base/Transport.swift @@ -2,71 +2,198 @@ import Logging import struct Foundation.Data -/// Protocol defining the transport layer for MCP communication +/// A connection that carries JSON-RPC messages between a client and a server. +/// +/// ``Client`` and ``Server`` hold their transport as `any Transport`. Each `Data` value a +/// transport sends or yields is one complete JSON-RPC message or batch, without framing. +/// +/// ## Contract +/// +/// - ``connect()`` throws when the transport is already connected, and after +/// ``disconnect()``: a transport serves one connection. Create a new one to connect again. +/// - ``disconnect()`` can be called any number of times, also before ``connect()``. It +/// finishes the stream that ``receive()`` returns. +/// - ``send(_:options:)`` throws ``MCPError/connectionClosed`` after ``disconnect()``, and +/// once the transport knows the peer can no longer read. +/// - ``receive()`` returns the same stream on every call. Iterate it from one task only: two +/// concurrent iterators of an `AsyncThrowingStream` trap. ``Client`` and ``Server`` iterate +/// it themselves, so a wrapper that taps the stream iterates the wrapped transport's stream +/// and returns one of its own. +/// - The end of the stream, normally or with an error, means the peer sends nothing more: +/// ``Client`` stops reading and calls ``disconnect()``, and ``Server`` stops reading. A +/// transport may still send, as ``StdioTransport`` does after the end of its input. +/// +/// ## Hooks +/// +/// ``didNegotiate(protocolVersion:)``, ``abandonRequest(_:)``, ``authorizationEnd(of:)``, +/// ``prepare(servingProtocolVersions:)``, ``isSessionless`` and ``httpRequest(for:)`` have +/// default implementations that do nothing. ``Client`` and ``Server`` call them on every +/// transport; implement the ones that apply to yours. +/// +/// Implement a hook with the requirement's exact signature, `async` included. A synchronous +/// method also satisfies the requirement, but a call to it on the concrete type with `await` +/// resolves to the `async` default implementation instead, which does nothing. +/// +/// A transport that wraps another one adopts ``TransportWrapper``, which forwards every +/// requirement and hook. A hook added in a later 1.x release is added to this protocol, to +/// its default implementations and to ``TransportWrapper``'s forwarding in the same release. +/// +/// - SeeAlso: https://modelcontextprotocol.io/specification/2025-11-25/basic/transports +/// - SeeAlso: https://modelcontextprotocol.io/specification/2026-07-28/basic/transports public protocol Transport: Actor { - var logger: Logger { get } + /// The logger the transport, and the client or server using it, write to. + nonisolated var logger: Logger { get } - /// Establishes connection with the transport + /// Opens the connection. + /// + /// - Throws: An error when the connection cannot be opened, when the transport is + /// already connected, or after ``disconnect()``. func connect() async throws - /// Disconnects from the transport + /// Closes the connection and finishes the stream that ``receive()`` returns. /// - /// This should finish the stream returned by ``receive()``, so that a - /// client reading it stops. + /// It can be called any number of times, also before ``connect()``. Once it has run, + /// the transport stays closed: ``connect()`` throws. func disconnect() async - /// Sends data - func send(_ data: Data) async throws + /// Sends one JSON-RPC message or batch. + /// + /// - Parameters: + /// - data: The encoded message, without framing. + /// - options: What the transport needs besides the bytes: the request the message + /// belongs to, and HTTP headers. + /// - Throws: ``MCPError/connectionClosed`` after ``disconnect()``, or once the transport + /// knows the peer can no longer read; otherwise the error that stopped the send. + func send(_ data: Data, options: TransportSendOptions) async throws - /// Sends data that belongs to an in-flight request. + /// Returns the stream of messages from the peer. /// - /// `relatedRequestID` is the id of the incoming request whose handler - /// produced the message (a progress or log notification, or a - /// server-to-client request). Transports with per-request streams deliver - /// the message on that request's stream. The default implementation - /// ignores the id and calls ``send(_:)``. - func send(_ data: Data, relatedRequestID: ID?) async throws + /// Every call returns the same stream. Iterate it from one task only: two concurrent + /// iterators of an `AsyncThrowingStream` trap. Each element is one JSON-RPC message or + /// batch. The stream finishes when the peer sends nothing more: at ``disconnect()``, and, + /// normally or with an error, when the peer closes its side or the connection fails. + func receive() async -> AsyncThrowingStream - /// Sends a request together with HTTP headers that belong to it. + /// Tells the transport the protocol version of the connection. /// - /// At 2026-07-28, ``Client`` mirrors the `tools/call` arguments that a - /// tool's input schema marks with `x-mcp-header` into `Mcp-Param-` - /// headers (SEP-2243), and passes them here; a server that serves that - /// revision answers a call without them with -32020 - /// (``MCPError/headerMismatch(_:)``). The client calls this method only - /// when there are headers to send. + /// ``Client`` calls it once the version is known: after `initialize` at a handshake + /// revision, and after `server/discover` at 2026-07-28. Read the version's + /// ``Version/profile(for:)``, for example ``ProtocolProfile/usesSessions``, instead of + /// comparing version strings. The default implementation does nothing. /// - /// A Streamable HTTP transport must send `additionalHeaders` on the - /// request's POST, as ``HTTPClientTransport`` does. A transport that is - /// not HTTP has no headers to set and can keep the default - /// implementation, which ignores them and calls ``send(_:)``. A - /// transport that wraps another one should implement this method and - /// forward the headers, so that they reach the HTTP transport. + /// - Parameter version: The negotiated protocol version, such as `"2025-11-25"`. + /// - SeeAlso: https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle#version-negotiation + func didNegotiate(protocolVersion version: String) async + + /// Stops the transport's work for request `id` without a message to the peer. /// - /// - SeeAlso: https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http#custom-headers-from-tool-parameters - func send(_ data: Data, additionalHeaders: [String: String]) async throws - - /// Receives data in an async sequence - /// - /// Finishing the returned stream, normally or by throwing an error, means - /// the connection is closed: ``Client`` then does what - /// ``Client/disconnect()`` does, calling ``disconnect()``, fails its - /// pending requests, and doesn't call `receive()` again. The exception is - /// an error for which ``MCPError/isResourceTemporarilyUnavailable(_:)`` - /// returns `true`: the client then calls `receive()` again, so a transport - /// that throws such an error must return a stream that can still deliver - /// messages. - func receive() -> AsyncThrowingStream + /// ``Client`` calls it when a request is cancelled on a 2026-07-28 connection, and + /// when `server/discover` times out. The default implementation does nothing and + /// returns `false`. + /// + /// - Parameter id: The JSON-RPC ID of a request the client sent. + /// - Returns: `true` when ending the request's exchange is how the peer learns of the + /// cancellation, as when Streamable HTTP closes the request's POST at 2026-07-28; + /// ``Client`` then sends no `notifications/cancelled`. + @discardableResult + func abandonRequest(_ id: ID) async -> Bool + + /// Returns when the transport's authorization work for request `id` last ended, + /// waiting while it runs. + /// + /// ``Client`` doesn't count that time, for example an interactive sign-in, against + /// ``Client/Configuration/discoveryTimeout``. The default implementation returns `nil`. + /// + /// - Parameter id: The JSON-RPC ID of a request the client sent. + /// - Returns: The end of the last authorization step for the request, or `nil` when + /// there was none. + func authorizationEnd(of id: ID) async -> ContinuousClock.Instant? + + /// Tells the transport which protocol versions its server serves, newest first. + /// + /// ``Server`` calls it in ``Server/start(transport:initializeHook:statelessRequestHook:)``, + /// before ``connect()``. The default implementation does nothing. + /// + /// - Parameter versions: The server's `Server.Configuration.protocolVersions`. + func prepare(servingProtocolVersions versions: [String]) async + + /// Whether messages share no connection or session, so that each handshake request + /// stands alone, as behind ``StatelessHTTPServerTransport``. + /// + /// ``Server`` reads it without `await`, so it must not change during the transport's + /// lifetime. The default implementation is `false`. + nonisolated var isSessionless: Bool { get } + + /// Returns the HTTP request that carried request `id`, while that request is in flight. + /// + /// ``Server`` puts it in ``Server/HandlerContext/httpContext`` for the request's + /// handler. The default implementation returns `nil`. + /// + /// - Parameter id: The JSON-RPC ID of a request the transport received. + /// - Returns: The HTTP request, or `nil` when the transport carries no HTTP or the + /// response has been sent. + func httpRequest(for id: ID) async -> HTTPRequest? } extension Transport { - /// Sends data, ignoring `relatedRequestID`. - public func send(_ data: Data, relatedRequestID: ID?) async throws { - try await send(data) + /// Sends one JSON-RPC message or batch with no options. + /// + /// - Parameter data: The encoded message, without framing. + /// - Throws: What ``send(_:options:)`` throws. + public func send(_ data: Data) async throws { + try await send(data, options: TransportSendOptions()) } - /// Sends data, ignoring `additionalHeaders`. - public func send(_ data: Data, additionalHeaders: [String: String]) async throws { - try await send(data) + /// Does nothing. + public func didNegotiate(protocolVersion version: String) async {} + + /// Does nothing and returns `false`. + @discardableResult + public func abandonRequest(_ id: ID) async -> Bool { false } + + /// Returns `nil`. + public func authorizationEnd(of id: ID) async -> ContinuousClock.Instant? { nil } + + /// Does nothing. + public func prepare(servingProtocolVersions versions: [String]) async {} + + /// Whether messages share no connection or session; `false` unless a transport says + /// otherwise. + public nonisolated var isSessionless: Bool { false } + + /// Returns `nil`. + public func httpRequest(for id: ID) async -> HTTPRequest? { nil } +} + +// MARK: - + +/// What a transport needs to know about a message besides its bytes. +public struct TransportSendOptions: Hashable, Sendable { + /// The incoming request whose handler produced the message, such as a progress + /// notification or a server-to-client request. + /// + /// Transports with a stream per request, such as the HTTP server transports, deliver the + /// message on that request's stream. Other transports ignore it. + public var relatedRequestID: ID? + + /// HTTP headers that belong to the message. + /// + /// At 2026-07-28 ``Client`` puts the `Mcp-Param-*` headers of a `tools/call` here + /// (SEP-2243). A Streamable HTTP transport sends them on the message's POST, as + /// ``HTTPClientTransport`` does; other transports ignore them. A server that serves + /// 2026-07-28 answers a call without its headers with -32020 + /// (``MCPError/headerMismatch(_:)``). + /// + /// - SeeAlso: https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http#custom-headers-from-tool-parameters + public var headers: [String: String] + + /// Creates send options. + /// + /// - Parameters: + /// - relatedRequestID: The incoming request whose handler produced the message. + /// - headers: HTTP headers that belong to the message. + public init(relatedRequestID: ID? = nil, headers: [String: String] = [:]) { + self.relatedRequestID = relatedRequestID + self.headers = headers } } diff --git a/Sources/MCP/Base/TransportWrapper.swift b/Sources/MCP/Base/TransportWrapper.swift new file mode 100644 index 00000000..201a1f33 --- /dev/null +++ b/Sources/MCP/Base/TransportWrapper.swift @@ -0,0 +1,93 @@ +import Logging + +import struct Foundation.Data + +/// A transport that wraps another one and forwards every requirement to it. +/// +/// Adopt it in a logging or metrics wrapper, and implement only what the wrapper changes: +/// +/// ```swift +/// actor CountingTransport: TransportWrapper { +/// nonisolated let wrapped: any Transport +/// private(set) var sent = 0 +/// +/// init(_ wrapped: any Transport) { self.wrapped = wrapped } +/// +/// func send(_ data: Data, options: TransportSendOptions) async throws { +/// sent += 1 +/// try await wrapped.send(data, options: options) +/// } +/// } +/// ``` +/// +/// Everything else, including ``Transport/logger`` and every hook, forwards to ``wrapped``, +/// so the wrapped transport keeps its behavior: an ``HTTPClientTransport`` still learns the +/// negotiated version and closes the POST of a cancelled request, and a +/// ``StatelessHTTPServerTransport`` still serves each request on its own. Hooks added in +/// later 1.x releases forward too. +/// +/// - Important: A method whose signature only nearly matches a requirement, such as +/// `didNegotiate(version:)` for ``Transport/didNegotiate(protocolVersion:)``, compiles +/// without a warning and is never called: the forwarding implementation stays in use. +/// Copy each signature from ``Transport``, `async` included: an override of +/// ``Transport/connect()``, ``Transport/disconnect()``, ``Transport/receive()`` or a hook +/// must be `async`, or a call with `await` on the concrete wrapper type reaches the +/// forwarding implementation and skips the override. +public protocol TransportWrapper: Transport { + /// The transport this one forwards to. + nonisolated var wrapped: any Transport { get } +} + +extension TransportWrapper { + /// The logger of ``wrapped``. + public nonisolated var logger: Logger { wrapped.logger } + + /// Forwards to ``wrapped``. + public func connect() async throws { + try await wrapped.connect() + } + + /// Forwards to ``wrapped``. + public func disconnect() async { + await wrapped.disconnect() + } + + /// Forwards to ``wrapped``. + public func send(_ data: Data, options: TransportSendOptions) async throws { + try await wrapped.send(data, options: options) + } + + /// Forwards to ``wrapped``. + public func receive() async -> AsyncThrowingStream { + await wrapped.receive() + } + + /// Forwards to ``wrapped``. + public func didNegotiate(protocolVersion version: String) async { + await wrapped.didNegotiate(protocolVersion: version) + } + + /// Forwards to ``wrapped``. + @discardableResult + public func abandonRequest(_ id: ID) async -> Bool { + await wrapped.abandonRequest(id) + } + + /// Forwards to ``wrapped``. + public func authorizationEnd(of id: ID) async -> ContinuousClock.Instant? { + await wrapped.authorizationEnd(of: id) + } + + /// Forwards to ``wrapped``. + public func prepare(servingProtocolVersions versions: [String]) async { + await wrapped.prepare(servingProtocolVersions: versions) + } + + /// Whether ``wrapped`` is sessionless. + public nonisolated var isSessionless: Bool { wrapped.isSessionless } + + /// Forwards to ``wrapped``. + public func httpRequest(for id: ID) async -> HTTPRequest? { + await wrapped.httpRequest(for: id) + } +} diff --git a/Sources/MCP/Base/Transports/HTTPClientTransport.swift b/Sources/MCP/Base/Transports/HTTPClientTransport.swift index 656ed95c..b418e24b 100644 --- a/Sources/MCP/Base/Transports/HTTPClientTransport.swift +++ b/Sources/MCP/Base/Transports/HTTPClientTransport.swift @@ -26,13 +26,38 @@ import Logging /// /// ``disconnect()`` ends the connection at once. A transport dropped without /// it is still released, and then stops its GET stream and invalidates its -/// URL sessions; a ``send(_:)`` still running keeps the transport alive until -/// it finishes or its task is cancelled. +/// URL sessions; a ``send(_:options:)`` still running keeps the transport +/// alive until it finishes or its task is cancelled. /// /// It behaves the same on Apple platforms and Linux. Response bodies are read /// as they arrive: with `URLSession.bytes(for:)` on Apple platforms, and with a /// data delegate on swift-corelibs-foundation, which has no `bytes(for:)`. /// +/// The transport follows HTTP redirects of its POST and GET requests, the +/// same way on every platform, to `http` and `https` URLs. It doesn't follow +/// one to another scheme, to a loopback host from a remote host, from `https` +/// to `http`, or from a loopback host to `http` on a host that is not a +/// loopback host: the 3xx is then the response, and the request fails with +/// its ``HTTPStatusError``. A redirect to the same origin (scheme, host and +/// port) keeps the request's `Proxy-Authorization`, `Cookie` and +/// `Mcp-Session-Id`. With an authorizer, it gets the authorizer's headers for +/// its new URL, with a DPoP proof made for that URL (RFC 9449 §4.2), and no +/// `Authorization` when the authorizer has none for it, so a 401 there is a +/// challenge for the endpoint; without one, it keeps its `Authorization`. A +/// redirect to another origin carries none of these headers, and neither does +/// any later redirect of the request, one back to the first origin included; +/// no redirect carries the first request's `DPoP` (RFC 9110 §15.4). This +/// holds for those headers in the configuration's `httpAdditionalHeaders` +/// too. Cookies from the configuration's cookie storage are added by +/// URLSession for each URL. Other headers are kept. A 307 or 308 keeps the +/// method and body; a 303, and a 301 or 302 of a POST, make the request a +/// `GET` without a body. When the authorizer throws for a redirect, the +/// request fails with its error. With an authorizer, a 401 or 403 reached +/// through another origin isn't passed to it: the request fails with +/// ``OAuthAuthorizationError/protectedResourceMismatch(expected:actual:)``, +/// which names the URL the server redirected to. Configure that URL as the +/// endpoint. +/// /// An SSE line, or the data of one event, longer than 16 MiB ends its /// stream with `internalError`. On a POST's stream the request fails and the /// stream is not resumed; the GET stream reconnects after its backoff, @@ -49,9 +74,7 @@ import Logging /// let transport = HTTPClientTransport( /// endpoint: URL(string: "https://api.example.com/mcp")!, /// requestModifier: { request in -/// var modifiedRequest = request -/// modifiedRequest.addValue("Bearer your-token-here", forHTTPHeaderField: "Authorization") -/// return modifiedRequest +/// request.setValue("Bearer your-token-here", forHTTPHeaderField: "Authorization") /// } /// ) /// @@ -66,6 +89,11 @@ public actor HTTPClientTransport: Transport { /// The server endpoint URL to connect to public let endpoint: URL private let session: URLSession + /// The `Authorization`, `Proxy-Authorization`, `Cookie`, `Mcp-Session-Id` + /// and `DPoP` headers of the configuration's `httpAdditionalHeaders`, which + /// the transport sets on each request instead of the session, so that a + /// redirect keeps them on the same origin only. + private let configurationCredentials: [String: String] /// The session ID assigned by the server, used for maintaining state across requests public private(set) var sessionID: String? @@ -84,8 +112,8 @@ public actor HTTPClientTransport: Transport { /// Maximum time to wait for a session ID before proceeding with SSE connection public let sseInitializationTimeout: TimeInterval - /// Closure to modify requests before they are sent - private let requestModifier: (URLRequest) -> URLRequest + /// Changes each request before it is sent. + private let requestModifier: @Sendable (inout URLRequest) async throws -> Void /// Optional OAuth 2.1 authorizer. private let authorizer: (any HTTPClientAuthorizer)? @@ -108,14 +136,14 @@ public actor HTTPClientTransport: Transport { /// The POSTs of requests in flight, by JSON-RPC ID. Cancelled by /// ``disconnect()`` and by an outgoing `notifications/cancelled`. - private var inFlightPosts: [String: Task] = [:] + private var inFlightPosts: [ID: Task] = [:] /// The other POSTs in flight: notifications, and responses to server /// requests. Cancelled by ``disconnect()``. private var otherPosts: [UUID: Task] = [:] /// The authorizer calls of requests in flight, by JSON-RPC ID. See /// ``authorizationEnd(of:)``. - private var authorizations: [String: Authorization] = [:] + private var authorizations: [ID: Authorization] = [:] private struct Authorization { /// Authorizer calls in progress for the request's POST. @@ -132,9 +160,9 @@ public actor HTTPClientTransport: Transport { } } - /// Requests passed to ``cancelRequest(_:)`` before their POST started, + /// Requests passed to `cancelRequest(_:)` before their POST started, /// oldest first, at most ``maxCancelledBeforeSend``. - private var cancelledBeforeSend: [String] = [] + private var cancelledBeforeSend: [ID] = [] static let maxCancelledBeforeSend = 64 /// The bounds applied to a server's SSE `retry:` value, in milliseconds. @@ -155,7 +183,9 @@ public actor HTTPClientTransport: Transport { static func reconnectDelay(retryInterval: Int, consecutiveFailures: Int) -> Int { guard consecutiveFailures > 1 else { return retryInterval } let doublings = min(consecutiveFailures - 1, 16) - return min(retryInterval * (1 << doublings), maxReconnectDelay) + // Saturates: 60 s doubled 16 times is past a 32-bit `Int`. + let (delay, overflow) = retryInterval.multipliedReportingOverflow(by: 1 << doublings) + return overflow ? maxReconnectDelay : min(delay, maxReconnectDelay) } /// The per-host connection limit of ``defaultConfiguration``. @@ -188,12 +218,35 @@ public actor HTTPClientTransport: Transport { /// ``defaultConfiguration``. A custom configuration needs an /// `httpMaximumConnectionsPerHost` above the number of concurrent requests plus one; /// the transport logs a warning when it is at the platform default of 6 or lower. + /// The transport sets an `Authorization`, `Proxy-Authorization`, `Cookie`, + /// `Mcp-Session-Id` or `DPoP` of its `httpAdditionalHeaders` on each of its + /// requests that doesn't set that header itself, so a redirect treats them + /// as the request's own; `configuration` is not changed. The requests of + /// the authorizer, such as token requests, don't get them. /// - streaming: Whether to enable SSE streaming mode (default: true) /// - sseInitializationTimeout: Maximum time to wait for session ID before proceeding with SSE (default: 10 seconds) /// - protocolVersion: The MCP protocol version to use (default: "2025-11-25") /// - authorizer: Optional ``HTTPClientAuthorizer`` for automatic token acquisition and retries. - /// - requestModifier: Optional closure to customize requests before they are sent (default: no modification). - /// The `authorizer`'s headers are set after it, for the final URL and method. + /// With one, the transport requires `endpoint` to be `https`, or `http` on a + /// loopback host, without a fragment, and fails each request to another one with + /// ``MCPError/transportError(_:)`` wrapping + /// ``OAuthAuthorizationError/insecureOAuthEndpoint(context:url:)`` (or + /// ``OAuthAuthorizationError/invalidResourceURI(_:)`` for a fragment) before it + /// calls the authorizer. It checks the URL of each request again after the + /// `requestModifier`, before it asks the authorizer for headers. It asks again + /// for each redirect to the same origin, during the request: unlike the first + /// call, that time counts against ``Client/Configuration/discoveryTimeout``. + /// - requestModifier: Changes each request before it is sent, for example to add a + /// header. It runs after the transport's headers and before the authorizer's, + /// which it can't replace; the transport sets `Mcp-Session-Id` after it. An error + /// fails the request with ``MCPError/transportError(_:)``. Like the authorizer's + /// time, its time doesn't count against ``Client/Configuration/discoveryTimeout``, + /// so it can wait for the user, for example to unlock a Keychain item. A redirect + /// keeps the headers it adds, except `DPoP`, and `Authorization`, + /// `Proxy-Authorization`, `Cookie` and `Mcp-Session-Id` once it has gone to + /// another origin. With an authorizer, a redirect to the same origin has the + /// authorizer's `Authorization` for its URL, or none, instead of one the + /// modifier set. /// - logger: Optional logger instance for transport events public init( endpoint: URL, @@ -202,7 +255,7 @@ public actor HTTPClientTransport: Transport { sseInitializationTimeout: TimeInterval = 10, protocolVersion: String = Version.latestHandshake, authorizer: (any HTTPClientAuthorizer)? = nil, - requestModifier: @escaping (URLRequest) -> URLRequest = { $0 }, + requestModifier: @escaping @Sendable (inout URLRequest) async throws -> Void = { _ in }, logger: Logger? = nil ) { if configuration.httpMaximumConnectionsPerHost <= Self.platformDefaultMaximumConnectionsPerHost { @@ -210,9 +263,11 @@ public actor HTTPClientTransport: Transport { "URLSessionConfiguration allows \(configuration.httpMaximumConnectionsPerHost) connections per host; concurrent requests that wait for a server-to-client reply can deadlock. Raise httpMaximumConnectionsPerHost, or use HTTPClientTransport.defaultConfiguration." ) } + let (configuration, credentials) = HTTPRedirect.separatingCredentials(of: configuration) self.init( endpoint: endpoint, session: URLSession(configuration: configuration), + configurationCredentials: credentials, streaming: streaming, sseInitializationTimeout: sseInitializationTimeout, protocolVersion: protocolVersion, @@ -222,19 +277,33 @@ public actor HTTPClientTransport: Transport { ) } + /// A transport on `session`. Its configuration's `httpAdditionalHeaders` + /// are not separated: URLSession adds them to every request and redirect. + /// The public initializer takes the credentials out first and passes them + /// as `configurationCredentials`. internal init( endpoint: URL, session: URLSession, + configurationCredentials: [String: String] = [:], streaming: Bool = false, sseInitializationTimeout: TimeInterval = 10, protocolVersion: String = Version.latestHandshake, authorizer: (any HTTPClientAuthorizer)? = nil, - requestModifier: @escaping (URLRequest) -> URLRequest = { $0 }, + requestModifier: @escaping @Sendable (inout URLRequest) async throws -> Void = { _ in }, logger: Logger? = nil ) { + let logger = + logger + ?? Logger( + label: "mcp.transport.http.client", + factory: { _ in SwiftLogNoOpLogHandler() } + ) self.endpoint = endpoint self.session = session - self.streamingSession = StreamingSession(configuration: session.configuration) + self.configurationCredentials = configurationCredentials + self.streamingSession = StreamingSession( + configuration: session.configuration, + redirects: HTTPClientRedirects(authorize: Self.redirectAuthorization(authorizer), logger: logger)) self.streaming = streaming self.sseInitializationTimeout = sseInitializationTimeout self.protocolVersion = protocolVersion @@ -246,16 +315,11 @@ public actor HTTPClientTransport: Transport { self.messageStream = AsyncThrowingStream { continuation = $0 } self.messageContinuation = continuation - self.logger = - logger - ?? Logger( - label: "mcp.transport.http.client", - factory: { _ in SwiftLogNoOpLogHandler() } - ) + self.logger = logger } /// The wait of the GET stream for a session ID. It ends once: on a - /// session ID, the timeout, ``disconnect()``, ``useStatelessProtocol(_:)``, + /// session ID, the timeout, ``disconnect()``, `useStatelessProtocol(_:)`, /// the cancellation of the waiting task, or the release of the transport. /// The transport owns it; the waiting task holds it, not the transport. private final class SessionIDSignal: @unchecked Sendable { @@ -326,10 +390,13 @@ public actor HTTPClientTransport: Transport { /// connection. A transport dropped without it is still released, and its /// GET stream stops then. /// - /// - Throws: `MCPError.internalError` after ``disconnect()``: the - /// transport serves one connection; use a new one to reconnect. + /// - Throws: `MCPError.internalError` when the transport is already + /// connected, or after ``disconnect()``: the transport serves one + /// connection; use a new one to reconnect. public func connect() async throws { - guard !isConnected else { return } + guard !isConnected else { + throw MCPError.internalError("Transport already connected") + } // disconnect() finished the stream receive() returns. guard !streamingSession.lifetime.isInvalidated else { throw MCPError.internalError("Transport disconnected; create a new transport to reconnect") @@ -337,21 +404,30 @@ public actor HTTPClientTransport: Transport { isConnected = true sessionIDSignal = SessionIDSignal() - - if streaming { - let reference = WeakReference(self) - let signal = sessionIDSignal - let timeout = sseInitializationTimeout - let logger = logger - streamingTask = Task { - await HTTPClientTransport.listenForServerEvents( - reference, sessionIDSignal: signal, timeout: timeout, logger: logger) - } - } + startStreamingIfNeeded() logger.debug("HTTP transport connected") } + /// Whether the transport's current revision uses sessions and a standalone GET stream. + private var usesSessions: Bool { + !isStateless && (protocolVersion.map { Version.profile(for: $0).usesSessions } ?? true) + } + + /// Starts the standalone GET stream task when `streaming` is enabled and the + /// current protocol revision uses sessions. + private func startStreamingIfNeeded() { + guard streaming, isConnected, usesSessions, streamingTask == nil else { return } + let reference = WeakReference(self) + let signal = sessionIDSignal + let timeout = sseInitializationTimeout + let logger = logger + streamingTask = Task { + await HTTPClientTransport.listenForServerEvents( + reference, sessionIDSignal: signal, timeout: timeout, logger: logger) + } + } + deinit { // A send() in flight holds the transport, so only the GET stream // task can be running; a GET it is creating keeps the sessions @@ -369,9 +445,10 @@ public actor HTTPClientTransport: Transport { /// This ends the connection at once: it stops the GET stream, cancels /// the POSTs in flight, invalidates the URL sessions and finishes the /// stream ``receive()`` returns. The transport cannot connect again; use - /// a new one to reconnect. + /// a new one to reconnect. Calling it again, or before ``connect()``, + /// leaves the transport closed. public func disconnect() async { - guard isConnected else { return } + guard !streamingSession.lifetime.isInvalidated else { return } isConnected = false streamingTask?.cancel() @@ -396,14 +473,26 @@ public actor HTTPClientTransport: Transport { logger.debug("HTTP clienttransport disconnected") } - /// Updates the protocol version used for `MCP-Protocol-Version` headers on subsequent requests. - public func updateNegotiatedProtocolVersion(_ version: String) { - self.protocolVersion = version + /// Sends `version` in `MCP-Protocol-Version` from now on. + /// + /// At a revision without sessions (2026-07-28) the transport also drops + /// its session ID and its GET stream, and stops resuming response + /// streams. ``Client`` calls it after `initialize` and after + /// `server/discover`. + /// + /// - Parameter version: The negotiated protocol version. + public func didNegotiate(protocolVersion version: String) async { + if Version.profile(for: version).usesSessions { + protocolVersion = version + startStreamingIfNeeded() + } else { + useStatelessProtocol(version) + } } /// Switches the transport to a stateless revision (2026-07-28 and later): /// no session ID and no standalone GET stream. - public func useStatelessProtocol(_ version: String) { + func useStatelessProtocol(_ version: String) { protocolVersion = version isStateless = true sessionID = nil @@ -415,28 +504,36 @@ public actor HTTPClientTransport: Transport { /// Sends data through an HTTP POST request. /// /// A request's POST, including the resumption of its response stream, - /// runs until its response arrives, ``disconnect()`` is called, or the - /// client sends `notifications/cancelled` for it. Any other POST, such as - /// a notification's, ends when its response arrives or at ``disconnect()``. - public func send(_ data: Data) async throws { - try await send(data, additionalHeaders: [:]) - } - - /// Sends data through an HTTP POST request with extra headers, such as - /// the `Mcp-Param-*` headers of a `tools/call` (SEP-2243). + /// runs until its response arrives, ``disconnect()`` is called, the + /// client sends `notifications/cancelled` for it, or + /// ``abandonRequest(_:)`` aborts it. Any other POST, such as a + /// notification's, ends when its response arrives or at ``disconnect()``. /// - /// A header named here replaces one the transport sets before it, such - /// as `Mcp-Method`. Applied after it are `Mcp-Session-Id`, which the - /// transport adds on a connection with a session, the authorizer's - /// headers and the `requestModifier`. - public func send(_ data: Data, additionalHeaders: [String: String]) async throws { + /// `options.headers` are sent on the POST, such as the `Mcp-Param-*` + /// headers of a `tools/call` (SEP-2243). A header named there replaces + /// one the transport sets before it, such as `Mcp-Method`. Applied after + /// it are the `requestModifier`, the authorizer's headers, and last + /// `Mcp-Session-Id`, which the transport sets on a connection with a + /// session. `options.relatedRequestID` is ignored: a client's messages + /// need no stream of their own. + /// + /// - Parameters: + /// - data: The encoded message. + /// - options: The headers to send with the message. + /// - Throws: ``MCPError/connectionClosed`` after ``disconnect()``; + /// `MCPError.internalError` before ``connect()``; `CancellationError` + /// for a request abandoned before its POST started; otherwise the error + /// of the POST, such as ``MCPError/transportError(_:)`` with an + /// ``HTTPStatusError``. + public func send(_ data: Data, options: TransportSendOptions) async throws { + let headers = options.headers let message = OutgoingMessage(data) if let id = message.requestID { if let cancelled = cancelledBeforeSend.firstIndex(of: id) { cancelledBeforeSend.remove(at: cancelled) throw CancellationError() } - let task = Task { try await self.post(message, additionalHeaders: additionalHeaders) } + let task = Task { try await self.post(message, headers: headers) } inFlightPosts[id] = task defer { inFlightPosts[id] = nil @@ -457,7 +554,7 @@ public actor HTTPClientTransport: Transport { } // In a task of its own, so that disconnect() can end it. let key = UUID() - let task = Task { try await self.post(message, additionalHeaders: additionalHeaders) } + let task = Task { try await self.post(message, headers: headers) } otherPosts[key] = task defer { otherPosts[key] = nil } try await withTaskCancellationHandler { @@ -473,52 +570,72 @@ public actor HTTPClientTransport: Transport { /// Aborts the POST that carries request `id`, closing its response stream. /// - /// At protocol 2026-07-28 this is how a request is cancelled: the server - /// sees the client disconnect. When the request's POST has not started - /// yet, the next ``send(_:)`` of that request throws `CancellationError` + /// When the request's POST has not started yet, the next + /// ``send(_:options:)`` of that request throws `CancellationError` /// instead of posting it; the transport remembers the most recent such /// ids only. - public func cancelRequest(_ id: ID) { - let key = id.description - if let post = inFlightPosts[key] { + func cancelRequest(_ id: ID) { + if let post = inFlightPosts[id] { post.cancel() return } - guard !cancelledBeforeSend.contains(key) else { return } - cancelledBeforeSend.append(key) + guard !cancelledBeforeSend.contains(id) else { return } + cancelledBeforeSend.append(id) if cancelledBeforeSend.count > Self.maxCancelledBeforeSend { cancelledBeforeSend.removeFirst() } } - /// When the POST of request `id` last finished waiting on the authorizer, - /// or `nil` if it has not. While the POST waits on the authorizer, for - /// example for a user who signs in, this waits for it to finish. + /// Aborts the POST that carries request `id`, closing its response stream. + /// + /// When the request's POST has not started yet, the next + /// ``send(_:options:)`` of that request throws `CancellationError` + /// instead of posting it; the transport remembers the most recent such + /// ids only. + /// + /// - Parameter id: The JSON-RPC ID of the request. + /// - Returns: `true` on a connection at a revision without sessions + /// (2026-07-28), where the server learns of the cancellation when the + /// client closes the request's POST. At a handshake revision a closed + /// POST cancels nothing, so it returns `false`, and ``Client`` sends + /// `notifications/cancelled`. + /// - SeeAlso: https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http#cancellation + @discardableResult + public func abandonRequest(_ id: ID) async -> Bool { + cancelRequest(id) + return !usesSessions + } + + /// Returns when the POST of request `id` last finished waiting on the + /// authorizer, waiting while it does, for example for a user who signs in. /// /// ``Client`` does not count that time against /// ``Client/Configuration/discoveryTimeout``. - func authorizationEnd(of id: ID) async -> ContinuousClock.Instant? { - let key = id.description - if authorizations[key]?.active ?? 0 > 0 { + /// + /// - Parameter id: The JSON-RPC ID of the request. + /// - Returns: When the last authorizer call for the request's POST ended, + /// or `nil` when there was none, or the POST has finished. + public func authorizationEnd(of id: ID) async -> ContinuousClock.Instant? { + if authorizations[id]?.active ?? 0 > 0 { let waiter = UUID() await withTaskCancellationHandler { await withCheckedContinuation { (continuation: CheckedContinuation) in - guard !Task.isCancelled, authorizations[key]?.active ?? 0 > 0 else { + guard !Task.isCancelled, authorizations[id]?.active ?? 0 > 0 else { continuation.resume() return } - authorizations[key]?.waiters.append((waiter, continuation)) + authorizations[id]?.waiters.append((waiter, continuation)) } } onCancel: { - Task { await self.stopWaitingForAuthorization(waiter, of: key) } + Task { await self.stopWaitingForAuthorization(waiter, of: id) } } } - return authorizations[key]?.lastEnded + return authorizations[id]?.lastEnded } - private func stopWaitingForAuthorization(_ waiter: UUID, of key: String) { - guard let index = authorizations[key]?.waiters.firstIndex(where: { $0.id == waiter }) else { return } - authorizations[key]?.waiters.remove(at: index).continuation.resume() + private func stopWaitingForAuthorization(_ waiter: UUID, of id: ID) { + guard let index = authorizations[id]?.waiters.firstIndex(where: { $0.id == waiter }) else { return } + authorizations[id]?.waiters.remove(at: index).continuation.resume() } /// The callers of ``authorizationEnd(of:)`` waiting, for every request. @@ -544,25 +661,30 @@ public actor HTTPClientTransport: Transport { return try await body() } - private func post(_ message: OutgoingMessage, additionalHeaders: [String: String]) async throws { + /// The error of a send while the transport is not connected: + /// ``MCPError/connectionClosed`` after ``disconnect()``, `internalError` + /// before ``connect()``. + private var notConnectedError: MCPError { + streamingSession.lifetime.isInvalidated + ? .connectionClosed : .internalError("Transport not connected") + } + + private func post(_ message: OutgoingMessage, headers: [String: String]) async throws { guard isConnected else { - throw MCPError.internalError("Transport not connected") + throw notConnectedError } if let authorizer { + try Self.requireAuthorizableEndpoint(endpoint) do { - try authorizer.validateEndpointSecurity(for: endpoint) + try await authorizing(message) { + try await authorizer.prepare(for: endpoint, session: session) + } } catch { throw Self.authorizerError(error) } } - if let authorizer { - try? await authorizing(message) { - try await authorizer.prepareAuthorization(for: endpoint, session: session) - } - } - var attempts = 0 var retriedNonce = false let operationKey = message.operationKey @@ -591,51 +713,84 @@ public actor HTTPClientTransport: Transport { for (name, value) in standardHeaders { request.setValue(value, forHTTPHeaderField: name) } - for (name, value) in additionalHeaders { + for (name, value) in headers { request.setValue(value, forHTTPHeaderField: name) } - if let sessionID = sessionID, !isStateless { - request.addValue(sessionID, forHTTPHeaderField: HTTPHeaderName.sessionID) + // The modifier sees the session ID current now ... + setSessionHeader(on: &request) + // Its time, such as a Keychain read that waits for the user, is + // authorization time, as the authorizer's is. + do { + try await authorizing(message) { try await requestModifier(&request) } + } catch { + throw Self.authorizerError(error) } + if authorizer != nil { + // The token goes where the request goes: the modifier may + // have pointed it at another URL. + try Self.requireAuthorizableEndpoint(request.url ?? endpoint) + } + try await authorizing(message) { try await applyAuthorization(to: &request) } - request = requestModifier(request) - try applyAuthorization(to: &request) - - // disconnect() may have run while the authorizer was awaited. + // ... but the actor may have run other requests while this one + // waited: disconnect() may have run, and a response or a 404 may + // have replaced or dropped the session ID, or the connection may + // have switched to a stateless revision. Read the state again now. guard isConnected else { - throw MCPError.internalError("Transport not connected") + throw notConnectedError } - // What the server answers about: another request may drop or - // replace the session ID while this one waits. + setSessionHeader(on: &request) + HTTPRedirect.addingCredentials(configurationCredentials, to: &request) + // What the server answers about. let sentSessionID = request.value(forHTTPHeaderField: HTTPHeaderName.sessionID) + // The URL that answered, after the redirects, and what they did + // with the credentials. + var respondedURL: URL? + var redirectChain = HTTPRedirectChain() do { let (body, response) = try await session.responseBody(for: request, streaming: streamingSession) - noteResponse(response, to: request) + respondedURL = response.url + redirectChain = body.redirectChain + if let failure = redirectChain.failure { + // The authorizer's error stopped a redirect; the 3xx is not the answer. + body.cancel() + throw Self.authorizerError(failure) + } + await noteResponse(response, to: request) + let effectiveSessionID = redirectChain.sentSessionID ?? sentSessionID try await processResponse( - response: response, body: body, request: message, sentSessionID: sentSessionID) + response: response, body: body, request: message, sentSessionID: effectiveSessionID, + acceptSessionID: redirectChain.leftOrigin == nil) return } catch let authError as HTTPAuthenticationChallengeError { guard let authorizer else { throw mapAuthenticationChallengeError(authError) } + if let respondedURL, let error = Self.redirectedChallengeError( + sentTo: request.url ?? endpoint, answeredBy: respondedURL, chain: redirectChain) + { + throw error + } + let challenge = HTTPAuthorizationChallenge( + statusCode: authError.statusCode, headers: authError.headers, endpoint: endpoint, + operationKey: operationKey, + sentAuthorization: redirectChain.sentAuthorization + ?? request.value(forHTTPHeaderField: HTTPHeaderName.authorization)) let handled: HTTPChallengeResult do { handled = try await authorizing(message) { - try await authorizer.handleChallenge( - statusCode: authError.statusCode, - headers: authError.headers, - endpoint: endpoint, - operationKey: operationKey, - sentAuthorization: request.value(forHTTPHeaderField: HTTPHeaderName.authorization), - session: session - ) + try await authorizer.handleChallenge(challenge, session: session) } } catch { throw Self.authorizerError(error) } + guard handled.shouldRetry else { + throw mapAuthenticationChallengeError(authError) + } + // RFC 9449 §9: the authorizer says whether the retry only // answers a DPoP nonce challenge, retried once per request. if handled.isDPoPNonceRetry { @@ -647,7 +802,7 @@ public actor HTTPClientTransport: Transport { attempts += 1 } - if handled.retry, attempts < authorizer.maxAuthorizationAttempts { + if attempts < authorizer.maxAuthorizationAttempts { continue } @@ -657,7 +812,8 @@ public actor HTTPClientTransport: Transport { } private func processResponse( - response: URLResponse, body: ResponseBody, request message: OutgoingMessage, sentSessionID: String? + response: URLResponse, body: ResponseBody, request message: OutgoingMessage, sentSessionID: String?, + acceptSessionID: Bool ) async throws { guard let httpResponse = response as? HTTPURLResponse else { throw MCPError.internalError("Invalid HTTP response") @@ -666,12 +822,18 @@ public actor HTTPClientTransport: Transport { let contentType = httpResponse.value(forHTTPHeaderField: HTTPHeaderName.contentType) ?? "" if let newSessionID = httpResponse.value(forHTTPHeaderField: HTTPHeaderName.sessionID) { - let wasSessionIDNil = (self.sessionID == nil) - self.sessionID = newSessionID - if wasSessionIDNil { - triggerInitialSessionIDSignal() + if acceptSessionID, acceptsSessionID(inReplyTo: message) { + let wasSessionIDNil = (self.sessionID == nil) + self.sessionID = newSessionID + if wasSessionIDNil { + triggerInitialSessionIDSignal() + } + logger.debug("Session ID received", metadata: ["sessionID": "\(newSessionID)"]) + } else if !acceptSessionID { + logger.warning("Ignoring Mcp-Session-Id on a response redirected across origins") + } else { + logger.warning("Ignoring Mcp-Session-Id on a reply at a revision without sessions") } - logger.debug("Session ID received", metadata: ["sessionID": "\(newSessionID)"]) } if Self.mayCarryPeerError(httpResponse.statusCode), contentType.contains(ContentType.json) { @@ -728,6 +890,21 @@ public actor HTTPClientTransport: Transport { } } + /// Whether a reply to `message` may set the session ID. Revisions without + /// sessions (2026-07-28) have no `Mcp-Session-Id`, so neither a + /// connection switched to one nor a request whose effective revision has + /// no sessions takes it. The reply to `server/discover` arrives before + /// ``Client`` calls ``didNegotiate(protocolVersion:)``: a session ID on it + /// would open the GET stream first. `initialize` without a stateless + /// `_meta` version is always a handshake request, so fallback from a + /// transport configured with `2026-07-28` still records its session ID. + /// - SeeAlso: https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http#backward-compatibility + private func acceptsSessionID(inReplyTo message: OutgoingMessage) -> Bool { + guard !isStateless else { return false } + if message.method == Initialize.name, message.protocolVersion == nil { return true } + return (message.protocolVersion ?? protocolVersion).map { Version.profile(for: $0).usesSessions } ?? true + } + /// Throws the error of a non-2xx reply to a POST that carried /// `sentSessionID` as its `Mcp-Session-Id`. private func processHTTPResponse(_ response: HTTPURLResponse, sentSessionID: String?) throws { @@ -765,11 +942,11 @@ public actor HTTPClientTransport: Transport { } /// Sets the authorizer's headers for the final URL and method of `request`. - private func applyAuthorization(to request: inout URLRequest) throws { + private func applyAuthorization(to request: inout URLRequest) async throws { guard let authorizer else { return } let headers: [String: String] do { - headers = try authorizer.authorizationHeaders( + headers = try await authorizer.authorizationHeaders( for: request.url ?? endpoint, method: request.httpMethod ?? "POST") } catch { throw Self.authorizerError(error) @@ -779,20 +956,79 @@ public actor HTTPClientTransport: Transport { } } - /// Shows the authorizer the headers of a response to `request`. - private func noteResponse(_ response: URLResponse, to request: URLRequest) { + /// Sets `Mcp-Session-Id` to the current session ID, or removes it on a + /// connection without one. + private func setSessionHeader(on request: inout URLRequest) { + request.setValue(isStateless ? nil : sessionID, forHTTPHeaderField: HTTPHeaderName.sessionID) + } + + /// Shows the authorizer the headers of a response to `request`, for the + /// URL that answered (a DPoP nonce belongs to its origin). + private func noteResponse(_ response: URLResponse, to request: URLRequest) async { guard let authorizer, let response = response as? HTTPURLResponse else { return } - authorizer.didReceiveResponse( - headers: responseHeaders(from: response), for: request.url ?? endpoint) + await authorizer.didReceiveResponse( + headers: responseHeaders(from: response), for: response.url ?? request.url ?? endpoint) } - /// An error of the authorizer, as the transport throws it: wrapped in - /// ``MCPError/transportError(_:)``, except `CancellationError`, which is - /// thrown as is. + /// The error of a 401 or 403 from `answeredBy`, after redirects of the + /// request to `sentTo` that `chain` describes, when the request reached + /// it without credentials: on another origin, or after a hop through + /// one. `nil` when every hop stayed on the origin. The authorizer is not + /// asked: a token for the endpoint wouldn't reach that URL either. + static func redirectedChallengeError( + sentTo: URL, answeredBy: URL, chain: HTTPRedirectChain + ) -> MCPError? { + let leftOrigin = chain.leftOrigin + ?? (DefaultOAuthMetadataDiscovery.haveSameOrigin(sentTo, answeredBy) ? nil : answeredBy) + guard let leftOrigin else { return nil } + let target = OAuthURLValidator.redacted(leftOrigin) + let detail = + DefaultOAuthMetadataDiscovery.haveSameOrigin(leftOrigin, answeredBy) + ? "The server redirected the request to \(target), on another origin, which gets no credentials; configure \(target) as the endpoint" + : "The server redirected the request to \(target), on another origin, and from there to \(OAuthURLValidator.redacted(answeredBy)), which it reached without credentials; configure the URL that answers without a redirect as the endpoint" + return .transportError( + OAuthAuthorizationError( + code: .protectedResourceMismatch, detail: detail, + expected: [OAuthURLValidator.redacted(sentTo)], actual: [target])) + } + + /// An error of the authorizer or the `requestModifier`, as the transport + /// throws it: wrapped in ``MCPError/transportError(_:)``, except + /// `CancellationError`, which is thrown as is. private static func authorizerError(_ error: Swift.Error) -> Swift.Error { error is CancellationError ? error : MCPError.transportError(error) } + /// The headers of a redirect to the same origin: those a request to its + /// target gets, after the same check of its URL. + private static func redirectAuthorization( + _ authorizer: (any HTTPClientAuthorizer)? + ) -> HTTPClientRedirects.Authorize? { + guard let authorizer else { return nil } + return { @Sendable (url: URL, method: String) async throws -> [String: String] in + try OAuthURLValidator().validateHTTPSOrLoopback(url, context: "MCP endpoint") + return try await authorizer.authorizationHeaders(for: url, method: method) + } + } + + /// Requires a URL whose requests an authorizer authorizes to be `https`, + /// or `http` on a loopback host, without a fragment. The transport checks + /// the endpoint before it calls the authorizer, and the final URL of each + /// request after the `requestModifier`, before it asks for the token's + /// headers, on the POST and the GET paths, so that neither an authorizer + /// nor a modifier can send a token in the clear. + /// + /// - Throws: ``MCPError/transportError(_:)`` with + /// ``OAuthAuthorizationError/insecureOAuthEndpoint(context:url:)``, or with + /// ``OAuthAuthorizationError/invalidResourceURI(_:)`` for a fragment. + private static func requireAuthorizableEndpoint(_ endpoint: URL) throws { + do { + try OAuthURLValidator().validateHTTPSOrLoopback(endpoint, context: "MCP endpoint") + } catch { + throw authorizerError(error) + } + } + private func mapAuthenticationChallengeError(_ error: HTTPAuthenticationChallengeError) -> MCPError { .transportError(HTTPStatusError(statusCode: error.statusCode, headers: error.headers)) } @@ -869,17 +1105,11 @@ public actor HTTPClientTransport: Transport { streamingTask = nil } - /// Whether `error` reports a 400, 404 or 405 reply without a JSON-RPC - /// answer for the request: how a server that serves only the handshake - /// refuses a request without a session. - package static func isSessionlessRefusal(_ error: Swift.Error) -> Bool { - guard case .transportError(let underlying) = error as? MCPError, - let status = underlying as? HTTPStatusError, !status.isSessionExpired - else { return false } - return [400, 404, 405].contains(status.statusCode) - } - - /// Receives data in an async sequence + /// Returns the messages the server sends: responses and the messages of + /// the POST and GET streams. + /// + /// Every call returns the same stream; iterate it from one task only. It + /// finishes at ``disconnect()``. public func receive() -> AsyncThrowingStream { return messageStream } @@ -887,9 +1117,10 @@ public actor HTTPClientTransport: Transport { // MARK: - SSE /// What the GET stream loop reads from the transport before each step: - /// `nil` once the transport is disconnected. + /// `nil` once the transport is disconnected or serves a revision without + /// sessions. private func listenState() -> (hasSessionID: Bool, retryInterval: Int)? { - isConnected ? (sessionID != nil, retryInterval) : nil + isConnected && usesSessions ? (sessionID != nil, retryInterval) : nil } /// The standalone GET stream loop. It holds `reference`'s transport only @@ -1025,11 +1256,12 @@ public actor HTTPClientTransport: Transport { } /// Opens the standalone GET stream: its body once the server accepted - /// it, `nil` when the transport is not connected or was released. It - /// holds `reference`'s transport only while it reads or records state, - /// not while it waits for the authorizer or the response headers. + /// it, `nil` when the transport is not connected, serves a revision + /// without sessions, or was released. It holds `reference`'s transport + /// only while it reads or records state, not while it waits for the + /// authorizer or the response headers. private static func openStandaloneStream(_ reference: WeakReference, logger: Logger) async throws -> ResponseBody? { - guard let resumeFrom = try await reference.transport?.standaloneStreamStart() else { + guard let resumeFrom = await reference.transport?.standaloneStreamStart() else { logger.debug("⚠️ Skipping connectToEventStream - transport not connected") return nil } @@ -1045,18 +1277,10 @@ public actor HTTPClientTransport: Transport { return reply.stream } - /// Checks the endpoint for the standalone GET stream and reads what its - /// GET resumes from: `nil` when the transport is not connected. - private func standaloneStreamStart() throws -> (lastEventID: String?, protocolVersion: String?)? { - guard isConnected else { return nil } - - if let authorizer { - do { - try authorizer.validateEndpointSecurity(for: endpoint) - } catch { - throw Self.authorizerError(error) - } - } + /// Reads what the standalone GET stream resumes from: `nil` when the + /// transport is not connected or serves a revision without sessions. + private func standaloneStreamStart() -> (lastEventID: String?, protocolVersion: String?)? { + guard isConnected && usesSessions else { return nil } if let lastEventID = lastEventID { logger.info("→ Resuming SSE stream with Last-Event-ID", metadata: ["lastEventID": "\(lastEventID)"]) @@ -1067,8 +1291,14 @@ public actor HTTPClientTransport: Transport { } /// Records the reply to the standalone GET: its session ID, or why the - /// server refused the stream, which it throws. - private func acceptStandaloneStream(_ reply: EventStreamReply) throws { + /// server refused the stream, which it throws. Cancels `reply.stream` and + /// throws `CancellationError` if the transport disconnected or serves a + /// revision without sessions. + func acceptStandaloneStream(_ reply: EventStreamReply) throws { + guard isConnected && usesSessions else { + reply.stream.cancel() + throw CancellationError() + } guard reply.statusCode == 200 else { reply.stream.cancel() if reply.statusCode == 405 { @@ -1090,12 +1320,16 @@ public actor HTTPClientTransport: Transport { } if let newSessionID = reply.sessionID { - let wasSessionIDNil = (self.sessionID == nil) - self.sessionID = newSessionID - if wasSessionIDNil { - triggerInitialSessionIDSignal() + if reply.acceptSessionID { + let wasSessionIDNil = (self.sessionID == nil) + self.sessionID = newSessionID + if wasSessionIDNil { + triggerInitialSessionIDSignal() + } + logger.debug("Session ID received", metadata: ["sessionID": "\(newSessionID)"]) + } else { + logger.warning("Ignoring Mcp-Session-Id on a GET stream redirected across origins") } - logger.debug("Session ID received", metadata: ["sessionID": "\(newSessionID)"]) } } @@ -1133,7 +1367,7 @@ public actor HTTPClientTransport: Transport { } /// The reply to a GET for an SSE stream. - private struct EventStreamReply: Sendable { + struct EventStreamReply: Sendable { let stream: ResponseBody let statusCode: Int let headers: [String: String] @@ -1141,6 +1375,24 @@ public actor HTTPClientTransport: Transport { let sessionID: String? /// The `Mcp-Session-Id` the answered GET carried. let sentSessionID: String? + /// Whether `sessionID` may update the transport's session (false after a cross-origin redirect). + let acceptSessionID: Bool + + init( + stream: ResponseBody, + statusCode: Int, + headers: [String: String], + sessionID: String?, + sentSessionID: String?, + acceptSessionID: Bool = true + ) { + self.stream = stream + self.statusCode = statusCode + self.headers = headers + self.sessionID = sessionID + self.sentSessionID = sentSessionID + self.acceptSessionID = acceptSessionID + } /// The ``HTTPStatusError`` of the reply, as the transport throws it. func statusError(isSessionExpired: Bool = false) -> MCPError { @@ -1151,13 +1403,15 @@ public actor HTTPClientTransport: Transport { /// What a GET for an SSE stream uses of the transport while it waits. private var eventStreamInputs: ( endpoint: URL, session: URLSession, streamingSession: StreamingSession, - authorizer: (any HTTPClientAuthorizer)? + authorizer: (any HTTPClientAuthorizer)?, + requestModifier: @Sendable (inout URLRequest) async throws -> Void ) { - (endpoint, session, streamingSession, authorizer) + (endpoint, session, streamingSession, authorizer, requestModifier) } - /// A GET for an SSE stream with the transport's current headers. - private func eventStreamRequest(lastEventID: String?, protocolVersion: String?) throws -> URLRequest { + /// A GET for an SSE stream with the transport's current headers, before + /// the `requestModifier` and the authorizer's headers. + private func eventStreamBaseRequest(lastEventID: String?, protocolVersion: String?) -> URLRequest { var request = URLRequest(url: endpoint) request.httpMethod = "GET" request.addValue(ContentType.sse, forHTTPHeaderField: HTTPHeaderName.accept) @@ -1165,19 +1419,24 @@ public actor HTTPClientTransport: Transport { if let protocolVersion { request.addValue(protocolVersion, forHTTPHeaderField: HTTPHeaderName.protocolVersion) } - if let sessionID { - request.addValue(sessionID, forHTTPHeaderField: HTTPHeaderName.sessionID) - } + setSessionHeader(on: &request) if let lastEventID { request.addValue(lastEventID, forHTTPHeaderField: HTTPHeaderName.lastEventID) } - request = requestModifier(request) - try applyAuthorization(to: &request) + return request + } - // disconnect() may have run while the authorizer was awaited. + /// `request` once the `requestModifier` and the authorizer are done with + /// it: with the session ID current now. + private func finishEventStreamRequest(_ request: URLRequest) throws -> URLRequest { + // disconnect() may have run, and the session ID may have changed, + // while the modifier and the authorizer were awaited. guard isConnected else { - throw MCPError.internalError("Transport not connected") + throw notConnectedError } + var request = request + setSessionHeader(on: &request) + HTTPRedirect.addingCredentials(configurationCredentials, to: &request) return request } @@ -1193,46 +1452,88 @@ public actor HTTPClientTransport: Transport { ) async throws -> EventStreamReply? { guard let inputs = await reference.transport?.eventStreamInputs else { return nil } if let authorizer = inputs.authorizer { - try? await authorizer.prepareAuthorization(for: inputs.endpoint, session: inputs.session) + try Self.requireAuthorizableEndpoint(inputs.endpoint) + do { + try await authorizer.prepare(for: inputs.endpoint, session: inputs.session) + } catch { + throw Self.authorizerError(error) + } } var attempts = 0 var retriedNonce = false while true { guard - let request = try await reference.transport?.eventStreamRequest( + var request = await reference.transport?.eventStreamBaseRequest( lastEventID: lastEventID, protocolVersion: protocolVersion) else { return nil } + do { + try await inputs.requestModifier(&request) + } catch { + throw Self.authorizerError(error) + } + if let authorizer = inputs.authorizer { + // The token goes where the request goes: the modifier may + // have pointed it at another URL. + let url = request.url ?? inputs.endpoint + try Self.requireAuthorizableEndpoint(url) + do { + for (name, value) in try await authorizer.authorizationHeaders( + for: url, method: request.httpMethod ?? "GET") + { + request.setValue(value, forHTTPHeaderField: name) + } + } catch { + throw Self.authorizerError(error) + } + } + // Back on the transport: still connected, with which session ID? + guard let request = try await reference.transport?.finishEventStreamRequest(request) else { + return nil + } let (stream, response) = try await inputs.session.responseBody( for: request, streaming: inputs.streamingSession) + if let failure = stream.redirectChain.failure { + // The authorizer's error stopped a redirect; the 3xx is not the answer. + stream.cancel() + throw Self.authorizerError(failure) + } guard let httpResponse = response as? HTTPURLResponse else { stream.cancel() throw MCPError.internalError("Invalid HTTP response") } let headers = Self.headers(of: httpResponse) - inputs.authorizer?.didReceiveResponse(headers: headers, for: request.url ?? inputs.endpoint) + await inputs.authorizer?.didReceiveResponse( + headers: headers, for: httpResponse.url ?? request.url ?? inputs.endpoint) guard let authorizer = inputs.authorizer, httpResponse.statusCode == 401 || httpResponse.statusCode == 403 else { return EventStreamReply( stream: stream, statusCode: httpResponse.statusCode, headers: headers, sessionID: httpResponse.value(forHTTPHeaderField: HTTPHeaderName.sessionID), - sentSessionID: request.value(forHTTPHeaderField: HTTPHeaderName.sessionID)) + sentSessionID: stream.redirectChain.sentSessionID + ?? request.value(forHTTPHeaderField: HTTPHeaderName.sessionID), + acceptSessionID: stream.redirectChain.leftOrigin == nil) } stream.cancel() + if let respondedURL = httpResponse.url, let error = Self.redirectedChallengeError( + sentTo: request.url ?? inputs.endpoint, answeredBy: respondedURL, chain: stream.redirectChain) + { + throw error + } let failure = MCPError.transportError( HTTPStatusError(statusCode: httpResponse.statusCode, headers: headers)) + let challenge = HTTPAuthorizationChallenge( + statusCode: httpResponse.statusCode, headers: headers, endpoint: inputs.endpoint, + sentAuthorization: stream.redirectChain.sentAuthorization + ?? request.value(forHTTPHeaderField: HTTPHeaderName.authorization)) let handled: HTTPChallengeResult do { - handled = try await authorizer.handleChallenge( - statusCode: httpResponse.statusCode, - headers: headers, - endpoint: inputs.endpoint, - operationKey: nil, - sentAuthorization: request.value(forHTTPHeaderField: HTTPHeaderName.authorization), - session: inputs.session - ) + handled = try await authorizer.handleChallenge(challenge, session: inputs.session) } catch { throw Self.authorizerError(error) } + guard handled.shouldRetry else { + throw failure + } // RFC 9449 §9: a DPoP nonce retry is allowed once per GET, as for a POST. if handled.isDPoPNonceRetry { if retriedNonce { @@ -1242,7 +1543,7 @@ public actor HTTPClientTransport: Transport { } else { attempts += 1 } - guard handled.retry, attempts < authorizer.maxAuthorizationAttempts else { + guard attempts < authorizer.maxAuthorizationAttempts else { throw failure } } @@ -1259,7 +1560,7 @@ public actor HTTPClientTransport: Transport { /// error instead of waiting forever. Revisions without sessions /// (2026-07-28) have no resumability: the request fails at once. private func resumeResponseStream( - after eventID: String?, retry: Int?, awaiting id: String, request message: OutgoingMessage + after eventID: String?, retry: Int?, awaiting id: ID, request message: OutgoingMessage ) async throws { let requestData = message.data let version = message.protocolVersion ?? protocolVersion @@ -1374,7 +1675,7 @@ public actor HTTPClientTransport: Transport { /// The ID of the request a server message answers: a response, or one /// whose `jsonrpc` is not `"2.0"`. `Client` fails the request an answer /// it cannot read names, so the stream that carried it is done either way. - static func answeredRequestID(in data: Data) -> String? { + static func answeredRequestID(in data: Data) -> ID? { switch JSONRPCMessageKind(data: data) { case .response(let id?), .invalidResponse(let id): id default: nil @@ -1392,11 +1693,11 @@ public actor HTTPClientTransport: Transport { @discardableResult private func processSSE( _ stream: ResponseBody, - until responseID: String? = nil, + until responseID: ID? = nil, onEventID: (String) -> Void = { _ in }, onRetry: (Int) -> Void = { _ in }, onMessage: () -> Void = {}, - onResponse: ((String) -> Void)? = nil + onResponse: ((ID) -> Void)? = nil ) async throws -> Bool { logger.debug("📥 Starting SSE event processing") var eventCount = 0 @@ -1433,7 +1734,7 @@ public actor HTTPClientTransport: Transport { if !event.data.isEmpty, let data = event.data.data(using: .utf8) { hadDataEvent = true onMessage() - var delivered: String? + var delivered: ID? if responseID != nil || onResponse != nil, let id = Self.answeredRequestID(in: data) { @@ -1462,9 +1763,9 @@ public actor HTTPClientTransport: Transport { /// once per send. struct OutgoingMessage: Sendable { let data: Data - /// A request's ID, rendered like ``JSONRPCMessageKind`` IDs; `nil` for + /// A request's ID, read like ``JSONRPCMessageKind`` IDs; `nil` for /// notifications, responses and batches. - let requestID: String? + let requestID: ID? /// The method name, as sent. let method: String? /// The `Mcp-Name` value: `params.name`, `params.uri` or `params.taskId` @@ -1473,7 +1774,7 @@ struct OutgoingMessage: Sendable { /// `params._meta["io.modelcontextprotocol/protocolVersion"]`. let protocolVersion: String? /// The `requestId` of a `notifications/cancelled` message. - let cancelledRequestID: String? + let cancelledRequestID: ID? /// The trimmed method name; the operation key for authorization. var operationKey: String? { diff --git a/Sources/MCP/Base/Transports/HTTPRedirects.swift b/Sources/MCP/Base/Transports/HTTPRedirects.swift new file mode 100644 index 00000000..c26a8352 --- /dev/null +++ b/Sources/MCP/Base/Transports/HTTPRedirects.swift @@ -0,0 +1,384 @@ +import Foundation +import Logging +import Synchronization + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +/// Decides the HTTP redirects of a request sent through ``StreamingSession``. +/// +/// On Apple platforms an ``HTTPRedirectTaskDelegate`` asks the conformer for +/// each redirect of one request. On swift-corelibs-foundation +/// ``URLSession/responseBody(for:streaming:)`` follows each redirect itself +/// and asks the conformer: that platform sends no body after a redirect it +/// follows, and traps when a delegate answers after the task was cancelled. +protocol HTTPRedirectDeciding: Sendable { + /// The request to send for the redirect `response` asks for, given the + /// request URLSession proposes and the first request of the chain, or + /// `nil` not to follow it: the 3xx response is then the response. + /// `chain` records what the chain did with the credentials. + func request( + redirectedTo proposed: URLRequest, by response: HTTPURLResponse, original: URLRequest?, + chain: inout HTTPRedirectChain + ) async -> URLRequest? +} + +/// What the redirects of one request did with its credentials. +struct HTTPRedirectChain: Sendable { + /// The target of the first hop to another origin: from there on the + /// chain carries no credentials, also on a hop back to the origin. + var leftOrigin: URL? + /// Why a redirect to the same origin was not followed: the error of the + /// authorizer's headers for its target. + var failure: (any Error)? + /// The `Authorization` header of the last redirect hop the policy + /// followed: `.some(nil)` when that hop carried none, `nil` when no + /// redirect was followed. + var sentAuthorization: String?? + /// The `Mcp-Session-Id` header of the last redirect hop the policy + /// followed: `.some(nil)` when that hop carried none, `nil` when no + /// redirect was followed. + var sentSessionID: String?? +} + +/// The credentials of a request across an HTTP redirect, as the Fetch +/// standard, curl, Go and Python requests treat them. +/// +/// While every hop stays on the origin of the first request (RFC 6454 §4: +/// scheme, host and port), a redirect keeps its `Authorization`, +/// `Proxy-Authorization`, `Cookie` and `Mcp-Session-Id`. A hop to another +/// origin, including from `https` to `http` on the same host, carries none +/// of them (RFC 9110 §15.4 asks a client that follows a redirect to consider +/// removing such fields), and neither does any later hop, back to the origin +/// included. `DPoP` is dropped on every redirect: a proof names the URL and +/// method it was made for (RFC 9449 §4.2, `htu` and `htm`). +/// +/// URLSession on Apple platforms removes `Authorization` and +/// `Proxy-Authorization` from every redirect; swift-corelibs-foundation +/// keeps every header. Cookies URLSession takes from its cookie storage are +/// not headers of the request: the platform adds them to each hop for that +/// hop's URL. +enum HTTPRedirect { + /// The headers that only the origin they were sent to may receive. + static let credentialHeaders = [ + HTTPHeaderName.authorization, "Proxy-Authorization", "Cookie", HTTPHeaderName.sessionID, + ] + + /// The credential headers, and `DPoP`, which no redirect carries. + static let removedHeaders = credentialHeaders + [HTTPHeaderName.dpop] + + /// `proposed`, the request URLSession proposes for a redirect from + /// `source`, with the credentials of `original`, the first request of + /// the chain, while `chain` hasn't left its origin and `source` and the + /// target are on it; without credentials otherwise, recording in `chain` + /// where it left. Never with a `DPoP` header. + static func request( + redirectedTo proposed: URLRequest, original: URLRequest?, from source: URL?, + chain: inout HTTPRedirectChain + ) -> (request: URLRequest, isSameOrigin: Bool) { + var request = proposed + for name in removedHeaders { + request.setValue(nil, forHTTPHeaderField: name) + } + guard chain.leftOrigin == nil, let original, let origin = original.url, let target = proposed.url, + let source, + DefaultOAuthMetadataDiscovery.haveSameOrigin(target, origin), + DefaultOAuthMetadataDiscovery.haveSameOrigin(source, origin) + else { + if chain.leftOrigin == nil { chain.leftOrigin = proposed.url ?? source } + return (request, false) + } + for name in credentialHeaders { + request.setValue(original.value(forHTTPHeaderField: name), forHTTPHeaderField: name) + } + return (request, true) + } + + /// Why a redirect from `source` to `target` is not followed at all, or + /// `nil` when it may be: + /// - a target that is not an `http` or `https` URL with a host (the Fetch + /// standard's HTTP-redirect fetch, step 6), + /// - a target on a loopback or unspecified host + /// (``OAuthURLValidator/isLoopbackOrUnspecifiedHost(_:)``, including + /// non-canonical IPv4 spellings and embedded IPv6 forms) when `source` + /// is not itself on one, + /// - a hop from `https` to `http`, even on a loopback host, which would + /// resend the request and a 307 or 308 body without TLS, and + /// - a hop from a loopback or unspecified host to `http` on a host that + /// is not a canonical loopback host (`localhost`, `127.0.0.1`, `::1`), + /// which would send them off the machine without TLS. + static func refusal(of target: URL?, from source: URL?) -> String? { + guard let target, let components = URLComponents(url: target, resolvingAgainstBaseURL: false), + let scheme = components.scheme?.lowercased(), + scheme == OAuthURLScheme.http || scheme == OAuthURLScheme.https, + let targetHost = components.host?.lowercased(), !targetHost.isEmpty + else { return "its target is not an http or https URL" } + let sourceComponents = source.flatMap { URLComponents(url: $0, resolvingAgainstBaseURL: false) } + let sourceScheme = sourceComponents?.scheme?.lowercased() + let sourceHost = sourceComponents?.host + let sourceIsLoopback = sourceHost.map { OAuthURLValidator.isLoopbackOrUnspecifiedHost($0) } ?? false + if OAuthURLValidator.isLoopbackOrUnspecifiedHost(targetHost), !sourceIsLoopback { + return "it goes to a loopback host from a host that is not a loopback host" + } + guard scheme == OAuthURLScheme.http else { return nil } + if sourceScheme == OAuthURLScheme.https { + return "it goes from https to http" + } + if !OAuthLoopbackHost.isLoopback(targetHost) { + // Already in clear text off the machine: follow only from non-loopback http. + if sourceScheme == OAuthURLScheme.http, let sourceHost, !sourceHost.isEmpty, !sourceIsLoopback { + return nil + } + return "it goes from a loopback host to http on a host that is not a loopback host" + } + return nil + } + + /// A copy of `configuration` without the ``removedHeaders`` of its + /// `httpAdditionalHeaders`, in any case, and those headers; `configuration` + /// itself when it has none. + /// + /// URLSession adds the configuration's headers to every request it sends, + /// each redirect included, so they would reach any origin. Set on the + /// request instead (``addingCredentials(_:to:)``), they follow the rule + /// of ``request(redirectedTo:original:from:chain:)``. + static func separatingCredentials( + of configuration: URLSessionConfiguration + ) -> (configuration: URLSessionConfiguration, credentials: [String: String]) { + guard let additional = configuration.httpAdditionalHeaders else { return (configuration, [:]) } + let names = Set(removedHeaders.map { $0.lowercased() }) + var kept: [AnyHashable: Any] = [:] + var credentials: [String: String] = [:] + for (key, value) in additional { + if let name = key as? String, names.contains(name.lowercased()), let value = value as? String { + credentials[name] = value + } else { + kept[key] = value + } + } + guard !credentials.isEmpty else { return (configuration, [:]) } + let copy = configuration.copy() as! URLSessionConfiguration + copy.httpAdditionalHeaders = kept + return (copy, credentials) + } + + /// Sets each of `credentials` that `request` doesn't set itself: as in + /// URLSession, a request's header wins over the configuration's. + static func addingCredentials(_ credentials: [String: String], to request: inout URLRequest) { + for (name, value) in credentials where request.value(forHTTPHeaderField: name) == nil { + request.setValue(value, forHTTPHeaderField: name) + } + } + + /// The request swift-corelibs-foundation proposes for the redirect + /// `response` to `request` asks for, with the body of `request` for 307 + /// and 308 (RFC 9110 §15.4.8, §15.4.9), which that platform drops; `nil` + /// for a response that is not a redirect (301, 302, 303, 307 or 308). + static func proposedRequest(after request: URLRequest, response: HTTPURLResponse) -> URLRequest? { + guard let location = response.value(forHTTPHeaderField: "Location"), + let target = URL(string: location, relativeTo: response.url ?? request.url)?.absoluteURL + else { return nil } + var proposed = request + let method = request.httpMethod?.uppercased() ?? "GET" + switch response.statusCode { + case 301...302 where method == "POST", + 303 where method != "GET" && method != "HEAD": + // RFC 9110 §15.4.2-§15.4.4, Fetch HTTP-redirect fetch step 12. + proposed.httpMethod = "GET" + proposed.httpBody = nil + for name in ["Content-Type", "Content-Length", "Content-Encoding", "Content-Language", "Content-Location"] { + proposed.setValue(nil, forHTTPHeaderField: name) + } + case 301...303, 307...308: + break + default: + return nil + } + proposed.setValue(nil, forHTTPHeaderField: "Host") + proposed.url = target + return proposed + } +} + +#if !canImport(FoundationNetworking) + /// The delegate of a temporary `URLSession` made on Apple platforms to + /// drop credential headers from `httpAdditionalHeaders`: it passes each + /// call to the delegate of the caller's session, such as a server trust + /// challenge or a task's metrics, except the end of the temporary session, + /// which the caller didn't make. + final class ForwardingSessionDelegate: NSObject, URLSessionDelegate, Sendable { + private let target: (any URLSessionDelegate)? + private let end = Mutex<(ended: Bool, waiter: CheckedContinuation?)>((false, nil)) + + init(forwardingTo target: (any URLSessionDelegate)?) { + self.target = target + } + + override func responds(to selector: Selector!) -> Bool { + super.responds(to: selector) || (target?.responds(to: selector) ?? false) + } + + override func forwardingTarget(for selector: Selector!) -> Any? { + target?.responds(to: selector) == true ? target : nil + } + + func urlSession(_ session: URLSession, didBecomeInvalidWithError error: (any Error)?) { + let waiter = end.withLock { state in + state.ended = true + defer { state.waiter = nil } + return state.waiter + } + waiter?.resume() + } + + /// Cancels the tasks of `session`, whose delegate this is, and + /// invalidates it; returns once its delegate calls have ended. + func invalidate(_ session: URLSession) async { + session.invalidateAndCancel() + await withCheckedContinuation { continuation in + let ended = end.withLock { state in + if !state.ended { state.waiter = continuation } + return state.ended + } + if ended { continuation.resume() } + } + } + } + + /// The task delegate of one request on Apple platforms: it decides the + /// request's redirects with a policy and keeps their chain. + /// + /// Each redirect is decided in a task of its own, which ``cancel()`` + /// cancels. When a task is cancelled, URLSession neither cancels its + /// pending `willPerformHTTPRedirection` nor tells the task delegate that + /// the task ended, so the request's caller ends the decision. + final class HTTPRedirectTaskDelegate: NSObject, URLSessionTaskDelegate, Sendable { + private struct State { + var chain = HTTPRedirectChain() + var decision: Task<(URLRequest?, HTTPRedirectChain), Never>? + var ended = false + } + + private let policy: any HTTPRedirectDeciding + private let state = Mutex(State()) + + init(policy: any HTTPRedirectDeciding) { + self.policy = policy + } + + /// What the redirects so far did with the request's credentials. + var chain: HTTPRedirectChain { state.withLock { $0.chain } } + + func urlSession( + _ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest + ) async -> URLRequest? { + let original = task.originalRequest + let policy = self.policy + let decision = state.withLock { state -> Task<(URLRequest?, HTTPRedirectChain), Never>? in + guard !state.ended else { return nil } + let chain = state.chain + let decision = Task { + var chain = chain + let next = await policy.request( + redirectedTo: request, by: response, original: original, chain: &chain) + return (next, chain) + } + state.decision = decision + return decision + } + guard let decision else { return nil } + let (next, chain) = await decision.value + let ended = state.withLock { + $0.chain = chain + $0.decision = nil + return $0.ended + } + // A cancelled decision follows no redirect. + return (ended || decision.isCancelled) ? nil : next + } + + /// Ends the request: cancels the decision in progress, and follows + /// no later redirect. + func cancel() { + let decision = state.withLock { state in + state.ended = true + return state.decision + } + decision?.cancel() + } + } +#endif + +/// The redirects of ``HTTPClientTransport``'s requests: every redirect to an +/// `http` or `https` URL is followed, except one to a loopback host from a +/// remote host, one from `https` to `http`, or one from a loopback host to +/// `http` on a host that is not a loopback host +/// (``HTTPRedirect/refusal(of:from:)``), with the credentials +/// ``HTTPRedirect`` keeps. +/// +/// With an authorizer, a redirect to the same origin gets the headers the +/// transport would send to its target: `authorize` checks the URL and asks +/// the authorizer, which makes a DPoP proof for the target. Its headers +/// replace the first request's `Authorization`: when it has none for the +/// target, the hop has none, so a DPoP-bound token is never sent without a +/// proof (RFC 9449 §7.1). When it fails, the redirect is not followed, the +/// error is logged, and the chain records it for the transport to throw. +/// The authorizer is asked while the request is in flight, and cancelling +/// the request cancels the call. +final class HTTPClientRedirects: HTTPRedirectDeciding { + /// The authorization headers of a request to a URL with a method. + typealias Authorize = @Sendable (_ url: URL, _ method: String) async throws -> [String: String] + + private let authorize: Authorize? + private let logger: Logger? + + /// A policy that asks `authorize` for the headers of a redirect to the + /// same origin, and logs to `logger` the redirects it can't authorize; + /// without `authorize`, the request's credentials are kept. + init(authorize: Authorize?, logger: Logger? = nil) { + self.authorize = authorize + self.logger = logger + } + + func request( + redirectedTo proposed: URLRequest, by response: HTTPURLResponse, original: URLRequest?, + chain: inout HTTPRedirectChain + ) async -> URLRequest? { + if let refusal = HTTPRedirect.refusal(of: proposed.url, from: response.url) { + logger?.warning( + "Redirect not followed: \(refusal)", + metadata: ["target": "\(proposed.url.map { OAuthURLValidator.redacted($0) } ?? "none")"]) + return nil + } + var (request, isSameOrigin) = HTTPRedirect.request( + redirectedTo: proposed, original: original, from: response.url, chain: &chain) + guard isSameOrigin, let authorize, let url = request.url else { + chain.sentAuthorization = .some(request.value(forHTTPHeaderField: HTTPHeaderName.authorization)) + chain.sentSessionID = .some(request.value(forHTTPHeaderField: HTTPHeaderName.sessionID)) + return request + } + // The authorizer's headers are the hop's authorization, none included. + request.setValue(nil, forHTTPHeaderField: HTTPHeaderName.authorization) + do { + for (name, value) in try await authorize(url, request.httpMethod ?? "GET") { + request.setValue(value, forHTTPHeaderField: name) + } + } catch { + if !(error is CancellationError) { + logger?.warning( + "Redirect not followed: no authorization headers for its target", + metadata: [ + "target": "\(OAuthURLValidator.redacted(url))", + "error": "\(error.localizedDescription)", + ]) + } + chain.failure = error + return nil + } + chain.sentAuthorization = .some(request.value(forHTTPHeaderField: HTTPHeaderName.authorization)) + chain.sentSessionID = .some(request.value(forHTTPHeaderField: HTTPHeaderName.sessionID)) + return request + } +} diff --git a/Sources/MCP/Base/Transports/HTTPServer/HTTPRequestValidation.swift b/Sources/MCP/Base/Transports/HTTPServer/HTTPRequestValidation.swift index 27f035d1..878d53c1 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/HTTPRequestValidation.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/HTTPRequestValidation.swift @@ -4,25 +4,49 @@ import Foundation /// Validates an incoming HTTP request before the transport processes it. /// -/// Validators are composed into a pipeline and executed in order. The first validator -/// that returns a non-nil response short-circuits the pipeline and that error response -/// is returned to the client. +/// A transport runs its `validators` in order. The first validator that returns a +/// response ends the request with that response, usually an error. +/// +/// Conform to this protocol to add custom validation, such as authentication. A +/// validator may suspend, for example to look a key up in a database. Put it after the +/// cheap synchronous checks, such as ``OriginValidator``, so a request they refuse never +/// reaches the lookup, and before ``SessionValidator``: /// -/// Conform to this protocol to add custom validation (e.g., authentication): /// ```swift -/// struct BearerTokenValidator: HTTPRequestValidator { -/// func validate(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? { -/// guard let auth = request.header("Authorization"), -/// auth.hasPrefix("Bearer ") else { -/// return .error(statusCode: 401, .invalidRequest("Missing bearer token")) +/// struct APIKeyValidator: HTTPRequestValidator { +/// let keys: KeyStore // an actor +/// +/// func validate(_ request: HTTPRequest, context: HTTPValidationContext) async -> HTTPResponse? { +/// guard let key = request.header("X-API-Key"), await keys.contains(key) else { +/// return .error(statusCode: 401, .invalidRequest("Missing or unknown API key")) /// } /// return nil /// } /// } +/// +/// let transport = StatefulHTTPServerTransport(validators: [ +/// OriginValidator.localhost(), +/// AcceptHeaderValidator(mode: .sseRequired), +/// ContentTypeValidator(), +/// ProtocolVersionValidator(), +/// APIKeyValidator(keys: keys), +/// SessionValidator(), +/// ]) /// ``` public protocol HTTPRequestValidator: Sendable { - /// Validates the request. Returns an error response if invalid, or `nil` if valid. - func validate(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? + /// Validates the request. + /// + /// A synchronous implementation satisfies this requirement. The transport awaits + /// validators in order; while one suspends, the transport can handle other requests. + /// The built-in validators other than ``BearerTokenValidator``, which awaits its + /// token validator, run without suspending. + /// + /// - Parameters: + /// - request: The HTTP request. + /// - context: The transport's state the request is validated against. + /// - Returns: The response that ends the request, such as an error, or `nil` to let the + /// request through. + func validate(_ request: HTTPRequest, context: HTTPValidationContext) async -> HTTPResponse? } // MARK: - Validation Context @@ -395,8 +419,8 @@ public struct OriginValidator: HTTPRequestValidator { /// Metadata at `/.well-known/oauth-protected-resource` so that clients can discover /// authorization server endpoints automatically. /// -/// Place this validator **before** ``BearerTokenValidator`` in the pipeline so that -/// unauthenticated metadata discovery requests succeed. +/// Place this validator **before** ``BearerTokenValidator`` in a transport's validators so +/// that unauthenticated metadata discovery requests succeed. /// /// ```swift /// let prmValidator = ProtectedResourceMetadataValidator( @@ -405,7 +429,7 @@ public struct OriginValidator: HTTPRequestValidator { /// authorizationServers: [URL(string: "https://auth.example.com")!] /// ) /// ) -/// let pipeline = StandardValidationPipeline(validators: [ +/// let transport = StatefulHTTPServerTransport(validators: [ /// prmValidator, /// bearerTokenValidator, /// // ... @@ -490,8 +514,8 @@ public struct BearerTokenValidationResult: Sendable, Equatable { /// - `403` with `error="insufficient_scope"` for insufficient permissions /// - `400` with `error="invalid_request"` for malformed Bearer authorization requests /// -/// Include this validator early in your pipeline, before `SessionValidator`, so unauthenticated -/// initialization requests can return a challenge. +/// Include this validator early in a transport's validators, before ``SessionValidator``, so +/// unauthenticated initialization requests can return a challenge. /// /// ## Audience Validation (MUST) /// @@ -507,7 +531,7 @@ public struct BearerTokenValidationResult: Sendable, Equatable { /// resourceMetadataURL: metadataURL, /// resourceIdentifier: URL(string: "https://api.example.com")!, /// tokenValidator: { token, request, context in -/// guard let claims = verifyAndDecode(token) else { +/// guard let claims = await verifier.verifyAndDecode(token) else { /// return .invalidToken(errorDescription: "Token verification failed") /// } /// // MUST: Verify token audience matches this resource server @@ -520,11 +544,18 @@ public struct BearerTokenValidationResult: Sendable, Equatable { /// ``` public struct BearerTokenValidator: HTTPRequestValidator { /// Validates a bearer token and returns token info for audience and expiry enforcement. + /// + /// The closure may suspend: it can verify a JWT with keys it fetches, or ask the + /// authorization server's introspection endpoint (RFC 7662). While it suspends, the + /// transport handles other requests. It must check the token's audience, and map a + /// failed verification or introspection call to a result, usually + /// ``BearerTokenValidationResult/invalidToken(errorDescription:)``. A synchronous + /// closure also converts to this type. public typealias TokenValidator = @Sendable ( _ token: String, _ request: HTTPRequest, _ context: HTTPValidationContext - ) -> BearerTokenValidationResult + ) async -> BearerTokenValidationResult /// Closure that returns the scopes to advertise in `WWW-Authenticate` challenge headers. /// @@ -588,8 +619,9 @@ public struct BearerTokenValidator: HTTPRequestValidator { /// Bearer credentials (no `Authorization` header, or another scheme) and /// for an invalid, expired or wrong-audience token, 403 for insufficient /// scope, and 400 with an `error="invalid_request"` challenge for a - /// malformed Bearer `Authorization` header (RFC 6750 §3.1). - public func validate(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? { + /// malformed Bearer `Authorization` header (RFC 6750 §3.1). Awaits the + /// token validator. + public func validate(_ request: HTTPRequest, context: HTTPValidationContext) async -> HTTPResponse? { guard requiresAuthentication(request, context) else { return nil } let parsedToken: String @@ -611,7 +643,7 @@ public struct BearerTokenValidator: HTTPRequestValidator { sessionID: context.sessionID) } - switch tokenValidator(parsedToken, request, context).outcome { + switch await tokenValidator(parsedToken, request, context).outcome { case .valid(let info): // Expiry check if let exp = info.expiresAt, exp <= Date() { @@ -784,39 +816,107 @@ public struct BearerTokenValidator: HTTPRequestValidator { } } -// MARK: - Validation Pipeline Protocol - -/// Runs a validation pipeline against an HTTP request. -/// -/// Implementations execute a sequence of validators and return the first error, -/// or `nil` if all validations pass. -public protocol HTTPRequestValidationPipeline: Sendable { - /// Validates the request using the configured pipeline. - /// Returns an error response if validation fails, or `nil` if the request is valid. - func validate(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? -} - // MARK: - Standard Validation Pipeline -/// Standard implementation of `HTTPRequestValidationPipeline` that runs validators in sequence. +/// A validator that runs other validators in order and returns the first response. /// -/// The first validator that returns a non-nil error response short-circuits the pipeline. -public struct StandardValidationPipeline: HTTPRequestValidationPipeline { +/// Use it to group validators into one, for example to reuse them on several transports. +/// The HTTP server transports take an array of validators and run them the same way. +public struct StandardValidationPipeline: HTTPRequestValidator { + /// The validators in order, with nested pipelines expanded into their members. private let validators: [any HTTPRequestValidator] - /// Creates a pipeline with the given validators. - /// Validators are executed in the order provided. + /// Creates a validator that runs `validators` in the order given. public init(validators: [any HTTPRequestValidator]) { - self.validators = validators + // Running a nested pipeline's members in its place gives the same + // responses, and lets `validateInline` see each member. + self.validators = validators.flatMap { validator -> [any HTTPRequestValidator] in + (validator as? StandardValidationPipeline)?.validators ?? [validator] + } } - /// Returns the first error response of the validators, in order, or `nil`. - public func validate(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? { + /// Awaits each validator in order and returns the first response, or `nil` when every + /// validator lets the request through. Validators after the one that responds don't run. + public func validate(_ request: HTTPRequest, context: HTTPValidationContext) async -> HTTPResponse? { + for validator in validators { + if let response = await validator.validate(request, context: context) { + return response + } + } + return nil + } + + /// Runs the validators as `validate(_:context:)` does, on the caller's + /// actor: a `SynchronousRequestValidator` runs without a suspension + /// point, and only the other validators are awaited. + /// + /// With synchronous validators only, the HTTP server transports handle a + /// request from its arrival to its hand-off to the server without + /// suspending, so no other request runs in between. + func validateInline( + _ request: HTTPRequest, context: HTTPValidationContext, + isolation: isolated (any Actor)? = #isolation + ) async -> HTTPResponse? { for validator in validators { - if let errorResponse = validator.validate(request, context: context) { - return errorResponse + if let synchronous = validator as? any SynchronousRequestValidator { + if let response = synchronous.validateSynchronously(request, context: context) { + return response + } + } else if let response = await validator.validate(request, context: context) { + return response } } return nil } } + +// MARK: - Synchronous Validators + +/// A validator that never suspends, which the HTTP server transports run +/// without leaving their actor. +protocol SynchronousRequestValidator: HTTPRequestValidator { + /// Validates the request, as `validate(_:context:)` does. + func validateSynchronously(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? +} + +extension AcceptHeaderValidator: SynchronousRequestValidator { + func validateSynchronously(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? { + validate(request, context: context) + } +} + +extension ContentTypeValidator: SynchronousRequestValidator { + func validateSynchronously(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? { + validate(request, context: context) + } +} + +extension ProtocolVersionValidator: SynchronousRequestValidator { + func validateSynchronously(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? { + validate(request, context: context) + } +} + +extension SessionValidator: SynchronousRequestValidator { + func validateSynchronously(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? { + validate(request, context: context) + } +} + +extension OriginValidator: SynchronousRequestValidator { + func validateSynchronously(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? { + validate(request, context: context) + } +} + +extension ProtectedResourceMetadataValidator: SynchronousRequestValidator { + func validateSynchronously(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? { + validate(request, context: context) + } +} + +extension ServerCardValidator: SynchronousRequestValidator { + func validateSynchronously(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? { + response(to: request) + } +} diff --git a/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift b/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift index c8fdcf8e..8dd0d752 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift @@ -360,24 +360,6 @@ struct SSEEvent: Sendable { } } -// MARK: - HTTP Context Providing - -/// A transport that can surface the originating HTTP request for an in-flight JSON-RPC -/// request, keyed by its JSON-RPC id. -/// -/// The server consults this during dispatch so that registered method handlers can -/// observe the HTTP request that triggered them (headers, auth, path, body) via -/// ``Server/currentHandlerContext``, without changing the `withMethodHandler` signature. -/// -/// Only JSON-RPC *requests* (with an id) are addressable — notifications have no id and -/// are not correlated. -public protocol HTTPContextProviding: Sendable { - /// Returns the HTTP request associated with the given JSON-RPC id, if the - /// transport still has it on hand. Implementations must return `nil` once the - /// corresponding response has been delivered or the session has terminated. - func httpRequestContext(for id: ID) async -> HTTPRequest? -} - // MARK: - JSON-RPC Message Classification /// Classifies a raw JSON-RPC message for routing purposes. @@ -386,18 +368,18 @@ public protocol HTTPContextProviding: Sendable { /// - Responses are routed to the originating request's stream /// - Notifications and server requests are routed to the standalone GET stream package enum JSONRPCMessageKind: Decodable { - case request(id: String, method: String) + case request(id: ID, method: String) case notification(method: String) /// A response; `id` is `nil` for an error response whose `id` is /// `null`, which answers a request whose `id` could not be read and /// names no request (JSON-RPC 2.0 §5). A response may also carry a /// `method`, which is ignored. - case response(id: String?) + case response(id: ID?) /// An answer (a `result` or an `error`) whose `id` is a string or an /// integer but whose `jsonrpc` is not `"2.0"`. It is answered with /// -32600 and `"id": null`, and still given to the server, which fails /// the request it names instead of leaving it waiting. - case invalidResponse(id: String) + case invalidResponse(id: ID) /// A message with a string `method` that is neither a valid request /// nor a valid notification: its `id` is not a string or an integer, /// its `jsonrpc` is not `"2.0"`, or it has an `id` and also a `result` @@ -459,12 +441,12 @@ package enum JSONRPCMessageKind: Decodable { } else if let id, container.contains(.result) || container.contains(.error) { // Read as `Server` and `Client` read it: a response first. if (try? Response(from: decoder)) != nil { - self = .response(id: id.description) + self = .response(id: id) } else { self = .invalid(method: method, id: id, reason: InvalidRequestReason.resultOrError) } } else if let id { - self = .request(id: id.description, method: method) + self = .request(id: id, method: method) } else { // A number too large to decode as a `Value` is `nil` here. let reason = InvalidRequestReason.id(try? container.decode(Value.self, forKey: .id)) @@ -479,10 +461,10 @@ package enum JSONRPCMessageKind: Decodable { throw DecodingError.dataCorruptedError( forKey: .jsonrpc, in: container, debugDescription: InvalidRequestReason.jsonrpc) } - self = .invalidResponse(id: id.description) + self = .invalidResponse(id: id) return } - self = .response(id: id?.description) + self = .response(id: id) } else { throw DecodingError.dataCorrupted( DecodingError.Context( @@ -504,15 +486,17 @@ package enum JSONRPCMessageKind: Decodable { return false } - /// A message's `id`, rendered as a string; `nil` when absent or not a - /// string or an integer that fits `Int`. - package static func extractID(from json: [String: Any]) -> String? { + /// A message's `id`; `nil` when absent or not a string or an integer + /// that fits `Int`. The id `1` and the id `"1"` are different ids. + package static func extractID(from json: [String: Any]) -> ID? { switch json["id"] { case let string as String: - return string - // A JSON boolean is an `NSNumber` too, and `true as? Int` is 1 on Darwin. + return .string(string) + // A JSON boolean is an `NSNumber` too, and `true as? Int` is 1 on + // Darwin. A number `Int` does not hold exactly, such as one above + // 2^31 on a 32-bit platform, is `nil`. case let number as NSNumber where !isBoolean(number): - return (number as? Int).map(String.init) + return (number as? Int).map(ID.number) default: return nil } @@ -523,9 +507,9 @@ package enum JSONRPCMessageKind: Decodable { String(cString: number.objCType) == "c" } - /// The `requestId` of a `notifications/cancelled` message, rendered like - /// a request's ID, or `nil` for any other message. - static func cancelledRequestID(in data: Data) -> String? { + /// The `requestId` of a `notifications/cancelled` message, read like a + /// request's ID, or `nil` for any other message. + static func cancelledRequestID(in data: Data) -> ID? { guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], json["method"] as? String == CancelledNotification.name, let params = json["params"] as? [String: Any] diff --git a/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift b/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift index d2ee7774..139f0d02 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift @@ -28,14 +28,14 @@ import Logging /// and receive `HTTPResponse` values to convert to your framework's native types. /// For SSE responses, the `.stream` case provides an `AsyncThrowingStream` /// to pipe to the client. -public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { +public actor StatefulHTTPServerTransport: Transport { /// The logger of the transport; a no-op logger unless one was passed to `init`. public nonisolated let logger: Logger // MARK: - Dependencies private let sessionIDGenerator: any SessionIDGenerator - private let validationPipeline: any HTTPRequestValidationPipeline + private let validation: StandardValidationPipeline private let retryInterval: Int? // MARK: - State @@ -43,9 +43,16 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { private var sessionID: String? /// The JSON-RPC id of the `initialize` request that created the session, /// until it is answered. - private var initializeRequestID: String? + private var initializeRequestID: ID? private var terminated = false private var started = false + /// Changes whenever the session ID that validators see changes: the + /// session is created, or a refused `initialize` drops it. A request + /// whose validators ran across a change is validated again. Termination + /// leaves the session ID as it was, so it does not count: every handler + /// checks `terminated` after its validators ran instead, and running + /// them again would repeat their work, such as a token introspection. + private var stateGeneration = 0 // MARK: - Incoming message stream (client → server) @@ -55,17 +62,17 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { // MARK: - SSE streams for POST request responses /// Maps request ID → SSE stream continuation for active POST request streams. - private var requestSSEContinuations: [String: AsyncThrowingStream.Continuation] = [:] + private var requestSSEContinuations: [ID: AsyncThrowingStream.Continuation] = [:] /// Maps request ID → originating HTTP request, surfaced to handlers via /// `Server.currentHandlerContext?.httpContext`. Cleared when the response is routed, /// the stream is closed, or the session terminates. - private var httpRequestContexts: [String: HTTPRequest] = [:] + private var httpRequestContexts: [ID: HTTPRequest] = [:] /// IDs of client requests that have not been answered yet. Messages /// related to one of these are stored on its stream even while the /// stream is disconnected, so a resuming client receives them. - private var openRequestIDs: Set = [] + private var openRequestIDs: Set = [] // MARK: - Standalone GET SSE stream @@ -73,23 +80,89 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { /// Only one GET stream is allowed per session. private var standaloneSSEContinuation: AsyncThrowingStream.Continuation? - /// Internal identifier for the standalone GET stream in the event store. - private let standaloneStreamID = "_GET_stream" + /// A stream of the session: the standalone GET stream, or the stream of + /// one request. No request ID names the standalone stream. + private enum StreamKey: Hashable { + case standalone + case request(ID) + + /// The stream's part of an SSE event ID, `_`: `g` + /// for the standalone stream, `n` and the number for a number ID, + /// and `s` and the percent-encoded string for a string ID. It holds + /// only ASCII letters, digits, `-` and `%`: no `_`, and no CR or LF + /// for an `id:` line. The counter is decimal, without a sign or + /// leading zeros. + /// + /// - SeeAlso: https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#resumability-and-redelivery + var eventIDPrefix: String { + switch self { + case .standalone: + return "g" + case .request(.number(let number)): + return "n\(number)" + case .request(.string(let string)): + var prefix = "s" + for byte in string.utf8 { + switch byte { + case UInt8(ascii: "0")...UInt8(ascii: "9"), UInt8(ascii: "A")...UInt8(ascii: "Z"), + UInt8(ascii: "a")...UInt8(ascii: "z"): + prefix.append(Character(Unicode.Scalar(byte))) + default: + prefix += "%" + (byte < 0x10 ? "0" : "") + String(byte, radix: 16, uppercase: true) + } + } + return prefix + } + } + + /// Reads the prefix of an event ID this transport made; `nil` for any + /// other text, including another spelling of the same stream. + init?(eventIDPrefix prefix: Substring) { + let rest = prefix.dropFirst() + let key: StreamKey + switch prefix.first { + case "g": + key = .standalone + case "n": + guard let number = Int(rest) else { return nil } + key = .request(.number(number)) + case "s": + // `""` is a valid id; it is not left to how each platform + // percent-decodes an empty string. + guard let string = rest.isEmpty ? "" : String(rest).removingPercentEncoding else { return nil } + key = .request(.string(string)) + default: + return nil + } + // Byte for byte: `String` equality would also accept a + // canonically equivalent spelling, such as U+212A for `K`. + guard key.eventIDPrefix.utf8.elementsEqual(prefix.utf8) else { return nil } + self = key + } + + /// The SSE event ID of event `counter` on this stream. + func eventID(counter: Int) -> String { + "\(eventIDPrefix)_\(counter)" + } + } - /// The generation of each registered SSE stream, by stream ID. A stream - /// the client disconnects unregisters itself only while it is still the - /// current one for its ID, so it never removes a stream that replaced it. - private var streamGenerations: [String: Int] = [:] + /// The generation of each registered SSE stream. A stream the client + /// disconnects unregisters itself only while it is still the current + /// one for its key, so it never removes a stream that replaced it. + private var streamGenerations: [StreamKey: Int] = [:] private var streamGenerationCounter = 0 // MARK: - Event Store (Resumability) /// A message kept for `Last-Event-ID` replay. Its event ID is - /// `_`; priming events get an ID but are not stored. + /// `_` (see `StreamKey.eventIDPrefix`); priming events + /// get an ID but are not stored. private struct StoredEvent { - let streamID: String + let stream: StreamKey let counter: Int let message: Data + + var eventID: String { stream.eventID(counter: counter) } } /// Stored events, oldest first, from `storedEventsHead`. @@ -97,10 +170,10 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { private var storedEventsHead = 0 private var storedBytes = 0 /// Stored events per stream. - private var storedEventCounts: [String: Int] = [:] + private var storedEventCounts: [StreamKey: Int] = [:] /// The newest event dropped from each stream that still has events or /// is open. A resumption from before it cannot be served. - private var evictedThrough: [String: Int] = [:] + private var evictedThrough: [StreamKey: Int] = [:] private var eventCounter: Int = 0 /// The most events kept for replay; older events are dropped first. private let eventStoreCapacity: Int @@ -109,15 +182,43 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { // MARK: - Init + /// The validators the transport runs when `init` is called without + /// `validators:`, in order: `OriginValidator.localhost()`, + /// `AcceptHeaderValidator(mode: .sseRequired)`, `ContentTypeValidator()`, + /// `ProtocolVersionValidator()` and `SessionValidator()`. + /// + /// They check `Host` and `Origin` for a localhost server, the `Accept` header + /// (both JSON and SSE for a POST), `Content-Type`, `MCP-Protocol-Version`, and + /// the session. + public static var defaultValidators: [any HTTPRequestValidator] { + [ + OriginValidator.localhost(), + AcceptHeaderValidator(mode: .sseRequired), + ContentTypeValidator(), + ProtocolVersionValidator(), + SessionValidator(), + ] + } + /// Creates a new stateful HTTP server transport. /// /// - Parameters: /// - sessionIDGenerator: Generator for session IDs. The IDs MUST contain /// only visible ASCII characters (0x21-0x7E) per the MCP specification. /// Defaults to ``UUIDSessionIDGenerator``. - /// - validationPipeline: Custom validation pipeline. If `nil`, uses sensible defaults: - /// origin validation (localhost), Accept header (SSE required), Content-Type, - /// protocol version, and session validation. + /// - validators: The validators every request passes, in order; the + /// first that returns a response ends the request. Defaults to + /// ``defaultValidators``. Put an authentication validator such as + /// ``BearerTokenValidator`` before ``SessionValidator``. The built-in + /// validators other than ``BearerTokenValidator`` run without + /// suspending, so with them each request is handled without other + /// requests in between. While a validator suspends, the transport + /// handles other requests: a request whose session is created, or + /// dropped by a refused `initialize`, meanwhile is validated again + /// against the new state, and one whose session ended meanwhile gets + /// the answer of a terminated session. A `notifications/cancelled` + /// whose validators finish before those of the request it cancels + /// is ignored. /// - retryInterval: Retry interval in milliseconds for SSE priming events. /// Controls how long clients wait before attempting to reconnect. /// - eventStoreCapacity: The most SSE events kept for `Last-Event-ID` @@ -131,7 +232,7 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { /// - logger: Optional logger. If `nil`, a no-op logger is used. public init( sessionIDGenerator: any SessionIDGenerator = UUIDSessionIDGenerator(), - validationPipeline: (any HTTPRequestValidationPipeline)? = nil, + validators: [any HTTPRequestValidator] = defaultValidators, retryInterval: Int? = nil, eventStoreCapacity: Int = 1000, eventStoreByteCapacity: Int = 16 << 20, @@ -140,13 +241,7 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { self.eventStoreCapacity = max(1, eventStoreCapacity) self.eventStoreByteCapacity = max(1, eventStoreByteCapacity) self.sessionIDGenerator = sessionIDGenerator - self.validationPipeline = validationPipeline ?? StandardValidationPipeline(validators: [ - OriginValidator.localhost(), - AcceptHeaderValidator(mode: .sseRequired), - ContentTypeValidator(), - ProtocolVersionValidator(), - SessionValidator(), - ]) + self.validation = StandardValidationPipeline(validators: validators) self.retryInterval = retryInterval self.logger = logger ?? Logger( label: "mcp.transport.http.server.stateful", @@ -163,10 +258,14 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { /// Marks the transport started; it opens no socket, since the framework /// adapter delivers requests through ``handleRequest(_:)``. /// - /// - Throws: ``MCPError/internalError(_:)`` when already started. + /// - Throws: ``MCPError/internalError(_:)`` when already connected, or + /// after ``disconnect()``: a transport serves one session. public func connect() async throws { + guard !terminated else { + throw MCPError.internalError("Transport disconnected; create a new transport to reconnect") + } guard !started else { - throw MCPError.internalError("Transport already started") + throw MCPError.internalError("Transport already connected") } started = true logger.debug("Stateful HTTP server transport started") @@ -175,25 +274,27 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { /// Terminates the session: closes every SSE stream and the incoming /// stream, and drops stored events. After validation, later requests /// without a session ID get 400; if a session existed, requests with any - /// session ID get 404. + /// session ID get 404. Calling it again, or before ``connect()``, leaves + /// the transport terminated. public func disconnect() async { terminate() } /// Routes outgoing server messages to the appropriate client connection. /// - /// - Responses are routed to the SSE stream matching the response's JSON-RPC ID. - /// - Notifications and server-initiated requests are routed to the standalone GET stream. - public func send(_ data: Data) async throws { - try await send(data, relatedRequestID: nil) - } - - /// Routes outgoing server messages to the appropriate client connection. + /// - Responses go to the SSE stream of the request with the response's + /// JSON-RPC ID. + /// - Notifications and server-initiated requests related to a request + /// that has not been answered yet (`options.relatedRequestID`) go to + /// that request's SSE stream; others go to the standalone GET stream. /// - /// Notifications and server-initiated requests related to a request that - /// has not been answered yet go to that request's SSE stream; others go - /// to the standalone GET stream. - public func send(_ data: Data, relatedRequestID: ID?) async throws { + /// - Parameters: + /// - data: The encoded message. + /// - options: The request the message belongs to. Headers are ignored: + /// a message on an SSE stream has none of its own. + /// - Throws: ``MCPError/connectionClosed`` once the session has + /// terminated, by ``disconnect()`` or by the client's DELETE. + public func send(_ data: Data, options: TransportSendOptions) async throws { guard !terminated else { throw MCPError.connectionClosed } @@ -217,10 +318,11 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { if JSONRPCMessageFields.errorCode(in: data) != nil { logger.info("Initialization failed; session dropped", metadata: ["sessionID": "\(sessionID ?? "none")"]) sessionID = nil + stateGeneration += 1 } } case .notification, .request: - if let related = relatedRequestID?.description, openRequestIDs.contains(related) { + if let related = options.relatedRequestID, openRequestIDs.contains(related) { routeToRequestStream(data, requestID: related) } else { routeServerInitiatedMessage(data) @@ -233,6 +335,9 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { } /// The JSON-RPC messages that clients POST to the session. + /// + /// Every call returns the same stream; iterate it from one task only. It + /// finishes when the session terminates. public func receive() -> AsyncThrowingStream { incomingStream } @@ -246,44 +351,38 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { /// - **GET**: Establish standalone SSE stream for server-initiated messages /// - **DELETE**: Terminate the session /// - Others: 405 Method Not Allowed + /// + /// The transport handles other requests while this one's validators + /// suspend. A request whose session ends while its validators run gets + /// the answer of a terminated session. public func handleRequest(_ request: HTTPRequest) async -> HTTPResponse { if terminated { - let context = HTTPValidationContext( - httpMethod: request.method.uppercased(), sessionID: sessionID, - supportedProtocolVersions: Set(Version.handshake)) - if let response = validationPipeline.validate(request, context: context) { - return withoutSessionHeader(response) + let response = await validate(request) { + HTTPValidationContext( + httpMethod: request.method.uppercased(), sessionID: sessionID, + supportedProtocolVersions: Set(Version.handshake)) } - - let requestedSessionID = request.header(HTTPHeaderName.sessionID) - let isTerminatedSession = sessionID != nil && requestedSessionID == sessionID - let hasEndedSession = sessionID != nil && requestedSessionID != nil - return .error( - statusCode: hasEndedSession ? 404 : 400, - .invalidRequest(hasEndedSession - ? "Not Found: Session has been terminated" - : "Bad Request: No active session"), - sessionID: isTerminatedSession ? sessionID : nil - ) + return terminatedResponse(to: request, validated: response) } switch request.method.uppercased() { case "POST": - return handlePost(request) + return await handlePost(request) case "GET": - return handleGet(request) + return await handleGet(request) case "DELETE": - return handleDelete(request) + return await handleDelete(request) default: // Validators that answer a request themselves, such as // ServerCardValidator for a CORS preflight or a HEAD (200 or // 304), run for every method. - let context = HTTPValidationContext( - httpMethod: request.method.uppercased(), sessionID: sessionID, - supportedProtocolVersions: Set(Version.handshake)) - if let response = validationPipeline.validate(request, context: context), - (200..<300).contains(response.statusCode) || response.statusCode == 304 - { + let response = await validate(request) { + HTTPValidationContext( + httpMethod: request.method.uppercased(), sessionID: sessionID, + supportedProtocolVersions: Set(Version.handshake)) + } + guard !terminated else { return terminatedResponse(to: request, validated: response) } + if let response, (200..<300).contains(response.statusCode) || response.statusCode == 304 { return response } return .error( @@ -295,9 +394,58 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { } } + // MARK: - Validation + + /// How many times a request's validators run when the session state + /// changes each time they run. + private static let maxValidationRuns = 3 + + /// Runs the validators against the current session state. Synchronous + /// validators run on the actor without suspending; only the others are + /// awaited. When the session state changes while they run, runs them + /// again against the new state, up to `maxValidationRuns` times; the + /// caller re-checks `terminated` before it acts on the request. + /// + /// - Returns: The validators' response, `nil` to let the request through, + /// or 503 when the state changed during every run: a response from a + /// state that is no longer current could let a request into a session + /// it was not validated against. + private func validate( + _ request: HTTPRequest, makeContext: () -> HTTPValidationContext + ) async -> HTTPResponse? { + for _ in 0.. HTTPResponse { + if let response { + return withoutSessionHeader(response) + } + let requestedSessionID = request.header(HTTPHeaderName.sessionID) + let isTerminatedSession = sessionID != nil && requestedSessionID == sessionID + let hasEndedSession = sessionID != nil && requestedSessionID != nil + return .error( + statusCode: hasEndedSession ? 404 : 400, + .invalidRequest(hasEndedSession + ? "Not Found: Session has been terminated" + : "Bad Request: No active session"), + sessionID: isTerminatedSession ? sessionID : nil + ) + } + // MARK: - POST Handler - private func handlePost(_ request: HTTPRequest) -> HTTPResponse { + private func handlePost(_ request: HTTPRequest) async -> HTTPResponse { // Parse body first so we can determine if it's an initialization request guard let body = request.body, !body.isEmpty else { return .error( @@ -328,10 +476,13 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { Version.handshake.contains($0) ? nil : $0 }) { - let sessionless = HTTPValidationContext( - httpMethod: "POST", sessionID: nil, isInitializationRequest: true, - supportedProtocolVersions: Set(Version.handshake)) - if let errorResponse = validationPipeline.validate(request, context: sessionless) { + let errorResponse = await validate(request) { + HTTPValidationContext( + httpMethod: "POST", sessionID: nil, isInitializationRequest: true, + supportedProtocolVersions: Set(Version.handshake)) + } + guard !terminated else { return terminatedResponse(to: request, validated: errorResponse) } + if let errorResponse { return errorResponse } // Echo the session ID only to a client that already holds it. @@ -339,25 +490,28 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { return .error( statusCode: 400, .unsupportedProtocolVersion(supported: Version.handshake, requested: version), - id: JSONRPCMessageFields.id(in: body) ?? .string(id), + id: id, sessionID: knownSession ) } - // Build validation context - let context = HTTPValidationContext( - httpMethod: "POST", - sessionID: sessionID, - isInitializationRequest: messageKind.isInitializeRequest, - supportedProtocolVersions: Set(Version.handshake) - ) - - // Run validation pipeline - if let errorResponse = validationPipeline.validate(request, context: context) { + let errorResponse = await validate(request) { + HTTPValidationContext( + httpMethod: "POST", + sessionID: sessionID, + isInitializationRequest: messageKind.isInitializeRequest, + supportedProtocolVersions: Set(Version.handshake) + ) + } + // The session may have ended while the validators ran; nothing below + // may open a stream or reach the server then. + guard !terminated else { return terminatedResponse(to: request, validated: errorResponse) } + if let errorResponse { return errorResponse } - // Handle initialization request specially + // Handle initialization request specially. A second `initialize` + // validated while the first created the session gets 400 here. if messageKind.isInitializeRequest { return handleInitializationRequest(body, request: request) } @@ -424,6 +578,7 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { } self.sessionID = newSessionID + stateGeneration += 1 logger.info("Session initialized", metadata: ["sessionID": "\(newSessionID)"]) // Extract request ID for routing the response @@ -440,10 +595,10 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { return handleJSONRPCRequest(body, requestID: requestID, request: request) } - private func handleJSONRPCRequest(_ body: Data, requestID: String, request: HTTPRequest) -> HTTPResponse { + private func handleJSONRPCRequest(_ body: Data, requestID: ID, request: HTTPRequest) -> HTTPResponse { // Create SSE stream for this request let (sseStream, sseContinuation) = AsyncThrowingStream.makeStream() - register(sseContinuation, streamID: requestID) + register(sseContinuation, for: .request(requestID)) httpRequestContexts[requestID] = request openRequestIDs.insert(requestID) @@ -452,7 +607,7 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { // Send priming event for resumability sendPrimingEvent( - streamID: requestID, + on: .request(requestID), continuation: sseContinuation, protocolVersion: protocolVersion ) @@ -471,17 +626,19 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { // MARK: - GET Handler - private func handleGet(_ request: HTTPRequest) -> HTTPResponse { - // Build validation context (GET is never an initialization request) - let context = HTTPValidationContext( - httpMethod: "GET", - sessionID: sessionID, - isInitializationRequest: false, - supportedProtocolVersions: Set(Version.handshake) - ) - - // Run validation pipeline - if let errorResponse = validationPipeline.validate(request, context: context) { + private func handleGet(_ request: HTTPRequest) async -> HTTPResponse { + // GET is never an initialization request. + let errorResponse = await validate(request) { + HTTPValidationContext( + httpMethod: "GET", + sessionID: sessionID, + isInitializationRequest: false, + supportedProtocolVersions: Set(Version.handshake) + ) + } + // A stream registered on a terminated session would never finish. + guard !terminated else { return terminatedResponse(to: request, validated: errorResponse) } + if let errorResponse { return errorResponse } @@ -501,14 +658,14 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { // Create standalone SSE stream let (sseStream, sseContinuation) = AsyncThrowingStream.makeStream() - register(sseContinuation, streamID: standaloneStreamID) + register(sseContinuation, for: .standalone) // Extract protocol version for priming event let protocolVersion = request.header(HTTPHeaderName.protocolVersion) ?? Version.latestHandshake // Send priming event sendPrimingEvent( - streamID: standaloneStreamID, + on: .standalone, continuation: sseContinuation, protocolVersion: protocolVersion ) @@ -524,16 +681,18 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { // MARK: - DELETE Handler - private func handleDelete(_ request: HTTPRequest) -> HTTPResponse { - // Validate session - let context = HTTPValidationContext( - httpMethod: "DELETE", - sessionID: sessionID, - isInitializationRequest: false, - supportedProtocolVersions: Set(Version.handshake) - ) - - if let errorResponse = validationPipeline.validate(request, context: context) { + private func handleDelete(_ request: HTTPRequest) async -> HTTPResponse { + let errorResponse = await validate(request) { + HTTPValidationContext( + httpMethod: "DELETE", + sessionID: sessionID, + isInitializationRequest: false, + supportedProtocolVersions: Set(Version.handshake) + ) + } + // A DELETE validated while another one ended the session gets 404. + guard !terminated else { return terminatedResponse(to: request, validated: errorResponse) } + if let errorResponse { return errorResponse } @@ -544,50 +703,52 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { // MARK: - Stream Registration - /// Registers `continuation` as the current stream for `streamID` and + /// Registers `continuation` as the current stream for `stream` and /// unregisters it when the client disconnects. A stream it replaces is /// finished: nothing is sent on it any more. private func register( - _ continuation: AsyncThrowingStream.Continuation, streamID: String + _ continuation: AsyncThrowingStream.Continuation, for stream: StreamKey ) { streamGenerationCounter += 1 let generation = streamGenerationCounter - streamGenerations[streamID] = generation + streamGenerations[stream] = generation let replaced: AsyncThrowingStream.Continuation? - if streamID == standaloneStreamID { + switch stream { + case .standalone: replaced = standaloneSSEContinuation standaloneSSEContinuation = continuation - } else { - replaced = requestSSEContinuations.updateValue(continuation, forKey: streamID) + case .request(let requestID): + replaced = requestSSEContinuations.updateValue(continuation, forKey: requestID) } replaced?.finish() continuation.onTermination = { [weak self] termination in guard case .cancelled = termination else { return } - Task { await self?.streamDisconnected(streamID, generation: generation) } + Task { await self?.streamDisconnected(stream, generation: generation) } } } /// Forgets a stream the client disconnected. Messages for it are still /// stored, so a client that resumes receives them. - private func streamDisconnected(_ streamID: String, generation: Int) { - guard streamGenerations[streamID] == generation else { return } - streamGenerations[streamID] = nil - if streamID == standaloneStreamID { + private func streamDisconnected(_ stream: StreamKey, generation: Int) { + guard streamGenerations[stream] == generation else { return } + streamGenerations[stream] = nil + switch stream { + case .standalone: standaloneSSEContinuation = nil - } else { - requestSSEContinuations[streamID] = nil + case .request(let requestID): + requestSSEContinuations[requestID] = nil } - logger.debug("SSE stream disconnected", metadata: ["streamID": "\(streamID)"]) + logger.debug("SSE stream disconnected", metadata: ["stream": "\(stream)"]) } /// Releases a request the client cancelled (`notifications/cancelled`). /// The server sends no response for it, so nothing else would. - private func releaseCancelledRequest(_ requestID: String) { + private func releaseCancelledRequest(_ requestID: ID) { guard openRequestIDs.remove(requestID) != nil else { return } httpRequestContexts.removeValue(forKey: requestID) - streamGenerations[requestID] = nil + streamGenerations[.request(requestID)] = nil requestSSEContinuations.removeValue(forKey: requestID)?.finish() - if storedEventCounts[requestID] == nil { evictedThrough[requestID] = nil } + if storedEventCounts[.request(requestID)] == nil { evictedThrough[.request(requestID)] = nil } logger.debug("Released a cancelled request", metadata: ["requestID": "\(requestID)"]) } @@ -595,8 +756,8 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { /// Routes a message to a specific request's SSE stream without closing it. /// Used for server-initiated messages during request handling. - private func routeToRequestStream(_ data: Data, requestID: String) { - let eventID = storeEvent(streamID: requestID, message: data) + private func routeToRequestStream(_ data: Data, requestID: ID) { + let eventID = storeEvent(on: .request(requestID), message: data) guard let continuation = requestSSEContinuations[requestID] else { logger.debug( @@ -613,13 +774,13 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { /// Routes a response to a specific request's SSE stream and closes it. /// Used for final responses to client requests. - private func routeResponse(_ data: Data, requestID: String) { + private func routeResponse(_ data: Data, requestID: ID) { routeToRequestStream(data, requestID: requestID) openRequestIDs.remove(requestID) // Response means the request is complete — close the stream - streamGenerations[requestID] = nil - if storedEventCounts[requestID] == nil { evictedThrough[requestID] = nil } + streamGenerations[.request(requestID)] = nil + if storedEventCounts[.request(requestID)] == nil { evictedThrough[.request(requestID)] = nil } if let continuation = requestSSEContinuations[requestID] { continuation.finish() requestSSEContinuations.removeValue(forKey: requestID) @@ -628,7 +789,7 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { } private func routeServerInitiatedMessage(_ data: Data) { - let eventID = storeEvent(streamID: standaloneStreamID, message: data) + let eventID = storeEvent(on: .standalone, message: data) guard let continuation = standaloneSSEContinuation else { logger.debug("No standalone GET stream connected, message stored for replay") @@ -660,7 +821,7 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { // A request stream whose request is answered or cancelled has // nothing more to send: replay it and close it. - if replay.streamID != standaloneStreamID, !openRequestIDs.contains(replay.streamID) { + if !isOpenStream(replay.stream) { sseContinuation.finish() var headers = sessionHeaders() headers[HTTPHeaderName.contentType] = ContentType.sse @@ -669,12 +830,12 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { } // Re-register the stream for future messages - register(sseContinuation, streamID: replay.streamID) + register(sseContinuation, for: replay.stream) // Send a new priming event so the client can resume again if disconnected let protocolVersion = request.header(HTTPHeaderName.protocolVersion) ?? Version.latestHandshake sendPrimingEvent( - streamID: replay.streamID, + on: replay.stream, continuation: sseContinuation, protocolVersion: protocolVersion ) @@ -691,41 +852,41 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { /// The IDs of the events kept for replay, oldest first (for tests). var storedEventIDs: [String] { - storedEvents[storedEventsHead...].map { "\($0.streamID)_\($0.counter)" } + storedEvents[storedEventsHead...].map(\.eventID) } - /// Stores `message` for replay on `streamID` and returns its event ID. - private func storeEvent(streamID: String, message: Data) -> String { + /// Stores `message` for replay on `stream` and returns its event ID. + private func storeEvent(on stream: StreamKey, message: Data) -> String { eventCounter += 1 - storedEvents.append(StoredEvent(streamID: streamID, counter: eventCounter, message: message)) + storedEvents.append(StoredEvent(stream: stream, counter: eventCounter, message: message)) storedBytes += message.count - storedEventCounts[streamID, default: 0] += 1 + storedEventCounts[stream, default: 0] += 1 while storedEvents.count - storedEventsHead > 1, storedEvents.count - storedEventsHead > eventStoreCapacity || storedBytes > eventStoreByteCapacity { evictOldestEvent() } - return "\(streamID)_\(eventCounter)" + return stream.eventID(counter: eventCounter) } - /// A new event ID on `streamID` for an event that is not stored. - private func unstoredEventID(streamID: String) -> String { + /// A new event ID on `stream` for an event that is not stored. + private func unstoredEventID(on stream: StreamKey) -> String { eventCounter += 1 - return "\(streamID)_\(eventCounter)" + return stream.eventID(counter: eventCounter) } private func evictOldestEvent() { let event = storedEvents[storedEventsHead] storedEventsHead += 1 storedBytes -= event.message.count - let remaining = (storedEventCounts[event.streamID] ?? 1) - 1 - if remaining > 0 || isOpenStream(event.streamID) { - storedEventCounts[event.streamID] = remaining > 0 ? remaining : nil - evictedThrough[event.streamID] = event.counter + let remaining = (storedEventCounts[event.stream] ?? 1) - 1 + if remaining > 0 || isOpenStream(event.stream) { + storedEventCounts[event.stream] = remaining > 0 ? remaining : nil + evictedThrough[event.stream] = event.counter } else { // Nothing of this stream is left to replay. - storedEventCounts[event.streamID] = nil - evictedThrough[event.streamID] = nil + storedEventCounts[event.stream] = nil + evictedThrough[event.stream] = nil } // Compact once the dropped prefix is large. if storedEventsHead > 256, storedEventsHead * 2 > storedEvents.count { @@ -734,36 +895,42 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { } } - private func isOpenStream(_ streamID: String) -> Bool { - streamID == standaloneStreamID || openRequestIDs.contains(streamID) + private func isOpenStream(_ stream: StreamKey) -> Bool { + switch stream { + case .standalone: true + case .request(let requestID): openRequestIDs.contains(requestID) + } } /// The stream of `lastEventID` and its stored events after it, or `nil` - /// when the stream is unknown or an event after it was dropped. - private func replayEventsAfter(_ lastEventID: String) -> (streamID: String, events: [(eventID: String, message: Data)])? { - guard let separator = lastEventID.lastIndex(of: "_"), - let counter = Int(lastEventID[lastEventID.index(after: separator)...]), - counter <= eventCounter + /// when the event ID is not one the transport made, the stream is + /// unknown, or an event after it was dropped. + private func replayEventsAfter(_ lastEventID: String) -> (stream: StreamKey, events: [(eventID: String, message: Data)])? { + guard let separator = lastEventID.lastIndex(of: "_") else { return nil } + let counterText = lastEventID[lastEventID.index(after: separator)...] + // Only the counter's own spelling: positive, no sign, no leading zero. + guard let counter = Int(counterText), counter >= 1, String(counter) == counterText, + counter <= eventCounter, + let stream = StreamKey(eventIDPrefix: lastEventID[.. counter { return nil } + guard isOpenStream(stream) || storedEventCounts[stream] != nil else { return nil } + if let evicted = evictedThrough[stream], evicted > counter { return nil } let events = storedEvents[storedEventsHead...] - .filter { $0.streamID == streamID && $0.counter > counter } - .map { (eventID: "\($0.streamID)_\($0.counter)", message: $0.message) } - return (streamID, events) + .filter { $0.stream == stream && $0.counter > counter } + .map { (eventID: $0.eventID, message: $0.message) } + return (stream, events) } // MARK: - SSE Helpers private func sendPrimingEvent( - streamID: String, + on stream: StreamKey, continuation: AsyncThrowingStream.Continuation, protocolVersion: String ) { guard Version.profile(for: protocolVersion).allowsPrimingEvents else { return } - let primingEventID = unstoredEventID(streamID: streamID) + let primingEventID = unstoredEventID(on: stream) let primingEvent = SSEEvent.priming(id: primingEventID, retry: retryInterval) continuation.yield(primingEvent.formatted()) } @@ -823,20 +990,25 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { /// /// Used to trigger client reconnection mid-call (SEP-1699). The response, /// when eventually sent, will be stored and replayed to the reconnected stream. - package func closeSSEStream(forRequestID requestID: String) { + package func closeSSEStream(forRequestID requestID: ID) { guard let continuation = requestSSEContinuations[requestID] else { return } - streamGenerations[requestID] = nil + streamGenerations[.request(requestID)] = nil continuation.finish() requestSSEContinuations.removeValue(forKey: requestID) httpRequestContexts.removeValue(forKey: requestID) } - // MARK: - HTTPContextProviding + // MARK: - HTTP Context - /// The HTTP request that carried the JSON-RPC request `id`, until its - /// response is routed, its stream closes or the session terminates. - public func httpRequestContext(for id: ID) -> HTTPRequest? { - httpRequestContexts[id.description] + /// Returns the HTTP request that carried the JSON-RPC request `id`, until + /// its response is routed, its stream closes or the session terminates. + /// + /// ``Server`` puts it in ``Server/HandlerContext/httpContext``. + /// + /// - Parameter id: The JSON-RPC ID of a request the client POSTed. + /// - Returns: The HTTP request, or `nil` when the request is no longer in flight. + public func httpRequest(for id: ID) async -> HTTPRequest? { + httpRequestContexts[id] } // MARK: - Termination diff --git a/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift b/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift index 3dd0143a..e6bf7947 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift @@ -55,13 +55,13 @@ import Logging /// To serve both session-based and stateless clients on one endpoint, route /// requests whose ``HTTPRequest/statelessProtocolVersion`` is non-`nil` to /// this transport and the rest to a ``StatefulHTTPServerTransport``. -public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { +public actor StatelessHTTPServerTransport: Transport { /// The logger of the transport; a no-op logger unless one was passed to `init`. public nonisolated let logger: Logger // MARK: - Dependencies - private let validationPipeline: any HTTPRequestValidationPipeline + private let validation: StandardValidationPipeline // MARK: - State @@ -99,8 +99,9 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { /// slowly. The oldest are dropped first; the response is always last. public static let maxBufferedMessages = 1024 - /// In-flight requests keyed by the internal id given to the server. - private var exchanges: [String: Exchange] = [:] + /// In-flight requests keyed by the internal id given to the server, + /// always a `.string` ID. + private var exchanges: [ID: Exchange] = [:] /// The interval of `: keep-alive` comments on open SSE streams; `nil` /// sends none. @@ -110,14 +111,25 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { static let keepAliveComment = Data(": keep-alive\n\n".utf8) /// The protocol versions the server on this transport serves, newest - /// first; set by ``Server/start(transport:initializeHook:statelessRequestHook:)``. + /// first; set by ``prepare(servingProtocolVersions:)``. Until then, every + /// version the SDK implements. private var servedVersions = Version.stateless + Version.handshake - /// Sets the protocol versions the server on this transport serves. - func serve(protocolVersions: [String]) { - servedVersions = protocolVersions + /// Sets the protocol versions the server on this transport serves, which + /// validators check `MCP-Protocol-Version` against and -32022 lists. + /// + /// ``Server/start(transport:initializeHook:statelessRequestHook:)`` calls + /// it with `Server.Configuration.protocolVersions` before ``connect()``. + /// + /// - Parameter versions: The versions, newest first. + public func prepare(servingProtocolVersions versions: [String]) async { + servedVersions = versions } + /// `true`: requests share no session, so ``Server`` serves each + /// handshake request on its own, without `initialize`. + public nonisolated var isSessionless: Bool { true } + /// Whether the server serves a handshake revision. A server that serves /// none answers every request by the 2026-07-28 rules, including the /// HTTP status of its errors. @@ -127,27 +139,44 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { // MARK: - Init + /// The validators the transport runs when `init` is called without + /// `validators:`, in order: `OriginValidator.localhost()`, + /// `AcceptHeaderValidator(mode: .jsonOnly)`, `ContentTypeValidator()` and + /// `ProtocolVersionValidator()`. + /// + /// They check `Host` and `Origin` for a localhost server, the `Accept` header + /// (JSON for a POST), `Content-Type` and `MCP-Protocol-Version`. + public static var defaultValidators: [any HTTPRequestValidator] { + [ + OriginValidator.localhost(), + AcceptHeaderValidator(mode: .jsonOnly), + ContentTypeValidator(), + ProtocolVersionValidator(), + ] + } + /// Creates a new stateless HTTP server transport. /// /// - Parameters: - /// - validationPipeline: Custom validation pipeline. If `nil`, uses sensible defaults: - /// origin validation (localhost), Accept header (JSON required), Content-Type, - /// and protocol version validation. + /// - validators: The validators every request passes, in order; the + /// first that returns a response ends the request. Defaults to + /// ``defaultValidators``. Put an authentication validator such as + /// ``BearerTokenValidator`` early, after + /// ``ProtectedResourceMetadataValidator``. The built-in validators + /// other than ``BearerTokenValidator`` run without suspending. While + /// a validator suspends, the transport handles other requests; a + /// `notifications/cancelled` whose validators finish before those of + /// the request it cancels is ignored. /// - keepAliveInterval: The interval of `: keep-alive` comments on /// open SSE streams; `nil` sends none. /// - logger: Optional logger. If `nil`, a no-op logger is used. public init( - validationPipeline: (any HTTPRequestValidationPipeline)? = nil, + validators: [any HTTPRequestValidator] = defaultValidators, keepAliveInterval: Duration? = .seconds(15), logger: Logger? = nil ) { self.keepAliveInterval = keepAliveInterval - self.validationPipeline = validationPipeline ?? StandardValidationPipeline(validators: [ - OriginValidator.localhost(), - AcceptHeaderValidator(mode: .jsonOnly), - ContentTypeValidator(), - ProtocolVersionValidator(), - ]) + self.validation = StandardValidationPipeline(validators: validators) self.logger = logger ?? Logger( label: "mcp.transport.http.server.stateless", factory: { _ in SwiftLogNoOpLogHandler() } @@ -163,35 +192,38 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { /// Marks the transport started; it opens no socket, since the framework /// adapter delivers requests through ``handleRequest(_:)``. /// - /// - Throws: ``MCPError/internalError(_:)`` when already started. + /// - Throws: ``MCPError/internalError(_:)`` when already connected, or + /// after ``disconnect()``. public func connect() async throws { + guard !terminated else { + throw MCPError.internalError("Transport disconnected; create a new transport to reconnect") + } guard !started else { - throw MCPError.internalError("Transport already started") + throw MCPError.internalError("Transport already connected") } started = true logger.debug("Stateless HTTP server transport started") } /// Stops the transport: ends every in-flight exchange and the incoming - /// stream; later requests get 404. + /// stream; later requests get 404. Calling it again, or before + /// ``connect()``, leaves the transport stopped. public func disconnect() async { terminate() } /// Routes outgoing server messages to the HTTP exchange they belong to. /// - /// Responses are matched by JSON-RPC ID. Other messages are dropped: - /// there is no stream outside a request. - public func send(_ data: Data) async throws { - try await send(data, relatedRequestID: nil) - } - - /// Routes outgoing server messages to the HTTP exchange they belong to. - /// - /// Notifications and requests related to an in-flight request are + /// Responses are matched by JSON-RPC ID. Notifications and requests + /// related to an in-flight request (`options.relatedRequestID`) are /// delivered on that request's response stream; unrelated ones are - /// dropped. - public func send(_ data: Data, relatedRequestID: ID?) async throws { + /// dropped: there is no stream outside a request. + /// + /// - Parameters: + /// - data: The encoded message. + /// - options: The request the message belongs to. Headers are ignored. + /// - Throws: ``MCPError/connectionClosed`` after ``disconnect()``. + public func send(_ data: Data, options: TransportSendOptions) async throws { guard !terminated else { throw MCPError.connectionClosed } @@ -207,6 +239,8 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { // was already answered. logger.debug("Outgoing response without an id dropped") case .response(let id?): + // The server answers with the internal id the transport gave + // the request. guard let exchange = exchanges.removeValue(forKey: id) else { logger.debug("No waiter for response", metadata: ["requestID": "\(id)"]) return @@ -218,7 +252,7 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { exchange.outgoing.finish() case .notification(let method), .request(_, let method): - guard let related = relatedRequestID?.description, let exchange = exchanges[related] + guard let related = options.relatedRequestID, let exchange = exchanges[related] else { logger.debug( "Message without an in-flight request dropped in stateless mode", @@ -241,6 +275,9 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { /// The JSON-RPC messages that clients POST, each request carrying an /// internal id in place of the client's. + /// + /// Every call returns the same stream; iterate it from one task only. It + /// finishes at ``disconnect()``. public func receive() -> AsyncThrowingStream { incomingStream } @@ -254,12 +291,13 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { /// - **GET**: 405 Method Not Allowed /// - **DELETE**: 405 Method Not Allowed /// - Others: 405 Method Not Allowed + /// + /// The transport handles other requests while this one's validators + /// suspend. A request whose validators finish after ``disconnect()`` gets + /// 404, as one that arrives after it. public func handleRequest(_ request: HTTPRequest) async -> HTTPResponse { if terminated { - return .error( - statusCode: 404, - .invalidRequest("Not Found: Transport has been terminated") - ) + return Self.terminatedResponse } switch request.method.uppercased() { @@ -273,9 +311,9 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { let context = HTTPValidationContext( httpMethod: request.method.uppercased(), sessionID: nil, supportedProtocolVersions: Set(servedVersions)) - if let response = validationPipeline.validate(request, context: context), - (200..<300).contains(response.statusCode) || response.statusCode == 304 - { + let response = await validation.validateInline(request, context: context) + guard !terminated else { return Self.terminatedResponse } + if let response, (200..<300).contains(response.statusCode) || response.statusCode == 304 { return response } return .error( @@ -286,6 +324,11 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { } } + /// The answer to a request after ``disconnect()``. + private static var terminatedResponse: HTTPResponse { + .error(statusCode: 404, .invalidRequest("Not Found: Transport has been terminated")) + } + // MARK: - POST Handler private func handlePost(_ request: HTTPRequest) async -> HTTPResponse { @@ -322,7 +365,11 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { supportedProtocolVersions: Set(servedVersions) ) - if let errorResponse = validationPipeline.validate(request, context: context) { + let errorResponse = await validation.validateInline(request, context: context) + // The transport may have stopped while the validators ran; nothing + // below may reach the server then. + guard !terminated else { return Self.terminatedResponse } + if let errorResponse { return errorResponse.withRequestID(requestID) } @@ -434,7 +481,7 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { guard !request.isRepeated(MCPRequestHeaders.method) else { return .headerMismatch("\(MCPRequestHeaders.method) header appears more than once") } - guard methodHeader == method else { + guard methodHeader.isExactly(method) else { return .headerMismatch( "\(MCPRequestHeaders.method) header \(methodHeader) does not match method \(method)") } @@ -447,7 +494,7 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { guard !request.isRepeated(MCPRequestHeaders.name, valuesMayContainCommas: true) else { return .headerMismatch("\(MCPRequestHeaders.name) header appears more than once") } - guard MCPRequestHeaders.decode(raw) == expected else { + guard MCPRequestHeaders.decode(raw)?.isExactly(expected) == true else { return .headerMismatch("\(MCPRequestHeaders.name) header does not match the request") } return nil @@ -459,8 +506,8 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { isStateless: Bool, request: HTTPRequest ) async -> HTTPResponse { - let internalID = "mcp-http-\(UUID().uuidString)" - guard let rewritten = JSONRPCMessageFields.replacingID(in: body, with: .string(internalID)) + let internalID = ID.string("mcp-http-\(UUID().uuidString)") + guard let rewritten = JSONRPCMessageFields.replacingID(in: body, with: internalID) else { return .error(statusCode: 400, .parseError("Invalid JSON-RPC message"), id: clientID) } @@ -488,7 +535,7 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { /// Waits for the server's messages for one request and turns them into /// the HTTP response: JSON, or an SSE stream once a notification arrives. private func respond( - to outgoing: AsyncStream, internalID: String, clientID: ID, + to outgoing: AsyncStream, internalID: ID, clientID: ID, isStateless: Bool, acceptsSSE: Bool, keepAliveInterval: Duration?, logger: Logger ) async -> HTTPResponse { await withCheckedContinuation { (decision: CheckedContinuation) in @@ -565,11 +612,11 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { /// Forgets a request whose client went away and cancels it in the /// server, so that long-lived handlers such as `subscriptions/listen` end. - private func abandon(_ internalID: String) { + private func abandon(_ internalID: ID) { guard let exchange = exchanges.removeValue(forKey: internalID) else { return } exchange.outgoing.finish() let cancelled = CancelledNotification.message( - .init(requestId: .string(internalID), reason: "Client disconnected")) + .init(requestId: internalID, reason: "Client disconnected")) if let data = try? JSONEncoder().encode(cancelled) { incomingContinuation.yield(data) } @@ -595,7 +642,7 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { exchange.outgoing.yield(.cancelled) exchange.outgoing.finish() let cancelled = CancelledNotification.message( - .init(requestId: .string(internalID), reason: "Cancelled by the client")) + .init(requestId: internalID, reason: "Cancelled by the client")) return try? JSONEncoder().encode(cancelled) } @@ -613,11 +660,16 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { data, statusCode: status, headers: [HTTPHeaderName.contentType: ContentType.json]) } - // MARK: - HTTPContextProviding + // MARK: - HTTP Context - /// The HTTP request of the in-flight exchange with internal id `id`. - public func httpRequestContext(for id: ID) -> HTTPRequest? { - exchanges[id.description]?.request + /// Returns the HTTP request of the in-flight exchange with internal id `id`. + /// + /// ``Server`` puts it in ``Server/HandlerContext/httpContext``. + /// + /// - Parameter id: The internal JSON-RPC ID the transport gave the request. + /// - Returns: The HTTP request, or `nil` once the response is sent. + public func httpRequest(for id: ID) async -> HTTPRequest? { + exchanges[id]?.request } // MARK: - Termination @@ -748,15 +800,16 @@ enum JSONRPCMessageFields { /// The message with `_meta["io.modelcontextprotocol/subscriptionId"]` of /// its `params` or `result` replaced when it equals `internalID`. /// Returns `data` unchanged otherwise. - static func replacingSubscriptionID(in data: Data, internalID: String, with id: ID) -> Data { - guard data.range(of: Data(internalID.utf8)) != nil, + static func replacingSubscriptionID(in data: Data, internalID: ID, with id: ID) -> Data { + guard case .string(let internalString) = internalID, + data.range(of: Data(internalString.utf8)) != nil, var json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return data } var changed = false for member in ["params", "result"] { guard var object = json[member] as? [String: Any], var meta = object["_meta"] as? [String: Any], - meta[MetaKey.subscriptionID] as? String == internalID + (meta[MetaKey.subscriptionID] as? String).map(ID.string) == internalID else { continue } switch id { case .string(let string): meta[MetaKey.subscriptionID] = string diff --git a/Sources/MCP/Base/Transports/HTTPStatusError.swift b/Sources/MCP/Base/Transports/HTTPStatusError.swift index d9765884..5fc98c1c 100644 --- a/Sources/MCP/Base/Transports/HTTPStatusError.swift +++ b/Sources/MCP/Base/Transports/HTTPStatusError.swift @@ -52,6 +52,18 @@ public struct HTTPStatusError: LocalizedError, Hashable, Sendable { } } +extension HTTPStatusError { + /// Whether `error` reports a 400, 404 or 405 reply without a JSON-RPC + /// answer for the request: how a server that serves only the handshake + /// refuses a request without a session. + static func isSessionlessRefusal(_ error: Swift.Error) -> Bool { + guard case .transportError(let underlying) = error as? MCPError, + let status = underlying as? HTTPStatusError, !status.isSessionExpired + else { return false } + return [400, 404, 405].contains(status.statusCode) + } +} + extension HTTPStatusError: CustomDebugStringConvertible { /// The status code, ``isSessionExpired`` and the names of the headers. /// Header values, such as `Set-Cookie` or `WWW-Authenticate`, are left diff --git a/Sources/MCP/Base/Transports/InMemoryTransport.swift b/Sources/MCP/Base/Transports/InMemoryTransport.swift index 9e7b2b5a..1fe8a2cb 100644 --- a/Sources/MCP/Base/Transports/InMemoryTransport.swift +++ b/Sources/MCP/Base/Transports/InMemoryTransport.swift @@ -20,11 +20,15 @@ public actor InMemoryTransport: Transport { public nonisolated let logger: Logger private var isConnected = false + /// Whether ``disconnect()`` ran or the peer disconnected: the transport + /// cannot connect again. + private var isClosed = false private var pairedTransport: InMemoryTransport? - // Message queues - private var incomingMessages: [Data] = [] - private var messageContinuation: AsyncThrowingStream.Continuation? + /// The stream ``receive()`` returns. It buffers messages that arrive + /// before anyone reads it. + private let messageStream: AsyncThrowingStream + private let messageContinuation: AsyncThrowingStream.Continuation /// Creates a new in-memory transport /// @@ -36,6 +40,7 @@ public actor InMemoryTransport: Transport { label: "mcp.transport.in-memory", factory: { _ in SwiftLogNoOpLogHandler() } ) + (messageStream, messageContinuation) = AsyncThrowingStream.makeStream() } /// Creates a connected pair of in-memory transports @@ -90,13 +95,16 @@ public actor InMemoryTransport: Transport { /// Establishes connection with the transport /// /// For in-memory transports, this validates that the transport is properly - /// paired and sets up the message stream. + /// paired. Messages the peer sends before this are dropped. /// - /// - Throws: MCPError.internalError if the transport is not paired + /// - Throws: `MCPError.internalError` if the transport is not paired, is + /// already connected, or was disconnected. public func connect() async throws { guard !isConnected else { - logger.debug("Transport already connected") - return + throw MCPError.internalError("Transport already connected") + } + guard !isClosed else { + throw MCPError.internalError("Transport disconnected; create a new transport to reconnect") } guard pairedTransport != nil else { @@ -110,40 +118,51 @@ public actor InMemoryTransport: Transport { /// Disconnects from the transport /// - /// This closes the message stream and marks the transport as disconnected. + /// This finishes the message stream and marks the transport as closed. It + /// also closes the paired transport, connected or not: its stream finishes + /// with ``MCPError/connectionClosed``, and its sends throw that error. + /// Calling it again, or before ``connect()``, leaves the transport closed. public func disconnect() async { - guard isConnected else { return } - + guard !isClosed else { return } isConnected = false - messageContinuation?.finish() - messageContinuation = nil + isClosed = true + let paired = pairedTransport + pairedTransport = nil + messageContinuation.finish() // Notify paired transport of disconnection - if let paired = pairedTransport { + if let paired { await paired.handlePeerDisconnection() } logger.info("Transport disconnected") } - /// Handles disconnection from the paired transport + /// Handles disconnection from the paired transport, also before this + /// transport connected: the pair is closed for good. private func handlePeerDisconnection() { - if isConnected { - messageContinuation?.finish(throwing: MCPError.connectionClosed) - messageContinuation = nil - isConnected = false - logger.info("Peer transport disconnected") - } + pairedTransport = nil + guard !isClosed else { return } + messageContinuation.finish(throwing: MCPError.connectionClosed) + isConnected = false + isClosed = true + logger.info("Peer transport disconnected") } /// Sends a message to the paired transport /// /// Messages are delivered directly to the paired transport's receive queue - /// without any additional encoding or framing. + /// without any additional encoding or framing. `options` are ignored. /// - /// - Parameter data: The message data to send - /// - Throws: MCPError.internalError if not connected or no paired transport - public func send(_ data: Data) async throws { + /// - Parameters: + /// - data: The message data to send + /// - options: Ignored: the transport has no streams per request and no headers. + /// - Throws: ``MCPError/connectionClosed`` after ``disconnect()`` or once + /// the peer disconnected; `MCPError.internalError` before ``connect()``. + public func send(_ data: Data, options: TransportSendOptions) async throws { + guard !isClosed else { + throw MCPError.connectionClosed + } guard isConnected else { throw MCPError.internalError("Transport not connected") } @@ -166,32 +185,18 @@ public actor InMemoryTransport: Transport { } logger.debug("Message received", metadata: ["size": "\(data.count)"]) - - if let continuation = messageContinuation { - continuation.yield(data) - } else { - // Queue message if stream not yet created - incomingMessages.append(data) - } + messageContinuation.yield(data) } /// Receives messages from the paired transport /// + /// Every call returns the same stream, which buffers the messages that + /// arrive before it is read; iterate it from one task only. It finishes at + /// ``disconnect()``, and with ``MCPError/connectionClosed`` when the peer + /// disconnects. + /// /// - Returns: An AsyncThrowingStream of Data objects representing messages public func receive() -> AsyncThrowingStream { - return AsyncThrowingStream { continuation in - self.messageContinuation = continuation - - // Deliver any queued messages - for message in self.incomingMessages { - continuation.yield(message) - } - self.incomingMessages.removeAll() - - // Check if already disconnected - if !self.isConnected { - continuation.finish() - } - } + messageStream } } diff --git a/Sources/MCP/Base/Transports/MCPRequestHeaders.swift b/Sources/MCP/Base/Transports/MCPRequestHeaders.swift index b6dbb953..8d9c6053 100644 --- a/Sources/MCP/Base/Transports/MCPRequestHeaders.swift +++ b/Sources/MCP/Base/Transports/MCPRequestHeaders.swift @@ -70,7 +70,8 @@ public enum MCPRequestHeaders { case .bool(let bool): return bool ? "true" : "false" case .int(let int): return String(int) case .double(let double) where double.rounded() == double && abs(double) < 9_007_199_254_740_992: - return String(Int(double)) + // Int64, not Int: the value may be past a 32-bit Int. + return String(Int64(double)) default: return nil } } @@ -258,14 +259,32 @@ public enum MCPRequestHeaders { } } - /// The argument at `path`, or `nil` when absent or null. - static func argument(at path: [String], in arguments: Value?) -> Value? { + private enum ArgumentLookup { + case absent + case value(Value) + /// A key along the path matched only by Unicode canonical equivalence: + /// Swift's `Dictionary` subscript would read it, while exact-scalar + /// matching would treat it as absent. + case canonicalKeyMismatch + } + + private static func lookupArgument(at path: [String], in arguments: Value?) -> ArgumentLookup { var current = arguments for key in path { - current = current?.objectValue?[key] + guard let object = current?.objectValue, let index = object.index(forKey: key) else { + return .absent + } + guard object[index].key.isExactly(key) else { return .canonicalKeyMismatch } + current = object[index].value } - if current == .null { return nil } - return current + guard let current, current != .null else { return .absent } + return .value(current) + } + + /// The argument at `path`, or `nil` when absent or null. + static func argument(at path: [String], in arguments: Value?) -> Value? { + guard case .value(let value) = lookupArgument(at: path, in: arguments) else { return nil } + return value } /// The `Mcp-Param-*` headers for a `tools/call`. @@ -290,22 +309,24 @@ public enum MCPRequestHeaders { ) -> String? { for parameter in parameters { let raw = header(parameter.fieldName) - let value = argument(at: parameter.path, in: arguments) - switch (raw, value) { - case (nil, nil): - continue - case (nil, .some): - return "Missing \(parameter.fieldName) header" - case (.some, nil): - return "\(parameter.fieldName) header sent for an absent argument" - case (.some(let raw), .some(let value)): + switch lookupArgument(at: parameter.path, in: arguments) { + case .canonicalKeyMismatch: + return "\(parameter.fieldName) argument key spelling does not match the schema" + case .absent: + if raw != nil { + return "\(parameter.fieldName) header sent for an absent argument" + } + case .value(let value): + guard let raw else { + return "Missing \(parameter.fieldName) header" + } guard let decoded = decode(raw) else { return "\(parameter.fieldName) header has invalid Base64" } guard let expected = render(value) else { return "\(parameter.fieldName) argument is not a primitive value" } - guard decoded == expected else { + guard decoded.isExactly(expected) else { return "\(parameter.fieldName) header does not match the argument" } } diff --git a/Sources/MCP/Base/Transports/NetworkTransport.swift b/Sources/MCP/Base/Transports/NetworkTransport.swift index 7b8d4eb6..9a95c430 100644 --- a/Sources/MCP/Base/Transports/NetworkTransport.swift +++ b/Sources/MCP/Base/Transports/NetworkTransport.swift @@ -3,10 +3,12 @@ import Logging #if canImport(Network) import Network + import Synchronization - /// Protocol that abstracts the Network.NWConnection functionality needed for NetworkTransport - @preconcurrency protocol NetworkConnectionProtocol { + /// The parts of `NWConnection` that ``NetworkTransport`` uses, so tests can substitute a mock. + protocol NetworkConnectionProtocol: AnyObject, Sendable { var state: NWConnection.State { get } + var currentPath: NWPath? { get } var stateUpdateHandler: ((@Sendable (NWConnection.State) -> Void))? { get set } func start(queue: DispatchQueue) @@ -21,21 +23,58 @@ import Logging ) -> Void) } - /// Extension to conform NWConnection to internal NetworkConnectionProtocol extension NWConnection: NetworkConnectionProtocol {} - /// An implementation of a custom MCP transport using Apple's Network framework. + /// A transport that carries newline-delimited JSON-RPC messages over an `NWConnection`. /// - /// This transport allows MCP clients and servers to communicate over TCP/UDP connections - /// using Apple's Network framework. + /// The transport sends each message as one line of JSON text ending in a newline, and sends + /// nothing else. It has no keep-alive of its own, and a failed send doesn't end the + /// connection: to check that the peer is still there, call ``Client/ping()`` periodically, + /// which sends `server/discover` at 2026-07-28. To have the system detect a TCP connection + /// whose peer went away without closing it, turn on TCP keepalive in the parameters of the + /// connection you pass in (`NWProtocolTCP.Options` `enableKeepalive` and `keepaliveIdle`, as + /// in the example below). Once keepalive gives up, the read in progress fails, which + /// finishes the receive stream or, with reconnection on, reconnects. /// - /// A received message longer than 16 MiB, or than - /// ``BufferConfiguration/maxReceiveBufferSize`` when that is larger, ends the receive stream - /// with `internalError` and cancels the connection. With ``BufferConfiguration/unlimited`` - /// a message has no limit. + /// The transport frames messages by newlines, and reads a close by the peer from a completed + /// final content context, the end of the stream on TCP. On a protocol whose messages each + /// complete a context that isn't final, such as UDP or WebSocket, it keeps reading after + /// each message. /// - /// - Important: This transport is available exclusively on Apple platforms - /// (macOS, iOS, watchOS, tvOS, visionOS) as it depends on the Network framework. + /// A received message longer than `maximumMessageLength` (16 MiB by default) ends the receive + /// stream with `internalError` and cancels the connection. The 12-byte heartbeat frames that a + /// 0.12 `NetworkTransport` sends are skipped where a message would start, so a 0.12 peer + /// keeps working. + /// + /// ## Connecting + /// + /// ``connect()`` returns once the connection is ready. While the connection waits for a usable + /// network path (`.waiting`), `connect()` keeps waiting: `NWConnection` tries again by itself + /// when the path changes, and when the user grants Local Network access. A connection that + /// fails (`.failed`, for example refused or reset) ends `connect()` with its error, unless + /// reconnection is on. `connectionTimeout`, 30 seconds by default, bounds the whole call: once + /// it passes, `connect()` cancels the connection, logs the path's `unsatisfiedReason`, and + /// throws the last `NWError` it saw, or `ETIMEDOUT`. + /// + /// Reconnection is off by default; see ``ReconnectionConfiguration`` for when to turn it on. + /// A graceful close by the peer finishes the receive stream with ``MCPError/connectionClosed`` + /// and never reconnects. + /// + /// ## Local network and watchOS + /// + /// - A peer on the local network needs Local Network access on iOS, iPadOS, visionOS and + /// macOS. Add `NSLocalNetworkUsageDescription` to the app's `Info.plist`. The first + /// connection waits while the system shows the Local Network prompt; if the user denies + /// access, `connect()` throws once `connectionTimeout` passes and logs `localNetworkDenied`. + /// See [TN3179: Understanding local network privacy](https://developer.apple.com/documentation/technotes/tn3179-understanding-local-network-privacy). + /// - On watchOS, an app may use `NWConnection` only while it streams audio, during a CallKit + /// call, or for a DeviceDiscoveryUI listener. Otherwise the connection stays waiting with + /// `ENETDOWN`, and `connect()` throws once `connectionTimeout` passes. Use + /// ``HTTPClientTransport`` there: watchOS allows `URLSession`. + /// See [TN3135: Low-level networking on watchOS](https://developer.apple.com/documentation/technotes/tn3135-low-level-networking-on-watchos). + /// + /// - Important: This transport is available on Apple platforms only, as it depends on the + /// Network framework. /// /// ## Example Usage /// @@ -43,113 +82,45 @@ import Logging /// import MCP /// import Network /// - /// // Create a TCP connection to a server + /// // TCP keepalive detects a peer that went away without closing the connection. + /// let tcp = NWProtocolTCP.Options() + /// tcp.enableKeepalive = true + /// tcp.keepaliveIdle = 30 + /// /// let connection = NWConnection( /// host: NWEndpoint.Host("localhost"), /// port: NWEndpoint.Port(8080)!, - /// using: .tcp + /// using: NWParameters(tls: nil, tcp: tcp) /// ) - /// - /// // Initialize the transport with the connection /// let transport = NetworkTransport(connection: connection) /// - /// // For messages longer than 16 MiB (e.g., images), configure unlimited buffer size - /// let largeBufferTransport = NetworkTransport( - /// connection: connection, - /// bufferConfig: .unlimited - /// ) - /// - /// // Use the transport with an MCP client /// let client = Client(name: "MyApp", version: "1.0.0") /// try await client.connect(transport: transport) /// ``` public actor NetworkTransport: Transport { - /// Represents a heartbeat message for connection health monitoring. - public struct Heartbeat: RawRepresentable, Hashable, Sendable { - /// Magic bytes used to identify a heartbeat message. + /// The frame a 0.12 `NetworkTransport` sent every 15 seconds by default: the bytes of + /// U+1F493 and a little-endian `UInt64` of milliseconds since 2001, with no newline. + /// + /// The transport no longer sends it, and skips it on receive so a 0.12 peer keeps + /// working with a 1.x one. Remove the skip in 2.0. + struct Heartbeat: Hashable, Sendable { + /// The bytes a heartbeat starts with: U+1F493 in UTF-8. private static let magicBytes: [UInt8] = [0xF0, 0x9F, 0x92, 0x93] - /// The timestamp of when the heartbeat was created. - public let timestamp: Date + /// When the heartbeat was created. + let timestamp: Date - /// Creates a new heartbeat with the current timestamp. - public init() { - self.timestamp = Date() - } - - /// Creates a heartbeat with a specific timestamp. - /// - /// - Parameter timestamp: The timestamp for the heartbeat. - public init(timestamp: Date) { + /// Creates a heartbeat with `timestamp`. + init(timestamp: Date = Date()) { self.timestamp = timestamp } - // MARK: - RawRepresentable - - public typealias RawValue = [UInt8] - - /// Creates a heartbeat from its raw representation. - /// - /// - Parameter rawValue: The raw bytes of the heartbeat message. - /// - Returns: A heartbeat if the raw value is valid, nil otherwise. - public init?(rawValue: [UInt8]) { - // Check if the data has the correct format (magic bytes + timestamp) - guard rawValue.count >= Self.encodedLength, - rawValue.prefix(Self.magicBytes.count).elementsEqual(Self.magicBytes) - else { - return nil - } - - // Extract the timestamp - let timestampData = Data(rawValue[Self.magicBytes.count.. Bool { - guard data.count >= Self.magicBytes.count else { - return false - } - - return data.prefix(Self.magicBytes.count).elementsEqual(Self.magicBytes) - } - - /// Attempts to parse a heartbeat from the given data. - /// - /// - Parameter data: The data to parse. - /// - Returns: A heartbeat if the data is valid, nil otherwise. - public static func from(data: Data) -> Heartbeat? { - guard data.count >= Self.encodedLength else { - return nil - } - - return Heartbeat(rawValue: Array(data)) + let milliseconds = UInt64(timestamp.timeIntervalSinceReferenceDate * 1000) + withUnsafeBytes(of: milliseconds.littleEndian) { result.append(contentsOf: $0) } + return result } /// The size of a heartbeat on the wire: the magic bytes and the timestamp. @@ -173,40 +144,39 @@ import Logging return false } let milliseconds = data.dropFirst(magicBytes.count) - .withUnsafeBytes { $0.loadUnaligned(as: UInt64.self) } + .withUnsafeBytes { UInt64(littleEndian: $0.loadUnaligned(as: UInt64.self)) } return milliseconds >> 48 == 0 } } - /// Configuration for heartbeat behavior. - public struct HeartbeatConfiguration: Hashable, Sendable { - /// Whether heartbeats are enabled. - public let enabled: Bool - /// Interval between heartbeats in seconds. - public let interval: TimeInterval - - /// Creates a new heartbeat configuration. - /// - /// - Parameters: - /// - enabled: Whether heartbeats are enabled (default: true) - /// - interval: Interval in seconds between heartbeats (default: 15.0) - public init(enabled: Bool = true, interval: TimeInterval = 15.0) { - self.enabled = enabled - self.interval = interval - } - - /// Default heartbeat configuration. - public static let `default` = HeartbeatConfiguration() - - /// Configuration with heartbeats disabled. - public static let disabled = HeartbeatConfiguration(enabled: false) - } - - /// Configuration for connection retry behavior. + /// Whether and how a ``NetworkTransport`` dials a new connection after a failure. + /// + /// Reconnection is off by default (``disabled``). Turn it on for an outbound connection + /// to a peer that keeps no session per connection, for example a server at 2026-07-28. + /// At the handshake revisions (2025-11-25 and earlier), the server's session doesn't + /// survive a reconnect, so the client's later requests fail; create a new transport and + /// client instead. + /// + /// With reconnection on: + /// + /// - ``NetworkTransport/connect()`` retries a connection that fails (`.failed`) on a new + /// connection after a backoff, up to ``maxAttempts`` times. A connection that waits for + /// a network path (`.waiting`) uses no attempt. + /// - When the connection is lost after it was ready, the transport dials again under the + /// same rules. If that fails, the receive stream finishes with the error. + /// - The transport's `connectionTimeout` bounds each dial: every attempt, wait and + /// backoff. + /// + /// A graceful close by the peer never reconnects, and neither does a failed send: the + /// receive loop sees the same loss and owns the reconnection. + /// + /// Each new connection goes to the first connection's endpoint, with its parameters, so + /// reconnection is for outbound connections only. A connection accepted from an + /// `NWListener` would dial the remote client's ephemeral port. public struct ReconnectionConfiguration: Hashable, Sendable { - /// Whether the transport should attempt to reconnect on failure. + /// Whether the transport dials a new connection after a failure. public let enabled: Bool - /// Maximum number of reconnection attempts. + /// The most times one dial retries a failed connection. public let maxAttempts: Int /// Multiplier for exponential backoff on reconnect. public let backoffMultiplier: Double @@ -214,8 +184,9 @@ import Logging /// Creates a new reconnection configuration. /// /// - Parameters: - /// - enabled: Whether reconnection should be attempted on failure (default: true) - /// - maxAttempts: Maximum number of reconnection attempts (default: 5) + /// - enabled: Whether the transport dials a new connection after a failure + /// (default: true) + /// - maxAttempts: The most times one dial retries a failed connection (default: 5) /// - backoffMultiplier: Multiplier for exponential backoff on reconnect (default: 1.5) public init( enabled: Bool = true, @@ -227,10 +198,12 @@ import Logging self.backoffMultiplier = backoffMultiplier } - /// Default reconnection configuration. + /// Reconnection on, with up to 5 retries and a backoff multiplier of 1.5. + /// + /// Despite its name, this isn't the transport's default, which is ``disabled``. public static let `default` = ReconnectionConfiguration() - /// Configuration with reconnection disabled. + /// Configuration with reconnection disabled: the transport's default. public static let disabled = ReconnectionConfiguration(enabled: false) /// Calculates the backoff delay for a given attempt number. @@ -243,36 +216,51 @@ import Logging } } - /// Configuration for buffer behavior. - public struct BufferConfiguration: Hashable, Sendable { - /// Maximum buffer size for receiving data chunks. - /// Set to nil for unlimited (uses system default). A received message may be as long - /// as 16 MiB or this size, whichever is larger; a longer one ends the receive stream. - /// With nil, a message has no limit. - public let maxReceiveBufferSize: Int? + /// What one read from the connection brought. + private enum Read: Sendable { + /// Bytes from the peer; `peerClosed` when they are the last it sends. + case data(Data, peerClosed: Bool) + /// The peer closed the connection gracefully, with no more bytes. + case closedByPeer + } - /// Creates a new buffer configuration. - /// - /// - Parameter maxReceiveBufferSize: Maximum buffer size in bytes (default: 10MB, nil for unlimited). - /// A received message may be as long as 16 MiB or this size, whichever is larger. - public init(maxReceiveBufferSize: Int? = 10 * 1024 * 1024) { - self.maxReceiveBufferSize = maxReceiveBufferSize - } + /// How reading from one connection ended. + private enum ReadEnd { + /// The transport stopped, or the receive stream is finished. + case finished + /// The connection failed with `error`, and the stream is still open. + case failed(any Swift.Error) + } - /// Default buffer configuration with 10MB limit. - public static let `default` = BufferConfiguration() + /// What a wait for a connection, or a backoff, can wake up for. + private enum ConnectEvent: Sendable { + case state(NWConnection.State) + case deadline + case stopped + } - /// Configuration with no buffer size limit, and no limit on the length of a - /// received message. - public static let unlimited = BufferConfiguration(maxReceiveBufferSize: nil) + /// How one connection attempt ended, when it didn't throw. + private enum AttemptOutcome { + case ready + case failed(NWError) + /// The deadline passed; `lastError` is the last error the connection waited with. + case timedOut(lastError: NWError?) } // State tracking private var isConnected = false + /// Whether ``disconnect()`` ran. private var isStopping = false - private var reconnectAttempt = 0 - private var heartbeatTask: Task? - private var lastHeartbeatTime: Date? + /// Whether the connection ended for good: ``disconnect()`` ran, or the receive stream + /// finished without a reconnection. Sends then throw `connectionClosed`. + private var isClosed = false + /// Whether the receive loop is dialing a new connection after a lost one. + private var isReconnecting = false + /// Wakes the wait for a connection, or the backoff, in progress, for ``disconnect()``. + private var wakeOnStop: AsyncStream.Continuation? + /// The task that reads messages, and reconnects, from ``connect()`` on. ``disconnect()`` + /// cancels it; tests wait for it to end. + private(set) var receiveLoopTask: Task? private let messageStream: AsyncThrowingStream private let messageContinuation: AsyncThrowingStream.Continuation /// The bytes the receive buffer's storage spans after the last read was parsed: the @@ -282,19 +270,21 @@ import Logging /// received in many pieces is searched once, not again with each read. private(set) var searchedByteCount = 0 - /// The most bytes a received message may hold, unless the buffer configuration allows - /// more: the limit of one SSE line in `HTTPClientTransport`. A longer message ends the - /// receive stream. + /// The default limit of a received message: the limit of one SSE line in + /// `HTTPClientTransport`. static let maxMessageLength = ServerSentEventParser.maxLineLength + /// The most bytes one read asks for. It bounds one chunk, not a message. + static let readLength = 1 << 20 + /// The error of a received message longer than `limit` bytes. static func messageTooLong(limit: Int) -> String { limit == maxMessageLength ? "Message longer than 16 MiB" : "Message longer than \(limit) bytes" } - // Connection is marked nonisolated(unsafe) to allow access from closures - private nonisolated(unsafe) var connection: NetworkConnectionProtocol + /// The connection in use. Each attempt after the first replaces it. + private var connection: any NetworkConnectionProtocol // Whether `connection` has been started or cancelled. Such a connection is never reused, // because a cancelled NWConnection cannot be restarted. Tracked here because // `connection.state` reports `.cancelled` only once the platform delivers it on the @@ -305,35 +295,41 @@ import Logging // Builds a fresh connection for each connection attempt after the first. A cancelled // NWConnection cannot be restarted, so a retry uses a new connection to the same endpoint. - private let makeConnection: () -> NetworkConnectionProtocol + private let makeConnection: () -> any NetworkConnectionProtocol + + /// The queue every connection delivers its events on. + private let queue = DispatchQueue(label: "mcp.transport.network") /// Logger instance for transport-related events public nonisolated let logger: Logger - // Configuration - private let heartbeatConfig: HeartbeatConfiguration - private let reconnectionConfig: ReconnectionConfiguration - private let bufferConfig: BufferConfiguration + // Configuration, internal so tests can check the initializer's defaults + let maximumMessageLength: Int + let connectionTimeout: Duration + let reconnection: ReconnectionConfiguration - /// Creates a new NetworkTransport with the specified NWConnection - /// - /// `connect()` uses `connection` for its first attempt. Each later attempt dials a fresh - /// connection to `connection.endpoint` with the same parameters, so retries are meant for - /// outbound (client) connections; a connection accepted from an `NWListener` cannot be - /// rebuilt this way. + /// Creates a transport over `connection`. /// /// - Parameters: - /// - connection: The NWConnection to use for communication - /// - logger: Optional logger instance for transport events - /// - reconnectionConfig: Configuration for reconnection behavior (default: .default) - /// - heartbeatConfig: Configuration for heartbeat behavior (default: .default) - /// - bufferConfig: Configuration for buffer behavior (default: .default) + /// - connection: The connection to use. With reconnection on, each later attempt dials + /// a new connection to `connection.endpoint` with the same parameters, so + /// reconnection is for outbound connections only. + /// - maximumMessageLength: The most bytes a received message may hold; a longer one + /// ends the receive stream with `internalError` and cancels the connection. Defaults + /// to 16 MiB, the limit of an SSE line in ``HTTPClientTransport``. Pass `Int.max` for + /// no limit. Must be positive. + /// - connectionTimeout: How long ``connect()`` may take in all, across every attempt, + /// wait and backoff; a reconnect after a lost connection gets the same limit. + /// Defaults to 30 seconds. Must be positive. + /// - reconnection: Whether and how to reconnect. Defaults to + /// ``ReconnectionConfiguration/disabled``. + /// - logger: The logger; a no-op logger when `nil`. public init( connection: NWConnection, - logger: Logger? = nil, - heartbeatConfig: HeartbeatConfiguration = .default, - reconnectionConfig: ReconnectionConfiguration = .default, - bufferConfig: BufferConfiguration = .default + maximumMessageLength: Int = 16 << 20, + connectionTimeout: Duration = .seconds(30), + reconnection: ReconnectionConfiguration = .disabled, + logger: Logger? = nil ) { // Capture the endpoint and parameters so a retry can build a fresh connection rather // than restart the cancelled one, which the platform does not allow. @@ -342,40 +338,43 @@ import Logging self.init( first: connection, makeConnection: { NWConnection(to: endpoint, using: parameters) }, - logger: logger, - heartbeatConfig: heartbeatConfig, - reconnectionConfig: reconnectionConfig, - bufferConfig: bufferConfig + maximumMessageLength: maximumMessageLength, + connectionTimeout: connectionTimeout, + reconnection: reconnection, + logger: logger ) } + /// Creates a transport whose every attempt uses `connection`. init( - _ connection: NetworkConnectionProtocol, - logger: Logger? = nil, - heartbeatConfig: HeartbeatConfiguration = .default, - reconnectionConfig: ReconnectionConfiguration = .default, - bufferConfig: BufferConfiguration = .default + _ connection: any NetworkConnectionProtocol, + maximumMessageLength: Int = 16 << 20, + connectionTimeout: Duration = .seconds(30), + reconnection: ReconnectionConfiguration = .disabled, + logger: Logger? = nil ) { self.init( first: connection, makeConnection: { connection }, - logger: logger, - heartbeatConfig: heartbeatConfig, - reconnectionConfig: reconnectionConfig, - bufferConfig: bufferConfig + maximumMessageLength: maximumMessageLength, + connectionTimeout: connectionTimeout, + reconnection: reconnection, + logger: logger ) } /// Designated initializer. `makeConnection` builds a fresh connection for each /// connection attempt after the first. init( - first connection: NetworkConnectionProtocol, - makeConnection: @escaping () -> NetworkConnectionProtocol, - logger: Logger? = nil, - heartbeatConfig: HeartbeatConfiguration = .default, - reconnectionConfig: ReconnectionConfiguration = .default, - bufferConfig: BufferConfiguration = .default + first connection: any NetworkConnectionProtocol, + makeConnection: @escaping () -> any NetworkConnectionProtocol, + maximumMessageLength: Int = 16 << 20, + connectionTimeout: Duration = .seconds(30), + reconnection: ReconnectionConfiguration = .disabled, + logger: Logger? = nil ) { + precondition(maximumMessageLength > 0, "maximumMessageLength must be positive") + precondition(connectionTimeout > .zero, "connectionTimeout must be positive") self.connection = connection self.makeConnection = makeConnection self.logger = @@ -384,25 +383,34 @@ import Logging label: "mcp.transport.network", factory: { _ in SwiftLogNoOpLogHandler() } ) - self.reconnectionConfig = reconnectionConfig - self.heartbeatConfig = heartbeatConfig - self.bufferConfig = bufferConfig - - // Create message stream - var continuation: AsyncThrowingStream.Continuation! - self.messageStream = AsyncThrowingStream { continuation = $0 } - self.messageContinuation = continuation + self.maximumMessageLength = maximumMessageLength + self.connectionTimeout = connectionTimeout + self.reconnection = reconnection + + (messageStream, messageContinuation) = AsyncThrowingStream.makeStream() } - /// Establishes connection with the transport + // MARK: - Connecting + + /// Opens the connection and starts reading messages from it. /// - /// This initiates the NWConnection and waits for it to become ready. - /// Once the connection is established, it starts the message receiving loop. + /// Returns once the connection is ready. A connection that waits for a network path + /// keeps waiting; one that fails is retried only with reconnection on. The whole call + /// takes at most `connectionTimeout`. /// - /// - Throws: Error if the connection fails to establish, or if another `connect()` is - /// still in progress + /// - Throws: The connection's `NWError` when it fails and no attempt is left, or the last + /// `NWError` it saw (`ETIMEDOUT` when there was none) once `connectionTimeout` passes; + /// ``MCPError/connectionClosed`` when ``disconnect()`` runs meanwhile; + /// `CancellationError` when the task is cancelled; `MCPError.internalError` when the + /// transport is already connected (also while it reconnects after a lost + /// connection), was disconnected, or another `connect()` is still in progress. public func connect() async throws { - guard !isConnected else { return } + guard !isConnected, !isReconnecting else { + throw MCPError.internalError("Transport already connected") + } + guard !isClosed else { + throw MCPError.internalError("Transport disconnected; create a new transport to reconnect") + } // A second connect() while one is dialing would cancel and replace the connection the // first is waiting on, and the two would go on cancelling each other's attempts. guard !isConnecting else { @@ -411,54 +419,62 @@ import Logging isConnecting = true defer { isConnecting = false } - // Reset state for fresh connection - isStopping = false - reconnectAttempt = 0 + try await dial(until: Self.deadline(after: connectionTimeout)) + isConnected = true + logger.debug("Network transport connected") + receiveLoopTask = Task { await self.receiveLoop() } + } - // A connection that was started or cancelled cannot be started again, so dial a fresh - // one before the first attempt, otherwise attemptConnection() would wait on a stream - // that never yields. cancel() repeats harmlessly if it already ran. - if connectionUsed { - connection.cancel() - replaceConnection() - } + /// Dials until the connection is ready. + /// + /// A `.failed` connection uses an attempt and, with reconnection on, is retried on a new + /// connection after a backoff; `.waiting` uses none. At `deadline` it cancels the + /// connection, logs the path's `unsatisfiedReason` and throws the last `NWError` seen, + /// or `ETIMEDOUT` when there was none. + private func dial(until deadline: ContinuousClock.Instant) async throws { + var failedAttempts = 0 + var lastError: NWError? + while true { + // disconnect() may have run during the backoff; do not dial after it, or the + // fresh connection would outlive the disconnect with nothing able to release it. + guard !isStopping else { throw MCPError.connectionClosed } + // A connection that was started or cancelled cannot be started again, so dial a + // fresh one. cancel() repeats harmlessly if it already ran. + if connectionUsed { + connection.cancel() + replaceConnection() + } - // Retry loop with exponential backoff - while !isConnected && reconnectAttempt <= reconnectionConfig.maxAttempts { - do { - try await attemptConnection() - return // Success - } catch { - guard !isStopping, - reconnectionConfig.enabled, - reconnectAttempt < reconnectionConfig.maxAttempts - else { - // Give up: release the current connection so the socket does not leak. - connection.cancel() - throw error - } + switch try await attempt(until: deadline) { + case .ready: + return - // Schedule retry with backoff - reconnectAttempt += 1 - let delay = reconnectionConfig.backoffDelay(for: reconnectAttempt) - logger.debug( - "Attempting reconnection (\(reconnectAttempt)/\(reconnectionConfig.maxAttempts))..." - ) + case .timedOut(let waitingError): + throw giveUp(lastError: waitingError ?? lastError) - // A cancelled connection cannot be restarted, so retry on a fresh one. Cancel - // before the backoff, so a sleep cancelled by the task cannot leak the started - // connection, and the failed connection does not keep dialing during the wait. + case .failed(let error): + lastError = error + // Release the failed connection, so it does not keep dialing during the + // backoff, and a cancelled backoff cannot leak it. connection.cancel() - try await Task.sleep(for: .seconds(delay)) - // disconnect() may have run during the backoff; do not dial after it, or the - // fresh connection would outlive the disconnect with nothing able to release it. - guard !isStopping else { throw MCPError.connectionClosed } - replaceConnection() + guard reconnection.enabled, failedAttempts < reconnection.maxAttempts else { + throw error + } + failedAttempts += 1 + logger.debug( + "Connection failed; retrying on a new connection", + metadata: [ + "error": "\(error)", + "attempt": "\(failedAttempts)/\(reconnection.maxAttempts)", + ]) + try await backOff( + Self.backoffDuration(seconds: reconnection.backoffDelay(for: failedAttempts)), + until: deadline) + guard ContinuousClock.now < deadline else { + throw giveUp(lastError: lastError) + } } } - - connection.cancel() - throw MCPError.internalError("Failed to connect after \(reconnectAttempt) attempts") } /// Replaces `connection` with a fresh one that has not been started. @@ -467,545 +483,510 @@ import Logging connectionUsed = false } - /// Attempts a single connection + /// Starts `connection` and waits until it is ready, fails, or `deadline` passes. /// - /// Creates a stream for connection state changes and waits for a terminal state. - /// - /// - Throws: Error if the connection fails - private func attemptConnection() async throws { - let stateStream = AsyncStream { continuation in - connection.stateUpdateHandler = { state in - continuation.yield(state) - switch state { - case .ready, .failed, .cancelled: - continuation.finish() - default: - break - } - } + /// - Throws: ``MCPError/connectionClosed`` when ``disconnect()`` runs or the connection + /// is cancelled; `CancellationError` when the task is cancelled. + private func attempt(until deadline: ContinuousClock.Instant) async throws -> AttemptOutcome { + let connection = self.connection + let (events, continuation) = AsyncStream.makeStream() + connection.stateUpdateHandler = { state in continuation.yield(.state(state)) } + let timer = Self.signal(.deadline, to: continuation, at: deadline) + wakeOnStop = continuation + // Runs on the actor's executor, whether the attempt returns or throws. + defer { + timer.cancel() + wakeOnStop = nil + connection.stateUpdateHandler = nil + continuation.finish() } - connection.start(queue: .main) + connection.start(queue: queue) connectionUsed = true - // Clear the handler on the actor's executor once the stream is exhausted, - // regardless of whether the function returns normally or throws. - defer { connection.stateUpdateHandler = nil } - - // Process states until terminal state - for await state in stateStream { - switch state { - case .ready: - // A disconnect() can run while a .ready is already buffered in the stream (the - // handler fires on .main), and the task can be cancelled; in either case do not - // mark the transport connected. - guard !isStopping, !Task.isCancelled else { - connection.cancel() + var lastError: NWError? + for await event in events { + switch event { + case .state(let state): + switch state { + case .ready: + // A disconnect() can run while a .ready is already buffered in the + // stream, and the task can be cancelled; in either case do not mark the + // transport connected. + guard !isStopping else { + connection.cancel() + throw MCPError.connectionClosed + } + guard !Task.isCancelled else { + connection.cancel() + throw CancellationError() + } + return .ready + + case .waiting(let error): + // NWConnection tries again by itself when the path changes, and when the + // user grants Local Network access (TN3179), so keep waiting. + lastError = error + logger.debug( + "Connection waiting for a usable path", + metadata: [ + "error": "\(error)", + "unsatisfiedReason": "\(Self.unsatisfiedReason(of: connection))", + ]) + + case .failed(let error): + logger.debug("Connection failed", metadata: ["error": "\(error)"]) + return .failed(error) + + case .cancelled: + logger.debug("Connection cancelled") throw MCPError.connectionClosed - } - await handleConnectionReady() - return // Success - exits loop and stream - case .failed(let error): - logger.error("Connection failed: \(error)") - throw error // Exits loop and stream + case .preparing: + logger.debug("Connection preparing...") - case .cancelled: - logger.warning("Connection cancelled") - throw MCPError.internalError("Connection cancelled") + case .setup: + logger.debug("Connection setup...") - case .waiting(let error): - // A connection that cannot reach its endpoint stays in .waiting indefinitely, - // so treat it as a failed attempt. The retry loop then dials a fresh - // connection with backoff and honours maxAttempts, and connect() no longer - // blocks forever on an unreachable peer. - logger.debug("Connection waiting: \(error)") - throw error - - case .preparing: - logger.debug("Connection preparing...") + @unknown default: + logger.warning("Unknown connection state") + } - case .setup: - logger.debug("Connection setup...") + case .deadline: + return .timedOut(lastError: lastError) - @unknown default: - logger.warning("Unknown connection state") + case .stopped: + connection.cancel() + throw MCPError.connectionClosed } } - // The stream ended without a terminal state, which happens only when the task is + // The stream ended without a terminal event, which happens only when the task is // cancelled while awaiting. Release the connection and throw rather than returning a // false success with isConnected == false and no receive loop. connection.cancel() throw CancellationError() } - /// Handles when the connection reaches the ready state - private func handleConnectionReady() async { - isConnected = true - reconnectAttempt = 0 - logger.debug("Network transport connected successfully") - - // Start the receive loop after connection is established - Task { await self.receiveLoop() } + /// Waits `delay`, or until `deadline` if that comes first. + /// + /// - Throws: ``MCPError/connectionClosed`` when ``disconnect()`` runs; `CancellationError` + /// when the task is cancelled. + private func backOff(_ delay: Duration, until deadline: ContinuousClock.Instant) async throws { + guard !isStopping else { throw MCPError.connectionClosed } + let (events, continuation) = AsyncStream.makeStream() + let timer = Self.signal(.deadline, to: continuation, at: min(Self.deadline(after: delay), deadline)) + wakeOnStop = continuation + defer { + timer.cancel() + wakeOnStop = nil + continuation.finish() + } - // Start heartbeat task if enabled - if heartbeatConfig.enabled { - startHeartbeat() + for await event in events { + switch event { + case .deadline: return + case .stopped: throw MCPError.connectionClosed + case .state: continue + } } + throw CancellationError() } - /// Starts a task to periodically send heartbeats to check connection health - private func startHeartbeat() { - // Cancel any existing heartbeat task - heartbeatTask?.cancel() - - // Start a new heartbeat task - heartbeatTask = Task { [weak self] in - guard let self = self else { return } - - // Initial delay before starting heartbeats - try? await Task.sleep(for: .seconds(1)) + /// Cancels the connection once a dial runs out of time, logs why, and returns the error + /// to throw: `lastError`, or `ETIMEDOUT` when there was none. + private func giveUp(lastError: NWError?) -> NWError { + let reason = Self.unsatisfiedReason(of: connection) + connection.cancel() + let error = lastError ?? NWError.posix(.ETIMEDOUT) + logger.warning( + "Connection not ready within the timeout", + metadata: [ + "timeout": "\(connectionTimeout)", + "error": "\(error)", + "unsatisfiedReason": "\(reason)", + ]) + return error + } - while !Task.isCancelled { - do { - // Check actor-isolated properties first - let isStopping = await self.isStopping - let isConnected = await self.isConnected + /// The reason the connection's path is unsatisfied, such as `localNetworkDenied`, or + /// `none` when it has no path. + private static func unsatisfiedReason(of connection: any NetworkConnectionProtocol) -> String { + connection.currentPath.map { "\($0.unsatisfiedReason)" } ?? "none" + } - guard !isStopping && isConnected else { break } + /// Caps timeouts before adding them to `ContinuousClock.now` so values such + /// as `.seconds(Int64.max)` cannot overflow `Instant` or `Task.sleep(until:)`. + private static let maxTimeoutSeconds: Double = 100 * 365 * 24 * 60 * 60 + private static let maxTimeoutDuration: Duration = .seconds(100 * 365 * 24 * 60 * 60) - try await self.sendHeartbeat() - try await Task.sleep(for: .seconds(self.heartbeatConfig.interval)) - } catch { - // If heartbeat fails, log and retry after a shorter interval - self.logger.warning("Heartbeat failed: \(error)") - try? await Task.sleep(for: .seconds(2)) - } - } - } + private static func deadline(after duration: Duration) -> ContinuousClock.Instant { + .now + min(duration, maxTimeoutDuration) } - /// Sends a heartbeat message to verify connection health - private func sendHeartbeat() async throws { - guard isConnected && !isStopping else { return } + /// Converts a backoff delay in seconds to a safe `Duration`, clamping non-finite + /// or oversized values so `Duration.seconds(_:)` cannot trap. + private static func backoffDuration(seconds: TimeInterval) -> Duration { + guard !seconds.isNaN, seconds > 0 else { return .zero } + guard seconds.isFinite, seconds < maxTimeoutSeconds else { return maxTimeoutDuration } + return .seconds(seconds) + } - // Try to send the heartbeat (without the newline delimiter used for normal messages) - try await withCheckedThrowingContinuation { - [weak self] (continuation: CheckedContinuation) in - guard let self = self else { - continuation.resume(throwing: MCPError.internalError("Transport deallocated")) + /// Yields `event` to `continuation` at `instant`, unless the returned task is cancelled + /// first. + private static func signal( + _ event: ConnectEvent, + to continuation: AsyncStream.Continuation, + at instant: ContinuousClock.Instant + ) -> Task { + Task { + do { + try await Task.sleep(until: instant, clock: .continuous) + } catch { return } - - connection.send( - content: Heartbeat().data, - contentContext: .defaultMessage, - isComplete: true, - completion: .contentProcessed { [weak self] error in - if let error = error { - continuation.resume(throwing: error) - } else { - Task { [weak self] in - await self?.setLastHeartbeatTime(Date()) - } - continuation.resume() - } - }) + continuation.yield(event) } - - logger.trace("Heartbeat sent") } - - /// Disconnects from the transport + /// Closes the connection and finishes the stream that ``receive()`` returns. /// - /// This cancels the NWConnection, finalizes the message stream, - /// and releases associated resources. + /// This also stops a ``connect()`` or a reconnection in progress, and releases the + /// socket. Calling it again, or before ``connect()``, leaves the transport closed. public func disconnect() async { // Guard on isStopping, not isConnected, so a disconnect while connect() is still // dialing (when isConnected is false) stops it and releases the socket. guard !isStopping else { return } - // Mark as stopping to prevent reconnection attempts during disconnect isStopping = true + isClosed = true isConnected = false - - // Cancel heartbeat task if it exists - heartbeatTask?.cancel() - heartbeatTask = nil + // NWConnection reports .cancelled later, on its queue, or not at all if it was never + // started, so wake a dial or backoff in progress directly. + wakeOnStop?.yield(.stopped) connection.cancel() - // The connection may never have been started, but once cancelled it cannot be, so the - // next connect() must dial a fresh one. + // The connection may never have been started, but once cancelled it cannot be. connectionUsed = true + // Stops the receive loop at its next suspension, also during a reconnection. Its + // read in progress ends once the cancelled connection completes it. + receiveLoopTask?.cancel() messageContinuation.finish() logger.debug("Network transport disconnected") } + // MARK: - Sending + /// Sends data through the network connection /// /// This sends a JSON-RPC message through the NWConnection, adding a newline - /// delimiter to mark the end of the message. + /// delimiter to mark the end of the message. A failed send doesn't reconnect: the + /// receive loop sees the same loss. /// - /// - Parameter message: The JSON-RPC message to send - /// - Throws: MCPError for transport failures or connection issues - public func send(_ message: Data) async throws { + /// - Parameters: + /// - message: The JSON-RPC message to send + /// - options: Ignored: the connection has no streams per request and no headers. + /// - Throws: ``MCPError/connectionClosed`` after ``disconnect()`` or once the + /// connection ended; `MCPError.internalError("Transport not connected")` before + /// ``connect()`` returns, and while the transport reconnects after a lost connection; + /// `MCPError.internalError` with the `NWError` when the connection fails the send. + public func send(_ message: Data, options: TransportSendOptions) async throws { + guard !isClosed else { + throw MCPError.connectionClosed + } guard isConnected else { throw MCPError.internalError("Transport not connected") } - // Add newline as delimiter var messageWithNewline = message messageWithNewline.append(UInt8(ascii: "\n")) - // Use a main-isolated variable to track continuation state - let sendContinuationResumed = MainFlag() - - try await withCheckedThrowingContinuation { - [weak self] (continuation: CheckedContinuation) in - guard let self = self else { - continuation.resume(throwing: MCPError.internalError("Transport deallocated")) - return - } - + let connection = self.connection + let logger = self.logger + let resumed = ResumeOnce() + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in connection.send( content: messageWithNewline, contentContext: .defaultMessage, isComplete: true, - completion: .contentProcessed { [weak self] error in - Task { @MainActor [weak self] in - if !sendContinuationResumed.flag { - sendContinuationResumed.flag = true - if let error = error { - await self?.handleSendFailure(error) - continuation.resume( - throwing: MCPError.internalError("Send error: \(error)")) - } else { - continuation.resume() - } - } + completion: .contentProcessed { error in + guard resumed.claim() else { return } + if let error { + logger.error( + "Send failed", + metadata: [ + "error": "\(error)", + "connectionLost": "\(error.isConnectionLost)", + ]) + continuation.resume(throwing: MCPError.internalError("Send error: \(error)")) + } else { + continuation.resume() } }) } } - /// Logs a failed send, and schedules a reconnection when it shows the connection was lost - private func handleSendFailure(_ error: NWError) { - logger.error("Send error: \(error)") - - // Check if we should attempt to reconnect on send failure - guard !isStopping && reconnectionConfig.enabled && isConnected && error.isConnectionLost - else { return } - - logger.warning("Connection appears broken, will attempt to reconnect...") - - // Schedule connection restart - Task { [weak self] in - guard let self = self else { return } - - await self.setIsConnected(false) - - try? await Task.sleep(for: .milliseconds(500)) - - let currentIsStopping = await self.isStopping - if !currentIsStopping { - // connect() cancels the lost connection and dials a fresh one. Cancelling it - // here as well could cancel the one another loss's connect() just dialed. - try? await self.connect() - } - } - } + // MARK: - Receiving /// Receives data in an async sequence /// /// This returns an AsyncThrowingStream that emits Data objects representing - /// each JSON-RPC message received from the network connection. + /// each JSON-RPC message received from the network connection. Every call returns + /// the same stream; iterate it from one task only. + /// + /// The stream finishes with ``MCPError/connectionClosed`` when the peer closes the + /// connection, with `internalError` when a message is longer than + /// `maximumMessageLength`, and with `MCPError.transportError` when the connection fails + /// and reconnection is off or doesn't succeed. /// /// - Returns: An AsyncThrowingStream of Data objects public func receive() -> AsyncThrowingStream { return messageStream } - /// Continuous loop to receive and process incoming messages + /// Reads messages until the transport stops or the stream finishes, reconnecting after a + /// lost connection when reconnection is on. + private func receiveLoop() async { + while true { + guard case .failed(let error) = await readMessages() else { return } + guard !isStopping, !Task.isCancelled else { return } + + guard reconnection.enabled else { + finishReceiving(throwing: MCPError.transportError(error)) + return + } + do { + try await reconnect(after: error) + } catch { + // disconnect() already finished the stream. + guard !isStopping else { return } + logger.error("Reconnection failed", metadata: ["error": "\(error)"]) + finishReceiving(throwing: (error as? MCPError) ?? MCPError.transportError(error)) + return + } + } + } + + /// Dials a new connection after the current one failed with `error`. /// - /// This method runs continuously while the connection is active, - /// receiving data and yielding complete messages to the message stream. - /// Messages are delimited by newline characters. A heartbeat from the peer is + /// It waits the first backoff, then dials as ``connect()`` does, within + /// `connectionTimeout` in all. + private func reconnect(after error: any Swift.Error) async throws { + isConnected = false + isReconnecting = true + defer { isReconnecting = false } + connection.cancel() + + let deadline = Self.deadline(after: connectionTimeout) + logger.warning("Connection lost; reconnecting", metadata: ["error": "\(error)"]) + try await backOff( + Self.backoffDuration(seconds: reconnection.backoffDelay(for: 1)), until: deadline) + guard ContinuousClock.now < deadline else { + throw giveUp(lastError: error as? NWError) + } + try await dial(until: deadline) + isConnected = true + logger.debug("Network transport reconnected") + } + + /// Ends the connection for good: cancels it and finishes the receive stream with `error`. + private func finishReceiving(throwing error: any Swift.Error) { + isConnected = false + isClosed = true + connection.cancel() + messageContinuation.finish(throwing: error) + } + + /// Reads from the current connection and yields each message, until the transport stops, + /// the stream finishes, or the connection fails. + /// + /// Messages are delimited by newline characters. A heartbeat from a 0.12 peer is /// 12 bytes with no newline after it, and its timestamp can contain a newline /// byte, so it is consumed by length where a message would start. A message longer - /// than `maxMessageLength`, or than a larger `maxReceiveBufferSize`, ends the stream; - /// without a buffer size limit a message has no limit. - private func receiveLoop() async { + /// than `maximumMessageLength` ends the stream. + private func readMessages() async -> ReadEnd { var buffer = Data() // The bytes at the start of `buffer` already searched for a newline, so each read // searches only the bytes it added. var searched = 0 - let maxLength = - bufferConfig.maxReceiveBufferSize.map { max($0, Self.maxMessageLength) } ?? Int.max var consecutiveEmptyReads = 0 let maxConsecutiveEmptyReads = 5 while isConnected && !Task.isCancelled && !isStopping { + let newData: Data + let peerClosed: Bool do { - let newData = try await receiveData() - - // Check for EOF or empty data - if newData.isEmpty { - consecutiveEmptyReads += 1 - - if consecutiveEmptyReads >= maxConsecutiveEmptyReads { - logger.warning( - "Multiple consecutive empty reads (\(consecutiveEmptyReads)), possible connection issue" - ) - - // Check connection state - if connection.state != .ready { - logger.warning("Connection no longer ready, exiting receive loop") - if !isStopping { - // Release the underlying socket and finish the stream so - // receive() callers don't hang. - isConnected = false - heartbeatTask?.cancel() - heartbeatTask = nil - connection.cancel() - messageContinuation.finish(throwing: MCPError.connectionClosed) - } - break - } - } - - // Brief pause before retry - try await Task.sleep(for: .milliseconds(100)) - continue + switch try await read() { + case .data(let data, let closed): + newData = data + peerClosed = closed + case .closedByPeer: + guard !isStopping else { return .finished } + logger.debug("Connection closed by peer") + finishReceiving(throwing: MCPError.connectionClosed) + return .finished } + } catch { + guard !isStopping, !Task.isCancelled else { return .finished } + let lost = (error as? NWError)?.isConnectionLost ?? false + logger.error( + lost ? "Connection lost" : "Receive failed", metadata: ["error": "\(error)"]) + return .failed(error) + } - // Reset counter on successful data read - consecutiveEmptyReads = 0 - buffer.append(newData) - - // Process complete messages and heartbeats. A read can start or end anywhere - // in the byte stream, so a heartbeat is recognized only where a message would - // start: at the start of the stream, after a message, or after a heartbeat. - // A message never starts with the magic bytes: JSON text starts with `{`, `[` - // or whitespace. A line that does is framed by its newline like a message, - // unless it passes for a heartbeat (see `Heartbeat.isAtStart(of:)`). - var tooLong = false - while !buffer.isEmpty { - if Heartbeat.mayStart(buffer) { - // Wait for the rest of the heartbeat. - guard buffer.count >= Heartbeat.encodedLength else { break } - if Heartbeat.isAtStart(of: buffer) { - let heartbeatData = Data(buffer.prefix(Heartbeat.encodedLength)) - buffer = buffer.dropFirst(Heartbeat.encodedLength) - searched = 0 - - logger.trace("Received heartbeat from peer") - if let heartbeat = Heartbeat.from(data: heartbeatData) { - logger.trace("Heartbeat timestamp: \(heartbeat.timestamp)") - } - continue + // An empty read without an error or a close. The real NWConnection delivers one, + // with minimumIncompleteLength: 1, only for an empty message on a message + // protocol; the mock does while idle. + if newData.isEmpty && !peerClosed { + consecutiveEmptyReads += 1 + if consecutiveEmptyReads >= maxConsecutiveEmptyReads { + logger.warning( + "Multiple consecutive empty reads (\(consecutiveEmptyReads)), possible connection issue" + ) + if connection.state != .ready { + logger.warning("Connection no longer ready, exiting receive loop") + if !isStopping { + finishReceiving(throwing: MCPError.connectionClosed) } + return .finished } + } + do { + try await Task.sleep(for: .milliseconds(100)) + } catch { + return .finished + } + continue + } - let unsearched = buffer[(buffer.startIndex + searched)...] - guard let newlineIndex = unsearched.firstIndex(of: UInt8(ascii: "\n")) else { - searchedByteCount &+= unsearched.count - searched = buffer.count - break - } - searchedByteCount &+= newlineIndex + 1 - unsearched.startIndex - let messageData = buffer[..= Heartbeat.encodedLength else { break } + if Heartbeat.isAtStart(of: buffer) { + buffer = buffer.dropFirst(Heartbeat.encodedLength) + searched = 0 + // The skip keeps 0.12 peers, which send heartbeats by default, + // working. Remove it in 2.0. + logger.debug("Skipped a heartbeat frame from a 0.12 peer") + continue } } - // A message over the limit, or the unterminated start of one, ends the stream - // and releases the connection instead of growing the buffer without bound or - // skipping to the next line. - if tooLong || buffer.count > maxLength { - if !isStopping { - logger.error( - "Received a message longer than the limit", - metadata: ["limit": "\(maxLength)"]) - isConnected = false - heartbeatTask?.cancel() - heartbeatTask = nil - connection.cancel() - messageContinuation.finish( - throwing: MCPError.internalError(Self.messageTooLong(limit: maxLength))) - } + + let unsearched = buffer[(buffer.startIndex + searched)...] + guard let newlineIndex = unsearched.firstIndex(of: UInt8(ascii: "\n")) else { + searchedByteCount &+= unsearched.count + searched = buffer.count break } - // Slicing only moves startIndex, and the next append grows the same - // storage, so drop the consumed prefix. - if buffer.startIndex != 0 { - buffer = buffer.isEmpty ? Data() : Data(buffer) + searchedByteCount &+= newlineIndex + 1 - unsearched.startIndex + let messageData = buffer[.. maximumMessageLength { + if !isStopping { + logger.error( + "Received a message longer than the limit", + metadata: ["limit": "\(maximumMessageLength)"]) + finishReceiving( + throwing: MCPError.internalError( + Self.messageTooLong(limit: maximumMessageLength))) } - break + return .finished + } + // Slicing only moves startIndex, and the next append grows the same + // storage, so drop the consumed prefix. + if buffer.startIndex != 0 { + buffer = buffer.isEmpty ? Data() : Data(buffer) + } + receiveBufferSpan = buffer.endIndex + + // A graceful close after the peer's last bytes: deliver them, then finish. + if peerClosed { + guard !isStopping else { return .finished } + logger.debug("Connection closed by peer") + finishReceiving(throwing: MCPError.connectionClosed) + return .finished } } - - // If stopping normally, finish the stream without error - if isStopping { - logger.debug("Receive loop stopping normally") - messageContinuation.finish() - } + return .finished } - /// Receives a chunk of data from the network connection + /// Reads the next chunk from the connection. /// - /// - Returns: The received data chunk - /// - Throws: Network errors or transport failures - private func receiveData() async throws -> Data { - // Use a main-isolated variable to track continuation state - let receiveContinuationResumed = MainFlag() - - return try await withCheckedThrowingContinuation { - [weak self] (continuation: CheckedContinuation) in - guard let self = self else { - continuation.resume(throwing: MCPError.internalError("Transport deallocated")) - return - } - - let maxLength = bufferConfig.maxReceiveBufferSize ?? Int.max - connection.receive(minimumIncompleteLength: 1, maximumLength: maxLength) { - content, _, isComplete, error in - Task { @MainActor in - if !receiveContinuationResumed.flag { - receiveContinuationResumed.flag = true - if let error = error { - continuation.resume(throwing: MCPError.transportError(error)) - } else if let content = content { - continuation.resume(returning: content) - } else if isComplete { - self.logger.trace("Connection completed by peer") - continuation.resume(throwing: MCPError.connectionClosed) - } else { - // EOF: Resume with empty data instead of throwing an error - continuation.resume(returning: Data()) - } - } + /// The peer has closed the connection when the chunk completes a final context: on TCP, + /// the one context of the stream completes at the peer's FIN. On a protocol with a + /// context per message, such as UDP or WebSocket, `isComplete` ends each message and + /// the context isn't final, so reading goes on. + /// + /// - Throws: The connection's `NWError`. + private func read() async throws -> Read { + let connection = self.connection + let resumed = ResumeOnce() + return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + connection.receive(minimumIncompleteLength: 1, maximumLength: Self.readLength) { + content, context, isComplete, error in + guard resumed.claim() else { return } + // A completion without a context has no message boundary to report, so + // `isComplete` there can only be the end of the connection. + let peerClosed = isComplete && (context?.isFinal ?? true) + if let error { + continuation.resume(throwing: error) + } else if let content, !content.isEmpty { + continuation.resume(returning: .data(content, peerClosed: peerClosed)) + } else if peerClosed { + continuation.resume(returning: .closedByPeer) + } else { + continuation.resume(returning: .data(Data(), peerClosed: false)) } } } } + } - private func setLastHeartbeatTime(_ time: Date) { - self.lastHeartbeatTime = time - } + /// Resumes a continuation at most once, from any thread. + private final class ResumeOnce: Sendable { + private let resumed = Mutex(false) - private func setIsConnected(_ connected: Bool) { - self.isConnected = connected + /// Returns `true` the first time only. + func claim() -> Bool { + resumed.withLock { resumed in + defer { resumed = true } + return !resumed + } } } - @MainActor final class MainFlag { var flag = false } extension NWError { - /// Whether this error indicates a connection has been lost or reset. + /// Whether this error shows the connection was lost: reset by the peer, or no longer + /// connected. fileprivate var isConnectionLost: Bool { - let nsError = self as NSError - return nsError.code == 57 // Socket is not connected (EHOSTUNREACH or ENOTCONN) - || nsError.code == 54 // Connection reset by peer (ECONNRESET) + guard case .posix(let code) = self else { return false } + return code == .ECONNRESET || code == .ENOTCONN } } #endif diff --git a/Sources/MCP/Base/Transports/ResponseBody.swift b/Sources/MCP/Base/Transports/ResponseBody.swift index 81522c42..827b5fe0 100644 --- a/Sources/MCP/Base/Transports/ResponseBody.swift +++ b/Sources/MCP/Base/Transports/ResponseBody.swift @@ -12,6 +12,10 @@ import Foundation struct ResponseBody: AsyncSequence, Sendable { typealias Element = UInt8 + /// What the redirects before this response did with the request's + /// credentials. + var redirectChain = HTTPRedirectChain() + #if canImport(FoundationNetworking) let chunks: AsyncThrowingStream let task: URLSessionDataTask @@ -102,15 +106,16 @@ struct ResponseBody: AsyncSequence, Sendable { } private let lock = NSLock() - private let redirects: OAuthRedirectGuard? + private let redirects: (any HTTPRedirectDeciding)? private var pending: [Int: Pending] = [:] /// Tasks that completed before ``start(_:body:)`` registered them, as /// one cancelled first does: their error, `nil` for success. private var completedEarly: [Int: Swift.Error?] = [:] - /// A delegate that follows the redirects `redirects` allows, or every - /// redirect. - init(redirects: OAuthRedirectGuard? = nil) { + /// A delegate that leaves the redirects to + /// ``URLSession/responseBody(for:streaming:)`` when there is a + /// `redirects` policy, and follows every redirect otherwise. + init(redirects: (any HTTPRedirectDeciding)? = nil) { self.redirects = redirects super.init() } @@ -169,10 +174,11 @@ struct ResponseBody: AsyncSequence, Sendable { _ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void ) { - guard let redirects else { return completionHandler(request) } - redirects.urlSession( - session, task: task, willPerformHTTPRedirection: response, newRequest: request, - completionHandler: completionHandler) + // swift-corelibs-foundation sends no body after a redirect it + // follows, and traps when the handler is called after the task + // was cancelled: the 3xx is the response, and responseBody(for: + // streaming:) sends the request the policy returns. + completionHandler(redirects == nil ? request : nil) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { @@ -234,17 +240,85 @@ struct ResponseBody: AsyncSequence, Sendable { #endif extension URLSession { - /// The response to `request` and its body, read as it arrives. + /// The response to `request` and its body, read as it arrives, after the + /// redirects `streaming.redirects` follows. /// /// On swift-corelibs-foundation, `streaming` is a session with this - /// session's configuration and a ``StreamingSessionDelegate``. + /// session's configuration and a ``StreamingSessionDelegate``, and this + /// method follows the redirects: that platform sends no body after a + /// redirect it follows. func responseBody( for request: URLRequest, streaming: StreamingSession ) async throws -> (ResponseBody, URLResponse) { - guard streaming.lifetime.begin() else { throw MCPError.internalError("Transport not connected") } #if canImport(FoundationNetworking) - let task = streaming.session.dataTask( - with: request.addingAdditionalHeaders(of: streaming.session.configuration)) + let original = request.addingAdditionalHeaders(of: streaming.session.configuration) + var current = original + var redirects = 0 + var chain = HTTPRedirectChain() + while true { + var (body, response) = try await streamingResponseBody(for: current, streaming: streaming) + guard let policy = streaming.redirects, let response = response as? HTTPURLResponse, + let proposed = HTTPRedirect.proposedRequest(after: current, response: response) + else { + body.redirectChain = chain + return (body, response) + } + // As URLSession on Apple platforms, which stops after 20. + redirects += 1 + guard redirects <= 20 else { + body.cancel() + throw URLError(.httpTooManyRedirects) + } + let next = await policy.request( + redirectedTo: proposed, by: response, original: original, chain: &chain) + if Task.isCancelled { + body.cancel() + throw CancellationError() + } + guard let next else { + body.redirectChain = chain + return (body, response) + } + body.cancel() + current = next + } + #else + // The lifetime ends at the transport's disconnect(). + guard streaming.lifetime.begin() else { throw MCPError.connectionClosed } + // `bytes(for:)` creates its task after a suspension, so the + // session stays valid until it returns. + defer { streaming.lifetime.end() } + let delegate = streaming.redirects.map(HTTPRedirectTaskDelegate.init(policy:)) + let (bytes, response): (URLSession.AsyncBytes, URLResponse) + do { + (bytes, response) = try await withTaskCancellationHandler { + try await self.bytes(for: request, delegate: delegate) + } onCancel: { + delegate?.cancel() + } + } catch { + // A redirect decision still runs when the task failed. + delegate?.cancel() + throw error + } + var body = ResponseBody(bytes: bytes) + if Task.isCancelled { + body.cancel() + throw CancellationError() + } + if let delegate { body.redirectChain = delegate.chain } + return (body, response) + #endif + } + + #if canImport(FoundationNetworking) + /// The response to `request` and its body, without following redirects. + private func streamingResponseBody( + for request: URLRequest, streaming: StreamingSession + ) async throws -> (ResponseBody, URLResponse) { + // The lifetime ends at the transport's disconnect(). + guard streaming.lifetime.begin() else { throw MCPError.connectionClosed } + let task = streaming.session.dataTask(with: request) let (chunks, continuation) = AsyncThrowingStream.makeStream() let cancellation = ResponseBody.Cancellation() // A body nobody reads any more stops its task. The handler runs @@ -256,14 +330,8 @@ extension URLSession { let response = try await streaming.delegate.start( task, body: continuation, resumed: streaming.lifetime.end) return (ResponseBody(chunks: chunks, task: task, cancellation: cancellation), response) - #else - // `bytes(for:)` creates its task after a suspension, so the - // session stays valid until it returns. - defer { streaming.lifetime.end() } - let (bytes, response) = try await self.bytes(for: request, delegate: streaming.redirects) - return (ResponseBody(bytes: bytes), response) - #endif - } + } + #endif } /// The session that streams response bodies on swift-corelibs-foundation; on @@ -272,10 +340,10 @@ struct StreamingSession: Sendable { #if canImport(FoundationNetworking) let session: URLSession let delegate: StreamingSessionDelegate - #else - /// The task delegate that checks the redirects, if any. - let redirects: OAuthRedirectGuard? #endif + /// The policy that decides the redirects, if any: on Apple platforms + /// through an ``HTTPRedirectTaskDelegate`` for each request. + let redirects: (any HTTPRedirectDeciding)? let lifetime = Lifetime() /// Orders the creation of tasks against invalidation: a session @@ -323,7 +391,8 @@ struct StreamingSession: Sendable { /// A session with `configuration` that follows the redirects /// `redirects` allows, or every redirect. - init(configuration: URLSessionConfiguration, redirects: OAuthRedirectGuard? = nil) { + init(configuration: URLSessionConfiguration, redirects: (any HTTPRedirectDeciding)? = nil) { + self.redirects = redirects #if canImport(FoundationNetworking) let delegate = StreamingSessionDelegate(redirects: redirects) self.delegate = delegate @@ -331,8 +400,6 @@ struct StreamingSession: Sendable { // server card fetches, which revalidate with their own ETag. self.session = URLSession( configuration: configuration.withoutURLCache(), delegate: delegate, delegateQueue: nil) - #else - self.redirects = redirects #endif } diff --git a/Sources/MCP/Base/Transports/ServerSentEvents.swift b/Sources/MCP/Base/Transports/ServerSentEvents.swift index 8cab9eb8..7608835e 100644 --- a/Sources/MCP/Base/Transports/ServerSentEvents.swift +++ b/Sources/MCP/Base/Transports/ServerSentEvents.swift @@ -8,7 +8,8 @@ struct ServerSentEvent: Equatable, Sendable { var event: String? /// The `data` lines, joined with line feeds. var data: String - /// The `retry` field, when it is ASCII digits only. + /// The `retry` field, when it is ASCII digits only; `Int.max` when the + /// digits are past `Int`'s range. var retry: Int? } @@ -124,10 +125,10 @@ struct ServerSentEventParser { guard !value.contains("\0") else { return nil } id = value case "retry": - guard !value.isEmpty, value.allSatisfy({ $0.isASCII && $0.isNumber }), - let milliseconds = Int(value) - else { return nil } - retry = milliseconds + guard !value.isEmpty, value.allSatisfy({ $0.isASCII && $0.isNumber }) else { return nil } + // Digits past `Int`'s range (32 bits on arm64_32) saturate, so a + // huge value is clamped the same way on every platform. + retry = Int(value) ?? .max default: return nil } diff --git a/Sources/MCP/Base/Transports/StdioTransport.swift b/Sources/MCP/Base/Transports/StdioTransport.swift index fa2067fd..ad5fd527 100644 --- a/Sources/MCP/Base/Transports/StdioTransport.swift +++ b/Sources/MCP/Base/Transports/StdioTransport.swift @@ -1,6 +1,8 @@ import Logging +import Dispatch import struct Foundation.Data +import Synchronization #if canImport(System) import System @@ -20,14 +22,22 @@ import struct Foundation.Data #if canImport(Darwin) || canImport(Glibc) || canImport(Musl) /// An implementation of the MCP stdio transport protocol. /// - /// This transport implements the [stdio transport](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#stdio) + /// This transport implements the [stdio transport](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#stdio) /// specification from the Model Context Protocol. /// /// The stdio transport works by: /// - Reading JSON-RPC messages from standard input /// - Writing JSON-RPC messages to standard output /// - Using newline characters as message delimiters - /// - Supporting non-blocking I/O operations + /// + /// The transport never changes the descriptors' flags: it works with blocking and + /// non-blocking descriptors alike. On a pipe, a socket or a terminal it waits until the + /// descriptor is ready before each read and write; the wait blocks no thread, and + /// ``disconnect()`` ends a read or a send that is waiting. A regular file, or a device + /// such as `/dev/null`, is read and written directly. The read or write itself runs on the + /// transport's actor, so on a blocking descriptor that another process reads or writes too, + /// or on a terminal that reports room for less than `PIPE_BUF` bytes, one call can block, + /// and the transport waits for it. /// /// This transport is the recommended option for most MCP applications due to its /// simplicity and broad platform support. @@ -37,8 +47,13 @@ import struct Foundation.Data /// The limit is fixed, as it is for an SSE line on `HTTPClientTransport`: no setting /// raises or removes it. /// - /// - Important: This transport is available on Apple platforms and Linux distributions with glibc - /// (Ubuntu, Debian, Fedora, CentOS, RHEL). + /// The end of the input finishes the receive stream normally. A read that fails, for + /// example with `EIO`, finishes it by throwing ``MCPError/transportError(_:)`` with the + /// error, so a ``Client`` fails its pending requests with that error instead of + /// ``MCPError/connectionClosed``, and ``Server/waitUntilCompleted()`` throws it. + /// + /// - Important: This transport is available on Apple platforms, Linux distributions with + /// glibc (Ubuntu, Debian, Fedora, CentOS, RHEL), and the static Linux SDK (musl). /// /// ## Example Usage /// @@ -59,31 +74,40 @@ import struct Foundation.Data public nonisolated let logger: Logger private var isConnected = false + /// Whether ``disconnect()`` ran: the transport cannot connect again. + private var isClosed = false private var readTask: Task? private var disconnectTask: Task? + /// The queue the readiness sources of both descriptors run their handlers on. + private let queue = DispatchQueue(label: "mcp.transport.stdio") + /// Waits until `input` can be read; set by ``connect()``. + private var readable: DescriptorReadiness? + /// Waits until `output` can be written; set by ``connect()``. + private var writable: DescriptorReadiness? /// The sends in progress, including those waiting for their turn. Tests wait on it. private(set) var activeSends = 0 private var sendsDrained: CheckedContinuation? - /// Whether a send holds the output. A send can suspend mid-frame on `EAGAIN`, so - /// the others wait in `sendWaiters`, oldest first, and are handed the output in turn. + /// Whether a send holds the output. A send can suspend mid-frame waiting for room, + /// so the others wait in `sendWaiters`, oldest first, and are handed the output in turn. private var isSending = false private var sendWaiters: [(id: UInt64, continuation: CheckedContinuation)] = [] private var nextSendWaiterID: UInt64 = 0 private let messageStream: AsyncThrowingStream private let messageContinuation: AsyncThrowingStream.Continuation - private struct DescriptorState { - let flags: CInt - let device: UInt64 - let inode: UInt64 - } - private var inputState: DescriptorState? - private var outputState: DescriptorState? /// The bytes the read buffer's storage spans after the last read was parsed: the /// unparsed remainder, plus any consumed prefix still held. Tests check it stays bounded. private(set) var receiveBufferSpan = 0 /// The bytes the read loop has searched for a newline. Tests check that a message read /// in many pieces is searched once, not again with each read. private(set) var searchedByteCount = 0 + /// The `read` calls the read loop has made, those that failed included. Tests check that + /// an idle transport makes none. + private(set) var readCount = 0 + /// The bytes the read loop has read. Tests use it to end a write where a read ends. + private(set) var receivedByteCount = 0 + /// The times sends have waited for room in the output. Tests check that a send to an + /// output with room doesn't wait. + private(set) var sendWaitCount = 0 /// The most bytes a received message may hold: the limit of one SSE line in /// `HTTPClientTransport`. A longer message ends the receive stream. @@ -92,6 +116,19 @@ import struct Foundation.Data /// The error of a received message longer than `maxMessageLength`. static let messageTooLong = "Message longer than 16 MiB" + /// The most bytes one `write` to a blocking descriptor sends. A pipe reported writable + /// has room for `PIPE_BUF` bytes (POSIX `write`; kqueue and epoll report a pipe writable + /// at that mark), and a socket reported writable has at least its send low-water mark + /// free (`SO_SNDLOWAT`, 2048 bytes on Darwin, where `PIPE_BUF` is 512; Linux reports a + /// Unix socket writable once three quarters of its send buffer are free, far more than + /// its `PIPE_BUF` of 4096), so such a write returns without blocking. A terminal can + /// report room for less, and then the write blocks until the terminal takes the rest. + static let blockingWriteLength = Int(PIPE_BUF) + + /// The bytes a read loop or a send moves without waiting before it lets other work on + /// the actor run, such as ``disconnect()`` or the other direction. + static let bytesBetweenYields = 64 * 1024 + /// Creates a new stdio transport with the specified file descriptors /// /// - Parameters: @@ -119,85 +156,54 @@ import struct Foundation.Data /// Establishes connection with the transport /// - /// This method configures the file descriptors for non-blocking I/O - /// and starts the background message reading loop. + /// This method checks both file descriptors and starts the background message + /// reading loop. It doesn't change the descriptors' flags. /// - /// - Throws: Error if the file descriptors cannot be configured + /// - Throws: ``MCPError/transportError(_:)`` when a descriptor is not open, and + /// `MCPError.internalError` when the transport is already connected or + /// was disconnected. public func connect() async throws { - await disconnectTask?.value - guard !isConnected else { return } + guard !isConnected else { + throw MCPError.internalError("Transport already connected") + } + guard !isClosed else { + throw MCPError.internalError("Transport disconnected; create a new transport to reconnect") + } - // Set non-blocking mode - let originalInputState = try setNonBlocking(fileDescriptor: input) + let readable = try DescriptorReadiness(input, for: .read, queue: queue) + let writable: DescriptorReadiness do { - outputState = try setNonBlocking(fileDescriptor: output) + writable = try DescriptorReadiness(output, for: .write, queue: queue) } catch { - restoreFlags(originalInputState, for: input) + await readable.close() throw error } - inputState = originalInputState + self.readable = readable + self.writable = writable isConnected = true logger.debug("Transport connected successfully") // Start reading loop in background readTask = Task { - await readLoop() + await readLoop(readable) } } - /// Configures a file descriptor for non-blocking I/O - /// - /// - Parameter fileDescriptor: The file descriptor to configure - /// - Throws: Error if the operation fails - private func setNonBlocking(fileDescriptor: FileDescriptor) throws -> DescriptorState { - #if canImport(Darwin) || canImport(Glibc) || canImport(Musl) - // Get current flags - let flags = fcntl(fileDescriptor.rawValue, F_GETFL) - guard flags >= 0 else { - throw MCPError.transportError(Errno(rawValue: CInt(errno))) - } - var status = stat() - guard fstat(fileDescriptor.rawValue, &status) == 0 else { - throw MCPError.transportError(Errno(rawValue: CInt(errno))) - } - - // Set non-blocking flag - let result = fcntl(fileDescriptor.rawValue, F_SETFL, flags | O_NONBLOCK) - guard result >= 0 else { - throw MCPError.transportError(Errno(rawValue: CInt(errno))) - } - return DescriptorState( - flags: flags, device: UInt64(truncatingIfNeeded: status.st_dev), - inode: UInt64(truncatingIfNeeded: status.st_ino)) - #else - // For platforms where non-blocking operations aren't supported - throw MCPError.internalError( - "Setting non-blocking mode not supported on this platform") - #endif - } - - private func restoreFlags(_ state: DescriptorState, for fileDescriptor: FileDescriptor) { - guard state.flags & O_NONBLOCK == 0 else { return } - var status = stat() - guard fstat(fileDescriptor.rawValue, &status) == 0, - UInt64(truncatingIfNeeded: status.st_dev) == state.device, - UInt64(truncatingIfNeeded: status.st_ino) == state.inode - else { return } - let currentFlags = fcntl(fileDescriptor.rawValue, F_GETFL) - guard currentFlags >= 0 else { return } - if fcntl(fileDescriptor.rawValue, F_SETFL, currentFlags & ~O_NONBLOCK) < 0 { - logger.warning("Failed to restore file descriptor blocking mode") - } + /// Whether `error` is `EAGAIN`: a read or write on a descriptor that the caller made + /// non-blocking found no data, or no room. + private static func wouldBlock(_ error: any Swift.Error) -> Bool { + (error as? Errno) == .resourceTemporarilyUnavailable } /// Continuous loop that reads and processes incoming messages /// /// This method runs in the background while the transport is connected, /// parsing complete messages delimited by newlines and yielding them - /// to the message stream. A message longer than `maxMessageLength` - /// ends the stream with `internalError`. - private func readLoop() async { + /// to the message stream. Before each read it waits until the input is + /// readable. A message longer than `maxMessageLength` ends the stream + /// with `internalError`, and a failed read with `transportError`. + private func readLoop(_ readable: DescriptorReadiness) async { let bufferSize = 4096 var buffer = [UInt8](repeating: 0, count: bufferSize) var pendingData = Data() @@ -205,9 +211,30 @@ import struct Foundation.Data // read searches only the bytes it added. var searched = 0 var failure: MCPError? + // Whether the last read found no data: the next one waits for the source, whatever + // `poll` says. + var mustWait = false + var bytesSinceYield = 0 while isConnected && !Task.isCancelled { do { + // Reading without waiting keeps the actor until the input runs dry; give + // sends and disconnect() a turn now and then. + if bytesSinceYield >= Self.bytesBetweenYields { + bytesSinceYield = 0 + await Task.yield() + continue + } + // A readable descriptor returns at least one byte, or 0 at the end of the + // input, without blocking, whatever its flags. Waiting hops off the actor, + // so only wait when the input isn't readable now. + if mustWait || !readable.isReadyNow() { + try await readable.wait(cancellable: true, afterWouldBlock: mustWait) + bytesSinceYield = 0 + guard isConnected else { break } + } + mustWait = false + readCount &+= 1 let bytesRead = try buffer.withUnsafeMutableBufferPointer { pointer in try input.read(into: UnsafeMutableRawBufferPointer(pointer)) } @@ -216,8 +243,10 @@ import struct Foundation.Data logger.notice("EOF received") break } + receivedByteCount &+= bytesRead + bytesSinceYield += bytesRead - pendingData.append(Data(buffer[.. 0 { await withCheckedContinuation { continuation in sendsDrained = continuation } } - if let inputState { restoreFlags(inputState, for: input) } - if let outputState { restoreFlags(outputState, for: output) } - inputState = nil - outputState = nil readTask = nil + self.readable = nil + self.writable = nil messageContinuation.finish() } disconnectTask = cleanup @@ -319,12 +366,23 @@ import struct Foundation.Data /// task is cancelled, so the next message doesn't continue a partial line. If the peer /// stops reading but keeps the pipe open, only ``disconnect()`` ends such a send. /// - /// - Parameter message: The message data to send (without a trailing newline) - /// - Throws: Error if the message cannot be sent, or `CancellationError` if the task is + /// The end of the input doesn't close the output, and neither does a failed read: a + /// peer that closes its end of the input pipe can still read what is sent, until + /// ``disconnect()``. + /// + /// - Parameters: + /// - message: The message data to send (without a trailing newline) + /// - options: Ignored: stdio has no streams per request and no headers. + /// - Throws: ``MCPError/connectionClosed`` after ``disconnect()``, + /// ``MCPError/transportError(_:)`` (`ENOTCONN`) before ``connect()``, + /// `CancellationError` if the task is /// cancelled while the message waits for an earlier one or for room in the output, - /// before any of it is written - public func send(_ message: Data) async throws { - guard isConnected else { + /// before any of it is written, or the error of the write. + public func send(_ message: Data, options: TransportSendOptions) async throws { + guard !isClosed else { + throw MCPError.connectionClosed + } + guard isConnected, let writable else { throw MCPError.transportError(Errno(rawValue: ENOTCONN)) } activeSends += 1 @@ -342,39 +400,63 @@ import struct Foundation.Data var messageWithNewline = message messageWithNewline.append(UInt8(ascii: "\n")) - var remaining = messageWithNewline + // A write to a blocking pipe, socket or terminal waits for room first, and writes + // what that room holds. A non-blocking descriptor is written at once and fails with + // `EAGAIN` when full; a regular file or a device such as /dev/null is always ready. + // Waiting hops off the actor, so it waits only when the output has no room now. + var wouldBlock = false + var bytesSinceYield = 0 + // Read once before the loop and refresh after a readiness wait, EAGAIN, or yield + // so a blocking pipe does not invoke fcntl(F_GETFL) on every PIPE_BUF chunk. + var isBlocking = writable.waitsForReadiness && !Self.isNonBlocking(output) + var remaining = messageWithNewline[...] while !remaining.isEmpty { + // Writing without waiting keeps the actor until the output fills; give the + // read loop and disconnect() a turn now and then. + if bytesSinceYield >= Self.bytesBetweenYields { + bytesSinceYield = 0 + await Task.yield() + isBlocking = writable.waitsForReadiness && !Self.isNonBlocking(output) + } guard isConnected else { - throw MCPError.transportError(Errno(rawValue: ENOTCONN)) + throw MCPError.connectionClosed + } + // Nothing is written yet, so a cancelled send passes the output on. Once part + // of the line is out, finish it even if cancelled, or the next send's message + // would continue that line. + let nothingWritten = remaining.count == messageWithNewline.count + if wouldBlock || (isBlocking && !writable.isReadyNow()) { + // After EAGAIN, checks cancellation and awaits the source; otherwise + // returns at once when the output has room. + sendWaitCount &+= 1 + try await writable.wait(cancellable: nothingWritten, afterWouldBlock: wouldBlock) + bytesSinceYield = 0 + guard isConnected else { + throw MCPError.connectionClosed + } + isBlocking = writable.waitsForReadiness && !Self.isNonBlocking(output) } do { - let written = try remaining.withUnsafeBytes { buffer in + let chunk = isBlocking ? remaining.prefix(Self.blockingWriteLength) : remaining + let written = try chunk.withUnsafeBytes { buffer in try output.write(UnsafeRawBufferPointer(buffer)) } - if written > 0 { - remaining = remaining.dropFirst(written) - } - } catch let error where MCPError.isResourceTemporarilyUnavailable(error) { - if remaining.count == messageWithNewline.count { - // Nothing is written yet, so a cancelled send passes the output on. - try await Task.sleep(for: .milliseconds(10)) - } else { - // Part of the line is out: finish it even if cancelled, or the next - // send's message would continue that line. - await Self.sleepIgnoringCancellation(for: .milliseconds(10)) - } - continue + remaining = remaining.dropFirst(written) + bytesSinceYield += written + wouldBlock = false + } catch let error where Self.wouldBlock(error) { + wouldBlock = true + isBlocking = writable.waitsForReadiness && !Self.isNonBlocking(output) } catch { throw MCPError.transportError(error) } } } - /// Sleeps for `duration` even if the current task is cancelled. - private static func sleepIgnoringCancellation(for duration: Duration) async { - // An unstructured task isn't cancelled with the task that awaits it, and nothing - // else cancels it, so it always sleeps the full duration. - _ = await Task { try await Task.sleep(for: duration) }.result + /// Whether `descriptor` is in non-blocking mode. Reads its flags without changing them. + private static func isNonBlocking(_ descriptor: FileDescriptor) -> Bool { + let flags = fcntl(descriptor.rawValue, F_GETFL) + return flags >= 0 && flags & O_NONBLOCK != 0 } /// Waits until no other send holds the output, then takes it. @@ -386,7 +468,7 @@ import struct Foundation.Data return } let id = nextSendWaiterID - nextSendWaiterID += 1 + nextSendWaiterID &+= 1 try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { continuation in sendWaiters.append((id: id, continuation: continuation)) @@ -422,9 +504,262 @@ import struct Foundation.Data /// or batches containing multiple requests/notifications encoded as JSON arrays. /// Each message is guaranteed to be a complete JSON object or array. /// + /// Every call returns the same stream; iterate it from one task only. It finishes at + /// the end of the input and at ``disconnect()``. A read that fails, such as with `EIO`, + /// or with `ECONNRESET` on a socket, finishes it by throwing + /// ``MCPError/transportError(_:)`` with the error. After the end of the input or a + /// failed read, sends still work until ``disconnect()``: the output is a descriptor of + /// its own. + /// /// - Returns: An AsyncThrowingStream of Data objects representing JSON-RPC messages public func receive() -> AsyncThrowingStream { return messageStream } } + + // MARK: - DescriptorReadiness + + /// Waits until a descriptor can be read or written, without changing its flags. + /// + /// A pipe, a socket or a terminal is watched by a dispatch source, created once and kept + /// suspended while nobody waits, so an idle descriptor costs no wake-ups. A `poll` that + /// doesn't wait checks the descriptor before each wait and after each wake-up. Other + /// descriptors are always ready: POSIX `select` reports a regular file ready, kqueue never + /// reports one at its end ready, and epoll refuses regular files and devices such as + /// /dev/null, whose reads and writes don't block. + // @unchecked Sendable: `source` is a dispatch source, which libdispatch lets any thread + // resume, suspend and cancel; this class calls those only while it holds `state`, so the + // source's suspend count stays balanced. Every mutable field is in `state`, behind a Mutex. + final class DescriptorReadiness: @unchecked Sendable { + /// Whether to wait until the descriptor can be read, or written. + enum Direction { + case read + case write + } + + private struct Waiter { + let id: UInt64 + let continuation: CheckedContinuation + let isCancellable: Bool + } + + private struct State { + var waiters: [Waiter] = [] + var nextWaiterID: UInt64 = 0 + /// Whether the source is resumed. A new source is inactive, which `resume()` ends + /// as it ends a suspension. + var isRunning = false + var isClosed = false + /// Whether the source no longer watches the descriptor: its cancel handler ran. + var isReleased = false + var releaseWaiters: [CheckedContinuation] = [] + } + + private let descriptor: FileDescriptor + private let direction: Direction + /// The source, or `nil` for a descriptor that is always ready. + private let source: (any DispatchSourceProtocol)? + private let state = Mutex(State()) + + /// Whether the descriptor is watched for readiness, rather than always ready. + var waitsForReadiness: Bool { source != nil } + + /// Creates a waiter for `descriptor`, whose source runs its handlers on `queue`. + /// + /// - Throws: ``MCPError/transportError(_:)`` when the descriptor is not open. + init(_ descriptor: FileDescriptor, for direction: Direction, queue: DispatchQueue) throws { + var status = stat() + guard fstat(descriptor.rawValue, &status) == 0 else { + throw MCPError.transportError(Errno(rawValue: errno)) + } + let type = status.st_mode & mode_t(S_IFMT) + let watched = + type == mode_t(S_IFIFO) || type == mode_t(S_IFSOCK) || isatty(descriptor.rawValue) == 1 + self.descriptor = descriptor + self.direction = direction + guard watched else { + self.source = nil + state.withLock { $0.isReleased = true } + return + } + let source: any DispatchSourceProtocol = + switch direction { + case .read: DispatchSource.makeReadSource(fileDescriptor: descriptor.rawValue, queue: queue) + case .write: DispatchSource.makeWriteSource(fileDescriptor: descriptor.rawValue, queue: queue) + } + self.source = source + source.setEventHandler { [weak self] in self?.descriptorIsReady() } + source.setCancelHandler { [weak self] in self?.sourceIsReleased() } + } + + deinit { + // `close()` normally ran. A source must not be released while inactive or + // suspended, so end both. + state.withLock { state in + guard !state.isClosed else { return } + state.isClosed = true + source?.cancel() + if !state.isRunning { + state.isRunning = true + source?.resume() + } + } + } + + /// Returns once the descriptor is ready: at once when it is ready now, even if the task + /// is cancelled. + /// + /// A wake-up the descriptor no longer backs, such as an event the source delivers once + /// resumed for data read since, is checked and waited out, so a read or write on a + /// blocking descriptor that follows doesn't block. + /// + /// - Parameters: + /// - cancellable: Whether cancelling the task ends the wait. + /// - afterWouldBlock: Whether the preceding non-blocking I/O call returned `EAGAIN`: + /// checks cancellation and awaits the source before re-checking `poll`. + /// - Throws: ``MCPError/connectionClosed`` after ``close()``; `CancellationError` when + /// `cancellable` and the task is cancelled while the descriptor isn't ready. + func wait(cancellable: Bool, afterWouldBlock: Bool = false) async throws { + guard source != nil else { + try state.withLock { state in + if state.isClosed { throw MCPError.connectionClosed } + } + if afterWouldBlock && cancellable && Task.isCancelled { throw CancellationError() } + // Lets the actor that waits run other work between reads of a long file. + await Task.yield() + return + } + var woke = false + var skipInitialPoll = afterWouldBlock + while true { + try state.withLock { state in + if state.isClosed { throw MCPError.connectionClosed } + } + if !skipInitialPoll { + switch readinessNow() { + case true?: return + // `poll` can't tell: trust the source once it fired. + case nil where woke: return + default: break + } + } + skipInitialPoll = false + try await nextEvent(cancellable: cancellable) + woke = true + } + } + + /// Returns at the source's next event. + private func nextEvent(cancellable: Bool) async throws { + let id = state.withLock { state in + defer { state.nextWaiterID &+= 1 } + return state.nextWaiterID + } + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + let failure: (any Swift.Error)? = state.withLock { state in + if state.isClosed { return MCPError.connectionClosed } + if cancellable && Task.isCancelled { return CancellationError() } + state.waiters.append( + Waiter(id: id, continuation: continuation, isCancellable: cancellable)) + if !state.isRunning { + state.isRunning = true + source?.resume() + } + return nil + } + if let failure { continuation.resume(throwing: failure) } + } + } onCancel: { + guard cancellable else { return } + let waiter = state.withLock { state -> Waiter? in + guard let index = state.waiters.firstIndex(where: { $0.id == id }) else { return nil } + let waiter = state.waiters.remove(at: index) + if state.waiters.isEmpty && state.isRunning && !state.isClosed { + state.isRunning = false + source?.suspend() + } + return waiter + } + waiter?.continuation.resume(throwing: CancellationError()) + } + } + + /// Whether the descriptor is ready now, without waiting: an always-ready descriptor + /// is, and a watched one when a `poll` that doesn't wait says so. Callers that get + /// `false` call ``wait(cancellable:)``. + func isReadyNow() -> Bool { + source == nil || readinessNow() == true + } + + /// Whether the descriptor is ready now, from a `poll` that doesn't wait; `nil` when + /// `poll` can't tell. + private func readinessNow() -> Bool? { + let events = direction == .read ? POLLIN : POLLOUT + var entry = pollfd(fd: descriptor.rawValue, events: Int16(events), revents: 0) + var result: CInt + repeat { + result = poll(&entry, 1, 0) + } while result < 0 && errno == EINTR + guard result >= 0, entry.revents & Int16(POLLNVAL) == 0 else { return nil } + // An error or hang-up is ready too: the read or write that follows reports it. + return result == 1 + } + + /// Wakes every waiter with ``MCPError/connectionClosed``, and returns once the source + /// no longer watches the descriptor, so its owner may close it. + func close() async { + let waiters = state.withLock { state -> [Waiter] in + guard !state.isClosed else { return [] } + state.isClosed = true + source?.cancel() + if !state.isRunning { + // The cancel handler of an inactive or suspended source runs once resumed. + state.isRunning = true + source?.resume() + } + defer { state.waiters = [] } + return state.waiters + } + for waiter in waiters { + waiter.continuation.resume(throwing: MCPError.connectionClosed) + } + await withCheckedContinuation { (continuation: CheckedContinuation) in + let isReleased = state.withLock { state in + if !state.isReleased { state.releaseWaiters.append(continuation) } + return state.isReleased + } + if isReleased { continuation.resume() } + } + } + + /// The source's event handler: resumes the waiters and suspends the source until the + /// next wait. + private func descriptorIsReady() { + let waiters = state.withLock { state -> [Waiter] in + guard !state.isClosed else { return [] } + if state.isRunning { + state.isRunning = false + source?.suspend() + } + defer { state.waiters = [] } + return state.waiters + } + for waiter in waiters { + waiter.continuation.resume() + } + } + + /// The source's cancel handler. + private func sourceIsReleased() { + let waiters = state.withLock { state in + state.isReleased = true + defer { state.releaseWaiters = [] } + return state.releaseWaiters + } + for waiter in waiters { + waiter.resume() + } + } + } #endif diff --git a/Sources/MCP/Base/UnknownBlock.swift b/Sources/MCP/Base/UnknownBlock.swift index abddabd4..6e63c177 100644 --- a/Sources/MCP/Base/UnknownBlock.swift +++ b/Sources/MCP/Base/UnknownBlock.swift @@ -3,14 +3,15 @@ import Foundation /// The coding of blocks and requests whose kind the SDK does not know: the /// whole JSON object, kept as received. enum UnknownBlock { - /// The object `decoder` holds, with strings as written: a `data:` URL - /// stays a string, so the block encodes back to the same JSON value, - /// except that a number is read as an `Int` or a `Double`, so one outside - /// their range or precision is rounded. The bytes can differ: key order, - /// whitespace, string escapes and number formatting may change (`1.0` is - /// written `1`). + /// The whole JSON object `decoder` holds, kept as a `Value`. + /// + /// It encodes back to the same JSON, strings exactly as sent, except that + /// a number is read as an `Int` or a `Double`, so one outside their range + /// or precision can change value, not only spelling. The bytes can + /// differ: key order, whitespace, string escapes and number formatting + /// (`1.0` is written `1`). static func decode(from decoder: any Decoder) throws -> Value { - try Value.Preserved(from: decoder).value + try Value(from: decoder) } /// Encodes `value` with its kind under `key` (`type` for content blocks). diff --git a/Sources/MCP/Base/Utilities/Progress.swift b/Sources/MCP/Base/Utilities/Progress.swift index 763ed6f1..c399ea26 100644 --- a/Sources/MCP/Base/Utilities/Progress.swift +++ b/Sources/MCP/Base/Utilities/Progress.swift @@ -54,10 +54,18 @@ public struct ProgressNotification: Notification { /// A token used to associate progress notifications with their originating request. /// -/// Progress tokens can be either strings or integers. -/// Progress tokens MUST be unique across all active requests. +/// Progress tokens can be either strings or integers, chosen by the sender +/// of the request, and MUST be unique across all active requests; the +/// receiver sends them back unchanged. Two tokens are the same token when +/// their JSON values are: `.string("1")` and `.integer(1)` differ, and so do +/// two strings with different Unicode scalars. Equality and hashing compare +/// a string's scalars exactly, as ``ID`` does, unlike Swift `String` +/// equality, which treats canonically equivalent spellings such as +/// `"\u{E9}"` and `"e\u{301}"` as equal. /// /// Frozen: no case is added in 1.x (a progress token is a string or an integer). +/// +/// - SeeAlso: https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/progress public enum ProgressToken: Hashable, Codable, Sendable { /// A string token. case string(String) @@ -92,6 +100,34 @@ public enum ProgressToken: Hashable, Codable, Sendable { public static func unique() -> ProgressToken { .string(UUID().uuidString) } + + /// Returns whether two tokens are the same token: integers that are + /// equal, or strings with the same Unicode scalars. + /// + /// - Complexity: O(*n*), where *n* is the length of the strings in UTF-8. + public static func == (lhs: ProgressToken, rhs: ProgressToken) -> Bool { + switch (lhs, rhs) { + case (.integer(let lhs), .integer(let rhs)): + return lhs == rhs + case (.string(let lhs), .string(let rhs)): + return lhs.isExactly(rhs) + case (.integer, .string), (.string, .integer): + return false + } + } + + /// Hashes the case and the integer, or the string's UTF-8 bytes, so + /// tokens that are equal hash alike. + public func hash(into hasher: inout Hasher) { + switch self { + case .integer(let integer): + hasher.combine(0) + hasher.combine(integer) + case .string(let string): + hasher.combine(1) + string.hashExactly(into: &hasher) + } + } } /// Metadata that can be included in request parameters. diff --git a/Sources/MCP/Base/Value.swift b/Sources/MCP/Base/Value.swift index 978d0d04..1aa8f7b2 100644 --- a/Sources/MCP/Base/Value.swift +++ b/Sources/MCP/Base/Value.swift @@ -4,7 +4,7 @@ import class Foundation.JSONEncoder /// A codable value. /// -/// Frozen: no case is added in 1.x (the cases are the JSON data model, plus `data`). +/// Frozen: no case is added in 1.x (the cases are the JSON data model). public enum Value: Hashable, Sendable { /// JSON `null`. case null @@ -16,18 +16,6 @@ public enum Value: Hashable, Sendable { case double(Double) /// A JSON string. case string(String) - /// Binary data, encoded as a `data:` URL string with its MIME type, if any. - /// - /// A plain decode gives this case for a string that is a whole `data:` - /// URL, always with a MIME type. ``Value/init(from:)`` gives the rules - /// and lists where the SDK decodes plainly, so that a tool argument or - /// `structuredContent` can hold this case. - /// - /// This case encodes as `data:;base64,`, with - /// `text/plain` for a `nil` MIME type. The spelling of the decoded - /// string is not kept: `data:,hi` encodes as - /// `data:text/plain;base64,aGk=`. - case data(mimeType: String? = nil, Data) /// A JSON array. case array([Value]) /// A JSON object. @@ -36,8 +24,7 @@ public enum Value: Hashable, Sendable { /// Create a `Value` from an `Encodable` value. /// /// A `Value` is returned as is. Any other value is encoded and the JSON - /// is decoded plainly: a string that is a whole `data:` URL becomes - /// ``Value/data(mimeType:_:)``. See ``Value/init(from:)`` for the rules. + /// is decoded as ``Value/init(from:)`` describes. Strings stay strings. /// - Parameter value: The encodable value /// - Returns: A value public init(_ value: T) throws { @@ -49,21 +36,6 @@ public enum Value: Hashable, Sendable { } } - /// Creates a `Value` that encodes to the same JSON as `value`: strings, - /// including `data:` URLs, stay strings. - static func preservingStrings(_ value: T) throws -> Value { - if let valueAsValue = value as? Value { return valueAsValue } - let decoder = JSONDecoder() - decoder.userInfo[.valuePreservesStrings] = true - return try decoder.decode(Value.self, from: JSONEncoder().encode(value)) - } - - /// The value a plain `JSONDecoder` gives for the JSON this value encodes - /// to: `data:` URL strings become `.data`. - var decodingDataURLs: Value { - (try? JSONDecoder().decode(Value.self, from: JSONEncoder().encode(self))) ?? self - } - /// Returns whether the value is `null`. public var isNull: Bool { return self == .null @@ -122,11 +94,12 @@ public enum Value: Hashable, Sendable { return value } - /// Returns the data value and optional MIME type if the value is `data`, - /// otherwise returns `nil`. + /// Parses the value as a `data:` URL when it is a ``string(_:)``, returning its MIME type + /// and decoded bytes, or `nil` otherwise. + @available(*, deprecated, message: "Parse with DataURL(_:) instead") public var dataValue: (mimeType: String?, Data)? { - guard case let .data(mimeType: mimeType, data) = self else { return nil } - return (mimeType: mimeType, data) + guard case .string(let string) = self, let url = DataURL(string) else { return nil } + return (mimeType: url.mimeType, url.data) } /// Returns the `[Value]` value if the value is an `array`, @@ -146,85 +119,16 @@ public enum Value: Hashable, Sendable { // MARK: - Codable -extension CodingUserInfoKey { - /// When `true` in a decoder's `userInfo`, ``Value`` decodes `data:` URL - /// strings as `.string` instead of `.data`. - static let valuePreservesStrings = CodingUserInfoKey(rawValue: "mcp.value.preservesStrings")! -} - -extension Value { - /// A `Value` decoded with strings as written: a `data:` URL stays a - /// string, at any depth. It encodes as its value. - struct Preserved: Hashable, Codable, Sendable { - let value: Value - - func encode(to encoder: Encoder) throws { - try value.encode(to: encoder) - } - - init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - if container.decodeNil() { - value = .null - } else if let bool = try? container.decode(Bool.self) { - value = .bool(bool) - } else if let int = try? container.decode(Int.self) { - value = .int(int) - } else if let double = try? container.decode(Double.self) { - value = .double(double) - } else if let string = try? container.decode(String.self) { - value = .string(string) - } else if let array = try? container.decode([Preserved].self) { - value = .array(array.map(\.value)) - } else if let object = try? container.decode([String: Preserved].self) { - value = .object(object.mapValues(\.value)) - } else { - throw DecodingError.dataCorruptedError(in: container, debugDescription: "Value type not found") - } - } - } -} - extension Value: Codable { /// Creates a value from a decoder. /// /// The decoder tries `null`, `Bool`, `Int`, `Double`, `String`, an array - /// and an object, in this order. A string becomes - /// ``Value/data(mimeType:_:)`` when all of these are true: + /// and an object, in this order. /// - /// - The whole string is a `data:` URL (RFC 2397). It starts with - /// `data:` in lowercase, with no space before it. - /// - Before the first `,`, it has an optional media type, then an - /// optional `;charset=`, then an optional `;base64`. The media - /// type is `type/subtype`, and the type, the subtype and the charset - /// value are RFC 2045 tokens: printable ASCII with no space and none of - /// `()<>@,;:\"/[]?=`. - /// - The payload after that `,` decodes: it is valid base64, or every - /// `%` in it starts a well-formed `%XX` escape. Other text, spaces and - /// commas included, is allowed there. - /// - /// Other strings stay ``Value/string(_:)``, for example `DATA:,hi`, - /// `data: 3 rows, 2 columns`, a `data:` URL with a `;name=` parameter, - /// or text with a `data:` URL after its start. - /// - /// The MIME type of the result is never `nil`: it is `text/plain` for an - /// empty media type. `;charset=` is kept, in the MIME type, only for a - /// `text/` or empty media type, as in `text/plain;charset=utf-8`. For - /// other media types it is dropped. - /// - /// The SDK's own message paths keep strings as written: the message - /// decoders of `Client` and `Server`, type-erased requests and - /// responses, and handler results. These decodes are plain: - /// - /// - The typed decode of a handler's parameters, and of a result before - /// a request returns it. Thus a tool argument, `structuredContent`, an - /// elicitation's `content`, a multi round-trip answer and the `input` - /// of a sampling tool use can hold `.data`. - /// - The `data` of a decoded ``MCPError``. - /// - ``Value/init(_:)-(T)`` for a value that is not a `Value`. - /// `CallTool.Result(content:structuredContent:isError:_meta:)` uses it - /// for a `Codable` output, so a `data:` URL string in that output is - /// sent in its base64 form. + /// A string is always ``Value/string(_:)``, as written. A number is an + /// `Int` when it is a whole number in `Int`'s range, else a `Double`, so + /// a very large or very precise number can change value, not only + /// spelling. To read a `data:` URL string, use ``DataURL``. public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() @@ -237,14 +141,7 @@ extension Value: Codable { } else if let value = try? container.decode(Double.self) { self = .double(value) } else if let value = try? container.decode(String.self) { - if decoder.userInfo[.valuePreservesStrings] as? Bool != true, - Data.isDataURL(string: value), - case let (mimeType, data)? = Data.parseDataURL(value) - { - self = .data(mimeType: mimeType, data) - } else { - self = .string(value) - } + self = .string(value) } else if let value = try? container.decode([Value].self) { self = .array(value) } else if let value = try? container.decode([String: Value].self) { @@ -269,8 +166,6 @@ extension Value: Codable { try container.encode(value) case .string(let value): try container.encode(value) - case let .data(mimeType, value): - try container.encode(value.dataURLEncoded(mimeType: mimeType)) case .array(let value): try container.encode(value) case .object(let value): @@ -292,8 +187,6 @@ extension Value: CustomStringConvertible { return value.description case .string(let value): return value.description - case let .data(mimeType, value): - return value.dataURLEncoded(mimeType: mimeType) case .array(let value): return value.description case .object(let value): diff --git a/Sources/MCP/Client/Client.swift b/Sources/MCP/Client/Client.swift index df64062e..fa1d2fe1 100644 --- a/Sources/MCP/Client/Client.swift +++ b/Sources/MCP/Client/Client.swift @@ -110,19 +110,33 @@ public actor Client { } private enum CodingKeys: String, CodingKey { - case strict, protocolMode, logLevel, discoveryTimeout, multiRoundTrip, maxConcurrentServerRequests + case strict, protocolMode, logLevel, discoveryTimeoutMs, multiRoundTrip, maxConcurrentServerRequests case tasks, maxContextInclusion + // The `Duration` form of prereleases, still read. + case discoveryTimeout } /// Decodes a configuration; keys added after `strict` are optional. + /// + /// `discoveryTimeoutMs` holds ``discoveryTimeout`` in milliseconds: + /// `null` means no timeout, and an absent key or a value that is not + /// a non-negative number means the default, 10 seconds. A + /// configuration saved by a prerelease, with `discoveryTimeout` in + /// `Duration`'s own `Codable` form, still decodes. public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) strict = try container.decode(Bool.self, forKey: .strict) protocolMode = try container.decodeIfPresent(ProtocolMode.self, forKey: .protocolMode) ?? .automatic logLevel = try container.decodeIfPresent(LogLevel.self, forKey: .logLevel) - discoveryTimeout = - container.contains(.discoveryTimeout) - ? try container.decodeIfPresent(Duration.self, forKey: .discoveryTimeout) : .seconds(10) + if container.contains(.discoveryTimeoutMs) { + discoveryTimeout = + try container.decodeNil(forKey: .discoveryTimeoutMs) + ? nil : container.decodeDuration(forKey: .discoveryTimeoutMs) ?? .seconds(10) + } else if container.contains(.discoveryTimeout) { + discoveryTimeout = try container.decodeIfPresent(Duration.self, forKey: .discoveryTimeout) + } else { + discoveryTimeout = .seconds(10) + } multiRoundTrip = try container.decodeIfPresent(MultiRoundTrip.self, forKey: .multiRoundTrip) ?? .init() maxConcurrentServerRequests = try container.decodeIfPresent(Int.self, forKey: .maxConcurrentServerRequests) ?? 4 @@ -131,12 +145,18 @@ public actor Client { try container.decodeIfPresent(Sampling.ContextInclusion.self, forKey: .maxContextInclusion) ?? .none } + /// Encodes the configuration, with ``discoveryTimeout`` in whole + /// milliseconds under `discoveryTimeoutMs` (`null` for no timeout). + /// + /// A duration is rounded down to whole milliseconds, a positive one + /// shorter than a millisecond is written as 1, and a negative one as + /// 0. public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(strict, forKey: .strict) try container.encode(protocolMode, forKey: .protocolMode) try container.encodeIfPresent(logLevel, forKey: .logLevel) - try container.encode(discoveryTimeout, forKey: .discoveryTimeout) + try container.encodeMillisecondsOrNull(discoveryTimeout, forKey: .discoveryTimeoutMs) try container.encode(multiRoundTrip, forKey: .multiRoundTrip) try container.encode(maxConcurrentServerRequests, forKey: .maxConcurrentServerRequests) try container.encodeIfPresent(tasks, forKey: .tasks) @@ -144,6 +164,12 @@ public actor Client { } /// How the client uses tasks. + /// + /// Its `Codable` form holds each duration in whole milliseconds: + /// `minimumPollIntervalMs`, `maximumPollIntervalMs`, + /// `defaultPollIntervalMs` and `requestedTimeToLiveMs`. A duration is + /// rounded down to whole milliseconds, a positive one shorter than a + /// millisecond is written as 1, and a negative one as 0. public struct Tasks: Hashable, Codable, Sendable { /// The shortest wait between two polls of a task, whatever the /// server suggests. @@ -222,39 +248,46 @@ public actor Client { } private enum CodingKeys: String, CodingKey { - case minimumPollInterval, maximumPollInterval, defaultPollInterval, augmentation, requestedTTL + case minimumPollIntervalMs, maximumPollIntervalMs, defaultPollIntervalMs, augmentation + // Uses the 1.0 JSON key name ("requestedTimeToLiveMs"); the Swift property is `requestedTTL`. + case requestedTimeToLiveMs + // The `Duration` form of prereleases, still read. + case minimumPollInterval, maximumPollInterval, defaultPollInterval, requestedTTL } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(minimumPollInterval, forKey: .minimumPollInterval) - try container.encode(maximumPollInterval, forKey: .maximumPollInterval) - try container.encode(defaultPollInterval, forKey: .defaultPollInterval) + try container.encodeMilliseconds(minimumPollInterval, forKey: .minimumPollIntervalMs) + try container.encodeMilliseconds(maximumPollInterval, forKey: .maximumPollIntervalMs) + try container.encodeMilliseconds(defaultPollInterval, forKey: .defaultPollIntervalMs) try container.encode(augmentation, forKey: .augmentation) - try container.encodeIfPresent(requestedTTL, forKey: .requestedTTL) + try container.encodeMilliseconds(requestedTTL, forKey: .requestedTimeToLiveMs) } - /// Decodes the options; missing keys take their defaults. + /// Decodes the options; missing keys, and durations that are not + /// non-negative numbers, take their defaults. Options saved by a + /// prerelease, with durations in `Duration`'s own `Codable` form + /// under the property names, still decode. public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let defaults = Tasks() minimumPollInterval = - try container.decodeIfPresent(Duration.self, forKey: .minimumPollInterval) + try container.decodeDuration(forKey: .minimumPollIntervalMs, legacyKey: .minimumPollInterval) ?? defaults.minimumPollInterval maximumPollInterval = - try container.decodeIfPresent(Duration.self, forKey: .maximumPollInterval) + try container.decodeDuration(forKey: .maximumPollIntervalMs, legacyKey: .maximumPollInterval) ?? defaults.maximumPollInterval defaultPollInterval = - try container.decodeIfPresent(Duration.self, forKey: .defaultPollInterval) + try container.decodeDuration(forKey: .defaultPollIntervalMs, legacyKey: .defaultPollInterval) ?? defaults.defaultPollInterval augmentation = try container.decodeIfPresent(Augmentation.self, forKey: .augmentation) ?? defaults.augmentation - requestedTTL = try container.decodeIfPresent(Duration.self, forKey: .requestedTTL) + requestedTTL = try container.decodeDuration(forKey: .requestedTimeToLiveMs, legacyKey: .requestedTTL) } /// The wait before the next poll, from the server's suggestion. func pollInterval(suggested milliseconds: Int?) -> Duration { - let suggested = milliseconds.map { Duration.milliseconds($0) } ?? defaultPollInterval + let suggested = milliseconds.map(Duration.init(wireMilliseconds:)) ?? defaultPollInterval return min(max(suggested, minimumPollInterval), maximumPollInterval) } } @@ -462,11 +495,7 @@ public actor Client { /// The connection to the server private var connection: (any Transport)? /// The logger for the client - var logger: Logger? { - get async { - await connection?.logger - } - } + var logger: Logger? { connection?.logger } /// The client information private let clientInfo: Client.Info @@ -527,7 +556,11 @@ public actor Client { private(set) var subscribedResources: [String] = [] /// The subscribed URIs that `subscribeToResource` added and no stream has /// served yet; one is dropped when the last call waiting for it is cancelled. - private var unservedResources: Set = [] + private var unservedResources: Set = [] + /// Resource URIs whose `resources/subscribe` succeeded on this handshake + /// connection and that were not unsubscribed. Keyed by `ExactString` so + /// canonically equivalent spellings stay distinct. + private var handshakeSubscriptions: Set = [] /// `subscribeToResource` calls waiting for a stream that names their URI. private(set) var resourceWaiters: [(id: UUID, uri: String, continuation: CheckedContinuation)] = [] /// Multi round-trip exchanges in progress: first request id to the id of the current round. @@ -546,8 +579,8 @@ public actor Client { /// Tool names logged as invalid (SEP-986). private var toolNameWarnings = ToolNameWarnings() /// Task pollers waiting for the next poll, by task id then token; a task - /// notification wakes them early. - private var taskWakeups: [String: [Int: ResponseSlot]] = [:] + /// notification with the same code points wakes them early. + private var taskWakeups: [ExactString: [Int: ResponseSlot]] = [:] private var nextTaskWakeup = 0 /// `tools/call` requests awaiting their response. private(set) var pendingToolCalls: Set = [] @@ -556,7 +589,7 @@ public actor Client { private var abandonedToolCalls: [ID] = [] /// Tasks notified while no poller waited, oldest first, at most /// ``maxNotifiedTasks``: the next wait for one ends at once. - private var notifiedTasks: [String] = [] + private var notifiedTasks: [ExactString] = [] private static let maxNotifiedTasks = 256 /// Whether the connection uses a stateless revision (2026-07-28 and later), /// where every request carries its `_meta` envelope. @@ -564,10 +597,12 @@ public actor Client { negotiatedProtocolVersion.map { Version.profile(for: $0).usesRequestMeta } ?? false } - /// A dictionary of type-erased notification handlers, keyed by method name - private var notificationHandlers: [String: [NotificationHandlerBox]] = [:] - /// Method handlers for server-to-client requests - private var methodHandlers: [String: RequestHandlerBox] = [:] + /// A dictionary of type-erased notification handlers, keyed by method + /// name; a message selects them only by the same code points. + private var notificationHandlers: [ExactString: [NotificationHandlerBox]] = [:] + /// Method handlers for server-to-client requests, by method name + /// (`ExactString`, as above). + private var methodHandlers: [ExactString: RequestHandlerBox] = [:] /// The task for the message handling loop private var task: Task? /// Changes on every connect, disconnect and close of the connection. A @@ -580,6 +615,10 @@ public actor Client { /// Registered requests not yet handed to the transport. A request /// cancelled while here is never sent. private var unsentRequests: Set = [] + /// The batches whose `withBatch` body is running, by batch id: the + /// connection generation each was opened on and the requests added so far. + private var openBatches: [Int: (generation: Int, requests: [OutgoingRequest])] = [:] + private var nextBatchID = 0 /// A running handler of a server-to-client request. private struct IncomingHandler { /// Tells this run from a later request that reuses the id. @@ -597,6 +636,55 @@ public actor Client { private var queuedIncomingRequests: [Request] = [] /// The most server-to-client requests that wait for a slot. static let incomingRequestBacklog = 64 + /// Tracks active and draining tasks for one class of out-of-band server + /// response (`ping` replies or error refusals). + private struct ImmediateResponsePool { + var active: [UUID: Task] = [:] + var draining: Set = [] + var didLogDrop = false + var count: Int { active.count + draining.count } + + mutating func detach(sparing caller: UUID?) { + for (token, task) in active where token != caller { + task.cancel() + } + draining.formUnion(active.keys) + active = [:] + didLogDrop = false + } + } + + private enum ImmediateResponseKind { + case ping + case refusal + + var limit: Int { + switch self { + case .ping: Client.incomingPingLimit + case .refusal: Client.incomingRefusalLimit + } + } + + var label: String { + switch self { + case .ping: "ping" + case .refusal: "refusal" + } + } + } + + /// Out-of-band `ping` replies in flight or draining. + private var pingResponses = ImmediateResponsePool() + /// Out-of-band error refusals in flight or draining. + private var refusalResponses = ImmediateResponsePool() + /// The most `ping` replies allowed in flight at once. + static let incomingPingLimit = 64 + /// The most error refusals allowed in flight at once. + static let incomingRefusalLimit = 64 + /// Active plus draining `ping` response tasks (for tests). + var inFlightPingResponseCount: Int { pingResponses.count } + /// Active plus draining refusal response tasks (for tests). + var inFlightRefusalResponseCount: Int { refusalResponses.count } /// Notifications in arrival order. Their handlers run one at a time. private var inboundQueue: AsyncStream>.Continuation? @@ -627,13 +715,7 @@ public actor Client { ] // Add reusable JSON encoder/decoder private let encoder = JSONEncoder() - /// Decodes incoming messages with `data:` URL strings kept as strings; - /// handlers get `.data` from their own typed decode. - private let decoder: JSONDecoder = { - let decoder = JSONDecoder() - decoder.userInfo[.valuePreservesStrings] = true - return decoder - }() + private let decoder = JSONDecoder() /// Creates a client with its implementation information, capabilities /// and configuration. @@ -690,6 +772,9 @@ public actor Client { /// connection: `server/discover` or `initialize`, depending on /// ``Configuration/protocolMode``. /// + /// The client calls the transport's ``Transport/connect()``, so pass one + /// that is not connected yet: a transport serves one connection. + /// /// If the client is already connected, it first disconnects the previous /// transport, and that connection's pending requests fail as they do with /// ``disconnect()``. @@ -759,7 +844,7 @@ public actor Client { throw MCPError.internalError("Client disconnected") } - await logger?.debug( + logger?.debug( "Client connected", metadata: ["name": "\(name)", "version": "\(version)"]) // Notification handlers run in arrival order, outside the receive @@ -784,11 +869,11 @@ public actor Client { task = Task { let connection = transport var streamError: (any Swift.Error)? - repeat { + // Read until the stream finishes, which means the transport is + // closed: receive() would return the same, finished stream. + do { // Stop if cancelled, or if this connection was closed or replaced. - if Task.isCancelled || connectionGeneration != generation { break } - - do { + if !Task.isCancelled && connectionGeneration == generation { let stream = await connection.receive() for try await data in stream { if Task.isCancelled || connectionGeneration != generation { break } @@ -807,7 +892,7 @@ public actor Client { if Self.inlineNotifications.contains(message.method) { await handleBuiltIn(message) } - if notificationHandlers[message.method]?.isEmpty == false { + if notificationHandlers[ExactString(message.method)]?.isEmpty == false { if let token = Self.progressToken(of: message) { queuedProgress[token, default: 0] += 1 } @@ -824,7 +909,7 @@ public actor Client { id: id, error: .internalError("The server sent an invalid response"))) } // Peer text: only a sanitized prefix is logged. - await logger?.warning( + logger?.warning( "Unexpected message received by client (not single/batch response or notification)", metadata: [ "message": .string( @@ -833,20 +918,13 @@ public actor Client { ) } } - // The stream finished, so the transport is closed. Calling - // receive() again would return a stream that has already ended. - break - } catch let error where MCPError.isResourceTemporarilyUnavailable(error) { - try? await Task.sleep(for: .milliseconds(10)) - continue - } catch { - await logger?.error( - "Error in message handling loop", metadata: ["error": "\(error)"]) - streamError = error - break } - } while true - await self.logger?.debug("Client message handling loop task is terminating.") + } catch { + logger?.error( + "Error in message handling loop", metadata: ["error": "\(error)"]) + streamError = error + } + self.logger?.debug("Client message handling loop task is terminating.") await connectionDidClose(generation: generation, error: streamError) } @@ -874,7 +952,7 @@ public actor Client { /// transport closes the connection, the client's receive loop keeps the /// client and its transport alive. public func disconnect() async { - await logger?.debug("Initiating client disconnect...") + logger?.debug("Initiating client disconnect...") // A message loop that ends from here on leaves the teardown to this method. connectionGeneration += 1 @@ -891,26 +969,26 @@ public actor Client { // Resume continuations first closed.fail(with: MCPError.internalError("Client disconnected")) - await logger?.debug("Pending requests cancelled.") + logger?.debug("Pending requests cancelled.") // Cancel the task closed.task?.cancel() - await logger?.debug("Message loop task cancellation requested.") + logger?.debug("Message loop task cancellation requested.") // Disconnect the transport *before* awaiting the task // This should ensure the transport stream is finished, unblocking the loop. if let conn = closed.transport { await conn.disconnect() - await logger?.debug("Transport disconnected.") + logger?.debug("Transport disconnected.") } else { - await logger?.debug("No active transport connection to disconnect.") + logger?.debug("No active transport connection to disconnect.") } // Await the task completion *after* transport disconnect _ = await closed.task?.value - await logger?.debug("Client message loop task finished.") + logger?.debug("Client message loop task finished.") - await logger?.debug("Client disconnect complete.") + logger?.debug("Client disconnect complete.") } /// What is left to finish once the state of a connection is cleared. @@ -975,6 +1053,7 @@ public actor Client { self.task = nil self.connection = nil self.pendingRequests = [:] + handshakeSubscriptions = [] pendingToolCalls = [] abandonedToolCalls = [] for cancel in roundTripCancellers.values { cancel() } @@ -999,6 +1078,8 @@ public actor Client { drainingIncomingRequests.formUnion(incomingRequests.values.map(\.token)) incomingRequests = [:] queuedIncomingRequests = [] + pingResponses.detach(sparing: caller) + refusalResponses.detach(sparing: caller) immediateResponses = [] progressTokens = [:] queuedProgress = [:] @@ -1045,11 +1126,11 @@ public actor Client { } let closed = detachConnection(sparingCaller: false) - // Release the transport before resuming the callers, so that a caller - // that reconnects with the same transport is not disconnected afterwards. + // Close the transport before resuming the callers, so that a caller + // that retries with the same transport gets its connect() error at once. await closed.transport?.disconnect() closed.fail(with: failure) - await closed.transport?.logger.warning( + closed.transport?.logger.warning( "Client connection closed by the transport", metadata: [ "error": "\(failure)", @@ -1073,7 +1154,7 @@ public actor Client { _ type: N.Type, handler: @escaping @Sendable (Message) async throws -> Void ) async -> Self { - notificationHandlers[N.name, default: []].append(TypedNotificationHandler(handler)) + notificationHandlers[ExactString(N.name), default: []].append(TypedNotificationHandler(handler)) if Self.listChangeMethods.contains(N.name) { refreshNotificationStream() } @@ -1093,7 +1174,7 @@ public actor Client { _ type: M.Type, handler: @escaping @Sendable (M.Parameters) async throws -> M.Result ) -> Self { - methodHandlers[M.name] = TypedRequestHandler { [weak self] (request: Request) -> Response in + methodHandlers[ExactString(M.name)] = TypedRequestHandler { [weak self] (request: Request) -> Response in var params = request.params if let sampling = params as? CreateSamplingMessage.Parameters { try await self?.checkSamplingRequest(sampling) @@ -1248,7 +1329,7 @@ public actor Client { { var calls: [(String, InputRequest, RequestHandlerBox, AnyRequest)] = [] for (key, request) in requests { - guard let handler = methodHandlers[request.method] else { + guard let handler = methodHandlers[ExactString(request.method)] else { throw MCPError.methodNotFound("No handler registered for \(request.method)") } calls.append((key, request, handler, Request(method: request.method, params: try request.params()))) @@ -1308,7 +1389,7 @@ public actor Client { if Client.isHandlingNotification { immediateResponses.insert(request.id) } - if notificationHandlers[ProgressNotification.name]?.isEmpty == false, + if notificationHandlers[ExactString(ProgressNotification.name)]?.isEmpty == false, let token = Self.progressToken(ofRequest: data) { progressTokens[request.id] = token @@ -1332,7 +1413,7 @@ public actor Client { } } if let listed = value as? ListTools.Result, - let filtered = await self.recordTools(listed, firstPage: firstToolPage) + let filtered = self.recordTools(listed, firstPage: firstToolPage) { return filtered as! M.Result } @@ -1367,11 +1448,7 @@ public actor Client { ) async { guard unsentRequests.remove(outgoing.id) != nil else { return } do { - if !outgoing.headers.isEmpty { - try await connection.send(outgoing.data, additionalHeaders: outgoing.headers) - } else { - try await connection.send(outgoing.data) - } + try await connection.send(outgoing.data, options: TransportSendOptions(headers: outgoing.headers)) } catch { removePendingRequest(id: outgoing.id)?.resume( throwing: markingSendFailures ? SendFailure(error: error) : error) @@ -1425,7 +1502,7 @@ public actor Client { /// sends and the client has a handler for, and the subscribed resources. private var wantedNotifications: SubscriptionFilter { func wants(_ method: String, _ declared: Bool?) -> Bool? { - declared == true && notificationHandlers[method]?.isEmpty == false ? true : nil + declared == true && notificationHandlers[ExactString(method)]?.isEmpty == false ? true : nil } return SubscriptionFilter( toolsListChanged: wants(ToolListChangedNotification.name, serverCapabilities?.tools?.listChanged), @@ -1449,7 +1526,7 @@ public actor Client { guard isStateless, connection != nil else { return } let wanted = wantedNotifications let none = SubscriptionFilter() - guard wanted != (notificationStreamFilter ?? none) else { return } + guard !wanted.isExactly(notificationStreamFilter ?? none) else { return } notificationStreamRetry?.cancel() notificationStreamRetry = nil notificationStreamGeneration += 1 @@ -1471,7 +1548,7 @@ public actor Client { opened = try await listen(wanted) } catch { guard generation == notificationStreamGeneration else { return } - await logger?.warning( + logger?.warning( "Could not open the notification stream", metadata: ["error": "\(error)"]) // Keep the stream that works. notificationStreamFilter = notificationStreamRequest @@ -1542,7 +1619,7 @@ public actor Client { /// Retries ``refreshNotificationStream()`` after the backoff delay. private func scheduleNotificationStreamRetry() { guard notificationStreamRetry == nil, connection != nil, - wantedNotifications != (notificationStreamFilter ?? SubscriptionFilter()) + !wantedNotifications.isExactly(notificationStreamFilter ?? SubscriptionFilter()) else { return } let delay = Self.notificationStreamDelay(failures: notificationStreamFailures) let generation = connectionGeneration @@ -1568,12 +1645,12 @@ public actor Client { /// Completes the `subscribeToResource` calls for the URIs `requested` /// named. URIs the server did not honor fail and are unsubscribed. private func resolveResourceWaiters(requested: SubscriptionFilter, honored: SubscriptionFilter) { - let named = Set(requested.resourceSubscriptions ?? []) - let served = Set(honored.resourceSubscriptions ?? []) + let named = Set((requested.resourceSubscriptions ?? []).map(ExactString.init)) + let served = Set((honored.resourceSubscriptions ?? []).map(ExactString.init)) let refused = named.subtracting(served) unservedResources.subtract(named) if !refused.isEmpty { - subscribedResources.removeAll { refused.contains($0) } + subscribedResources.removeAll { refused.contains(ExactString($0)) } if wantedNotifications == SubscriptionFilter() { refreshNotificationStream() // closes the stream } else { @@ -1583,9 +1660,10 @@ public actor Client { } var waiting: [(id: UUID, uri: String, continuation: CheckedContinuation)] = [] for waiter in resourceWaiters { - if served.contains(waiter.uri) { + let key = ExactString(waiter.uri) + if served.contains(key) { waiter.continuation.resume() - } else if refused.contains(waiter.uri) { + } else if refused.contains(key) { waiter.continuation.resume( throwing: MCPError.invalidRequest("The server does not send updates for \(waiter.uri)")) } else { @@ -1599,16 +1677,16 @@ public actor Client { /// stream that could not be opened, named. Established subscriptions /// stay, so a stream that failed keeps being reopened for them. private func failResourceWaiters(requested: SubscriptionFilter, error: Swift.Error) { - let served = Set(notificationStream?.notifications.resourceSubscriptions ?? []) - let failed = Set(requested.resourceSubscriptions ?? []) - .intersection(resourceWaiters.map(\.uri)) + let served = Set((notificationStream?.notifications.resourceSubscriptions ?? []).map(ExactString.init)) + let failed = Set((requested.resourceSubscriptions ?? []).map(ExactString.init)) + .intersection(resourceWaiters.map { ExactString($0.uri) }) .subtracting(served) guard !failed.isEmpty else { return } - subscribedResources.removeAll { failed.contains($0) } + subscribedResources.removeAll { failed.contains(ExactString($0)) } unservedResources.subtract(failed) var waiting: [(id: UUID, uri: String, continuation: CheckedContinuation)] = [] for waiter in resourceWaiters { - if failed.contains(waiter.uri) { + if failed.contains(ExactString(waiter.uri)) { waiter.continuation.resume(throwing: error) } else { waiting.append(waiter) @@ -1717,9 +1795,9 @@ public actor Client { return } - // At 2026-07-28 over HTTP, closing the response stream cancels the request. - if isStateless, let http = connection as? HTTPClientTransport { - await http.cancelRequest(requestID) + // At 2026-07-28, a transport that ends the request's exchange, as + // Streamable HTTP closes its response stream, has told the server. + if isStateless, let connection, await connection.abandonRequest(requestID) { return } @@ -1836,7 +1914,8 @@ public actor Client { else { return } acknowledge(id, params.notifications) case TaskStatusNotification.name, TaskUpdatedNotification.name: - guard let id = message.params.objectValue?["taskId"]?.stringValue else { return } + guard let taskID = message.params.objectValue?["taskId"]?.stringValue else { return } + let id = ExactString(taskID) let waiting = taskWakeups.removeValue(forKey: id) ?? [:] if waiting.isEmpty { if !notifiedTasks.contains(id) { notifiedTasks.append(id) } @@ -1846,7 +1925,7 @@ public actor Client { } case CancelledNotification.name: guard let params = Self.decode(message.params, as: CancelledNotification.Parameters.self) else { return } - await logger?.debug( + logger?.debug( "Received cancellation notification", metadata: [ "requestId": params.requestId.map { "\($0)" } ?? "none", @@ -1865,7 +1944,7 @@ public actor Client { /// Forgets the notifications of a task no one drives any more. func endDriving(_ id: String) { - notifiedTasks.removeAll { $0 == id } + notifiedTasks.removeAll { $0 == ExactString(id) } } /// Waits for `timeout`, or less when a notification for the task arrives @@ -1874,7 +1953,8 @@ public actor Client { /// - Throws: The connection's error when it closes during the wait, and /// ``MCPError/connectionClosed`` when it closed before. func waitForTask(_ id: String, timeout: Duration) async throws { - if let index = notifiedTasks.firstIndex(of: id) { + let key = ExactString(id) + if let index = notifiedTasks.firstIndex(of: key) { notifiedTasks.remove(at: index) return } @@ -1882,10 +1962,10 @@ public actor Client { nextTaskWakeup += 1 let token = nextTaskWakeup let slot = ResponseSlot() - taskWakeups[id, default: [:]][token] = slot + taskWakeups[key, default: [:]][token] = slot defer { - taskWakeups[id]?[token] = nil - if taskWakeups[id]?.isEmpty == true { taskWakeups[id] = nil } + taskWakeups[key]?[token] = nil + if taskWakeups[key]?.isEmpty == true { taskWakeups[key] = nil } } let timer = Task { try? await Task.sleep(for: timeout) @@ -1906,62 +1986,104 @@ public actor Client { // MARK: - Batching - /// A batch of requests. + /// A batch of requests that ``Client/withBatch(isolation:body:)`` sends as + /// one JSON-RPC array. /// - /// Objects of this type are passed as an argument to the closure - /// of the ``Client/withBatch(body:)`` method. - public actor Batch { - unowned let client: Client - /// The client's connection generation when the batch was created. - let generation: Int - var requests: [OutgoingRequest] = [] - - init(client: Client, generation: Int) { + /// It is valid only while the `body` closure of `withBatch` runs: once + /// `withBatch` returns or throws, ``addRequest(_:)`` throws. It can be used + /// from child tasks of the closure. + public struct Batch: Sendable { + private let client: Client + /// The key of the batch in the client's open batches. + let id: Int + + init(client: Client, id: Int) { self.client = client - self.generation = generation + self.id = id } - /// Adds a request to the batch and prepares its expected response task. - /// The actual sending happens when the `withBatch` scope completes. + /// Adds a request to the batch and returns the task for its result. /// - /// The request gets what ``Client/send(_:)`` adds: the 2026-07-28 - /// `_meta` envelope and header parameters, and the multi round-trip - /// loop for `tools/call`, `prompts/get` and `resources/read`. - /// - Returns: A `Task` that will eventually produce the result or throw an error. + /// The request is sent when the `body` closure of + /// ``Client/withBatch(isolation:body:)`` returns. It gets what + /// ``Client/send(_:)`` adds: the 2026-07-28 `_meta` envelope and + /// header parameters, and the multi round-trip loop for `tools/call`, + /// `prompts/get` and `resources/read`. + /// + /// - Parameter request: The request to add. + /// - Returns: A task that produces the result, or throws the peer's error. + /// - Throws: ``MCPError/internalError(_:)`` when `withBatch` has already + /// returned or thrown; ``MCPError/connectionClosed`` when the + /// connection closed or was replaced while the closure ran. public func addRequest(_ request: Request) async throws -> Task< M.Result, Swift.Error > { - let (outgoing, task) = try await client.registerBatchRequest(request, generation: generation) - requests.append(outgoing) - return task + try await client.addBatchRequest(request, toBatch: id) } } - private func registerBatchRequest(_ request: Request, generation: Int) throws -> ( - OutgoingRequest, Task - ) { + /// Registers a request of the open batch `id`. Registering and adding run + /// in one actor call, so no request is registered without being added, and + /// a closed batch can't gain one. + private func addBatchRequest(_ request: Request, toBatch id: Int) throws -> Task< + M.Result, Error + > { + guard let batch = openBatches[id] else { + throw MCPError.internalError("Batch.addRequest(_:) was called after withBatch returned") + } // The connection the batch is for closed or was replaced. - guard connectionGeneration == generation else { + guard batch.generation == connectionGeneration else { throw MCPError.connectionClosed } guard connection != nil else { throw MCPError.internalError("Client connection not initialized") } let (outgoing, first) = try register(request) - return (outgoing, withRoundTrips(request, first: first)) + openBatches[id]?.requests.append(outgoing) + return withRoundTrips(request, first: first) + } + + /// Opens a batch on the current connection. + private func openBatch() throws -> Batch { + guard connection != nil else { + throw MCPError.internalError("Client connection not initialized") + } + nextBatchID += 1 + openBatches[nextBatchID] = (generation: connectionGeneration, requests: []) + return Batch(client: self, id: nextBatchID) + } + + /// Closes batch `id` without sending it: its registered requests fail with `error`. + private func abandonBatch(_ id: Int, with error: Swift.Error) { + guard let batch = openBatches.removeValue(forKey: id) else { return } + failUnsent(batch.requests, with: error) } /// Fails registered batch requests that will not be sent. - private func abandonBatch(_ requests: [OutgoingRequest], with error: Swift.Error) { + private func failUnsent(_ requests: [OutgoingRequest], with error: Swift.Error) { for request in requests where unsentRequests.remove(request.id) != nil { removePendingRequest(id: request.id)?.resume(throwing: error) } } - /// Sends the batch requests that were not cancelled as one JSON array. - /// On a stateless connection each request is sent alone: 2026-07-28 - /// requests carry per-request HTTP headers. - private func sendBatch(_ requests: [OutgoingRequest], on connection: any Transport) async throws { + /// Closes batch `id` and sends its requests that were not cancelled as + /// one JSON array. On a stateless connection each request is sent alone: + /// 2026-07-28 requests carry per-request HTTP headers. + private func sendBatch(_ id: Int) async throws { + guard let batch = openBatches.removeValue(forKey: id) else { return } + let requests = batch.requests + guard !requests.isEmpty else { + logger?.debug("Batch requested but no requests were added.") + return + } + + logger?.debug( + "Sending batch request", metadata: ["count": "\(requests.count)"]) + // Not on a connection that closed or was replaced while the batch was built. + guard connectionGeneration == batch.generation, let connection else { + failUnsent(requests, with: MCPError.connectionClosed) + throw MCPError.connectionClosed + } if isStateless { for request in requests { Task { await self.transmit(request, on: connection) } @@ -1983,120 +2105,85 @@ public actor Client { } } - /// Executes multiple requests in a single batch. - /// - /// This method allows you to group multiple MCP requests together, - /// which are then sent to the server as a single JSON array. - /// The server processes these requests and sends back a corresponding - /// JSON array of responses. + /// Sends several requests as one JSON-RPC batch and returns the value of `body`. /// - /// Within the `body` closure, use the provided `Batch` actor to add - /// requests using `batch.addRequest(_:)`. Each call to `addRequest` - /// returns a `Task` handle representing the asynchronous operation - /// for that specific request's result. + /// Add requests with ``Batch/addRequest(_:)`` inside `body`; each call + /// returns a `Task` for that request's result. `body` runs on the + /// caller's actor, so it can assign to local variables and change the + /// caller's state. The requests are sent when `body` returns. Await the + /// tasks after `withBatch` returns: awaiting one inside `body` waits + /// forever, because nothing has been sent yet. /// - /// It's recommended to collect these `Task` handles into an array - /// within the `body` closure`. After the `withBatch` method returns - /// (meaning the batch request has been sent), you can then process - /// the results by awaiting each `Task` in the collected array. + /// JSON-RPC batching is part of MCP 2025-03-26 only; 2025-06-18 removed + /// it. Use it with peers that accept batches. An SDK `Server` on a stream + /// transport (stdio, network, in-memory) accepts one at every handshake + /// revision. The SDK's HTTP server transports answer a JSON array with + /// HTTP 400, and other servers at 2025-06-18 or later may refuse it. At + /// 2026-07-28 the requests are sent one by one, because each carries its + /// own HTTP headers. /// - /// Example 1: Batching multiple tool calls and collecting typed tasks: + /// Example 1, returning the tasks: /// ```swift - /// // Array to hold the task handles for each tool call - /// var toolTasks: [Task] = [] - /// try await client.withBatch { batch in + /// let tasks = try await client.withBatch { batch in + /// var tasks: [Task] = [] /// for i in 0..<10 { - /// toolTasks.append( - /// try await batch.addRequest( - /// CallTool.request(.init(name: "square", arguments: ["n": i])) - /// ) - /// ) + /// tasks.append(try await batch.addRequest( + /// CallTool.request(.init(name: "square", arguments: ["n": .int(i)])))) /// } + /// return tasks /// } - /// - /// // Process results after the batch is sent - /// print("Processing \(toolTasks.count) tool results...") - /// for (index, task) in toolTasks.enumerated() { + /// for (index, task) in tasks.enumerated() { /// do { - /// let result = try await task.value - /// print("\(index): \(result.content)") + /// print("\(index): \(try await task.value.content)") /// } catch { /// print("\(index) failed: \(error)") /// } /// } /// ``` /// - /// Example 2: Batching different request types and awaiting individual tasks: + /// Example 2, assigning to captured variables: /// ```swift - /// // Declare optional task variables beforehand /// var pingTask: Task? /// var promptTask: Task? - /// /// try await client.withBatch { batch in - /// // Assign the tasks within the batch closure /// pingTask = try await batch.addRequest(Ping.request()) /// promptTask = try await batch.addRequest(GetPrompt.request(.init(name: "greeting"))) /// } - /// - /// // Await the results after the batch is sent - /// do { - /// if let pingTask = pingTask { - /// try await pingTask.value // Await ping result (throws if ping failed) - /// print("Ping successful") - /// } - /// if let promptTask = promptTask { - /// let promptResult = try await promptTask.value // Await prompt result - /// print("Prompt description: \(promptResult.description ?? "None")") - /// } - /// } catch { - /// print("Error processing batch results: \(error)") + /// _ = try await pingTask?.value + /// if let prompt = try await promptTask?.value { + /// print(prompt.description ?? "No description") /// } /// ``` /// - /// - Parameter body: An asynchronous closure that takes a `Batch` object as input. - /// Use this object to add requests to the batch. + /// - Parameters: + /// - isolation: The actor `body` runs on; leave the default, the caller's. + /// - body: A closure that adds requests to the batch it is passed. + /// - Returns: The value `body` returns. /// - Throws: `MCPError.internalError` if the client is not connected. - /// `MCPError.connectionClosed` if, while `body` ran, the connection - /// closed or was replaced by ``disconnect()`` or - /// ``connect(transport:)``; the batch is then not sent. - /// Can also rethrow errors from the `body` closure or from sending the batch request. - public func withBatch(body: @escaping @Sendable (Batch) async throws -> Void) async throws { - guard let connection = connection else { - throw MCPError.internalError("Client connection not initialized") - } - - // Create Batch actor, passing self (Client) - let generation = connectionGeneration - let batch = Batch(client: self, generation: generation) - - // Populate the batch actor by calling the user's closure. + /// `MCPError.connectionClosed` if, while `body` ran, the connection + /// closed or was replaced by ``disconnect()`` or + /// ``connect(transport:)``; the batch is then not sent. The error + /// `body` throws, after the requests it added fail with it. The error + /// of sending the batch, which its requests fail with too. + /// - SeeAlso: https://modelcontextprotocol.io/specification/2025-03-26/changelog + /// - SeeAlso: https://modelcontextprotocol.io/specification/2025-06-18/changelog + @discardableResult + public func withBatch( + isolation: isolated (any Actor)? = #isolation, + body: (Batch) async throws -> R + ) async throws -> R { + let batch = try await openBatch() + let result: R do { - try await body(batch) + result = try await body(batch) } catch { // The requests added so far are never sent. - abandonBatch(await batch.requests, with: error) + await abandonBatch(batch.id, with: error) throw error } - - // Get the collected requests from the batch actor - let requests = await batch.requests - - // Check if there are any requests to send - guard !requests.isEmpty else { - await logger?.debug("Batch requested but no requests were added.") - return // Nothing to send - } - - await logger?.debug( - "Sending batch request", metadata: ["count": "\(requests.count)"]) - // Not on a connection that closed or was replaced while the batch was built. - guard connectionGeneration == generation else { - abandonBatch(requests, with: MCPError.connectionClosed) - throw MCPError.connectionClosed - } - try await sendBatch(requests, on: connection) - - // Responses will be handled asynchronously by the message loop and handleBatchResponse/handleResponse. + // Responses are delivered by the message loop, like those of `send(_:)`. + try await sendBatch(batch.id) + return result } // MARK: - Lifecycle @@ -2126,11 +2213,8 @@ public actor Client { self.serverInfo = result.serverInfo self.instructions = result.instructions - // For HTTP transport, ensure subsequent MCP-Protocol-Version headers - // reflect the negotiated lifecycle version. - if let httpTransport = connection as? HTTPClientTransport { - await httpTransport.updateNegotiatedProtocolVersion(result.protocolVersion) - } + // An HTTP transport sends the negotiated version in MCP-Protocol-Version. + await connection?.didNegotiate(protocolVersion: result.protocolVersion) try await notify(InitializedNotification.message()) } @@ -2139,14 +2223,10 @@ public actor Client { /// tools with invalid annotations, at revisions that define /// `Mcp-Param-*` headers (SEP-2243). Returns `nil` at other revisions. /// A first page (no cursor) replaces what earlier listings recorded. - /// - /// The record is replaced in one step before the warnings are logged: - /// logging awaits the transport's logger, and a `tools/call` sent - /// meanwhile must find every tool of the page. - private func recordTools(_ result: ListTools.Result, firstPage: Bool) async -> ListTools.Result? { + private func recordTools(_ result: ListTools.Result, firstPage: Bool) -> ListTools.Result? { // Names are not refused: the specification says SHOULD (SEP-986). for (name, problem) in toolNameWarnings.warnings(for: result.tools.map(\.name), checkDuplicates: false) { - await logger?.warning( + logger?.warning( "The server listed a tool whose name does not follow the specification (SEP-986): \(problem)", metadata: ["tool": "\(MCPRequestHeaders.sanitized(name))"]) } @@ -2168,7 +2248,7 @@ public actor Client { } toolHeaderParameters = recorded for (tool, error) in rejected { - await logger?.warning( + logger?.warning( "Ignoring tool with an invalid x-mcp-header annotation", metadata: ["tool": "\(tool)", "error": "\(error)"]) } @@ -2243,21 +2323,21 @@ public actor Client { } throw MCPError.unsupportedProtocolVersion(supported: supported, requested: requested) } catch let failure as SendFailure { - guard fallback, HTTPClientTransport.isSessionlessRefusal(failure.error) else { + guard fallback, HTTPStatusError.isSessionlessRefusal(failure.error) else { throw failure.error } - await logger?.info( + logger?.info( "server/discover refused; falling back to initialize", metadata: ["error": "\(failure.error)"]) return try await initialize() } catch is DiscoverTimeout { - await logger?.info("server/discover timed out; falling back to initialize") + logger?.info("server/discover timed out; falling back to initialize") return try await initialize() } catch let error as MCPError where fallback && connection != nil { // The peer answered with a JSON-RPC error. On a closed // connection the error is rethrown: there is nothing to fall back on. try ensureCurrent() - await logger?.info( + logger?.info( "server/discover failed; falling back to initialize", metadata: ["error": "\(error)"]) return try await initialize() @@ -2293,15 +2373,15 @@ public actor Client { guard (try? await Task.sleep(until: deadline, clock: .continuous)) != nil else { return } // An interactive sign-in can outlast the timeout: cancelling // it would sign in again for `initialize`. - guard let http = connection as? HTTPClientTransport, - let ended = await http.authorizationEnd(of: context.requestID), + guard let connection = self.connection, + let ended = await connection.authorizationEnd(of: context.requestID), ended + timeout > .now else { break } deadline = ended + timeout } guard let pending = removePendingRequest(id: context.requestID) else { return } // No notifications/cancelled: the server may not know the request. - await (connection as? HTTPClientTransport)?.cancelRequest(context.requestID) + await connection?.abandonRequest(context.requestID) pending.resume(throwing: DiscoverTimeout()) } defer { timer.cancel() } @@ -2311,7 +2391,7 @@ public actor Client { /// Logs a notice the first time a server declares a capability the /// specification deprecates (SEP-2577). private func logDeprecationNotices(_ capabilities: Server.Capabilities) async { - DeprecationNotices.current.log(forServer: capabilities, to: await logger) + DeprecationNotices.current.log(forServer: capabilities, to: logger) } /// Records a `server/discover` result as the connection state. @@ -2321,9 +2401,8 @@ public actor Client { negotiatedProtocolVersion = version serverInfo = result.serverInfo instructions = result.instructions - if let httpTransport = connection as? HTTPClientTransport { - await httpTransport.useStatelessProtocol(version) - } + // An HTTP transport drops its session and GET stream. + await connection?.didNegotiate(protocolVersion: version) } /// Checks that the server is reachable. @@ -2381,30 +2460,41 @@ public actor Client { /// Asks for `notifications/resources/updated` when the resource at `uri` changes. /// - /// On handshake connections this sends `resources/subscribe`. At - /// 2026-07-28 the URI joins the background `subscriptions/listen` - /// stream, which is replaced by one that names it; this returns once the - /// server acknowledges that stream. Subscribing again to a subscribed URI + /// On handshake connections this sends `resources/subscribe` on every + /// call, also for a URI that is already subscribed; the URI is listed in + /// ``subscribedResourceURIs`` once the server accepts it. At 2026-07-28 + /// the URI joins the background `subscriptions/listen` stream, which is + /// replaced by one that names it; this returns once the server + /// acknowledges that stream, and subscribing again to a subscribed URI /// does nothing. Cancelling the calling task ends the wait with - /// `CancellationError`; the URI is dropped again when no stream has - /// served it yet and no other call waits for it. + /// `CancellationError`; at 2026-07-28 the URI is dropped again when no + /// stream has served it yet and no other call waits for it. /// - /// - Throws: ``MCPError/invalidRequest(_:)`` when the server does not - /// send updates for `uri`, or the error that kept the stream from - /// opening. + /// - Throws: ``MCPError/methodNotFound(_:)`` when ``Configuration/strict-property`` + /// is set and the server does not declare `resources.subscribe: true`, + /// before anything is sent. A handshake connection otherwise throws the + /// error of the server's `resources/subscribe` response. At 2026-07-28, + /// ``MCPError/invalidRequest(_:)`` when the acknowledgement of the + /// stream omits `uri`, as it does for a server that does not declare + /// `resources.subscribe: true`, or the error that kept the stream from + /// opening; ``MCPError/internalError(_:)`` when the client is + /// disconnected. public func subscribeToResource(uri: String) async throws { - try validateServerCapability(\.resources?.subscribe, "Resource subscription") + try requireServerFlag(\.resources?.subscribe, "Resource subscription") guard isStateless else { + let generation = connectionGeneration let request = ResourceSubscribe.request(.init(uri: uri)) _ = try await send(request).value + if connectionGeneration == generation { handshakeSubscriptions.insert(ExactString(uri)) } return } guard connection != nil else { throw MCPError.internalError("Client disconnected") } - if subscribedResourceURIs.contains(uri) { return } + let key = ExactString(uri) + if servedResourceURIs.contains(key) { return } try Task.checkCancellation() - if !subscribedResources.contains(uri) { + if !subscribedResources.contains(where: { $0.isExactly(uri) }) { subscribedResources.append(uri) - unservedResources.insert(uri) + unservedResources.insert(key) } let waiter = UUID() try await withTaskCancellationHandler { () async throws -> Void in @@ -2436,32 +2526,44 @@ public actor Client { if let index = resourceWaiters.firstIndex(where: { $0.id == id }) { resourceWaiters.remove(at: index).continuation.resume(throwing: CancellationError()) } - guard unservedResources.contains(uri), !resourceWaiters.contains(where: { $0.uri == uri }) + let key = ExactString(uri) + guard unservedResources.contains(key), !resourceWaiters.contains(where: { $0.uri.isExactly(uri) }) else { return } - unservedResources.remove(uri) - subscribedResources.removeAll { $0 == uri } + unservedResources.remove(key) + subscribedResources.removeAll { $0.isExactly(uri) } refreshNotificationStream() } /// Stops `notifications/resources/updated` for the resource at `uri`. /// - /// On handshake connections this sends `resources/unsubscribe`. At - /// 2026-07-28 the background stream is replaced by one without the URI; - /// updates may arrive until the server acknowledges the replacement. It - /// does nothing when the URI is not subscribed. + /// On handshake connections this sends `resources/unsubscribe` on every + /// call, also for a URI that is not subscribed; the URI leaves + /// ``subscribedResourceURIs`` once the server accepts it. At 2026-07-28 + /// the background stream is replaced by one without the URI; updates may + /// arrive until the server acknowledges the replacement, and it does + /// nothing when the URI is not subscribed. + /// + /// - Throws: On handshake connections, ``MCPError/methodNotFound(_:)`` + /// when ``Configuration/strict-property`` is set and the server does + /// not declare `resources.subscribe: true`, before anything is sent; + /// otherwise the error of the server's `resources/unsubscribe` + /// response, and the URI then stays in ``subscribedResourceURIs``. It + /// does not throw at 2026-07-28. public func unsubscribeFromResource(uri: String) async throws { guard isStateless else { - try validateServerCapability(\.resources?.subscribe, "Resource subscription") + try requireServerFlag(\.resources?.subscribe, "Resource subscription") + let generation = connectionGeneration let request = ResourceUnsubscribe.request(.init(uri: uri)) _ = try await send(request).value + if connectionGeneration == generation { handshakeSubscriptions.remove(ExactString(uri)) } return } - guard subscribedResources.contains(uri) else { return } - subscribedResources.removeAll { $0 == uri } - unservedResources.remove(uri) + guard subscribedResources.contains(where: { $0.isExactly(uri) }) else { return } + subscribedResources.removeAll { $0.isExactly(uri) } + unservedResources.remove(ExactString(uri)) var waiting: [(id: UUID, uri: String, continuation: CheckedContinuation)] = [] for waiter in resourceWaiters { - if waiter.uri == uri { + if waiter.uri.isExactly(uri) { waiter.continuation.resume(throwing: CancellationError()) } else { waiting.append(waiter) @@ -2471,9 +2573,25 @@ public actor Client { refreshNotificationStream() } - /// The subscribed URIs the open background stream serves (2026-07-28). + /// The subscribed URIs the open background stream serves, by exact code points. + private var servedResourceURIs: Set { + Set((notificationStream?.notifications.resourceSubscriptions ?? []).map(ExactString.init)) + .intersection(subscribedResources.map(ExactString.init)) + } + + /// The resource URIs this connection receives + /// `notifications/resources/updated` for: at handshake revisions the URIs + /// whose `resources/subscribe` succeeded and that weren't unsubscribed; at + /// 2026-07-28 the subscribed URIs the open background stream serves. + /// + /// Subscriptions are tracked internally by exact Unicode scalars, so + /// canonically equivalent spellings (such as NFC and NFD) stay subscribed + /// and unsubscribed independently. Because the returned `Set` uses + /// Swift `String` equality, two canonically equivalent subscribed URIs + /// appear as one element here while both remain subscribed. public var subscribedResourceURIs: Set { - Set(notificationStream?.notifications.resourceSubscriptions ?? []).intersection(subscribedResources) + guard isStateless else { return Set(handshakeSubscriptions.map(\.value)) } + return Set(servedResourceURIs.map(\.value)) } /// Lists one page of the server's resource templates @@ -2738,7 +2856,7 @@ public actor Client { // MARK: - private func handleResponse(_ response: Response) async { - await logger?.trace( + logger?.trace( "Processing response", metadata: ["id": "\(response.id)"]) @@ -2764,7 +2882,7 @@ public actor Client { } else { // Request was already removed (e.g., by send error handler or disconnect). // Log this, but it's not an error in race condition scenarios. - await logger?.warning( + logger?.warning( "Attempted to handle response for already removed request", metadata: ["id": "\(response.id)"] ) @@ -2780,7 +2898,7 @@ public actor Client { } private func handleMessage(_ message: Message) async { - await logger?.trace( + logger?.trace( "Processing notification", metadata: ["method": "\(message.method)"]) @@ -2792,14 +2910,14 @@ public actor Client { } // Find notification handlers for this method - guard let handlers = notificationHandlers[message.method] else { return } + guard let handlers = notificationHandlers[ExactString(message.method)] else { return } // Convert notification parameters to concrete type and call handlers for handler in handlers { do { try await handler(message) } catch { - await logger?.error( + logger?.error( "Error handling notification", metadata: [ "method": "\(message.method)", @@ -2818,7 +2936,7 @@ public actor Client { case ResourceListChangedNotification.name: return wanted.resourcesListChanged == true case ResourceUpdatedNotification.name: guard case .string(let uri)? = message.params.objectValue?["uri"] else { return false } - return subscribedResources.contains(uri) + return subscribedResources.contains { $0.isExactly(uri) } default: return true } } @@ -2827,9 +2945,17 @@ public actor Client { /// that the receive loop keeps reading while it runs. At most /// ``Configuration/maxConcurrentServerRequests`` run at once; up to /// ``incomingRequestBacklog`` more wait, and further ones are refused. + /// Out-of-band `ping` replies and error refusals use separate bounded + /// pools (``incomingPingLimit`` and ``incomingRefusalLimit``) so a refusal + /// burst cannot starve `ping` liveness checks and a stalled peer cannot + /// accumulate unbounded tasks. private func startIncomingRequest(_ request: Request, on transport: any Transport) { func refuse(_ error: MCPError) { - Task { try? await self.send(AnyMethod.response(id: request.id, error: error), on: transport) } + let response = AnyMethod.response(id: request.id, error: error) + startImmediateIncomingResponse(.refusal) { + guard !Task.isCancelled else { return } + try? await self.send(response, on: transport) + } } // 2026-07-28 has no server-to-client requests. if isStateless { @@ -2838,11 +2964,16 @@ public actor Client { } // Answered at once, outside the handler slots: it checks liveness. if request.method == Ping.name { - Task { - if self.methodHandlers[Ping.name] != nil { + if methodHandlers[ExactString(Ping.name)] != nil { + startImmediateIncomingResponse(.ping) { + guard !Task.isCancelled else { return } await self.handleIncomingRequest(request, on: transport) - } else { - try? await self.send(Response(id: request.id, result: .object([:])), on: transport) + } + } else { + let response = Response(id: request.id, result: .object([:])) + startImmediateIncomingResponse(.ping) { + guard !Task.isCancelled else { return } + try? await self.send(response, on: transport) } } return @@ -2862,6 +2993,62 @@ public actor Client { queuedIncomingRequests.append(request) } + private func startImmediateIncomingResponse( + _ kind: ImmediateResponseKind, + _ body: @escaping @Sendable () async -> Void + ) { + let count: Int + let alreadyLogged: Bool + switch kind { + case .ping: + count = pingResponses.count + alreadyLogged = pingResponses.didLogDrop + case .refusal: + count = refusalResponses.count + alreadyLogged = refusalResponses.didLogDrop + } + guard count < kind.limit else { + if !alreadyLogged { + switch kind { + case .ping: pingResponses.didLogDrop = true + case .refusal: refusalResponses.didLogDrop = true + } + logger?.warning( + "Dropping out-of-band server response because too many are already in flight", + metadata: ["kind": "\(kind.label)", "limit": "\(kind.limit)"]) + } + return + } + let token = UUID() + let task = Task { + await Client.$incomingHandlerToken.withValue(token) { + await body() + } + self.immediateIncomingResponseFinished(token, kind: kind) + } + switch kind { + case .ping: pingResponses.active[token] = task + case .refusal: refusalResponses.active[token] = task + } + } + + private func immediateIncomingResponseFinished(_ token: UUID, kind: ImmediateResponseKind) { + switch kind { + case .ping: + pingResponses.active[token] = nil + pingResponses.draining.remove(token) + if pingResponses.count <= kind.limit / 2 { + pingResponses.didLogDrop = false + } + case .refusal: + refusalResponses.active[token] = nil + refusalResponses.draining.remove(token) + if refusalResponses.count <= kind.limit / 2 { + refusalResponses.didLogDrop = false + } + } + } + private func runIncomingRequest(_ request: Request, on transport: any Transport) { let token = UUID() let task = Task { @@ -2911,12 +3098,12 @@ public actor Client { } private func handleIncomingRequest(_ request: Request, on transport: any Transport) async { - await logger?.trace( + logger?.trace( "Processing incoming request from server", metadata: ["method": "\(request.method)", "id": "\(request.id)"]) - guard let handler = methodHandlers[request.method] else { - await logger?.warning( + guard let handler = methodHandlers[ExactString(request.method)] else { + logger?.warning( "No handler registered for method", metadata: ["method": "\(request.method)"]) let error = MCPError.methodNotFound("Unknown method: \(request.method)") @@ -2924,7 +3111,7 @@ public actor Client { do { try await send(response, on: transport) } catch { - await logger?.error( + logger?.error( "Failed to send error response", metadata: ["error": "\(error)"]) } @@ -2943,7 +3130,7 @@ public actor Client { do { try await send(response, on: transport) } catch { - await logger?.error( + logger?.error( "Failed to send error response", metadata: ["error": "\(error)"]) } @@ -2960,38 +3147,23 @@ public actor Client { ) throws { - if configuration.strict { - guard let capabilities = serverCapabilities else { - throw MCPError.methodNotFound("Server capabilities not initialized") - } - guard capabilities[keyPath: keyPath] != nil else { - throw MCPError.methodNotFound("\(name) is not supported by the server") - } - } + try validateServerCapability(name) { $0[keyPath: keyPath] != nil } } - // Add handler for batch responses - private func handleBatchResponse(_ responses: [AnyResponse]) async { - await logger?.trace("Processing batch response", metadata: ["count": "\(responses.count)"]) - for response in responses { - // Attempt to remove the pending request. - // If successful, pendingRequest contains the request. - if let pendingRequest = self.removePendingRequest(id: response.id) { - // If we successfully removed it, handle the response using the pending request. - switch response.result { - case .success(let value): - pendingRequest.resume(returning: value) - case .failure(let error): - pendingRequest.resume(throwing: error) - } - } else { - // If removal failed, it means the request ID was not found (or already handled). - // Log a warning. - await logger?.warning( - "Received response in batch for unknown or already handled request ID", - metadata: ["id": "\(response.id)"] - ) - } + /// Throws -32601 in strict mode when the server doesn't declare the flag `true`. + /// An absent flag, or an absent capability, reads as `false`. + private func requireServerFlag(_ keyPath: KeyPath, _ name: String) throws { + try validateServerCapability(name) { $0[keyPath: keyPath] == true } + } + + /// Throws -32601 in strict mode unless `isDeclared` accepts the server's capabilities. + private func validateServerCapability(_ name: String, _ isDeclared: (Server.Capabilities) -> Bool) throws { + guard configuration.strict else { return } + guard let capabilities = serverCapabilities else { + throw MCPError.methodNotFound("Server capabilities not initialized") + } + guard isDeclared(capabilities) else { + throw MCPError.methodNotFound("\(name) is not supported by the server") } } } @@ -3004,12 +3176,13 @@ extension Client.Capabilities.Sampling: Codable { } public init(from decoder: Decoder) throws { - // Handle both empty object {} and object with sub-capabilities + // Any object, `{}` included, reads its sub-capabilities; a value that + // isn't an object reads leniently as no sub-capabilities. if let container = try? decoder.container(keyedBy: CodingKeys.self) { self.tools = try container.decodeIfPresent(Tools.self, forKey: .tools) self.context = try container.decodeIfPresent(Context.self, forKey: .context) } else { - // Empty object - no capabilities + // Not an object: no sub-capabilities. self.tools = nil self.context = nil } @@ -3028,7 +3201,8 @@ extension Client.Capabilities.Elicitation: Codable { } public init(from decoder: Decoder) throws { - // Handle both empty object {} and object with sub-capabilities + // Any object, `{}` included, reads its sub-capabilities; a value that + // isn't an object reads leniently as form-only. if let container = try? decoder.container(keyedBy: CodingKeys.self) { self.form = try container.decodeIfPresent(Form.self, forKey: .form) self.url = try container.decodeIfPresent(URL.self, forKey: .url) @@ -3037,7 +3211,7 @@ extension Client.Capabilities.Elicitation: Codable { self.form = Form() } } else { - // Empty object - default to form-only for backward compatibility + // Not an object: form-only, as for `{}`. self.form = Form() self.url = nil } diff --git a/Sources/MCP/Client/ClientApps.swift b/Sources/MCP/Client/ClientApps.swift index 3059d7c0..eef71f57 100644 --- a/Sources/MCP/Client/ClientApps.swift +++ b/Sources/MCP/Client/ClientApps.swift @@ -20,8 +20,7 @@ public struct AppResourceError: Swift.Error, Hashable, Sendable, CustomStringCon public static let missingContent = Reason("missingContent") /// The content item's MIME type is not ``UIResource/mimeType``. public static let unsupportedMimeType = Reason("unsupportedMimeType") - /// The content item has neither `text` nor a `blob` of base64-encoded - /// UTF-8. + /// The content item is a blob that is not UTF-8. public static let invalidContent = Reason("invalidContent") } @@ -87,7 +86,9 @@ extension Client { /// /// - Throws: ``AppResourceError`` when `uri` is not a `ui://` URI (in /// lowercase, as ``UIResource`` requires), or the content is not an - /// HTML view; the server's error otherwise. + /// HTML view; ``ResponseDecodingError`` when the server's content item + /// has neither `text` nor `blob`, has both, or has a `blob` that is not + /// base64; the server's error otherwise. public func readAppResource(uri: String, listing: Resource? = nil) async throws -> AppResourceContents { guard uri.count > 5, uri.hasPrefix("ui://") else { throw AppResourceError(.notUIResource, uri: uri, message: "\(uri) is not a ui:// URI") @@ -102,15 +103,14 @@ extension Client { message: "\(uri) has MIME type \(content.mimeType ?? "none"), not \(UIResource.mimeType)") } let html: String - if let text = content.text { + switch content.body { + case .text(let text): html = text - } else if let blob = content.blob, let data = Data(base64Encoded: blob), - let decoded = String(data: data, encoding: .utf8) - { + case .blob(let data): + guard let decoded = String(data: data, encoding: .utf8) else { + throw AppResourceError(.invalidContent, uri: uri, message: "\(uri) has a blob that is not UTF-8") + } html = decoded - } else { - throw AppResourceError( - .invalidContent, uri: uri, message: "\(uri) has neither text nor a blob of base64-encoded UTF-8") } // The listing's only when `_meta.ui` is absent or null, as the // specification's `??`. diff --git a/Sources/MCP/Client/ClientSkills.swift b/Sources/MCP/Client/ClientSkills.swift index f0e0228a..15dfeacb 100644 --- a/Sources/MCP/Client/ClientSkills.swift +++ b/Sources/MCP/Client/ClientSkills.swift @@ -447,8 +447,9 @@ extension Client { guard let content = result.contents.first(where: { $0.uri == uri }) ?? result.contents.first else { throw SkillVerificationError(.unreadable, uri: uri, message: "\(uri) returned no content") } - if let text = content.text { return Data(text.utf8) } - if let blob = content.blob, let data = Data(base64Encoded: blob) { return data } - throw SkillVerificationError(.unreadable, uri: uri, message: "\(uri) returned no text or blob") + switch content.body { + case .text(let text): return Data(text.utf8) + case .blob(let data): return data + } } } diff --git a/Sources/MCP/Client/Sampling.swift b/Sources/MCP/Client/Sampling.swift index 1f44a2a1..0aac6ccf 100644 --- a/Sources/MCP/Client/Sampling.swift +++ b/Sources/MCP/Client/Sampling.swift @@ -65,16 +65,23 @@ public enum Sampling { /// Multiple content blocks case multiple([ContentBlock]) - /// Individual content blocks in messages + /// Individual content blocks in messages. /// /// No other case is added in 1.x: a kind from a later revision is ``unknown(type:_:)``. + /// + /// Binary `image` and `audio` blocks decode `data` as standard RFC 4648 §4 base64 + /// (accepting ASCII whitespace and omitted trailing `=` padding). Per the MCP + /// specification, non-standard URL-safe base64 (`-`, `_`), invalid base64, or a nested + /// ``Resource/Content`` in a `tool_result` block with both or neither of `text` and + /// `blob` throws `DecodingError.dataCorrupted` and fails decoding of the containing + /// message or result. public enum ContentBlock: Hashable, Sendable { /// Text content case text(String) - /// Image content - case image(data: String, mimeType: String) - /// Audio content - case audio(data: String, mimeType: String) + /// Image content: the image's bytes, sent base64-encoded in `data`, and its MIME type. + case image(_ data: Data, mimeType: String) + /// Audio content: the audio's bytes, sent base64-encoded in `data`, and its MIME type. + case audio(_ data: Data, mimeType: String) /// Tool use content case toolUse(Sampling.ToolUseContent) /// Tool result content @@ -86,6 +93,22 @@ public enum Sampling { /// rounded. The bytes can differ: key order, whitespace, string escapes /// and number formatting may change. case unknown(type: String, Value) + + /// Creates image content from a base64-encoded string. + /// + /// If `data` is not valid base64, this shim stores empty `Data()`. + @available(*, deprecated, message: "Pass Data directly with .image(_:mimeType:) instead") + public static func image(data: String, mimeType: String) -> Self { + .image(Data(lenientBase64Encoded: data) ?? Data(), mimeType: mimeType) + } + + /// Creates audio content from a base64-encoded string. + /// + /// If `data` is not valid base64, this shim stores empty `Data()`. + @available(*, deprecated, message: "Pass Data directly with .audio(_:mimeType:) instead") + public static func audio(data: String, mimeType: String) -> Self { + .audio(Data(lenientBase64Encoded: data) ?? Data(), mimeType: mimeType) + } } /// Returns true if this is a single content block @@ -109,14 +132,30 @@ public enum Sampling { .single(.text(text)) } - /// Creates content from an image (convenience) + /// Creates content from an image's bytes, sent base64-encoded. + public static func image(_ data: Data, mimeType: String) -> Content { + .single(.image(data, mimeType: mimeType)) + } + + /// Creates content from a base64-encoded image string. + /// + /// If `data` is not valid base64, this shim stores empty `Data()`. + @available(*, deprecated, message: "Pass Data directly with .image(_:mimeType:) instead") public static func image(data: String, mimeType: String) -> Content { - .single(.image(data: data, mimeType: mimeType)) + .single(.image(Data(lenientBase64Encoded: data) ?? Data(), mimeType: mimeType)) + } + + /// Creates content from audio bytes, sent base64-encoded. + public static func audio(_ data: Data, mimeType: String) -> Content { + .single(.audio(data, mimeType: mimeType)) } - /// Creates content from audio (convenience) + /// Creates content from a base64-encoded audio string. + /// + /// If `data` is not valid base64, this shim stores empty `Data()`. + @available(*, deprecated, message: "Pass Data directly with .audio(_:mimeType:) instead") public static func audio(data: String, mimeType: String) -> Content { - .single(.audio(data: data, mimeType: mimeType)) + .single(.audio(Data(lenientBase64Encoded: data) ?? Data(), mimeType: mimeType)) } } } @@ -246,16 +285,22 @@ public enum Sampling { /// Optional metadata public var _meta: Metadata? - /// Individual content blocks in tool results + /// Individual content blocks in tool results. /// /// No other case is added in 1.x: a kind from a later revision is ``unknown(type:_:)``. + /// + /// Binary `image` and `audio` blocks decode `data` as standard RFC 4648 §4 base64 + /// (accepting ASCII whitespace and omitted trailing `=` padding). Per the MCP + /// specification, non-standard URL-safe base64 (`-`, `_`), invalid base64, or an embedded + /// ``Resource/Content`` with both or neither of `text` and `blob` throws + /// `DecodingError.dataCorrupted` and fails decoding of the containing result. public enum ContentBlock: Hashable, Sendable { /// Text content case text(String) - /// Image content - case image(data: String, mimeType: String) - /// Audio content - case audio(data: String, mimeType: String) + /// Image content: the image's bytes, sent base64-encoded in `data`, and its MIME type. + case image(_ data: Data, mimeType: String) + /// Audio content: the audio's bytes, sent base64-encoded in `data`, and its MIME type. + case audio(_ data: Data, mimeType: String) /// Embedded resource content case resource(resource: Resource.Content, annotations: Resource.Annotations?, _meta: Metadata?) /// Resource link @@ -267,6 +312,22 @@ public enum Sampling { /// rounded. The bytes can differ: key order, whitespace, string escapes /// and number formatting may change. case unknown(type: String, Value) + + /// Creates image content from a base64-encoded string. + /// + /// If `data` is not valid base64, this shim stores empty `Data()`. + @available(*, deprecated, message: "Pass Data directly with .image(_:mimeType:) instead") + public static func image(data: String, mimeType: String) -> Self { + .image(Data(lenientBase64Encoded: data) ?? Data(), mimeType: mimeType) + } + + /// Creates audio content from a base64-encoded string. + /// + /// If `data` is not valid base64, this shim stores empty `Data()`. + @available(*, deprecated, message: "Pass Data directly with .audio(_:mimeType:) instead") + public static func audio(data: String, mimeType: String) -> Self { + .audio(Data(lenientBase64Encoded: data) ?? Data(), mimeType: mimeType) + } } /// Creates tool result content. @@ -324,13 +385,13 @@ extension Sampling.Message.Content.ContentBlock: Codable { let text = try container.decode(String.self, forKey: .text) self = .text(text) case "image": - let data = try container.decode(String.self, forKey: .data) + let data = try container.decodeBase64(forKey: .data) let mimeType = try container.decode(String.self, forKey: .mimeType) - self = .image(data: data, mimeType: mimeType) + self = .image(data, mimeType: mimeType) case "audio": - let data = try container.decode(String.self, forKey: .data) + let data = try container.decodeBase64(forKey: .data) let mimeType = try container.decode(String.self, forKey: .mimeType) - self = .audio(data: data, mimeType: mimeType) + self = .audio(data, mimeType: mimeType) case "tool_use": let id = try container.decode(String.self, forKey: .id) let name = try container.decode(String.self, forKey: .name) @@ -367,11 +428,11 @@ extension Sampling.Message.Content.ContentBlock: Codable { try container.encode(text, forKey: .text) case .image(let data, let mimeType): try container.encode("image", forKey: .type) - try container.encode(data, forKey: .data) + try container.encodeBase64(data, forKey: .data) try container.encode(mimeType, forKey: .mimeType) case .audio(let data, let mimeType): try container.encode("audio", forKey: .type) - try container.encode(data, forKey: .data) + try container.encodeBase64(data, forKey: .data) try container.encode(mimeType, forKey: .mimeType) case .toolUse(let toolUse): try container.encode("tool_use", forKey: .type) @@ -394,18 +455,18 @@ extension Sampling.Message.Content.ContentBlock: Codable { extension Sampling.Message.Content: Codable { public init(from decoder: Decoder) throws { - // Try to decode as an array first - if let blocks = try? [ContentBlock](from: decoder) { - // If it's a single-element array, unwrap it to single - if blocks.count == 1, let block = blocks.first { - self = .single(block) - } else { - self = .multiple(blocks) + // The `try?` only tests the JSON shape (an array or not), so an + // element's own error, such as data that is not base64, propagates. + if var container = try? decoder.unkeyedContainer() { + var blocks: [ContentBlock] = [] + if let count = container.count { blocks.reserveCapacity(count) } + while !container.isAtEnd { + blocks.append(try container.decode(ContentBlock.self)) } + // A single-element array reads as a single block. + self = blocks.count == 1 ? .single(blocks[0]) : .multiple(blocks) } else { - // Try to decode as a single block - let block = try ContentBlock(from: decoder) - self = .single(block) + self = .single(try ContentBlock(from: decoder)) } } @@ -452,13 +513,13 @@ extension Sampling.ToolResultContent.ContentBlock: Codable { let text = try container.decode(String.self, forKey: .text) self = .text(text) case "image": - let data = try container.decode(String.self, forKey: .data) + let data = try container.decodeBase64(forKey: .data) let mimeType = try container.decode(String.self, forKey: .mimeType) - self = .image(data: data, mimeType: mimeType) + self = .image(data, mimeType: mimeType) case "audio": - let data = try container.decode(String.self, forKey: .data) + let data = try container.decodeBase64(forKey: .data) let mimeType = try container.decode(String.self, forKey: .mimeType) - self = .audio(data: data, mimeType: mimeType) + self = .audio(data, mimeType: mimeType) case "resource": let resourceContent = try container.decode(Resource.Content.self, forKey: .resource) let annotations = try container.decodeIfPresent(Resource.Annotations.self, forKey: .annotations) @@ -492,11 +553,11 @@ extension Sampling.ToolResultContent.ContentBlock: Codable { try container.encode(text, forKey: .text) case .image(let data, let mimeType): try container.encode("image", forKey: .type) - try container.encode(data, forKey: .data) + try container.encodeBase64(data, forKey: .data) try container.encode(mimeType, forKey: .mimeType) case .audio(let data, let mimeType): try container.encode("audio", forKey: .type) - try container.encode(data, forKey: .data) + try container.encodeBase64(data, forKey: .data) try container.encode(mimeType, forKey: .mimeType) case .resource(let resourceContent, let annotations, let _meta): try container.encode("resource", forKey: .type) diff --git a/Sources/MCP/Extensions/Base64Coding.swift b/Sources/MCP/Extensions/Base64Coding.swift new file mode 100644 index 00000000..7b19eb1b --- /dev/null +++ b/Sources/MCP/Extensions/Base64Coding.swift @@ -0,0 +1,88 @@ +import Foundation + +// Binary payloads (image and audio `data`, a resource's `blob`) are base64 strings +// (`@format byte` in the schema). Every one is read and written through this file: +// decoding is lenient, encoding is strict. + +extension Data { + /// Creates data by decoding `string` as standard base64 (RFC 4648 §4), the way the + /// WHATWG forgiving-base64 decode (`atob`) does. + /// + /// ASCII whitespace is skipped (RFC 2045 §6.8 decoders ignore line breaks, and + /// Python's `base64.encodebytes` wraps at 76 columns). Trailing `=` padding may be + /// omitted completely (restored for a 2- or 3-symbol final quantum), or present in + /// canonical 4-character groups with at most two `=` characters (`XX==` or `XXX=`). + /// Partial padding (such as `"YQ="`), more than two trailing `=`, `=` before the end, + /// or any character outside the standard alphabet (including URL-safe `-` and `_`) + /// fails (RFC 4648 §3.3). + /// + /// The grammar is checked here, and Foundation only sees canonical padded input, + /// because its decoders differ between Darwin and Linux on the rest: `"===="` is one + /// zero byte on Darwin and empty on Linux, and `.ignoreUnknownCharacters` reads + /// `"YQ==YQ=="` as one byte on Darwin and fails on Linux. Here both fail everywhere. + /// + /// - Parameter string: The base64 text, such as a `blob` or an image's `data`. + /// - Returns: `nil` when `string` is not base64. + init?(lenientBase64Encoded string: some StringProtocol) { + var symbols = Data() + symbols.reserveCapacity(string.utf8.count + 2) + for byte in string.utf8 { + switch byte { + case 0x09, 0x0A, 0x0C, 0x0D, 0x20: continue // ASCII whitespace (WHATWG Infra) + default: symbols.append(byte) + } + } + if symbols.count % 4 == 0 { + if symbols.last == UInt8(ascii: "=") { symbols.removeLast() } + if symbols.last == UInt8(ascii: "=") { symbols.removeLast() } + } + guard symbols.count % 4 != 1, symbols.allSatisfy(Self.isBase64Symbol) else { return nil } + symbols.append(contentsOf: repeatElement(UInt8(ascii: "="), count: (4 - symbols.count % 4) % 4)) + guard let data = Data(base64Encoded: symbols) else { return nil } + self = data + } + + /// Whether `byte` is a character of the standard base64 alphabet (RFC 4648 §4), not `=`. + private static func isBase64Symbol(_ byte: UInt8) -> Bool { + switch byte { + case UInt8(ascii: "A")...UInt8(ascii: "Z"), UInt8(ascii: "a")...UInt8(ascii: "z"), + UInt8(ascii: "0")...UInt8(ascii: "9"), UInt8(ascii: "+"), UInt8(ascii: "/"): + return true + default: + return false + } + } +} + +extension KeyedDecodingContainerProtocol { + /// Decodes the base64 string at `key` leniently; see `Data(lenientBase64Encoded:)`. + /// + /// - Throws: `DecodingError.dataCorrupted` when the string is not base64, and the + /// errors of `decode(String.self, forKey:)` otherwise. The error names the key, + /// never the payload, which can be large or sensitive. + func decodeBase64(forKey key: Key) throws -> Data { + guard let data = Data(lenientBase64Encoded: try decode(String.self, forKey: key)) else { + throw DecodingError.dataCorruptedError( + forKey: key, in: self, debugDescription: "\(key.stringValue) is not base64") + } + return data + } + + /// Decodes the base64 string at `key` like `decodeBase64(forKey:)`; `nil` when the + /// key is absent or `null`. + /// + /// - Throws: The errors of `decodeBase64(forKey:)`, and those of `decodeNil(forKey:)`. + func decodeBase64IfPresent(forKey key: Key) throws -> Data? { + guard contains(key), try !decodeNil(forKey: key) else { return nil } + return try decodeBase64(forKey: key) + } +} + +extension KeyedEncodingContainerProtocol { + /// Encodes `data` as standard padded base64 (RFC 4648 §4), without line breaks. + /// + /// - Throws: The errors of `encode(_:forKey:)`, such as `EncodingError.invalidValue`. + mutating func encodeBase64(_ data: Data, forKey key: Key) throws { + try encode(data.base64EncodedString(), forKey: key) + } +} diff --git a/Sources/MCP/Extensions/Data+Extensions.swift b/Sources/MCP/Extensions/Data+Extensions.swift deleted file mode 100644 index f89699e9..00000000 --- a/Sources/MCP/Extensions/Data+Extensions.swift +++ /dev/null @@ -1,123 +0,0 @@ -import Foundation -import RegexBuilder - -extension Data { - /// A `token` character of RFC 2045 §5.1: printable US-ASCII without - /// space and `tspecials`. - @inline(__always) private static var mediaTypeTokenCharacter: CharacterClass { - CharacterClass(.anyOf("!#$%&'*+-.^_`{|}~"), "a"..."z", "A"..."Z", "0"..."9") - } - - /// Regex pattern for data URLs - @inline(__always) private static var dataURLRegex: - Regex<(Substring, Substring, Substring?, Substring?, Substring)> - { - Regex { - "data:" - // RFC 2397 §3: `[ type "/" subtype ]`, so prose such as - // `data: 3 rows, 2 columns` is not a data URL. - Capture { - Optionally { - OneOrMore(mediaTypeTokenCharacter) - "/" - OneOrMore(mediaTypeTokenCharacter) - } - } - Optionally { - ";charset=" - Capture { - OneOrMore(mediaTypeTokenCharacter) - } - } - Optionally { - Capture { ";base64" } - } - "," - Capture { - ZeroOrMore { .any } - } - } - } - - /// Checks if a given string is a valid data URL. - /// - /// - Parameter string: The string to check. - /// - Returns: `true` if the string is a valid data URL, otherwise `false`. - /// - SeeAlso: [RFC 2397](https://www.rfc-editor.org/rfc/rfc2397.html) - public static func isDataURL(string: String) -> Bool { - return string.wholeMatch(of: dataURLRegex) != nil - } - - /// Parses a data URL string into its MIME type and data components. - /// - /// - Parameter string: The data URL string to parse. - /// - Returns: A tuple containing the MIME type and decoded data, or `nil` if parsing fails. - /// - SeeAlso: [RFC 2397](https://www.rfc-editor.org/rfc/rfc2397.html) - public static func parseDataURL(_ string: String) -> (mimeType: String, data: Data)? { - guard let match = string.wholeMatch(of: dataURLRegex) else { - return nil - } - - // Extract components using strongly typed captures - let (_, mediatype, charset, base64Marker, encodedData) = match.output - - let isBase64 = base64Marker != nil - - // Process MIME type - var mimeType = mediatype.isEmpty ? "text/plain" : String(mediatype) - if let charset = charset, !charset.isEmpty, mimeType.starts(with: "text/") { - mimeType += ";charset=\(charset)" - } - - // Decode data - let decodedData: Data - if isBase64 { - guard let base64Data = Data(base64Encoded: String(encodedData)) else { return nil } - decodedData = base64Data - } else { - guard let percentDecodedData = percentDecoded(encodedData) else { return nil } - decodedData = percentDecodedData - } - - return (mimeType: mimeType, data: decodedData) - } - - /// Decodes `%XX` escapes directly into bytes, so any byte value is accepted. - /// - /// - Parameter string: The percent-encoded string. - /// - Returns: The decoded bytes, or `nil` if an escape is malformed. - private static func percentDecoded(_ string: Substring) -> Data? { - var bytes = Data(capacity: string.utf8.count) - var iterator = string.utf8.makeIterator() - while let byte = iterator.next() { - guard byte == UInt8(ascii: "%") else { - bytes.append(byte) - continue - } - guard let high = iterator.next().flatMap(hexValue), - let low = iterator.next().flatMap(hexValue) - else { return nil } - bytes.append(high << 4 | low) - } - return bytes - } - - private static func hexValue(_ byte: UInt8) -> UInt8? { - switch byte { - case UInt8(ascii: "0")...UInt8(ascii: "9"): return byte - UInt8(ascii: "0") - case UInt8(ascii: "a")...UInt8(ascii: "f"): return byte - UInt8(ascii: "a") + 10 - case UInt8(ascii: "A")...UInt8(ascii: "F"): return byte - UInt8(ascii: "A") + 10 - default: return nil - } - } - - /// Encodes the data as a data URL string with an optional MIME type. - /// - /// - Parameter mimeType: The MIME type of the data. If `nil`, "text/plain" will be used. - /// - Returns: A data URL string representation of the data. - /// - SeeAlso: [RFC 2397](https://www.rfc-editor.org/rfc/rfc2397.html) - public func dataURLEncoded(mimeType: String? = nil) -> String { - let base64Data = self.base64EncodedString() - return "data:\(mimeType ?? "text/plain");base64,\(base64Data)" - } -} diff --git a/Sources/MCP/FoundationModels/Client+LanguageModelTool.swift b/Sources/MCP/FoundationModels/Client+LanguageModelTool.swift index 602ba160..7a170ad6 100644 --- a/Sources/MCP/FoundationModels/Client+LanguageModelTool.swift +++ b/Sources/MCP/FoundationModels/Client+LanguageModelTool.swift @@ -123,7 +123,7 @@ import Foundation case .audio(_, let mimeType, _, _): others.append("[audio: \(mimeType)]") case .resource(let resource, _, _): - if let text = resource.text { + if case .text(let text) = resource.body { texts.append(text) } else { others.append("[resource: \(resource.uri)]") @@ -187,7 +187,7 @@ import Foundation do { tools.append(try LanguageModelTool(tool, client: self, approval: approval)) } catch { - await logger?.warning( + logger?.warning( "A tool is not offered to the language model: its input schema cannot be converted", metadata: [ "tool": "\(MCPRequestHeaders.sanitized(tool.name))", diff --git a/Sources/MCP/FoundationModels/GeneratedContent+Value.swift b/Sources/MCP/FoundationModels/GeneratedContent+Value.swift index adc30ae6..a78e8a30 100644 --- a/Sources/MCP/FoundationModels/GeneratedContent+Value.swift +++ b/Sources/MCP/FoundationModels/GeneratedContent+Value.swift @@ -40,12 +40,10 @@ import Foundation extension GeneratedContent { /// Creates FoundationModels generated content from a value. /// - /// ``Value/data(mimeType:_:)`` becomes the `data:` URL string it is - /// encoded as on the wire. `GeneratedContent` represents numbers as - /// `Double`, so integers with magnitude above `2^53` (`9_007_199_254_740_992`) - /// lose precision; ``CallTool/Parameters/arguments(as:)`` rejects - /// out-of-range integers before conversion. The properties of an object - /// are in sorted order. + /// `GeneratedContent` represents numbers as `Double`, so integers with + /// magnitude above `2^53` (`9_007_199_254_740_992`) lose precision; + /// ``CallTool/Parameters/arguments(as:)`` rejects out-of-range integers + /// before conversion. The properties of an object are in sorted order. public init(_ value: Value) { switch value { case .null: @@ -58,8 +56,6 @@ import Foundation self.init(kind: .number(value)) case .string(let value): self.init(kind: .string(value)) - case let .data(mimeType, data): - self.init(kind: .string(data.dataURLEncoded(mimeType: mimeType))) case .array(let elements): self.init(kind: .array(elements.map(GeneratedContent.init))) case .object(let properties): diff --git a/Sources/MCP/FoundationModels/GenerationSchema+JSONSchema.swift b/Sources/MCP/FoundationModels/GenerationSchema+JSONSchema.swift index 2b5ca058..41b95e38 100644 --- a/Sources/MCP/FoundationModels/GenerationSchema+JSONSchema.swift +++ b/Sources/MCP/FoundationModels/GenerationSchema+JSONSchema.swift @@ -1040,7 +1040,7 @@ import Foundation case .bool: return "boolean" case .int: return "integer" case .double: return "number" - case .string, .data: return "string" + case .string: return "string" case .array: return "array" case .object: return "object" case .null: return "null" diff --git a/Sources/MCP/FoundationModels/Tool+FoundationModels.swift b/Sources/MCP/FoundationModels/Tool+FoundationModels.swift index f051368b..2c5417d8 100644 --- a/Sources/MCP/FoundationModels/Tool+FoundationModels.swift +++ b/Sources/MCP/FoundationModels/Tool+FoundationModels.swift @@ -104,7 +104,7 @@ import Foundation ) throws { var outputSchema: Value? if let output = T.Output.self as? any Generable.Type { - let encoded = try Value.preservingStrings(output.generationSchema) + let encoded = try Value(output.generationSchema) if encoded.objectValue?["type"]?.stringValue == "object" { outputSchema = encoded } @@ -123,7 +123,7 @@ import Foundation /// `schema` as JSON Schema, which must be an object. static func objectSchema(_ schema: GenerationSchema, of role: String) throws -> Value { - let value = try Value.preservingStrings(schema) + let value = try Value(schema) guard value.objectValue?["type"]?.stringValue == "object" else { throw GenerationSchema.JSONSchemaError( pointer: "", reason: "The schema of the tool's \(role) must be an object") @@ -193,7 +193,7 @@ import Foundation for element in properties.values { try validateRepresentableNumbers(in: element, toolName: toolName) } - case .null, .bool, .string, .data: + case .null, .bool, .string: break } } diff --git a/Sources/MCP/MCP.docc/MCP.md b/Sources/MCP/MCP.docc/MCP.md index 7f26010d..7c121543 100644 --- a/Sources/MCP/MCP.docc/MCP.md +++ b/Sources/MCP/MCP.docc/MCP.md @@ -32,6 +32,8 @@ protocol versions, migration, testing and troubleshooting. - ``StatelessHTTPServerTransport`` - ``InMemoryTransport`` - ``Transport`` +- ``TransportWrapper`` +- ``TransportSendOptions`` ### Server features diff --git a/Sources/MCP/Server/Apps.swift b/Sources/MCP/Server/Apps.swift index 0fab0960..96c47090 100644 --- a/Sources/MCP/Server/Apps.swift +++ b/Sources/MCP/Server/Apps.swift @@ -26,13 +26,10 @@ public struct UIResource: Hashable, Sendable { /// The security and rendering configuration of the view. public var meta: UIResourceMeta? - /// The HTML document of a view. - public enum Body: Hashable, Sendable { - /// The document as text. - case text(String) - /// The document as bytes, sent base64-encoded. - case blob(Data) - } + /// The HTML document of a view: text, or bytes sent base64-encoded. + /// + /// The same type as the body of the view's content item. + public typealias Body = Resource.Content.Body /// A view that is not valid. public struct ValidationError: Error, Hashable, CustomStringConvertible { @@ -87,11 +84,7 @@ public struct UIResource: Hashable, Sendable { /// The `resources/read` content item of the view. public var contents: Resource.Content { - var content: Resource.Content - switch body { - case .text(let html): content = .text(html, uri: uri, mimeType: Self.mimeType) - case .blob(let data): content = .binary(data, uri: uri, mimeType: Self.mimeType) - } + var content = Resource.Content(uri: uri, mimeType: Self.mimeType, body: body) content.ui = meta return content } diff --git a/Sources/MCP/Server/BuiltInResources.swift b/Sources/MCP/Server/BuiltInResources.swift index 02e7870d..b3a6dfab 100644 --- a/Sources/MCP/Server/BuiltInResources.swift +++ b/Sources/MCP/Server/BuiltInResources.swift @@ -61,7 +61,7 @@ extension Server { guard let uri = params["uri"]?.stringValue else { return nil } for source in sources { if let result = try await source.read(uri) { - return Response(id: request.id, result: try Value.preservingStrings(result)) + return Response(id: request.id, result: try Value(result)) } } return nil @@ -105,7 +105,7 @@ extension Server { defer { earlierDone = earlierDone && current == .done } guard case .page(let cursor) = current, cursor == nil || earlierDone else { continue } let page = try await source.list(cursor) - let encoded = try Value.preservingStrings(page) + let encoded = try Value(page) resources += encoded.objectValue?["resources"]?.arrayValue ?? [] if meta == nil { meta = encoded.objectValue?["_meta"] } pages.append(encoded.objectValue ?? [:]) @@ -188,12 +188,12 @@ struct ResourceListingCursor: Equatable { /// The position a cursor of ``encoded`` names; `nil` for any other string. init?(_ cursor: String) { guard cursor.hasPrefix(Self.prefix), let data = Data(base64Encoded: String(cursor.dropFirst(Self.prefix.count))), - let value = try? JSONDecoder().decode([String: Value.Preserved].self, from: data) + let value = try? JSONDecoder().decode([String: Value].self, from: data) else { return nil } let known = Set([Self.applicationKey] + BuiltInResourceSource.Key.allCases.map(\.rawValue)) guard value.keys.allSatisfy(known.contains) else { return nil } func position(_ key: String) -> Position? { - switch value[key]?.value { + switch value[key] { case nil: return .done case .null?: return .page(nil) case .string(let cursor)?: return .page(cursor) diff --git a/Sources/MCP/Server/Prompts.swift b/Sources/MCP/Server/Prompts.swift index 15ad10d4..4ced5759 100644 --- a/Sources/MCP/Server/Prompts.swift +++ b/Sources/MCP/Server/Prompts.swift @@ -130,16 +130,22 @@ public struct Prompt: Hashable, Codable, Sendable { return Message(_role: .assistant, _content: content) } - /// Content types for messages + /// Content types for messages. /// /// No other case is added in 1.x: a kind from a later revision is ``unknown(type:_:)``. + /// + /// Binary `image` and `audio` blocks decode `data` as standard RFC 4648 §4 base64 + /// (accepting ASCII whitespace and omitted trailing `=` padding). Per the MCP + /// specification, non-standard URL-safe base64 (`-`, `_`), invalid base64, or an embedded + /// ``Resource/Content`` with both or neither of `text` and `blob` throws + /// `DecodingError.dataCorrupted` and fails decoding of the containing result. public enum Content: Hashable, Sendable { /// Text content case text(text: String) - /// Image content - case image(data: String, mimeType: String) - /// Audio content - case audio(data: String, mimeType: String) + /// Image content: the image's bytes, sent base64-encoded in `data`, and its MIME type. + case image(_ data: Data, mimeType: String) + /// Audio content: the audio's bytes, sent base64-encoded in `data`, and its MIME type. + case audio(_ data: Data, mimeType: String) /// Embedded resource content (EmbeddedResource from spec) case resource(resource: Resource.Content, annotations: Resource.Annotations? = nil, _meta: Metadata? = nil) /// Resource link @@ -151,6 +157,22 @@ public struct Prompt: Hashable, Codable, Sendable { /// rounded. The bytes can differ: key order, whitespace, string escapes /// and number formatting may change. case unknown(type: String, Value) + + /// Creates image content from a base64-encoded string. + /// + /// If `data` is not valid base64, this shim stores empty `Data()`. + @available(*, deprecated, message: "Pass Data directly with .image(_:mimeType:) instead") + public static func image(data: String, mimeType: String) -> Self { + .image(Data(lenientBase64Encoded: data) ?? Data(), mimeType: mimeType) + } + + /// Creates audio content from a base64-encoded string. + /// + /// If `data` is not valid base64, this shim stores empty `Data()`. + @available(*, deprecated, message: "Pass Data directly with .audio(_:mimeType:) instead") + public static func audio(data: String, mimeType: String) -> Self { + .audio(Data(lenientBase64Encoded: data) ?? Data(), mimeType: mimeType) + } } } @@ -208,11 +230,11 @@ extension Prompt.Message.Content: Codable { try container.encode(text, forKey: .text) case .image(let data, let mimeType): try container.encode("image", forKey: .type) - try container.encode(data, forKey: .data) + try container.encodeBase64(data, forKey: .data) try container.encode(mimeType, forKey: .mimeType) case .audio(let data, let mimeType): try container.encode("audio", forKey: .type) - try container.encode(data, forKey: .data) + try container.encodeBase64(data, forKey: .data) try container.encode(mimeType, forKey: .mimeType) case .resource(let resourceContent, let annotations, let _meta): try container.encode("resource", forKey: .type) @@ -241,13 +263,13 @@ extension Prompt.Message.Content: Codable { let text = try container.decode(String.self, forKey: .text) self = .text(text: text) case "image": - let data = try container.decode(String.self, forKey: .data) + let data = try container.decodeBase64(forKey: .data) let mimeType = try container.decode(String.self, forKey: .mimeType) - self = .image(data: data, mimeType: mimeType) + self = .image(data, mimeType: mimeType) case "audio": - let data = try container.decode(String.self, forKey: .data) + let data = try container.decodeBase64(forKey: .data) let mimeType = try container.decode(String.self, forKey: .mimeType) - self = .audio(data: data, mimeType: mimeType) + self = .audio(data, mimeType: mimeType) case "resource": let resourceContent = try container.decode(Resource.Content.self, forKey: .resource) let annotations = try container.decodeIfPresent(Resource.Annotations.self, forKey: .annotations) @@ -352,7 +374,7 @@ public enum ListPrompts: Method { prompts = try container.decode([Prompt].self, forKey: .prompts) nextCursor = try container.decodeIfPresent(String.self, forKey: .nextCursor) _meta = try container.decodeIfPresent(Metadata.self, forKey: ._meta) - ttlMs = container.decodeTTL(forKey: .ttlMs) + ttlMs = container.decodeMilliseconds(forKey: .ttlMs) cacheScope = container.decodeCacheScope(forKey: .cacheScope) } } diff --git a/Sources/MCP/Server/RequestState.swift b/Sources/MCP/Server/RequestState.swift index 31f0acc0..36160d7e 100644 --- a/Sources/MCP/Server/RequestState.swift +++ b/Sources/MCP/Server/RequestState.swift @@ -282,10 +282,12 @@ struct RequestStateBoundary: Sendable { guard claims.iat <= time + Self.futureSkew else { throw InvalidRequestState("issued in the future") } guard time < claims.exp else { throw InvalidRequestState("expired") } let expected = binding() - guard claims.m == method, claims.t == expected.target, claims.a == expected.digest else { + // By code points: a canonically equivalent method or target is + // another request on the wire. + guard claims.m.isExactly(method), claims.t.isExactly(expected.target), claims.a == expected.digest else { throw InvalidRequestState("request binding") } - guard claims.aud == audience else { throw InvalidRequestState("audience") } + guard claims.aud.isExactly(audience) else { throw InvalidRequestState("audience") } switch (claims.p, principal(context)) { case (nil, nil): break diff --git a/Sources/MCP/Server/Resources.swift b/Sources/MCP/Server/Resources.swift index 855b479c..059183ad 100644 --- a/Sources/MCP/Server/Resources.swift +++ b/Sources/MCP/Server/Resources.swift @@ -88,19 +88,61 @@ public struct Resource: Hashable, Codable, Sendable { try container.encodeIfPresent(_meta, forKey: ._meta) } - /// Content of a resource. + /// The contents of a resource: its text or its bytes, with the URI it was read from. + /// + /// On the wire it is `TextResourceContents` (`text`) or `BlobResourceContents` (`blob`, + /// standard RFC 4648 §4 base64). Per the MCP specification, decoding throws + /// `DecodingError.dataCorrupted` when an item has neither `text` nor `blob`, has both, or + /// has a `blob` that is not standard base64 (including non-standard URL-safe base64 using + /// `-` and `_`); ASCII whitespace and omitted trailing `=` padding in `blob` are accepted. + /// An embedded resource in a tool result, a prompt message, or a sampling tool result + /// decodes the same way, so a malformed item fails decoding of the containing result. + /// + /// - SeeAlso: https://modelcontextprotocol.io/specification/2025-11-25/server/resources/#resource-contents public struct Content: Hashable, Codable, Sendable { - /// The resource URI + /// The URI of the resource. public let uri: String - /// The resource MIME type + /// The MIME type of the resource, if known. public let mimeType: String? - /// The resource text content - public let text: String? - /// The resource binary content - public let blob: String? - /// Metadata fields (see spec for _meta usage) + /// The text or the bytes of the resource. + public let body: Body + /// Metadata (`_meta`). public var _meta: Metadata? + /// The text contents of the resource, or `nil` when ``body`` is ``Body/blob(_:)``. + @available(*, deprecated, message: "Switch on body (.text(String) or .blob(Data)) instead") + public var text: String? { + if case .text(let content) = body { return content } + return nil + } + + /// The binary contents of the resource encoded as standard base64, or `nil` when + /// ``body`` is ``Body/text(_:)``. + @available(*, deprecated, message: "Switch on body (.text(String) or .blob(Data)) instead") + public var blob: String? { + if case .blob(let data) = body { return data.base64EncodedString() } + return nil + } + + /// The text or the bytes of a resource contents item. + /// + /// Frozen: no case is added in 1.x (every revision defines `TextResourceContents` and + /// `BlobResourceContents` only). + public enum Body: Hashable, Sendable { + /// The contents as text, sent in `text`. + case text(String) + /// The contents as bytes, sent base64-encoded in `blob`. + case blob(Data) + } + + /// Creates the contents of the resource at `uri`. + public init(uri: String, mimeType: String? = nil, body: Body, _meta: Metadata? = nil) { + self.uri = uri + self.mimeType = mimeType + self.body = body + self._meta = _meta + } + /// Creates the text contents of the resource at `uri`. public static func text( _ content: String, @@ -108,50 +150,17 @@ public struct Resource: Hashable, Codable, Sendable { mimeType: String? = nil, _meta: Metadata? = nil ) -> Self { - .init(uri: uri, mimeType: mimeType, text: content, _meta: _meta) + .init(uri: uri, mimeType: mimeType, body: .text(content), _meta: _meta) } - /// Creates the binary contents of the resource at `uri`. - /// - /// The data is sent base64-encoded in `blob`. + /// Creates the binary contents of the resource at `uri`, sent base64-encoded in `blob`. public static func binary( _ data: Data, uri: String, mimeType: String? = nil, _meta: Metadata? = nil ) -> Self { - .init( - uri: uri, - mimeType: mimeType, - blob: data.base64EncodedString(), - _meta: _meta - ) - } - - private init( - uri: String, - mimeType: String? = nil, - text: String? = nil, - _meta: Metadata? = nil - ) { - self.uri = uri - self.mimeType = mimeType - self.text = text - self.blob = nil - self._meta = _meta - } - - private init( - uri: String, - mimeType: String? = nil, - blob: String, - _meta: Metadata? = nil - ) { - self.uri = uri - self.mimeType = mimeType - self.text = nil - self.blob = blob - self._meta = _meta + .init(uri: uri, mimeType: mimeType, body: .blob(data), _meta: _meta) } private enum CodingKeys: String, CodingKey { @@ -166,17 +175,35 @@ public struct Resource: Hashable, Codable, Sendable { let container = try decoder.container(keyedBy: CodingKeys.self) uri = try container.decode(String.self, forKey: .uri) mimeType = try container.decodeIfPresent(String.self, forKey: .mimeType) - text = try container.decodeIfPresent(String.self, forKey: .text) - blob = try container.decodeIfPresent(String.self, forKey: .blob) _meta = try container.decodeIfPresent(Metadata.self, forKey: ._meta) + let text = try container.decodeIfPresent(String.self, forKey: .text) + let blob = try container.decodeBase64IfPresent(forKey: .blob) + switch (text, blob) { + case (let text?, nil): + body = .text(text) + case (nil, let data?): + body = .blob(data) + case (nil, nil): + throw DecodingError.dataCorruptedError( + forKey: .text, in: container, + debugDescription: "Resource contents have neither text nor blob") + case (.some, .some): + throw DecodingError.dataCorruptedError( + forKey: .blob, in: container, + debugDescription: "Resource contents have both text and blob") + } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(uri, forKey: .uri) try container.encodeIfPresent(mimeType, forKey: .mimeType) - try container.encodeIfPresent(text, forKey: .text) - try container.encodeIfPresent(blob, forKey: .blob) + switch body { + case .text(let text): + try container.encode(text, forKey: .text) + case .blob(let data): + try container.encodeBase64(data, forKey: .blob) + } try container.encodeIfPresent(_meta, forKey: ._meta) } } @@ -324,7 +351,7 @@ public enum ListResources: Method { resources = try container.decode([Resource].self, forKey: .resources) nextCursor = try container.decodeIfPresent(String.self, forKey: .nextCursor) _meta = try container.decodeIfPresent(Metadata.self, forKey: ._meta) - ttlMs = container.decodeTTL(forKey: .ttlMs) + ttlMs = container.decodeMilliseconds(forKey: .ttlMs) cacheScope = container.decodeCacheScope(forKey: .cacheScope) } } @@ -468,7 +495,7 @@ public enum ReadResource: Method { return } contents = try container.decode([Resource.Content].self, forKey: .contents) - ttlMs = container.decodeTTL(forKey: .ttlMs) + ttlMs = container.decodeMilliseconds(forKey: .ttlMs) cacheScope = container.decodeCacheScope(forKey: .cacheScope) } } @@ -560,7 +587,7 @@ public enum ListResourceTemplates: Method { templates = try container.decode([Resource.Template].self, forKey: .templates) nextCursor = try container.decodeIfPresent(String.self, forKey: .nextCursor) _meta = try container.decodeIfPresent(Metadata.self, forKey: ._meta) - ttlMs = container.decodeTTL(forKey: .ttlMs) + ttlMs = container.decodeMilliseconds(forKey: .ttlMs) cacheScope = container.decodeCacheScope(forKey: .cacheScope) } } @@ -583,13 +610,18 @@ public enum ResourceSubscribe: Method { public struct Parameters: Hashable, Codable, Sendable { /// The URI of the resource to subscribe to. public let uri: String + + /// Creates the parameters for the resource at `uri`. + public init(uri: String) { + self.uri = uri + } } public typealias Result = Empty } /// Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. -/// - SeeAlso: https://modelcontextprotocol.io/specification/2025-06-18/schema#unsubscriberequest +/// - SeeAlso: https://modelcontextprotocol.io/specification/2025-11-25/server/resources/#subscriptions public enum ResourceUnsubscribe: Method { public static let name: String = "resources/unsubscribe" @@ -597,6 +629,11 @@ public enum ResourceUnsubscribe: Method { public struct Parameters: Hashable, Codable, Sendable { /// The URI of the resource to unsubscribe from. public let uri: String + + /// Creates the parameters for the resource at `uri`. + public init(uri: String) { + self.uri = uri + } } public typealias Result = Empty diff --git a/Sources/MCP/Server/Server.swift b/Sources/MCP/Server/Server.swift index 05482605..fa481991 100644 --- a/Sources/MCP/Server/Server.swift +++ b/Sources/MCP/Server/Server.swift @@ -51,8 +51,9 @@ public actor Server { /// streams are refused with -32600. public var maxSubscriptionStreams: Int - /// The most resource URIs one `subscriptions/listen` stream may name. - /// A stream that names more is refused with -32602. + /// The most resource URIs, and separately the most task IDs, that one + /// `subscriptions/listen` stream may name. A stream that names more + /// of either is refused with -32602. public var maxResourceSubscriptions: Int /// Creates a server configuration. @@ -132,14 +133,37 @@ public actor Server { /// Server capabilities public struct Capabilities: Hashable, Codable, Sendable { - /// Resources capabilities + /// The `resources` capability: the server serves resources. + /// + /// - SeeAlso: https://modelcontextprotocol.io/specification/2025-11-25/server/resources/#capabilities public struct Resources: Hashable, Codable, Sendable { - /// Whether the resource can be subscribed to + /// Whether the server sends `notifications/resources/updated` for + /// the resources a client subscribes to. + /// + /// With `true`, clients can call `resources/subscribe` (handshake) + /// or name resource URIs in a `subscriptions/listen` filter + /// (2026-07-28). With `nil` or `false`, the server does not + /// support subscriptions, and a listen stream honors no resource + /// URIs. Declaring the flag does not send anything: call + /// ``Server/notify(_:)`` when a resource changes. public var subscribe: Bool? - /// Whether the list of resources has changed + /// Whether the server sends `notifications/resources/list_changed` + /// when the list of resources changes. + /// + /// Declaring the flag does not send anything: call + /// ``Server/notify(_:)`` after each change. A + /// `subscriptions/listen` stream carries the notification only + /// when this is `true`; `nil` or `false` means the server does not + /// send it. public var listChanged: Bool? /// Creates the `resources` capability. + /// + /// - Parameters: + /// - subscribe: Whether the server sends + /// `notifications/resources/updated` for subscribed resources. + /// - listChanged: Whether the server sends + /// `notifications/resources/list_changed`. public init( subscribe: Bool? = nil, listChanged: Bool? = nil @@ -149,23 +173,43 @@ public actor Server { } } - /// Tools capabilities + /// The `tools` capability: the server serves tools. public struct Tools: Hashable, Codable, Sendable { - /// Whether the server notifies clients when tools change + /// Whether the server sends `notifications/tools/list_changed` + /// when the list of tools changes. + /// + /// Declaring the flag does not send anything: call + /// ``Server/notify(_:)`` after each change. A + /// `subscriptions/listen` stream carries the notification only + /// when this is `true`; `nil` or `false` means the server does not + /// send it. public var listChanged: Bool? /// Creates the `tools` capability. + /// + /// - Parameter listChanged: Whether the server sends + /// `notifications/tools/list_changed`. public init(listChanged: Bool? = nil) { self.listChanged = listChanged } } - /// Prompts capabilities + /// The `prompts` capability: the server serves prompts. public struct Prompts: Hashable, Codable, Sendable { - /// Whether the server notifies clients when prompts change + /// Whether the server sends `notifications/prompts/list_changed` + /// when the list of prompts changes. + /// + /// Declaring the flag does not send anything: call + /// ``Server/notify(_:)`` after each change. A + /// `subscriptions/listen` stream carries the notification only + /// when this is `true`; `nil` or `false` means the server does not + /// send it. public var listChanged: Bool? /// Creates the `prompts` capability. + /// + /// - Parameter listChanged: Whether the server sends + /// `notifications/prompts/list_changed`. public init(listChanged: Bool? = nil) { self.listChanged = listChanged } @@ -277,24 +321,14 @@ public actor Server { /// The server connection private var connection: (any Transport)? /// The server logger - private var logger: Logger? { - get async { - await connection?.logger - } - } + private var logger: Logger? { connection?.logger } private let encoder: JSONEncoder = { let e = JSONEncoder() e.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] return e }() - /// Decodes incoming messages with `data:` URL strings kept as strings; - /// handlers get `.data` from their own typed decode. - private let decoder: JSONDecoder = { - let decoder = JSONDecoder() - decoder.userInfo[.valuePreservesStrings] = true - return decoder - }() + private let decoder = JSONDecoder() /// The server name public nonisolated var name: String { serverInfo.name } @@ -314,16 +348,17 @@ public actor Server { /// The server configuration public var configuration: Configuration - /// Request handlers - private var methodHandlers: [String: RequestHandlerBox] = [:] + /// Request handlers, by method name. A request selects one only by the + /// same code points: `ExactString` keys. + private var methodHandlers: [ExactString: RequestHandlerBox] = [:] /// The methods whose handler is the SDK's default, which `start` may /// replace; a handler registered with `withMethodHandler` is never replaced. - private var defaultHandlerMethods: Set = [] + private var defaultHandlerMethods: Set = [] /// The level of the last `logging/setLevel` on this connection; `nil` /// before one, when every message is sent. private var clientLogLevel: LogLevel? - /// Notification handlers - private var notificationHandlers: [String: [NotificationHandlerBox]] = [:] + /// Notification handlers, by method name (`ExactString`, as requests). + private var notificationHandlers: [ExactString: [NotificationHandlerBox]] = [:] /// Whether the built-in `notifications/cancelled` handler is registered: /// once per server, not on every `start`. private var registeredCancellationHandler = false @@ -352,12 +387,30 @@ public actor Server { /// `notifications/tasks/status`, with when each task expires. private var notifiedTasks: [String: (status: TaskStatus, expiresAt: Date?)] = [:] - /// Pending requests sent to the client, awaiting responses - private var pendingRequests: [ID: AnyPendingRequest] = [:] - /// Requests to the client that `send` created but has not registered in - /// `pendingRequests` yet. Removing an id withdraws the request before it - /// is sent. - private var unsentRequests: Set = [] + /// Pending requests sent to the client, awaiting responses, paired with the + /// originating client request ID so withdrawals and deprecated `cancelRequest` + /// route on the same stream. + private var pendingRequests: [ID: (pending: AnyPendingRequest, relatedRequestID: ID?)] = [:] + /// Lifecycle phase of a server-to-client request before its initial + /// `connection.send` completes. Keeping these phases in one map ensures + /// `send`, `withdraw`, and `stop()` stay consistent. + private enum OutgoingRequestPhase { + /// Created by `send(_:)` but not yet registered in `pendingRequests`. + case unsent + /// Initial `connection.send` is in flight; registered in + /// `pendingRequests` unless the client already answered before send returned. + case sending + /// Withdrawn while `connection.send` was in flight; its withdrawal + /// notification and caller resume wait until that send completes. + case withdrawnWhileSending(pending: AnyPendingRequest, relatedRequestID: ID?, reason: String?) + } + private var outgoingRequestPhases: [ID: OutgoingRequestPhase] = [:] + /// Server-to-client send tasks currently running their send or post-send cleanup (for tests). + private(set) var inFlightSendCount = 0 + /// Completed `withdraw(_:relatedTo:reason:)` calls (for tests). + private(set) var completedWithdrawalCount = 0 + /// Optional hook run before `send(_:)` registers a request (for tests). + private var beforeRegisteringOutgoingRequest: (@Sendable () async -> Void)? /// Incremented by ``stop()``. Work started for a connection that `stop()` /// ended carries the old value: a request received on it is not answered, /// and a request to its client that was not sent yet is not sent. @@ -377,11 +430,27 @@ public actor Server { /// The tasks handling `subscriptions/listen` requests, by request id, so /// that ``stop()`` can wait for the results of the streams it ends. private var listenRequests: [ID: Task] = [:] - /// Whether ``stop()`` is ending the listen streams; a stream that would - /// open meanwhile is refused. + /// Whether a ``stop()`` is in progress: a listen stream that would open + /// meanwhile is refused, another ``stop()`` or a `start` waits for this one, and + /// a `start` that is connecting counts as stopped. private var isStopping = false + /// Whether a waiter resumed from ``stopWaiters`` has not yet handed off to the next + /// one. Keeping new callers queued until it runs preserves FIFO order across queued + /// `start` and `stop()` calls. + private var isDrainingStopWaiters = false + /// The ``stop()`` and `start` calls that wait for the stop in progress to finish. + private var stopWaiters: [CheckedContinuation] = [] /// The task for the message handling loop private var task: Task? + /// How the last run ended, for ``waitUntilCompleted()``: `nil` from the moment + /// ``start(transport:initializeHook:statelessRequestHook:)`` begins a run until its + /// loop ends, `stop()` ends it, or `start` fails. Before the first start it is a normal + /// end, so a wait returns at once. + private var loopOutcome: Result? = .success(()) + /// Counts the runs started, so the end of a replaced run doesn't settle the current one. + private var loopRun = 0 + /// The callers of ``waitUntilCompleted()`` waiting for the current run to end. + private var loopWaiters: [CheckedContinuation] = [] /// Whether ``start(transport:initializeHook:statelessRequestHook:)`` got an initialize hook. private var hasInitializeHook = false /// Runs before each stateless request; see ``start(transport:initializeHook:statelessRequestHook:)``. @@ -462,8 +531,12 @@ public actor Server { /// not sent on the connection, and with /// ``Configuration/strict-swift.property`` later requests are refused. /// + /// A call while ``stop()`` is in progress waits until that `stop()` has + /// disconnected its transport, and then begins a new run. + /// /// - Parameters: - /// - transport: The transport to use for the server + /// - transport: The transport to use for the server. `start` calls its + /// ``Transport/connect()``, so pass one that is not connected yet. /// - initializeHook: An optional hook that runs when the client sends an /// initialize request, in the SDK's `Initialize` handler /// - statelessRequestHook: An optional hook that runs before every @@ -475,11 +548,43 @@ public actor Server { /// `initializeHook` cannot be bypassed; clients then fall back to /// `initialize`. Behind ``StatelessHTTPServerTransport`` handshake /// requests other than `initialize` are then refused with -32600. + /// - Throws: The error ``Transport/connect()`` throws; + /// ``MCPError/internalError(_:)`` when the server is already starting or running, + /// or when ``stop()`` is called while `connect()` is pending and `connect()` then + /// succeeds. When `start` fails after beginning a run without a ``stop()``, the run + /// fails with the error: ``waitUntilCompleted()`` throws it until the next `start`. + /// A ``stop()`` meanwhile ends the run normally instead. public func start( transport: any Transport, initializeHook: (@Sendable (Client.Info, Client.Capabilities) async throws -> Void)? = nil, statelessRequestHook: StatelessRequestHook? = nil ) async throws { + // A stop() in progress releases the waiters of its run once it has disconnected: + // the next run begins after that, in FIFO order across queued start/stop calls. + var resumedFromQueue = false + while isStopping || (isDrainingStopWaiters && !resumedFromQueue) { + resumedFromQueue = false + await withCheckedContinuation { stopWaiters.append($0) } + resumedFromQueue = true + } + defer { + if resumedFromQueue { + resumeNextStopWaiter() + } + } + guard loopOutcome != nil else { + throw MCPError.internalError("Server is already started") + } + // A new run begins: from here on waitUntilCompleted() waits for it, not for the + // outcome of the run before. + loopRun += 1 + let run = loopRun + loopOutcome = nil + // No stop() is in progress here. One in progress later, or one that has + // incremented the generation, stopped this run while it connected: a stop() sets + // isStopping before it first suspends, and increments the generation only after. + let generation = connectionGeneration + func stopped() -> Bool { isStopping || connectionGeneration != generation || run != loopRun } self.connection = transport self.hasInitializeHook = initializeHook != nil self.statelessRequestHook = statelessRequestHook @@ -488,18 +593,37 @@ public actor Server { registeredCancellationHandler = true registerCancellationHandler() } - if let stateless = transport as? StatelessHTTPServerTransport { - await stateless.serve(protocolVersions: configuration.protocolVersions) + // Hand off the queue before the first suspension so any waiter behind us + // (such as a queued stop() or second start()) observes this run. + if resumedFromQueue { + resumedFromQueue = false + resumeNextStopWaiter() + } + do { + await transport.prepare(servingProtocolVersions: configuration.protocolVersions) + try await transport.connect() + guard !stopped() else { + // stop() disconnects the transport, if it has not yet, and ends the run. + await transport.disconnect() + throw MCPError.internalError("Server stopped while starting") + } + } catch { + // Fails the run's waiters with the error. After a stop(), that stop() ends + // the run normally once it has disconnected the transport. + if !stopped() { + self.connection = nil + loopDidEnd(run: run, error: error) + } + throw error } - try await transport.connect() - await logger?.debug( + logger?.debug( "Server started", metadata: ["name": "\(name)", "version": "\(version)"] ) // Start message handling loop - let generation = connectionGeneration task = Task { + var streamError: (any Swift.Error)? do { let stream = await transport.receive() for try await data in stream { @@ -526,7 +650,7 @@ public actor Server { do { try await self.handleBatch(admitted, generation: generation) } catch { - await self.logger?.error( + self.logger?.error( "Error processing batch", metadata: ["error": "\(error)"]) } } @@ -539,7 +663,7 @@ public actor Server { AnyMethod.response( id: request.id, error: .invalidRequest(Self.inProgress(request.id)))) } catch { - await logger?.error( + logger?.error( "Failed to send error response", metadata: ["id": "\(request.id)", "error": "\(error)"]) } @@ -576,12 +700,12 @@ public actor Server { // that request, which would otherwise never complete. guard let item = try? decoder.decode(Server.Batch.Item.self, from: data) else { let error = JSONRPCMessageKind.classificationError(for: data) - await logger?.warning("Invalid message", metadata: ["error": "\(error)"]) + logger?.warning("Invalid message", metadata: ["error": "\(error)"]) await sendUnattributedError(error) continue } let error = MCPError.invalidRequest("Invalid JSON-RPC message") - await logger?.warning("Invalid message", metadata: ["error": "\(error)"]) + logger?.warning("Invalid message", metadata: ["error": "\(error)"]) switch item { case .invalid(let id?, _): try? await send(AnyMethod.response(id: id, error: error)) @@ -593,22 +717,64 @@ public actor Server { await sendUnattributedError(error) } } - } catch let error where MCPError.isResourceTemporarilyUnavailable(error) { - // Resource temporarily unavailable, retry after a short delay - try? await Task.sleep(for: .milliseconds(10)) - continue } catch { // Unreadable messages are answered above; errors from // notification handling are only logged. - await logger?.error( + logger?.error( "Error processing message", metadata: ["error": "\(error)"]) } } } catch { - await logger?.error( - "Fatal error in message handling loop", metadata: ["error": "\(error)"]) + // The stream threw. An error after stop() cancelled the loop is part of + // stopping, and connectionClosed means the peer closed the connection: the + // normal end, like a stream that finishes. Any other error, a + // CancellationError from the stream of a loop stop() did not cancel included, + // is a failure of the transport, for example a stdio read. + if Task.isCancelled || isStopping { + logger?.debug( + "Message handling loop ended by stop()", metadata: ["error": "\(error)"]) + } else if case .connectionClosed? = error as? MCPError { + logger?.debug("Connection closed by the peer", metadata: [:]) + } else { + logger?.error( + "Fatal error in message handling loop", metadata: ["error": "\(error)"]) + streamError = error + } + } + logger?.debug("Server finished", metadata: [:]) + // Cancelled by stop() (or stop() is already in progress), which settles the + // waiters once it has disconnected. + if !Task.isCancelled && !isStopping { + loopDidEnd(run: run, error: streamError) } - await logger?.debug("Server finished", metadata: [:]) + } + } + + /// Settles ``waitUntilCompleted()`` for run `run`: every waiter returns, or throws + /// `error`. Does nothing when a later start replaced the run, or the loop, ``stop()`` + /// or a failed start already settled it. + private func loopDidEnd(run: Int, error: (any Swift.Error)?) { + guard run == loopRun, loopOutcome == nil else { return } + let outcome: Result = error.map { .failure($0) } ?? .success(()) + loopOutcome = outcome + let waiters = loopWaiters + loopWaiters = [] + for waiter in waiters { + waiter.resume(with: outcome) + } + } + + /// Hands off to the next queued `stop()` or `start()` call, or ends draining when none remain. + private func resumeNextStopWaiter() { + guard !isStopping else { + isDrainingStopWaiters = false + return + } + if !stopWaiters.isEmpty { + isDrainingStopWaiters = true + stopWaiters.removeFirst().resume() + } else { + isDrainingStopWaiters = false } } @@ -623,9 +789,34 @@ public actor Server { /// ``start(transport:initializeHook:statelessRequestHook:)``; the next /// connection starts from a fresh handshake, with no client info, /// capabilities or negotiated protocol version from the previous one. + /// + /// A call while another `stop()` is in progress waits until that one has + /// disconnected the transport. If a new run began before this call resumed + /// (for example from a `start` queued ahead of it on the same `stop()`), it + /// stops that run too before returning. public func stop() async { + // A second stop() would find no connection and release the waiters of + // waitUntilCompleted() while the first one is still disconnecting. + if isStopping || isDrainingStopWaiters { + var resumedFromQueue = false + while isStopping || (isDrainingStopWaiters && !resumedFromQueue) { + resumedFromQueue = false + await withCheckedContinuation { stopWaiters.append($0) } + resumedFromQueue = true + } + // If the server is already stopped, hand off to the next waiter and return. + // Otherwise stop the active run before returning. + if loopOutcome != nil && connection == nil { + resumeNextStopWaiter() + return + } + } isStopping = true - defer { isStopping = false } + isDrainingStopWaiters = false + defer { + isStopping = false + resumeNextStopWaiter() + } closeSubscriptions() // The handlers resume only once this suspends: closing the // transport first lost their results. @@ -640,6 +831,8 @@ public actor Server { notifiedTasks = [:] task?.cancel() task = nil + // Waiters return once the transport is disconnected below, whatever the stream does. + let stoppedRun = loopRun unassociatedRequestMethods = [] clientLogLevel = nil toolNameWarnings = ToolNameWarnings() @@ -657,9 +850,15 @@ public actor Server { // fails when it would register. let pendingRequestsToCancel = self.pendingRequests self.pendingRequests = [:] - unsentRequests.removeAll() - for (_, request) in pendingRequestsToCancel { - request.resume(throwing: MCPError.internalError("Server disconnected")) + let phasesToCancel = self.outgoingRequestPhases + self.outgoingRequestPhases = [:] + for (_, entry) in pendingRequestsToCancel { + entry.pending.resume(throwing: MCPError.internalError("Server disconnected")) + } + for (_, phase) in phasesToCancel { + if case .withdrawnWhileSending(let pending, _, _) = phase { + pending.resume(throwing: CancellationError()) + } } // The handshake belongs to the connection: after a restart the next @@ -674,16 +873,69 @@ public actor Server { let stoppedConnection = connection connection = nil await stoppedConnection?.disconnect() + loopDidEnd(run: stoppedRun, error: nil) } - /// Waits until the message handling loop ends. + /// Waits until the message handling loop ends, and throws the error it ended with. + /// + /// The loop ends normally, and this method returns, when: + /// + /// - the transport finishes its receive stream, for example when standard input closes; + /// - the stream throws ``MCPError/connectionClosed``: the peer closed the connection, as + /// when an ``InMemoryTransport``'s peer disconnects or a `NetworkTransport`'s peer + /// closes it gracefully; + /// - ``stop()`` ends it, once the transport is disconnected. + /// + /// The HTTP server transports end their stream normally, at ``stop()`` and when the + /// client ends the session. /// - /// The loop ends when the transport stops delivering messages or on - /// ``stop()``. Returns at once when the server was not started. - public func waitUntilCompleted() async { - await task?.value + /// The loop fails, and this method throws, when the stream throws any other error: the + /// transport failed, for example ``MCPError/transportError(_:)`` when a read from + /// standard input fails, or when a `NetworkTransport` loses its connection. + /// + /// The wait doesn't end when the calling task is cancelled: it lasts until the loop + /// ends, and after ``stop()`` until the transport is disconnected. To stop the server + /// when the caller is cancelled, call ``stop()`` from a cancellation handler: + /// + /// ```swift + /// try await withTaskCancellationHandler { + /// try await server.waitUntilCompleted() + /// } onCancel: { + /// Task { await server.stop() } + /// } + /// ``` + /// + /// Each ``start(transport:initializeHook:statelessRequestHook:)`` begins a run, and a + /// call waits for the current one: once `start` has begun its run, the outcome of the + /// run before no longer answers. `start` begins it at once, or, when a ``stop()`` is in + /// progress, once that `stop()` has disconnected its transport: a call in between gets + /// the stopped run's outcome. When `start` throws after beginning a run, for example + /// because ``Transport/connect()`` failed, the run fails with that error; a `start` + /// that throws because a run is already active leaves that run unaffected. A ``stop()`` + /// while `start` is still connecting ends the run normally, once the transport is + /// disconnected, and `start` throws. + /// + /// Every caller gets the same outcome. A call after the run ended returns or throws at + /// once, with that run's outcome, until the next `start`; a loop that failed before + /// ``stop()`` keeps its error. A call before the server was ever started returns at once. + /// + /// - Throws: The error the transport's receive stream threw, other than + /// ``MCPError/connectionClosed``, or the error + /// ``start(transport:initializeHook:statelessRequestHook:)`` threw for this run. + public func waitUntilCompleted() async throws { + if let loopOutcome { return try loopOutcome.get() } + try await withCheckedThrowingContinuation { + (continuation: CheckedContinuation) in + loopWaiters.append(continuation) + } } + /// The ``waitUntilCompleted()`` calls waiting for the loop to end. Tests wait on it. + var completionWaiterCount: Int { loopWaiters.count } + + /// The ``stop()`` and `start` calls waiting for the stop in progress. Tests wait on it. + var stopWaiterCount: Int { stopWaiters.count } + // MARK: - Request Context /// Per-dispatch context the SDK attaches to the currently executing handler. @@ -696,10 +948,10 @@ public actor Server { /// (e.g. transports closing an SSE stream mid-call per SEP-1699). package let id: ID - /// The originating HTTP request, if the active transport conforms to - /// ``HTTPContextProviding``. `nil` for transports that don't carry HTTP - /// context (stdio, in-memory) or for handlers reached off the dispatch - /// path. + /// The originating HTTP request, from the transport's + /// ``Transport/httpRequest(for:)``. `nil` for transports that don't + /// carry HTTP context (stdio, in-memory) or for handlers reached off the + /// dispatch path. public let httpContext: HTTPRequest? /// The protocol version of the request: from its `_meta` for stateless @@ -801,14 +1053,14 @@ public actor Server { handler: @escaping @Sendable (M.Parameters) async throws -> M.Result ) -> Self { let roundTrips = MRTR.carriers.contains(M.name) - methodHandlers[M.name] = TypedRequestHandler { [weak self] (request: Request) -> Response in + methodHandlers[ExactString(M.name)] = TypedRequestHandler { [weak self] (request: Request) -> Response in guard roundTrips, let self else { return Response(id: request.id, result: try await handler(request.params)) } let result = try await self.serveRoundTrips(M.self, request.params, handler: handler) return Response(id: request.id, result: result) } - defaultHandlerMethods.remove(M.name) + defaultHandlerMethods.remove(ExactString(M.name)) return self } @@ -816,9 +1068,10 @@ public actor Server { private func registerDefault( _ type: M.Type, handler: @escaping @Sendable (M.Parameters) async throws -> M.Result ) { - guard methodHandlers[M.name] == nil || defaultHandlerMethods.contains(M.name) else { return } + let name = ExactString(M.name) + guard methodHandlers[name] == nil || defaultHandlerMethods.contains(name) else { return } withMethodHandler(type, handler: handler) - defaultHandlerMethods.insert(M.name) + defaultHandlerMethods.insert(name) } // MARK: - Tasks (SEP-1686, SEP-2663) @@ -991,7 +1244,7 @@ public actor Server { let tasks = try await manager.list(context: context, generation: .v1) var start = 0 if let cursor = params.cursor { - guard let index = tasks.firstIndex(where: { $0.id == cursor }) else { + guard let index = tasks.firstIndex(where: { $0.id.isExactly(cursor) }) else { throw MCPError.invalidParams("Invalid cursor") } start = index @@ -1088,8 +1341,8 @@ public actor Server { else { return } try? await connection.send(data) case .v2: - guard listeners.values.contains(where: { $0.tasks.contains(record.id) }), - let snapshot = try? Value.preservingStrings(record.snapshot(detailed: true)) + guard listeners.values.contains(where: { $0.tasks.contains(ExactString(record.id)) }), + let snapshot = try? Value(record.snapshot(detailed: true)) else { return } publish(.task(id: record.id, snapshot: snapshot), to: nil) } @@ -1376,16 +1629,16 @@ public actor Server { return .roots(try await ask(ListRoots.request(_meta: meta))) case .unknown(let method, let params): return .unknown( - try await ask(Request(method: method, params: params, _meta: meta)).value) + try await ask(Request(method: method, params: params, _meta: meta))) } } /// A bridged input request of a method the SDK does not know: its - /// result is kept as received, with `data:` URL strings as written. + /// result is kept as received. private enum UnknownInputRequest: Method { static var name: String { "" } typealias Parameters = Value - typealias Result = Value.Preserved + typealias Result = Value } /// Sends one bridged request to the client. A client error fails the @@ -1393,18 +1646,59 @@ public actor Server { /// cancellation withdraws the request. private func ask(_ request: Request) async throws -> M.Result { try Task.checkCancellation() + let relatedRequestID = Server.currentHandlerContext?.id let task = try send(request) do { - return try await withTaskCancellationHandler { - try await task.value - } onCancel: { - Task { await self.withdraw(request.id) } - } + return try await result( + of: task, withdrawing: request.id, relatedTo: relatedRequestID, + reason: "The request that needed this input was cancelled") } catch let error as MCPError where !Self.isConnectionFailure(error) { throw MCPError.internalError("The client failed \(request.method): \(error.localizedDescription)") } } + /// Sends a request to the client and waits for its result. Cancelling the + /// caller withdraws the request: the client gets `notifications/cancelled`. + private func sendAndAwait(_ request: Request, cancellationReason: String) async throws -> M.Result { + try Task.checkCancellation() + let relatedRequestID = Server.currentHandlerContext?.id + return try await result( + of: send(request), withdrawing: request.id, relatedTo: relatedRequestID, reason: cancellationReason) + } + + /// Waits for the result of the request `id` names; cancelling the caller + /// withdraws the request. `relatedRequestID` is the client request the + /// request was sent for, as `send(_:)` routes it: the withdrawal takes the + /// same route, whichever task cancels the caller. + func result( + of task: Task, withdrawing id: ID, relatedTo relatedRequestID: ID?, reason: String + ) async throws -> R { + try await withTaskCancellationHandler { + try await task.value + } onCancel: { + Task { await self.withdraw(id, relatedTo: relatedRequestID, reason: reason) } + } + } + + /// Withdrawn server-to-client requests waiting for their initial send to finish (for tests). + var pendingWithdrawalCount: Int { + outgoingRequestPhases.values.reduce(into: 0) { count, phase in + if case .withdrawnWhileSending = phase { count += 1 } + } + } + + /// Server-to-client requests created by `send(_:)` and not yet registered (for tests). + var unsentRequestCount: Int { + outgoingRequestPhases.values.reduce(into: 0) { count, phase in + if case .unsent = phase { count += 1 } + } + } + + /// Installs a test hook that runs just before `send(_:)` registers a request. + func setBeforeRegisteringOutgoingRequest(_ hook: (@Sendable () async -> Void)?) { + beforeRegisteringOutgoingRequest = hook + } + /// Whether `error` is the transport's, not the client's answer. private static func isConnectionFailure(_ error: MCPError) -> Bool { switch error { @@ -1413,17 +1707,47 @@ public actor Server { } } - /// Ends a bridged request whose carrier was cancelled, and tells the - /// client. A request not sent yet is not sent at all. - private func withdraw(_ id: ID) async { - guard let pending = removePendingResponse(id: id) else { - unsentRequests.remove(id) + /// The `reason` of the `notifications/cancelled` that withdraws a request + /// whose caller was cancelled. + private static let stoppedWaitingReason = "The server stopped waiting for the response" + + /// Ends a request to the client whose caller was cancelled, and tells the + /// client. A request not sent yet is not sent at all; one whose initial + /// `connection.send` is still in flight is withdrawn once that send + /// finishes. The awaiting caller resumes only after the withdrawal send + /// returns, so a handler catching `CancellationError` cannot close the + /// parent stream first. The notification goes with `relatedRequestID`, the + /// route of the request it withdraws. + private func withdraw(_ id: ID, relatedTo relatedRequestID: ID?, reason: String) async { + defer { completedWithdrawalCount += 1 } + guard let pending = removePendingResponse(id: id)?.pending else { + if case .unsent = outgoingRequestPhases[id] { + outgoingRequestPhases.removeValue(forKey: id) + } + return + } + if case .sending = outgoingRequestPhases[id] { + outgoingRequestPhases[id] = .withdrawnWhileSending( + pending: pending, relatedRequestID: relatedRequestID, reason: reason) return } - pending.resume(throwing: CancellationError()) - try? await notify( - CancelledNotification.message( - .init(requestId: id, reason: "The request that needed this input was cancelled"))) + defer { pending.resume(throwing: CancellationError()) } + guard let connection else { return } + await sendWithdrawal(id: id, relatedTo: relatedRequestID, reason: reason, on: connection) + } + + /// Sends `notifications/cancelled` for `id` on `connection`, logging any + /// send failure at debug level. + private func sendWithdrawal( + id: ID, relatedTo relatedRequestID: ID?, reason: String?, on connection: any Transport + ) async { + do { + let cancelled = CancelledNotification.message(.init(requestId: id, reason: reason)) + try await connection.send( + encoder.encode(cancelled), options: TransportSendOptions(relatedRequestID: relatedRequestID)) + } catch { + logger?.debug("Withdrawal not sent", metadata: ["requestId": "\(id)", "error": "\(error)"]) + } } /// Register a notification handler @@ -1432,7 +1756,7 @@ public actor Server { _ type: N.Type, handler: @escaping @Sendable (Message) async throws -> Void ) -> Self { - notificationHandlers[N.name, default: []].append(TypedNotificationHandler(handler)) + notificationHandlers[ExactString(N.name), default: []].append(TypedNotificationHandler(handler)) return self } @@ -1498,17 +1822,17 @@ public actor Server { guard isInitialized || sessionlessHandshake else { return } } try await connection.send( - notificationData, relatedRequestID: Server.currentHandlerContext?.id) + notificationData, options: TransportSendOptions(relatedRequestID: Server.currentHandlerContext?.id)) } // MARK: - Subscriptions (2026-07-28) private struct Listener { let filter: SubscriptionFilter - /// `filter.resourceSubscriptions`, for lookups. - let resources: Set - /// `filter.taskIds`, for lookups. - let tasks: Set + /// `filter.resourceSubscriptions`, for lookups by the same code points. + let resources: Set + /// `filter.taskIds`, for lookups by the same code points. + let tasks: Set /// The caller, for ``notify(_:to:)``. let context: HandlerContext let events: AsyncStream.Continuation @@ -1583,8 +1907,8 @@ public actor Server { private func checked(_ requested: SubscriptionFilter) throws -> SubscriptionFilter { var filter = requested if let uris = requested.resourceSubscriptions { - var seen: Set = [] - let unique = uris.filter { seen.insert($0).inserted } + var seen: Set = [] + let unique = uris.filter { seen.insert(ExactString($0)).inserted } guard unique.count <= configuration.maxResourceSubscriptions else { throw MCPError.invalidParams( "A listen stream may name at most \(configuration.maxResourceSubscriptions) resources") @@ -1596,8 +1920,8 @@ public actor Server { filter.resourceSubscriptions = unique } if let ids = requested.taskIds { - var seen: Set = [] - let unique = ids.filter { seen.insert($0).inserted } + var seen: Set = [] + let unique = ids.filter { seen.insert(ExactString($0)).inserted } guard unique.count <= configuration.maxResourceSubscriptions else { throw MCPError.invalidParams( "A listen stream may name at most \(configuration.maxResourceSubscriptions) tasks") @@ -1656,18 +1980,20 @@ public actor Server { // Register before the acknowledgement so no event is lost; the // acknowledgement is still first because only this task writes. listeners[token] = Listener( - filter: filter, resources: Set(filter.resourceSubscriptions ?? []), tasks: Set(filter.taskIds ?? []), + filter: filter, resources: Set((filter.resourceSubscriptions ?? []).map { ExactString($0) }), + tasks: Set((filter.taskIds ?? []).map { ExactString($0) }), context: context, events: continuation) defer { listeners[token] = nil } let ack = Message( method: SubscriptionsAcknowledgedNotification.name, params: .init(notifications: filter), _meta: meta) - try await connection.send(encoder.encode(ack), relatedRequestID: context.id) + try await connection.send(encoder.encode(ack), options: TransportSendOptions(relatedRequestID: context.id)) for await event in events { try await connection.send( - encoder.encode(event.message(subscriptionID: context.id)), relatedRequestID: context.id) + encoder.encode(event.message(subscriptionID: context.id)), + options: TransportSendOptions(relatedRequestID: context.id)) } try Task.checkCancellation() return SubscriptionsListen.Result(_meta: meta) @@ -1686,12 +2012,12 @@ public actor Server { do { try await connection.send(encoder.encode(cancelled)) } catch { - await logger?.debug("Listen teardown not sent", metadata: ["error": "\(error)"]) + logger?.debug("Listen teardown not sent", metadata: ["error": "\(error)"]) } } /// Send a request to the client and return a Task for the response - private func send(_ request: Request) throws -> Task { + func send(_ request: Request) throws -> Task { guard let connection = connection else { throw MCPError.internalError("Server connection not initialized") } @@ -1705,12 +2031,17 @@ public actor Server { let generation = connectionGeneration let warning = unassociatedRequestWarning(M.name) - unsentRequests.insert(request.id) + outgoingRequestPhases[request.id] = .unsent + inFlightSendCount += 1 let requestTask = Task { try await withCheckedThrowingContinuation { continuation in Task { + defer { self.inFlightSendCount -= 1 } + if let hook = self.beforeRegisteringOutgoingRequest { + await hook() + } if let warning { - await self.logger?.warning("\(warning)", metadata: ["method": "\(M.name)"]) + self.logger?.warning("\(warning)", metadata: ["method": "\(M.name)"]) } // No suspension from here to the registration, so a // withdraw either finds the id unsent or registered. @@ -1720,7 +2051,7 @@ public actor Server { continuation.resume(throwing: MCPError.internalError("Server disconnected")) return } - guard self.unsentRequests.remove(request.id) != nil else { + guard case .unsent = self.outgoingRequestPhases.removeValue(forKey: request.id) else { // Withdrawn before it was registered. continuation.resume(throwing: CancellationError()) return @@ -1729,17 +2060,36 @@ public actor Server { self.addPendingResponse( id: request.id, continuation: continuation, - type: M.Result.self + type: M.Result.self, + relatedRequestID: relatedRequestID ) + self.outgoingRequestPhases[request.id] = .sending // Send the request + let sendError: (any Swift.Error)? do { try await connection.send( - requestData, relatedRequestID: relatedRequestID) + requestData, options: TransportSendOptions(relatedRequestID: relatedRequestID)) + sendError = nil } catch { + sendError = error + } + + guard generation == self.connectionGeneration else { return } + let phase = self.outgoingRequestPhases.removeValue(forKey: request.id) + if case .withdrawnWhileSending(let pending, let withdrawalRelatedID, let reason) = phase { + defer { pending.resume(throwing: CancellationError()) } + if sendError == nil { + await self.sendWithdrawal( + id: request.id, + relatedTo: withdrawalRelatedID, + reason: reason, + on: connection) + } + } else if let sendError { // If send fails, remove pending response and resume with error - if self.removePendingResponse(id: request.id) != nil { - continuation.resume(throwing: error) + if let pending = self.removePendingResponse(id: request.id)?.pending { + pending.resume(throwing: sendError) } } } @@ -1800,21 +2150,23 @@ public actor Server { private func addPendingResponse( id: ID, continuation: CheckedContinuation, - type: T.Type + type: T.Type, + relatedRequestID: ID? = nil ) { - pendingRequests[id] = AnyPendingRequest( - PendingRequest(continuation: continuation) + pendingRequests[id] = ( + pending: AnyPendingRequest(PendingRequest(continuation: continuation)), + relatedRequestID: relatedRequestID ) } - private func removePendingResponse(id: ID) -> AnyPendingRequest? { + private func removePendingResponse(id: ID) -> (pending: AnyPendingRequest, relatedRequestID: ID?)? { return pendingRequests.removeValue(forKey: id) } /// Fails the request `id` names, answered by a message that cannot be /// read; it would otherwise never complete. private func failPendingRequest(answeredBy id: ID) { - removePendingResponse(id: id)?.resume( + removePendingResponse(id: id)?.pending.resume( throwing: MCPError.internalError("The client sent an invalid response")) } @@ -1845,6 +2197,16 @@ public actor Server { /// `toolChoice: .init(mode: .none)` on the last round to get a final /// answer. /// + /// Cancelling the task that awaits this method withdraws the request: the + /// client gets `notifications/cancelled`, and this throws + /// `CancellationError`. The notification takes the route of the request. + /// Over HTTP, after the client cancelled the request whose handler awaits + /// this method, that route is closed: ``StatefulHTTPServerTransport`` sends + /// it on the session's GET stream, or stores it for replay when none is + /// open, and ``StatelessHTTPServerTransport`` doesn't send it. When the + /// client has already answered, this returns the answer and sends no + /// `notifications/cancelled`. + /// /// - Parameters: /// - messages: The conversation history to send to the LLM /// - modelPreferences: Model selection preferences @@ -1864,7 +2226,8 @@ public actor Server { /// `includeContext` is not `none` and the client did not declare /// `sampling.context`. ``MCPError/invalidParams(_:)`` when the messages /// break the rules for tool uses and tool results. The SDK checks these - /// before it sends the request. + /// before it sends the request. `CancellationError` when the task that + /// awaits this method is cancelled before the client answers. /// - SeeAlso: https://modelcontextprotocol.io/specification/2025-11-25/client/sampling @available(*, deprecated, message: "Sampling is deprecated by the specification (SEP-2577) and can be removed in the first revision released on or after 2027-07-28. To migrate, call the API of an LLM provider from the server.") public func requestSampling( @@ -1910,7 +2273,8 @@ public actor Server { throw MCPError.invalidParams(problem) } - return try await send(CreateSamplingMessage.request(params)).value + return try await sendAndAwait( + CreateSamplingMessage.request(params), cancellationReason: Self.stoppedWaitingReason) } // MARK: - Elicitation @@ -1932,13 +2296,24 @@ public actor Server { /// server handles no client request, it is sent anyway, and the server logs /// one warning for each method. /// + /// Cancelling the task that awaits this method withdraws the request: the + /// client gets `notifications/cancelled`, and this throws + /// `CancellationError`. The notification takes the route of the request. + /// Over HTTP, after the client cancelled the request whose handler awaits + /// this method, that route is closed: ``StatefulHTTPServerTransport`` sends + /// it on the session's GET stream, or stores it for replay when none is + /// open, and ``StatelessHTTPServerTransport`` doesn't send it. When the + /// client has already answered, this returns the answer and sends no + /// `notifications/cancelled`. + /// /// - Parameters: /// - message: The message to display to the user /// - mode: The elicitation mode (form or url) /// - requestedSchema: Optional JSON schema describing the expected response /// - _meta: Optional request metadata /// - Returns: The elicitation result containing the action and optional content - /// - Throws: MCPError if the request fails + /// - Throws: MCPError if the request fails; `CancellationError` when the + /// task that awaits this method is cancelled before the client answers. /// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/elicitation public func requestElicitation( message: String, @@ -1963,8 +2338,7 @@ public actor Server { ) ) - let result = try await send(request).value - return result + return try await sendAndAwait(request, cancellationReason: Self.stoppedWaitingReason) } /// Request user input from the client using URL-based elicitation @@ -1977,13 +2351,24 @@ public actor Server { /// server handles no client request, it is sent anyway, and the server logs /// one warning for each method. /// + /// Cancelling the task that awaits this method withdraws the request: the + /// client gets `notifications/cancelled`, and this throws + /// `CancellationError`. The notification takes the route of the request. + /// Over HTTP, after the client cancelled the request whose handler awaits + /// this method, that route is closed: ``StatefulHTTPServerTransport`` sends + /// it on the session's GET stream, or stores it for replay when none is + /// open, and ``StatelessHTTPServerTransport`` doesn't send it. When the + /// client has already answered, this returns the answer and sends no + /// `notifications/cancelled`. + /// /// - Parameters: /// - message: The message to display to the user /// - url: The URL to direct the user to /// - elicitationId: Unique identifier for this elicitation /// - _meta: Optional request metadata /// - Returns: The elicitation result containing the action and optional content - /// - Throws: MCPError if the request fails + /// - Throws: MCPError if the request fails; `CancellationError` when the + /// task that awaits this method is cancelled before the client answers. /// - SeeAlso: https://modelcontextprotocol.io/docs/concepts/elicitation public func requestElicitation( message: String, @@ -2008,8 +2393,7 @@ public actor Server { ) ) - let result = try await send(request).value - return result + return try await sendAndAwait(request, cancellationReason: Self.stoppedWaitingReason) } // MARK: - Logging @@ -2075,8 +2459,20 @@ public actor Server { /// The client must have declared the `roots` capability and registered /// a roots handler for this to work. /// + /// Cancelling the task that awaits this method withdraws the request: the + /// client gets `notifications/cancelled`, and this throws + /// `CancellationError`. The notification takes the route of the request. + /// Over HTTP, after the client cancelled the request whose handler awaits + /// this method, that route is closed: ``StatefulHTTPServerTransport`` sends + /// it on the session's GET stream, or stores it for replay when none is + /// open, and ``StatelessHTTPServerTransport`` doesn't send it. When the + /// client has already answered, this returns the answer and sends no + /// `notifications/cancelled`. + /// /// - Returns: Array of Root objects representing accessible directories/files - /// - Throws: MCPError if the client doesn't support roots or request fails + /// - Throws: MCPError if the client doesn't support roots or request fails; + /// `CancellationError` when the task that awaits this method is + /// cancelled before the client answers. /// - SeeAlso: https://modelcontextprotocol.io/specification/2025-11-25/client/roots @available(*, deprecated, message: "Roots is deprecated by the specification (SEP-2577) and can be removed in the first revision released on or after 2027-07-28. To migrate, pass directories or files in tool arguments, resource URIs or server configuration.") public func listRoots() async throws -> [Root] { @@ -2087,7 +2483,7 @@ public actor Server { try validateClientCapability(\.roots, "Roots") let request = ListRoots.request() - let result = try await send(request).value + let result = try await sendAndAwait(request, cancellationReason: Self.stoppedWaitingReason) return result.roots } @@ -2138,7 +2534,7 @@ public actor Server { /// - Parameter generation: The ``connectionGeneration`` the batch was /// received in; nothing is sent once ``stop()`` changed it. private func handleBatch(_ batch: Batch, generation: Int) async throws { - await logger?.trace("Processing batch request", metadata: ["size": "\(batch.items.count)"]) + logger?.trace("Processing batch request", metadata: ["size": "\(batch.items.count)"]) guard generation == connectionGeneration else { return } if batch.items.isEmpty { @@ -2238,7 +2634,7 @@ public actor Server { return nil } - await logger?.trace( + logger?.trace( "Processing request", metadata: [ "method": "\(request.method)", @@ -2341,15 +2737,14 @@ public actor Server { } // Find handler for method name - guard let handler = methodHandlers[request.method] else { + guard let handler = methodHandlers[ExactString(request.method)] else { return try await reject(.methodNotFound("Unknown method: \(request.method)")) } // Ask the transport for the originating HTTP request so handlers can observe // headers/auth via `Server.currentHandlerContext?.httpContext`. Transports - // that don't carry HTTP context (stdio, in-memory) don't conform. - let httpContext = await (connection as? any HTTPContextProviding)? - .httpRequestContext(for: request.id) + // that don't carry HTTP context (stdio, in-memory) return nil. + let httpContext = await connection?.httpRequest(for: request.id) // `stop()` may have run meanwhile, and a new connection may have started. guard generation == connectionGeneration else { untrackStarting() @@ -2400,7 +2795,8 @@ public actor Server { let resourceSources = request.method == ReadResource.name || request.method == ListResources.name ? builtInResourceSources : [] let applicationList = - defaultHandlerMethods.contains(ListResources.name) ? nil : methodHandlers[ListResources.name] + defaultHandlerMethods.contains(ExactString(ListResources.name)) + ? nil : methodHandlers[ExactString(ListResources.name)] let handlerContext = dispatchContext // Checked in the handler task, after the stateless hook, so it can be // cancelled and an unauthorized client cannot trigger it. @@ -2457,7 +2853,7 @@ public actor Server { } if let declared = handlerContext.clientCapabilities { - DeprecationNotices.current.log(forClient: declared, to: await self.logger) + DeprecationNotices.current.log(forClient: declared, to: self.logger) } var context = handlerContext @@ -2493,7 +2889,7 @@ public actor Server { return annotate(response) } catch is CancellationError { // Request was cancelled, don't send a response per MCP spec - await logger?.debug( + logger?.debug( "Request cancelled", metadata: ["id": "\(request.id)", "method": "\(request.method)"] ) @@ -2599,7 +2995,7 @@ public actor Server { let hasHeaders = http.headers.keys.contains { $0.lowercased().hasPrefix(prefix) } // Nothing to compare: skip the schema lookup. if arguments?.objectValue?.isEmpty ?? true, !hasHeaders { return nil } - guard methodHandlers[ListTools.name] != nil else { + guard methodHandlers[ExactString(ListTools.name)] != nil else { return hasHeaders ? .headerMismatch("No input schema to check the Mcp-Param headers against") : nil } let name = params?["name"]?.stringValue ?? "" @@ -2654,11 +3050,11 @@ public actor Server { context: HandlerContext, request: Request, listing: inout ToolListing? ) async throws -> [String: ToolInfo]? { if let listing { return listing.tools } - guard let handler = methodHandlers[ListTools.name] else { return nil } + guard let handler = methodHandlers[ExactString(ListTools.name)] else { return nil } let tools = try await Self.listTools(handler, context: context, request: request) listing = ToolListing(tools: tools) if tools == nil { - await logger?.warning( + logger?.warning( "Cannot read the tools/list input schemas; calls with Mcp-Param headers are refused") } return tools @@ -2705,7 +3101,7 @@ public actor Server { else { return } let names = tools.compactMap { $0.objectValue?["name"]?.stringValue } for (name, problem) in toolNameWarnings.warnings(for: names, checkDuplicates: true) { - await logger?.warning( + logger?.warning( "Tool name does not follow the specification (SEP-986): \(problem)", metadata: ["tool": "\(MCPRequestHeaders.sanitized(name))"]) } @@ -2726,7 +3122,7 @@ public actor Server { _ = try MCPRequestHeaders.parameters(in: tool.objectValue?["inputSchema"] ?? .null) valid.append(tool) } catch { - await logger?.warning( + logger?.warning( "Tool not listed: invalid x-mcp-header annotation", metadata: [ "tool": "\(MCPRequestHeaders.sanitized(tool.objectValue?["name"]?.stringValue ?? "?"))", @@ -2740,7 +3136,7 @@ public actor Server { } private func handleMessage(_ message: Message) async throws { - await logger?.trace( + logger?.trace( "Processing notification", metadata: ["method": "\(message.method)"]) @@ -2752,20 +3148,20 @@ public actor Server { if configuration.strict, !isInitialized, !isSessionless, !servedStatelessRequest, message.method != InitializedNotification.name, message.method != CancelledNotification.name { - await logger?.warning( + logger?.warning( "Notification before initialize ignored", metadata: ["method": "\(message.method)"]) return } // Find notification handlers for this method - guard let handlers = notificationHandlers[message.method] else { return } + guard let handlers = notificationHandlers[ExactString(message.method)] else { return } // Convert notification parameters to concrete type and call handlers for handler in handlers { do { try await handler(message) } catch { - await logger?.error( + logger?.error( "Error handling notification", metadata: [ "method": "\(message.method)", @@ -2776,7 +3172,7 @@ public actor Server { } private func handleResponse(_ response: Response) async { - if let pendingRequest = self.removePendingResponse(id: response.id) { + if let pendingRequest = self.removePendingResponse(id: response.id)?.pending { switch response.result { case .success(let value): pendingRequest.resume(returning: value) @@ -2784,7 +3180,7 @@ public actor Server { pendingRequest.resume(throwing: error) } } else { - await logger?.warning( + logger?.warning( "Received response for unknown request", metadata: ["id": "\(response.id)"] ) @@ -2798,7 +3194,7 @@ public actor Server { do { try await connection.send(try encoder.encode(BatchReply.unattributedError(error))) } catch { - await logger?.error("Failed to send error response", metadata: ["error": "\(error)"]) + logger?.error("Failed to send error response", metadata: ["error": "\(error)"]) } } @@ -2813,7 +3209,7 @@ public actor Server { /// Whether the transport has no connection or session, so that each /// handshake request stands alone (``StatelessHTTPServerTransport``). private var isSessionless: Bool { - connection is StatelessHTTPServerTransport + connection?.isSessionless ?? false } /// Validate the client capabilities. @@ -3037,27 +3433,52 @@ public actor Server { } } - /// Cancel a request by sending a CancelledNotification to the client. - /// - /// This is used when the server needs to cancel an in-progress request it made to the client - /// (e.g., a sampling request). + /// Cancels an in-progress request to the client by sending `notifications/cancelled`. /// - /// According to the MCP specification, cancellation is advisory: - /// - The client SHOULD stop processing and free resources - /// - The client MAY ignore the cancellation if the request is unknown, already completed, - /// or cannot be cancelled - /// - The server SHOULD ignore any response that arrives after cancellation + /// If `requestID` matches a pending server-to-client request, that request is + /// withdrawn so its awaiting caller throws `CancellationError`: a request not + /// yet sent is dropped without sending `notifications/cancelled`, one whose + /// initial send is in flight defers the notification until that send finishes + /// (logging any deferred send error at debug level rather than throwing it + /// here), and calls for a request already deferred or already answered while + /// its initial send is still unwinding are no-ops. Tracked withdrawals take + /// the originating request's route. For any other ID, `notifications/cancelled` + /// is sent as a notification on the connection. /// /// - Parameters: - /// - requestID: The ID of the request to cancel - /// - reason: An optional human-readable reason for the cancellation - /// - Throws: MCPError if the notification cannot be sent + /// - requestID: The ID of the request to cancel. + /// - reason: An optional human-readable reason for the cancellation. + /// - Throws: ``MCPError/internalError(_:)`` if the server is not connected, + /// or the transport error if an immediate notification send fails. /// - SeeAlso: https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/cancellation + @available(*, deprecated, message: "Cancel the task awaiting requestSampling, requestElicitation, or listRoots instead") public func cancelRequest(_ requestID: ID, reason: String? = nil) async throws { - // Send cancellation notification to client - let notification = CancelledNotification.message( - .init(requestId: requestID, reason: reason) - ) + guard let connection else { + throw MCPError.internalError("Server connection not initialized") + } + if let (pending, relatedRequestID) = removePendingResponse(id: requestID) { + if case .sending = outgoingRequestPhases[requestID] { + outgoingRequestPhases[requestID] = .withdrawnWhileSending( + pending: pending, relatedRequestID: relatedRequestID, reason: reason) + return + } + defer { pending.resume(throwing: CancellationError()) } + let cancelled = CancelledNotification.message(.init(requestId: requestID, reason: reason)) + try await connection.send( + encoder.encode(cancelled), + options: TransportSendOptions(relatedRequestID: relatedRequestID)) + return + } + switch outgoingRequestPhases[requestID] { + case .unsent: + outgoingRequestPhases.removeValue(forKey: requestID) + return + case .sending, .withdrawnWhileSending: + return + case nil: + break + } + let notification = CancelledNotification.message(.init(requestId: requestID, reason: reason)) try await notify(notification) } } diff --git a/Sources/MCP/Server/StatelessRequests.swift b/Sources/MCP/Server/StatelessRequests.swift index 6d4bce64..894be5c2 100644 --- a/Sources/MCP/Server/StatelessRequests.swift +++ b/Sources/MCP/Server/StatelessRequests.swift @@ -128,7 +128,7 @@ enum StatelessRequests { object[ResultKeys.resultType] = .string(ResultType.complete.rawValue) } var meta = object["_meta"]?.objectValue ?? [:] - if meta[MetaKey.serverInfo] == nil, let info = try? Value.preservingStrings(serverInfo) { + if meta[MetaKey.serverInfo] == nil, let info = try? Value(serverInfo) { meta[MetaKey.serverInfo] = info object["_meta"] = .object(meta) } @@ -159,4 +159,10 @@ public struct CacheHint: Hashable, Codable, Sendable { /// Immediately stale and private to the client. public static let uncached = CacheHint(ttlMs: 0, scope: .private) + + // The keys of `Server.Configuration`'s saved form: they do not change + // when a property is renamed. + private enum CodingKeys: String, CodingKey { + case ttlMs, scope + } } diff --git a/Sources/MCP/Server/TaskManager.swift b/Sources/MCP/Server/TaskManager.swift index 0421b92a..06fe87ba 100644 --- a/Sources/MCP/Server/TaskManager.swift +++ b/Sources/MCP/Server/TaskManager.swift @@ -39,6 +39,14 @@ public struct TaskRecord: Hashable, Codable, Sendable { /// The error the request failed with once the task failed. public var error: MCPError? + // The keys of the stored form: a store may hold records written by an + // earlier release, so these raw values do not change when a property is + // renamed. + private enum CodingKeys: String, CodingKey { + case id, owner, protocolVersion, method, status, statusMessage, createdAt, lastUpdatedAt + case ttlMs, pollIntervalMs, inputRequests, result, error + } + /// Creates a task record. public init( id: String, @@ -90,6 +98,28 @@ public struct TaskRecord: Hashable, Codable, Sendable { result?.objectValue?["isError"] == .bool(true) } + /// Whether this record has the same fields as `other`, treating two `NaN` + /// dates as equal so `waitForChange` does not see an unchanged corrupt + /// record as having changed on every poll. + func isUnchanged(from other: TaskRecord) -> Bool { + func sameDate(_ lhs: Date, _ rhs: Date) -> Bool { + lhs == rhs || (lhs.timeIntervalSinceReferenceDate.isNaN && rhs.timeIntervalSinceReferenceDate.isNaN) + } + return id.isExactly(other.id) + && owner.map(ExactString.init) == other.owner.map(ExactString.init) + && protocolVersion == other.protocolVersion + && method == other.method + && status == other.status + && statusMessage == other.statusMessage + && sameDate(createdAt, other.createdAt) + && sameDate(lastUpdatedAt, other.lastUpdatedAt) + && ttlMs == other.ttlMs + && pollIntervalMs == other.pollIntervalMs + && inputRequests == other.inputRequests + && result == other.result + && error == other.error + } + /// The task as its generation reports it. `detailed` adds the outcome /// or the outstanding input (2026-07-28, `tasks/get`). func snapshot(detailed: Bool) -> TaskSnapshot { @@ -161,35 +191,37 @@ public protocol TaskStore: Sendable { /// ``TaskManager/Configuration/maximumTTL``, or with a store that limits what /// it keeps. public actor InMemoryTaskStore: TaskStore { - private var tasks: [String: TaskRecord] = [:] + private var tasks: [ExactString: TaskRecord] = [:] /// Creates an empty store. public init() {} /// Adds a new task. public func insert(_ record: TaskRecord) { - tasks[record.id] = record + tasks[ExactString(record.id)] = record } /// The task with `id`, or `nil`. public func record(id: String) -> TaskRecord? { - tasks[id] + tasks[ExactString(id)] } /// Replaces the stored task with the same id; does nothing for an unknown task. public func update(_ record: TaskRecord) { - guard tasks[record.id] != nil else { return } - tasks[record.id] = record + let key = ExactString(record.id) + guard tasks[key] != nil else { return } + tasks[key] = record } /// Removes the task with `id`. public func remove(id: String) { - tasks[id] = nil + tasks[ExactString(id)] = nil } /// The tasks of `owner`, oldest first. public func records(owner: String?) -> [TaskRecord] { - tasks.values.filter { $0.owner == owner }.sorted { + let exactOwner = owner.map(ExactString.init) + return tasks.values.filter { $0.owner.map(ExactString.init) == exactOwner }.sorted { ($0.createdAt, $0.id) < ($1.createdAt, $1.id) } } @@ -197,7 +229,7 @@ public actor InMemoryTaskStore: TaskStore { /// Removes the tasks whose lifetime ended at `date` and returns their ids. public func removeExpired(asOf date: Date) -> [String] { let expired = tasks.values.filter { $0.isExpired(at: date) }.map(\.id) - for id in expired { tasks[id] = nil } + for id in expired { tasks[ExactString(id)] = nil } return expired } } @@ -302,18 +334,18 @@ public actor TaskManager { /// The tasks that are not finished, which this process runs or waits on. /// The cache is authoritative while a task runs. - private var active: [String: TaskRecord] = [:] + private var active: [ExactString: TaskRecord] = [:] /// The work of each running task. - private var work: [String: Task] = [:] + private var work: [ExactString: Task] = [:] /// Outstanding `requestInput` calls by task, then by token. - private var exchanges: [String: [Int: Exchange]] = [:] + private var exchanges: [ExactString: [Int: Exchange]] = [:] /// The input keys each task has sent, so a key is never reused. - private var usedInputKeys: [String: Set] = [:] + private var usedInputKeys: [ExactString: Set] = [:] /// Input requests being sent to the client by a `tasks/result` (2025-11-25). - private var delivering: [String: Set] = [:] + private var delivering: [ExactString: Set] = [:] private var nextToken = 0 /// Waiters for the next change of a task, by token. - private var changeWaiters: [String: [Int: ResponseSlot]] = [:] + private var changeWaiters: [ExactString: [Int: ResponseSlot]] = [:] /// Receives every change, in order, by token. private var observers: [Int: AsyncStream.Continuation] = [:] /// Store writes, in order. @@ -341,15 +373,15 @@ public actor TaskManager { /// application runs outside the task, and cancels the task's work. A /// task that already finished is unchanged. public func complete(_ id: String, with result: CallTool.Result) async throws { - let value = try Value.preservingStrings(result) - work.removeValue(forKey: id)?.cancel() + let value = try Value(result) + work.removeValue(forKey: ExactString(id))?.cancel() await finish(id, .result(value)) } /// Fails a task with a protocol error and cancels its work. A task that /// already finished is unchanged. public func fail(_ id: String, with error: MCPError) async throws { - work.removeValue(forKey: id)?.cancel() + work.removeValue(forKey: ExactString(id))?.cancel() await finish(id, .error(error)) } @@ -359,16 +391,17 @@ public actor TaskManager { public func cancel(_ id: String) async throws -> TaskRecord? { guard var record = try await current(id) else { return nil } guard !record.status.isTerminal else { return record } + let key = ExactString(record.id) record.status = .cancelled record.statusMessage = record.statusMessage ?? "The task was cancelled" record.inputRequests = [:] record.lastUpdatedAt = Date() - active[id] = record - let pending = exchanges.removeValue(forKey: id) ?? [:] + active[key] = record + let pending = exchanges.removeValue(forKey: key) ?? [:] for exchange in pending.values { exchange.slot.resolve(.failure(CancellationError())) } - work.removeValue(forKey: id)?.cancel() + work.removeValue(forKey: key)?.cancel() await persist(record) - retire(id) + retire(record.id) changed(record) return record } @@ -415,11 +448,12 @@ public actor TaskManager { createdAt: Date(), ttlMs: ttlMs.map { max(1, $0) }, pollIntervalMs: max(1, (pollInterval ?? configuration.pollInterval).wholeMilliseconds)) // Reserved before the first suspension, so the limits hold. - active[record.id] = record + let key = ExactString(record.id) + active[key] = record do { try await store.insert(record) } catch { - active[record.id] = nil + active[key] = nil throw error } creations += 1 @@ -430,8 +464,10 @@ public actor TaskManager { private func hasCapacity(for owner: String?) -> Bool { guard active.count < configuration.maxActiveTasks else { return false } // Without a principal hook every task has the same owner: only the overall limit applies. + let exactOwner = owner.map(ExactString.init) return !bindsPrincipals - || active.values.filter({ $0.owner == owner }).count < configuration.maxActiveTasksPerPrincipal + || active.values.filter({ $0.owner.map(ExactString.init) == exactOwner }).count + < configuration.maxActiveTasksPerPrincipal } /// Runs the work of a created task. @@ -440,8 +476,9 @@ public actor TaskManager { _ body: @escaping @Sendable (TaskContext) async throws -> CallTool.Result, context: TaskContext ) { - guard active[id] != nil, work[id] == nil else { return } - work[id] = Task { + let key = ExactString(id) + guard active[key] != nil, work[key] == nil else { return } + work[key] = Task { let outcome: Outcome do { let result = try await Server.$currentHandlerContext.withValue(nil) { @@ -450,7 +487,7 @@ public actor TaskManager { if result.isInputRequired || result.task != nil { outcome = .error(.internalError("Server bug: a task's work returned input requests or a task")) } else { - outcome = .result(try Value.preservingStrings(result)) + outcome = .result(try Value(result)) } } catch is CancellationError { outcome = .cancelled @@ -470,7 +507,8 @@ public actor TaskManager { } private func finish(_ id: String, _ outcome: Outcome) async { - work[id] = nil + let key = ExactString(id) + work[key] = nil guard var record = try? await current(id), !record.status.isTerminal else { return } switch outcome { case .result(let value): @@ -485,8 +523,8 @@ public actor TaskManager { } record.inputRequests = [:] record.lastUpdatedAt = Date() - active[id] = record - let pending = exchanges.removeValue(forKey: id) ?? [:] + active[key] = record + let pending = exchanges.removeValue(forKey: key) ?? [:] for exchange in pending.values { exchange.slot.resolve(.failure(CancellationError())) } await persist(record) retire(id) @@ -495,10 +533,11 @@ public actor TaskManager { /// Forgets the in-memory state of a finished task. private func retire(_ id: String) { - if active[id]?.status.isTerminal == true { active[id] = nil } - exchanges[id] = nil - usedInputKeys[id] = nil - delivering[id] = nil + let key = ExactString(id) + if active[key]?.status.isTerminal == true { active[key] = nil } + exchanges[key] = nil + usedInputKeys[key] = nil + delivering[key] = nil wakeWaiters(id) } @@ -506,16 +545,17 @@ public actor TaskManager { /// The task with `id`; `nil` when unknown or expired. private func current(_ id: String) async throws -> TaskRecord? { + let key = ExactString(id) let record: TaskRecord? - if let cached = active[id] { + if let cached = active[key] { record = cached } else { record = try await store.record(id: id) } - guard let record else { return nil } + guard let record, record.id.isExactly(id) else { return nil } if record.isExpired(at: Date()) { - await expire([id]) - try? await store.remove(id: id) + await expire([record.id]) + try? await store.remove(id: record.id) return nil } return record @@ -523,12 +563,16 @@ public actor TaskManager { /// The task with `id` as `context`'s caller may see it: `nil` when it is /// unknown, expired, owned by someone else or of another generation. + /// The id and owner match only the same code points, not a canonically + /// equivalent spelling that `String` keys would also find. func lookup(_ id: String, context: Server.HandlerContext, generation: TaskGeneration) async throws -> TaskRecord? { let owner = owner(of: context) if bindsPrincipals, owner == nil { return nil } - guard let record = try await current(id), record.owner == owner, record.generation == generation + guard let record = try await current(id), + record.owner.map(ExactString.init) == owner.map(ExactString.init), + record.generation == generation else { return nil } return record } @@ -537,10 +581,12 @@ public actor TaskManager { func list(context: Server.HandlerContext, generation: TaskGeneration) async throws -> [TaskRecord] { let owner = owner(of: context) if bindsPrincipals, owner == nil { return [] } + let exactOwner = owner.map(ExactString.init) let now = Date() return try await store.records(owner: owner).compactMap { stored in - let record = active[stored.id] ?? stored - return record.generation == generation && !record.isExpired(at: now) ? record : nil + let record = active[ExactString(stored.id)] ?? stored + return record.owner.map(ExactString.init) == exactOwner + && record.generation == generation && !record.isExpired(at: now) ? record : nil } } @@ -551,28 +597,47 @@ public actor TaskManager { func waitForChange(_ id: String, from seen: TaskRecord, timeout: Duration) async throws { var timeout = timeout if let expiresAt = seen.expiresAt { - timeout = min(timeout, .milliseconds(max(0, Int(expiresAt.timeIntervalSinceNow * 1000)))) + // A store may return any `Date`, and `.seconds(_:)` traps on one that is not + // finite or too far away, so only a time shorter than the timeout is converted. + // A NaN keeps the timeout. + let remaining = expiresAt.timeIntervalSinceNow + let (seconds, attoseconds) = timeout.components + if remaining <= 0 { + timeout = .zero + } else if remaining < Double(seconds) + Double(attoseconds) / 1e18 { + timeout = min(timeout, .seconds(remaining)) + } + } + guard timeout > .zero else { + try Task.checkCancellation() + return } - guard let current = active[id] else { + let key = ExactString(id) + guard let current = active[key] else { // It may also have just finished here. - guard try await store.record(id: id) == seen else { return } - let interval = Duration.milliseconds(seen.pollIntervalMs ?? configuration.pollInterval.wholeMilliseconds) + guard let stored = try await store.record(id: id), stored.id.isExactly(id), stored.isUnchanged(from: seen) else { + return + } + let intervalMs = + seen.pollIntervalMs.flatMap { $0 > 0 ? $0 : nil } + ?? max(1, configuration.pollInterval.wholeMilliseconds) + let interval = Duration(wireMilliseconds: intervalMs) try await Task.sleep(for: min(timeout, interval)) return } - guard current == seen else { return } + guard current.isUnchanged(from: seen) else { return } nextToken += 1 let token = nextToken let slot = ResponseSlot() - changeWaiters[id, default: [:]][token] = slot + changeWaiters[key, default: [:]][token] = slot let timer = Task { try? await Task.sleep(for: timeout) slot.resolve(.success(())) } defer { timer.cancel() - changeWaiters[id]?[token] = nil - if changeWaiters[id]?.isEmpty == true { changeWaiters[id] = nil } + changeWaiters[key]?[token] = nil + if changeWaiters[key]?.isEmpty == true { changeWaiters[key] = nil } } try await withTaskCancellationHandler { try await slot.value() @@ -583,10 +648,11 @@ public actor TaskManager { /// Waits until the task finished, expired or no longer runs here. func waitUntilFinished(_ id: String) async throws { - while let record = active[id], !record.status.isTerminal { + let key = ExactString(id) + while let record = active[key], !record.status.isTerminal { if record.isExpired(at: Date()) { - await expire([id]) - try? await store.remove(id: id) + await expire([record.id]) + try? await store.remove(id: record.id) return } try await waitForChange(id, from: record, timeout: .seconds(30)) @@ -595,7 +661,7 @@ public actor TaskManager { /// The number of `waitForChange` calls waiting on the task. func changeWaiterCount(_ id: String) -> Int { - changeWaiters[id]?.count ?? 0 + changeWaiters[ExactString(id)]?.count ?? 0 } // MARK: Input @@ -603,29 +669,30 @@ public actor TaskManager { /// Asks the client for input and waits for every response. func requestInput(_ id: String, _ requests: [String: InputRequest]) async throws -> [String: InputResponse] { guard !requests.isEmpty else { return [:] } - guard var record = active[id], !record.status.isTerminal else { throw CancellationError() } - var used = usedInputKeys[id] ?? [] + let key = ExactString(id) + guard var record = active[key], !record.status.isTerminal else { throw CancellationError() } + var used = usedInputKeys[key] ?? [] var wireKeys: [String: String] = [:] - for key in requests.keys.sorted() { - var wire = key + for requestKey in requests.keys.sorted() { + var wire = requestKey var suffix = 2 while used.contains(wire) { - wire = "\(key)#\(suffix)" + wire = "\(requestKey)#\(suffix)" suffix += 1 } used.insert(wire) - wireKeys[key] = wire - record.inputRequests[wire] = requests[key] + wireKeys[requestKey] = wire + record.inputRequests[wire] = requests[requestKey] } - usedInputKeys[id] = used + usedInputKeys[key] = used nextToken += 1 let token = nextToken let slot = ResponseSlot<[String: InputResponse]>() - exchanges[id, default: [:]][token] = Exchange( + exchanges[key, default: [:]][token] = Exchange( wireKeys: wireKeys, pending: Set(wireKeys.values), slot: slot) record.status = .inputRequired record.lastUpdatedAt = Date() - active[id] = record + active[key] = record await persist(record) changed(record) @@ -640,14 +707,15 @@ public actor TaskManager { /// Withdraws the input requests of a `requestInput` call its caller /// cancelled while the task goes on. private func withdrawInput(_ id: String, _ token: Int) async { - guard let exchange = exchanges[id]?.removeValue(forKey: token), - var record = active[id], !record.status.isTerminal + let key = ExactString(id) + guard let exchange = exchanges[key]?.removeValue(forKey: token), + var record = active[key], !record.status.isTerminal else { return } - for key in exchange.pending { record.inputRequests[key] = nil } - delivering[id]?.subtract(exchange.pending) + for requestKey in exchange.pending { record.inputRequests[requestKey] = nil } + delivering[key]?.subtract(exchange.pending) if record.inputRequests.isEmpty { record.status = .working } record.lastUpdatedAt = Date() - active[id] = record + active[key] = record await persist(record) changed(record) } @@ -655,33 +723,35 @@ public actor TaskManager { /// Takes the outstanding input requests no `tasks/result` is sending /// yet, by the keys sent; they stay outstanding until answered. func claimInput(_ id: String) -> [String: InputRequest] { - guard let record = active[id], !record.status.isTerminal else { return [:] } - let taken = delivering[id] ?? [] + let key = ExactString(id) + guard let record = active[key], !record.status.isTerminal else { return [:] } + let taken = delivering[key] ?? [] let claimed = record.inputRequests.filter { !taken.contains($0.key) } - delivering[id, default: []].formUnion(claimed.keys) + delivering[key, default: []].formUnion(claimed.keys) return claimed } /// Gives back claimed input requests that were not delivered, for the /// next `tasks/result`. func releaseInput(_ id: String, _ keys: some Sequence) { - delivering[id]?.subtract(keys) + delivering[ExactString(id)]?.subtract(keys) } /// Fails the calls waiting for the input requests `keys`: the client /// could not answer them. func failInput(_ id: String, _ keys: Set, _ error: MCPError) async { - delivering[id]?.subtract(keys) - guard var record = active[id], !record.status.isTerminal else { return } - for key in keys { record.inputRequests[key] = nil } - for (token, exchange) in exchanges[id] ?? [:] where !exchange.pending.isDisjoint(with: keys) { - exchanges[id]?[token] = nil - for key in exchange.pending { record.inputRequests[key] = nil } + let key = ExactString(id) + delivering[key]?.subtract(keys) + guard var record = active[key], !record.status.isTerminal else { return } + for requestKey in keys { record.inputRequests[requestKey] = nil } + for (token, exchange) in exchanges[key] ?? [:] where !exchange.pending.isDisjoint(with: keys) { + exchanges[key]?[token] = nil + for requestKey in exchange.pending { record.inputRequests[requestKey] = nil } exchange.slot.resolve(.failure(error)) } if record.inputRequests.isEmpty { record.status = .working } record.lastUpdatedAt = Date() - active[id] = record + active[key] = record await persist(record) changed(record) } @@ -692,41 +762,43 @@ public actor TaskManager { /// - Throws: -32602 when a response does not fit its request; -32603 for /// an unfinished task that runs in another process. func submit(_ id: String, _ responses: [String: InputResponse]) async throws { - guard var record = active[id] else { + let key = ExactString(id) + guard var record = active[key] else { // Stored by another process: its work, and the calls that wait // for input, are not here. - if let stored = try await store.record(id: id), !stored.status.isTerminal { + if let stored = try await store.record(id: id), stored.id.isExactly(id), !stored.status.isTerminal { throw MCPError.internalError("The task does not run in this process; its input cannot be delivered") } return } guard !record.status.isTerminal else { return } var accepted: [String: InputResponse] = [:] - for (key, response) in responses { - guard let request = record.inputRequests[key] else { continue } - accepted[key] = try Self.response(response, fitting: request, key: key) + for (responseKey, response) in responses { + // Only a key with the same code points answers a request. + guard let request = record.inputRequests.exactValue(forKey: responseKey) else { continue } + accepted[responseKey] = try Self.response(response, fitting: request, key: responseKey) } guard !accepted.isEmpty else { return } - for key in accepted.keys { record.inputRequests[key] = nil } - delivering[id]?.subtract(accepted.keys) + for responseKey in accepted.keys { record.inputRequests[responseKey] = nil } + delivering[key]?.subtract(accepted.keys) var resumed: [(ResponseSlot<[String: InputResponse]>, [String: InputResponse])] = [] - for (token, var exchange) in exchanges[id] ?? [:] { + for (token, var exchange) in exchanges[key] ?? [:] { for (callerKey, wire) in exchange.wireKeys { guard let response = accepted[wire], exchange.pending.contains(wire) else { continue } exchange.pending.remove(wire) exchange.responses[callerKey] = response } if exchange.pending.isEmpty { - exchanges[id]?[token] = nil + exchanges[key]?[token] = nil resumed.append((exchange.slot, exchange.responses)) } else { - exchanges[id]?[token] = exchange + exchanges[key]?[token] = exchange } } if record.inputRequests.isEmpty { record.status = .working } record.lastUpdatedAt = Date() - active[id] = record + active[key] = record await persist(record) for (slot, responses) in resumed { slot.resolve(.success(responses)) } changed(record) @@ -745,7 +817,7 @@ public actor TaskManager { } if fits { return response } // Decoding by shape may have picked another kind: read it as a result of the request's method. - if let value = try? Value.preservingStrings(response), + if let value = try? Value(response), let typed = try? InputResponse(method: request.method, result: value) { return typed @@ -755,10 +827,11 @@ public actor TaskManager { /// Sets the task's status message. func setStatusMessage(_ id: String, _ message: String?) async { - guard var record = active[id], !record.status.isTerminal else { return } + let key = ExactString(id) + guard var record = active[key], !record.status.isTerminal else { return } record.statusMessage = message record.lastUpdatedAt = Date() - active[id] = record + active[key] = record await persist(record) changed(record) } @@ -800,19 +873,20 @@ public actor TaskManager { /// Ends the work of tasks whose lifetime ended. private func expire(_ ids: [String]) async { for id in ids { - work.removeValue(forKey: id)?.cancel() - let pending = exchanges.removeValue(forKey: id) ?? [:] + let key = ExactString(id) + work.removeValue(forKey: key)?.cancel() + let pending = exchanges.removeValue(forKey: key) ?? [:] for exchange in pending.values { exchange.slot.resolve(.failure(CancellationError())) } - active[id] = nil - usedInputKeys[id] = nil - delivering[id] = nil + active[key] = nil + usedInputKeys[key] = nil + delivering[key] = nil wakeWaiters(id) } } /// Resolves and forgets the waiters for the next change of a task. private func wakeWaiters(_ id: String) { - for slot in (changeWaiters.removeValue(forKey: id) ?? [:]).values { + for slot in (changeWaiters.removeValue(forKey: ExactString(id)) ?? [:]).values { slot.resolve(.success(())) } } diff --git a/Sources/MCP/Server/Tools.swift b/Sources/MCP/Server/Tools.swift index b46b61ee..4473f8c8 100644 --- a/Sources/MCP/Server/Tools.swift +++ b/Sources/MCP/Server/Tools.swift @@ -128,16 +128,22 @@ public struct Tool: Hashable, Codable, Sendable { self.execution = execution } - /// Content types that can be returned by a tool + /// Content types that can be returned by a tool. /// /// No other case is added in 1.x: a kind from a later revision is ``unknown(type:_:)``. + /// + /// Binary `image` and `audio` blocks decode `data` as standard RFC 4648 §4 base64 (accepting + /// ASCII whitespace and omitted trailing `=` padding). Per the MCP specification, non-standard + /// URL-safe base64 (`-`, `_`), invalid base64, or an embedded ``Resource/Content`` with both + /// or neither of `text` and `blob` throws `DecodingError.dataCorrupted` and fails decoding of + /// the containing result. public enum Content: Hashable, Codable, Sendable { /// Text content case text(text: String, annotations: Resource.Annotations? = nil, _meta: Metadata? = nil) - /// Image content - case image(data: String, mimeType: String, annotations: Resource.Annotations? = nil, _meta: Metadata? = nil) - /// Audio content - case audio(data: String, mimeType: String, annotations: Resource.Annotations? = nil, _meta: Metadata? = nil) + /// Image content: the image's bytes, sent base64-encoded in `data`, and its MIME type. + case image(_ data: Data, mimeType: String, annotations: Resource.Annotations? = nil, _meta: Metadata? = nil) + /// Audio content: the audio's bytes, sent base64-encoded in `data`, and its MIME type. + case audio(_ data: Data, mimeType: String, annotations: Resource.Annotations? = nil, _meta: Metadata? = nil) /// Embedded resource content (EmbeddedResource from spec) case resource(resource: Resource.Content, annotations: Resource.Annotations? = nil, _meta: Metadata? = nil) /// Resource link @@ -154,6 +160,40 @@ public struct Tool: Hashable, Codable, Sendable { /// and number formatting may change. case unknown(type: String, Value) + /// Creates image content from a base64-encoded string. + /// + /// If `data` is not valid base64, this shim stores empty `Data()`. + @available(*, deprecated, message: "Pass Data directly with .image(_:mimeType:annotations:_meta:) instead") + public static func image( + data: String, + mimeType: String, + annotations: Resource.Annotations? = nil, + _meta: Metadata? = nil + ) -> Self { + .image( + Data(lenientBase64Encoded: data) ?? Data(), + mimeType: mimeType, + annotations: annotations, + _meta: _meta) + } + + /// Creates audio content from a base64-encoded string. + /// + /// If `data` is not valid base64, this shim stores empty `Data()`. + @available(*, deprecated, message: "Pass Data directly with .audio(_:mimeType:annotations:_meta:) instead") + public static func audio( + data: String, + mimeType: String, + annotations: Resource.Annotations? = nil, + _meta: Metadata? = nil + ) -> Self { + .audio( + Data(lenientBase64Encoded: data) ?? Data(), + mimeType: mimeType, + annotations: annotations, + _meta: _meta) + } + private enum CodingKeys: String, CodingKey { case type case text @@ -182,17 +222,17 @@ public struct Tool: Hashable, Codable, Sendable { let _meta = try container.decodeIfPresent(Metadata.self, forKey: ._meta) self = .text(text: text, annotations: annotations, _meta: _meta) case "image": - let data = try container.decode(String.self, forKey: .data) + let data = try container.decodeBase64(forKey: .data) let mimeType = try container.decode(String.self, forKey: .mimeType) let annotations = try container.decodeIfPresent(Resource.Annotations.self, forKey: .annotations) let _meta = try container.decodeIfPresent(Metadata.self, forKey: ._meta) - self = .image(data: data, mimeType: mimeType, annotations: annotations, _meta: _meta) + self = .image(data, mimeType: mimeType, annotations: annotations, _meta: _meta) case "audio": - let data = try container.decode(String.self, forKey: .data) + let data = try container.decodeBase64(forKey: .data) let mimeType = try container.decode(String.self, forKey: .mimeType) let annotations = try container.decodeIfPresent(Resource.Annotations.self, forKey: .annotations) let _meta = try container.decodeIfPresent(Metadata.self, forKey: ._meta) - self = .audio(data: data, mimeType: mimeType, annotations: annotations, _meta: _meta) + self = .audio(data, mimeType: mimeType, annotations: annotations, _meta: _meta) case "resource": let resourceContent = try container.decode(Resource.Content.self, forKey: .resource) let annotations = try container.decodeIfPresent(Resource.Annotations.self, forKey: .annotations) @@ -229,13 +269,13 @@ public struct Tool: Hashable, Codable, Sendable { try container.encodeIfPresent(_meta, forKey: ._meta) case .image(let data, let mimeType, let annotations, let _meta): try container.encode("image", forKey: .type) - try container.encode(data, forKey: .data) + try container.encodeBase64(data, forKey: .data) try container.encode(mimeType, forKey: .mimeType) try container.encodeIfPresent(annotations, forKey: .annotations) try container.encodeIfPresent(_meta, forKey: ._meta) case .audio(let data, let mimeType, let annotations, let _meta): try container.encode("audio", forKey: .type) - try container.encode(data, forKey: .data) + try container.encodeBase64(data, forKey: .data) try container.encode(mimeType, forKey: .mimeType) try container.encodeIfPresent(annotations, forKey: .annotations) try container.encodeIfPresent(_meta, forKey: ._meta) @@ -478,7 +518,7 @@ public enum ListTools: Method { tools = try container.decode([Tool].self, forKey: .tools) nextCursor = try container.decodeIfPresent(String.self, forKey: .nextCursor) _meta = try container.decodeIfPresent(Metadata.self, forKey: ._meta) - ttlMs = container.decodeTTL(forKey: .ttlMs) + ttlMs = container.decodeMilliseconds(forKey: .ttlMs) cacheScope = container.decodeCacheScope(forKey: .cacheScope) } } diff --git a/Tests/MCPTests/AppTests.swift b/Tests/MCPTests/AppTests.swift index b788492f..3f5372b8 100644 --- a/Tests/MCPTests/AppTests.swift +++ b/Tests/MCPTests/AppTests.swift @@ -192,7 +192,7 @@ struct AppWireTests { @Test("A data: URL string in _meta.ui is written and read as a string") func dataURLStrings() throws { func wire(_ value: some Encodable) throws -> Value { - try JSONDecoder().decode(Value.Preserved.self, from: JSONEncoder().encode(value)).value + try JSONDecoder().decode(Value.self, from: JSONEncoder().encode(value)) } var tool = Tool(name: "t", description: nil, inputSchema: ["type": "object"]) tool.ui = ToolUIMeta(visibility: ["data:,custom", .app]) @@ -368,7 +368,17 @@ struct AppServerTests { let read = try await result(wire, ReadResource.name, ["uri": "ui://b"]) #expect( read.objectValue?["contents"] - == [["uri": "ui://b", "mimeType": "text/html;profile=mcp-app", "blob": .string(html.base64EncodedString())]]) + == [["uri": "ui://b", "mimeType": "text/html;profile=mcp-app", "blob": "PGh0bWw+w6k8L2h0bWw+"]]) + } + + @Test("A view's body is the body of its content item") + func bodyIsContentBody() throws { + #expect(UIResource.Body.self == Resource.Content.Body.self) + let view = try UIResource(uri: "ui://b", name: "b", body: .blob(Data("é".utf8))) + #expect(view.contents.body == view.body) + #expect( + try wireString(view.contents) + == #"{"blob":"PGh0bWw+w6k8L2h0bWw+","mimeType":"text/html;profile=mcp-app","uri":"ui://b"}"#) } @Test("The first page has the application's page, the views and the skills; then the application continues") @@ -643,6 +653,47 @@ struct AppClientTests { } } + @Test( + "A malformed content item fails readAppResource with ResponseDecodingError", + arguments: [ + (Value.object([:]), "text"), (["text": "", "blob": "PGh0bWw+"], "blob"), + (["blob": "PGh0bWw+!"], "blob"), + ] as [(Value, String)]) + func malformedItem(body: Value, key: String) async throws { + var item = body.objectValue ?? [:] + item["uri"] = "ui://v" + item["mimeType"] = .string(UIResource.mimeType) + let reply: Value = ["contents": [.object(item)]] + let (client, server) = try await connect { server in + await server.withMethodHandler(RawResult.self) { _ in reply } + } + defer { Task { await client.disconnect(); await server.stop() } } + do { + _ = try await client.readAppResource(uri: "ui://v") + Issue.record("\(body) was read") + } catch let error as ResponseDecodingError { + #expect(error.expectedType == String(reflecting: ReadResource.Result.self)) + #expect(codingPath(of: error.underlyingError) == ["contents", "0", key]) + } + } + + @Test("A blob that is not UTF-8 is invalidContent") + func blobNotUTF8() async throws { + let (client, server) = try await connect { server in + await server.withMethodHandler(ReadResource.self) { params in + .init(contents: [.binary(Data([0xC3, 0x28]), uri: params.uri, mimeType: UIResource.mimeType)]) + } + } + defer { Task { await client.disconnect(); await server.stop() } } + do { + _ = try await client.readAppResource(uri: "ui://v") + Issue.record("A non-UTF-8 blob was read") + } catch let error as AppResourceError { + #expect(error.reason == .invalidContent) + #expect(error.message == "ui://v has a blob that is not UTF-8") + } + } + @Test("The view MIME type: case, whitespace, quotes and other parameters") func mimeType() { for valid in [ diff --git a/Tests/MCPTests/Base64DataTests.swift b/Tests/MCPTests/Base64DataTests.swift deleted file mode 100644 index 3a74012e..00000000 --- a/Tests/MCPTests/Base64DataTests.swift +++ /dev/null @@ -1,239 +0,0 @@ -import Foundation -import Testing - -@testable import MCP - -@Suite("Base64 Data Tests") -struct Base64DataTests { - - @Test("Check valid data URLs") - func testIsDataURL() { - // Basic valid data URL - #expect(Data.isDataURL(string: "data:,A%20brief%20note")) - - // Valid image data URL from RFC example - #expect( - Data.isDataURL(string: "data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw")) - - // Valid data URL with charset parameter - #expect(Data.isDataURL(string: "data:text/plain;charset=iso-8859-7,%be%fg%be")) - - // Valid custom application type from RFC example - #expect( - Data.isDataURL( - string: "data:application/vnd-xxx-query,select_vcount,fcol_from_fieldtable/local")) - - // Valid with implicit mediatype (defaults to text/plain) - #expect(Data.isDataURL(string: "data:,hello%20world")) - - // Valid with just charset parameter - #expect(Data.isDataURL(string: "data:;charset=utf-8,hello")) - } - - @Test("Check invalid data URLs") - func testInvalidDataURLs() { - // Not a data URL - #expect(!Data.isDataURL(string: "https://example.com")) - - // Missing comma separator - #expect(!Data.isDataURL(string: "data:text/plain")) - - // Malformed scheme - #expect(!Data.isDataURL(string: "dat:,hello")) - - // Empty string - #expect(!Data.isDataURL(string: "")) - } - - @Test( - "A media type that is not type/subtype makes no data URL (RFC 2397 §3)", - arguments: [ - "data: 3 rows, 2 columns", - "data:text,hi", - "data:text/,hi", - "data:/plain,hi", - "data:text/plain extra,hi", - "data:text/plain;charset=,hi", - "data:text/plain;charset=utf 8,hi", - ]) - func testMediaTypeMustBeTypeSlashSubtype(string: String) throws { - #expect(!Data.isDataURL(string: string)) - #expect(Data.parseDataURL(string) == nil) - let json = try JSONEncoder().encode(string) - #expect(try JSONDecoder().decode(Value.self, from: json) == .string(string)) - } - - @Test("Media types with token characters stay data URLs") - func testMediaTypeTokenCharacters() { - #expect(Data.parseDataURL("data:image/svg+xml;base64,PHN2Zy8+")?.mimeType == "image/svg+xml") - #expect( - Data.parseDataURL("data:application/vnd.example-v1+json,%7B%7D")?.mimeType - == "application/vnd.example-v1+json") - #expect(Data.parseDataURL("data:TEXT/PLAIN,hi")?.data == Data("hi".utf8)) - } - - @Test("Parse data URL with plain text") - func testParseDataURLPlainText() { - // Example from RFC 2397 - let result = Data.parseDataURL("data:,A%20brief%20note") - #expect(result != nil) - if let (mimeType, data) = result { - #expect(mimeType == "text/plain") - #expect(String(data: data, encoding: .utf8) == "A brief note") - } - } - - @Test("Parse data URL with charset") - func testParseDataURLWithCharset() { - // Modified example from RFC 2397 (using valid percent encoding) - let result = Data.parseDataURL( - "data:text/plain;charset=iso-8859-7,%CF%84%CE%B5%CF%83%CF%84") - #expect(result != nil) - if let (mimeType, _) = result { - #expect(mimeType == "text/plain;charset=iso-8859-7") - } - } - - @Test("Parse data URL with base64 encoding") - func testParseDataURLBase64() { - // Simple base64 encoded "Hello" - let result = Data.parseDataURL("data:text/plain;base64,SGVsbG8=") - #expect(result != nil) - if let (mimeType, data) = result { - #expect(mimeType == "text/plain") - #expect(String(data: data, encoding: .utf8) == "Hello") - } - } - - @Test("Parse data URL with implicit text/plain") - func testParseDataURLImplicitTextPlain() { - let result = Data.parseDataURL("data:,hello%20world") - #expect(result != nil) - if let (mimeType, data) = result { - #expect(mimeType == "text/plain") - #expect(String(data: data, encoding: .utf8) == "hello world") - } - } - - @Test("Parse percent-encoded bytes that are not valid UTF-8") - func testParseDataURLNonUTF8PercentEncoding() { - let result = Data.parseDataURL("data:application/octet-stream,%FF%00") - #expect(result != nil) - if let (mimeType, data) = result { - #expect(mimeType == "application/octet-stream") - #expect(data == Data([0xFF, 0x00])) - } - } - - @Test("Parse RFC 2397 example with non-UTF-8 charset") - func testParseDataURLRFCCharsetExample() { - // Example from RFC 2397: ISO-8859-7 bytes that are not valid UTF-8 - let result = Data.parseDataURL("data:text/plain;charset=iso-8859-7,%be%d3%be") - #expect(result != nil) - if let (mimeType, data) = result { - #expect(mimeType == "text/plain;charset=iso-8859-7") - #expect(data == Data([0xBE, 0xD3, 0xBE])) - } - } - - @Test("Parse data URL with malformed percent escapes") - func testParseDataURLMalformedPercentEscapes() { - // Truncated escape at end of payload - #expect(Data.parseDataURL("data:,%") == nil) - #expect(Data.parseDataURL("data:,%F") == nil) - - // Non-hex digit - #expect(Data.parseDataURL("data:,%fg") == nil) - } - - @Test("Parse data URL preserves literal plus sign") - func testParseDataURLPreservesPlus() { - // RFC 2397 uses URL percent-encoding, not form encoding, so `+` is not a space - #expect(Data.parseDataURL("data:,a+b%2B")?.data == Data("a+b+".utf8)) - } - - @Test("Parse invalid data URLs") - func testParseInvalidDataURLs() { - // Not a data URL - #expect(Data.parseDataURL("https://example.com") == nil) - - // Malformed base64 - #expect(Data.parseDataURL("data:text/plain;base64,SGVsbG8=!") == nil) - - // Empty base64 data (valid according to RFC 2397) - let result = Data.parseDataURL("data:text/plain;base64,") - #expect(result != nil) - if let (mimeType, data) = result { - #expect(mimeType == "text/plain") - #expect(data.isEmpty) - } - } - - @Test("Parse plain-text data URL whose payload contains ;base64,") - func testParseDataURLBase64MarkerInPayload() { - let dataURL = "data:text/plain,hello;base64,world" - #expect(Data.isDataURL(string: dataURL)) - - let result = Data.parseDataURL(dataURL) - #expect(result != nil) - if let (mimeType, data) = result { - #expect(mimeType == "text/plain") - #expect(String(data: data, encoding: .utf8) == "hello;base64,world") - } - } - - @Test("Parse data URL with ;base64, header still decodes base64") - func testParseDataURLBase64HeaderRegression() { - let result = Data.parseDataURL("data:application/octet-stream;base64,/wA=") - #expect(result != nil) - if let (mimeType, data) = result { - #expect(mimeType == "application/octet-stream") - #expect(data == Data([0xFF, 0x00])) - } - } - - @Test("Parse data URL with charset and ;base64,") - func testParseDataURLCharsetAndBase64() { - let result = Data.parseDataURL("data:text/plain;charset=utf-8;base64,SGk=") - #expect(result != nil) - if let (mimeType, data) = result { - #expect(mimeType == "text/plain;charset=utf-8") - #expect(String(data: data, encoding: .utf8) == "Hi") - } - } - - @Test("Test data URL encoding") - func testDataURLEncoding() { - let testData = "Hello, world!".data(using: .utf8)! - - // Default mime type (text/plain) - let url1 = testData.dataURLEncoded() - #expect(url1.hasPrefix("data:text/plain;base64,")) - #expect(Data.isDataURL(string: url1)) - - // Custom mime type - let url2 = testData.dataURLEncoded(mimeType: "application/octet-stream") - #expect(url2.hasPrefix("data:application/octet-stream;base64,")) - #expect(Data.isDataURL(string: url2)) - - // Roundtrip test - if let (mimeType, data) = Data.parseDataURL(url2) { - #expect(mimeType == "application/octet-stream") - #expect(data == testData) - } else { - #expect(Bool(false), "Failed to parse encoded data URL") - } - } - - @Test("Test complex example from RFC 2397") - func testComplexExample() { - // Partial example of image from RFC (shortened for test brevity) - let dataURL = "data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw" - - let result = Data.parseDataURL(dataURL) - #expect(result != nil) - if let (mimeType, _) = result { - #expect(mimeType == "image/gif") - } - } -} diff --git a/Tests/MCPTests/CancellationTests.swift b/Tests/MCPTests/CancellationTests.swift index d91f5398..0440ca62 100644 --- a/Tests/MCPTests/CancellationTests.swift +++ b/Tests/MCPTests/CancellationTests.swift @@ -58,49 +58,26 @@ struct CancellationTests { await client.disconnect() } - @Test("Client receives and processes CancelledNotification") + @Test("A notifications/cancelled naming a pending request fails it with CancellationError") func testClientReceivesCancellation() async throws { - let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() - + let transport = MockTransport() let client = Client(name: "TestClient", version: "1.0", configuration: .handshake) - let server = Server( - name: "TestServer", - version: "1.0", - capabilities: .init() - ) - - // Start server and connect client - try await server.start(transport: serverTransport) - - // Register a slow ping handler (must be after start to override default) - let started = Flag() - await server.withMethodHandler(Ping.self) { _ in - await started.set() - try await Task.sleep(for: .seconds(5)) - return Empty() - } - _ = try await client.connect(transport: clientTransport) + try await connectAnsweringInitialize(client, over: transport) - // Send a request using send let pingRequest = Ping.request() let context = try await client.send(pingRequest) + // Initialize + Initialized notification + Ping + try await transport.waitForSentMessages(count: 3) - // Server cancels the request while it's being awaited - #expect(await eventually { await started.isSet }) - try await server.cancelRequest(pingRequest.id, reason: "Server cancelled") + // The peer cancels the request: the client stops waiting for it. + try await transport.queue( + notification: CancelledNotification.message( + .init(requestId: pingRequest.id, reason: "Server cancelled"))) - // Try to get result - should throw CancellationError - do { - _ = try await context.value - Issue.record("Expected CancellationError but request succeeded") - } catch is CancellationError { - // Expected - } catch { - Issue.record("Expected CancellationError but got: \(error)") - } + let result = await outcome(within: .seconds(30)) { try await context.value } + #expect(result.error is CancellationError, "got \(result)") await client.disconnect() - await server.stop() } @Test("RequestContext structure") @@ -641,6 +618,717 @@ struct CancellationTests { await peer.stop() await server.stop() } + + @Test( + "Withdrawal sends notifications/cancelled before the awaiting handler resumes", + .timeLimit(.minutes(1))) + func testWithdrawalSendsBeforeHandlerResumes() async throws { + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + let gated = GatedSendTransport(serverTransport, gatingMethod: CancelledNotification.name) + defer { Task { await gated.release() } } + + let server = Server(name: "s", version: "1", capabilities: .init(tools: .init())) + let elicitationStarted = Flag() + let handlerResumed = Flag() + let heldTask = TaskHolder() + await server.withMethodHandler(CallTool.self) { [weak server] _ in + guard let server else { throw MCPError.internalError("The server is gone") } + let elicitation = Task { + try await server.requestElicitation(message: "Confirm?", requestedSchema: .init()) + } + await heldTask.hold(elicitation) + _ = try? await elicitation.value + await handlerResumed.set() + return CallTool.Result(content: []) + } + + let client = Client( + name: "c", version: "1", + capabilities: .init(elicitation: .init()), configuration: .handshake) + await client.withElicitationHandler { _ in + await elicitationStarted.set() + try await Task.sleep(for: .seconds(60)) + return CreateElicitation.Result(action: .decline) + } + + try await server.start(transport: gated) + try await client.connect(transport: clientTransport) + + let callContext = try await client.send(CallTool.request(.init(name: "confirm"))) + try #require(await eventually { + guard await elicitationStarted.isSet else { return false } + return await heldTask.isHeld + }) + + await heldTask.cancel() + try #require(await eventually { await gated.isHeld }) + + // Round-trip a ping while notifications/cancelled is held at the gate: + // the handler must not resume and send the parent response yet. + try await client.ping() + #expect(await !handlerResumed.isSet) + let callID = try JSONDecoder().decode(Value.self, from: JSONEncoder().encode(callContext.requestID)) + #expect(await !gated.hasResponse(forID: callID)) + + await gated.release() + _ = try await callContext.value + #expect(await handlerResumed.isSet) + + let cancelIndex = try #require(await gated.firstIndex(method: CancelledNotification.name)) + let responseIndex = try #require(await gated.firstResponseIndex(forID: callID)) + #expect(cancelIndex < responseIndex) + + await client.disconnect() + await server.stop() + } + + @Test( + "Cancelling during an in-flight request send waits until the send finishes before sending notifications/cancelled", + .timeLimit(.minutes(1))) + func testWithdrawalWaitsForInFlightRequestSend() async throws { + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + let gated = GatedSendTransport(serverTransport, gatingMethod: CreateElicitation.name) + defer { Task { await gated.release() } } + + let server = Server(name: "s", version: "1") + let client = Client( + name: "c", version: "1", + capabilities: .init(elicitation: .init()), configuration: .handshake) + await client.withElicitationHandler { _ in + try await Task.sleep(for: .seconds(60)) + return CreateElicitation.Result(action: .decline) + } + + try await server.start(transport: gated) + try await client.connect(transport: clientTransport) + + let elicitation = Task { + try await server.requestElicitation(message: "Confirm?", requestedSchema: .init()) + } + try #require(await eventually { await gated.isHeld }) + + elicitation.cancel() + try #require(await eventually { await server.pendingWithdrawalCount == 1 }) + #expect(await !gated.forwardedMethods.contains(CancelledNotification.name)) + + await gated.release() + let result = await outcome(within: .seconds(10)) { try await elicitation.value } + #expect(result.error is CancellationError, "got \(result)") + try #require(await eventually { await server.inFlightSendCount == 0 }) + + let requestIndex = try #require(await gated.firstIndex(method: CreateElicitation.name)) + let cancelIndex = try #require(await gated.firstIndex(method: CancelledNotification.name)) + #expect(requestIndex < cancelIndex) + + let requestID = try #require(await gated.forwarded[requestIndex].objectValue?["id"]) + let cancelledID = await gated.forwarded[cancelIndex].objectValue?["params"]?.objectValue?["requestId"] + #expect(cancelledID == requestID) + + await client.disconnect() + await server.stop() + } + + @Test( + "Cancelling during a failing in-flight request send sends no notifications/cancelled", + .timeLimit(.minutes(1))) + func testWithdrawalSkippedWhenInFlightRequestSendFails() async throws { + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + let gated = GatedSendTransport(serverTransport, gatingMethod: CreateElicitation.name) + defer { Task { await gated.release() } } + + let server = Server(name: "s", version: "1") + let client = Client( + name: "c", version: "1", + capabilities: .init(elicitation: .init()), configuration: .handshake) + + try await server.start(transport: gated) + try await client.connect(transport: clientTransport) + + let elicitation = Task { + try await server.requestElicitation(message: "Confirm?", requestedSchema: .init()) + } + try #require(await eventually { await gated.isHeld }) + + elicitation.cancel() + try #require(await eventually { await server.pendingWithdrawalCount == 1 }) + #expect(await !gated.forwardedMethods.contains(CancelledNotification.name)) + + await gated.release(throwing: MCPError.connectionClosed) + let result = await outcome(within: .seconds(10)) { try await elicitation.value } + #expect(result.error is CancellationError, "got \(result)") + try #require(await eventually { await server.inFlightSendCount == 0 }) + #expect(await !gated.forwardedMethods.contains(CancelledNotification.name)) + + await client.disconnect() + await server.stop() + } + + @Test( + "Server.stop() during a withdrawn in-flight send resumes the caller once and sends no cancellation", + .timeLimit(.minutes(1))) + func testStopDuringWithdrawnInFlightSend() async throws { + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + let gated = GatedSendTransport(serverTransport, gatingMethod: CreateElicitation.name) + defer { Task { await gated.release() } } + + let server = Server(name: "s", version: "1") + let client = Client( + name: "c", version: "1", + capabilities: .init(elicitation: .init()), configuration: .handshake) + + try await server.start(transport: gated) + try await client.connect(transport: clientTransport) + + let elicitation = Task { + try await server.requestElicitation(message: "Confirm?", requestedSchema: .init()) + } + try #require(await eventually { await gated.isHeld }) + + elicitation.cancel() + try #require(await eventually { await server.pendingWithdrawalCount == 1 }) + + await server.stop() + let result = await outcome(within: .seconds(10)) { try await elicitation.value } + #expect(result.error is CancellationError, "got \(result)") + + // Releasing the stuck send after stop() must neither send a cancellation nor double-resume. + await gated.release() + try #require(await eventually { await gated.completedGatedSendCount == 1 }) + try #require(await eventually { await server.inFlightSendCount == 0 }) + #expect(await !gated.forwardedMethods.contains(CancelledNotification.name)) + + await client.disconnect() + } + + @Test( + "Cancelling between Server.send and registration never sends the request or a cancellation", + .timeLimit(.minutes(1))) + func testCancellationBetweenSendAndRegistrationSendsNothing() async throws { + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + let recorder = RecordingTransport(serverTransport) + let server = Server(name: "s", version: "1") + let client = Client( + name: "c", version: "1", + capabilities: .init(elicitation: .init()), configuration: .handshake) + + let registrationGate = AsyncGate() + defer { Task { await registrationGate.release() } } + await server.setBeforeRegisteringOutgoingRequest { + await registrationGate.wait() + } + + try await server.start(transport: recorder) + try await client.connect(transport: clientTransport) + + let elicitation = Task { + try await server.requestElicitation(message: "Confirm?", requestedSchema: .init()) + } + // The task passed Task.checkCancellation(), called send(_:), inserted .unsent, + // and paused just before registering in pendingRequests. + try #require(await eventually { await registrationGate.isWaiting }) + #expect(await server.unsentRequestCount == 1) + + elicitation.cancel() + try #require(await eventually { await server.unsentRequestCount == 0 }) + + await registrationGate.release() + let result = await outcome(within: .seconds(10)) { try await elicitation.value } + #expect(result.error is CancellationError, "got \(result)") + try #require(await eventually { await server.inFlightSendCount == 0 }) + + let methods = await recorder.methods + #expect(!methods.contains(CreateElicitation.name)) + #expect(!methods.contains(CancelledNotification.name)) + + await client.disconnect() + await server.stop() + } + + @Test( + "Cancelling after the client has already answered returns the answer and sends no cancellation", + .timeLimit(.minutes(1))) + func testCancellationAfterClientAnsweredReturnsAnswerWithoutWithdrawal() async throws { + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + let recorder = RecordingTransport(serverTransport) + let server = Server(name: "s", version: "1") + let client = Client( + name: "c", version: "1", + capabilities: .init(elicitation: .init()), configuration: .handshake) + let expected = CreateElicitation.Result(action: .accept, content: ["ok": .bool(true)]) + await client.withElicitationHandler { _ in expected } + + try await server.start(transport: recorder) + try await client.connect(transport: clientTransport) + + let request = CreateElicitation.request(.form(.init(message: "Confirm?", requestedSchema: .init()))) + let requestTask = try await server.send(request) + // Wait until the client has already answered and resolved requestTask. + let initialAnswer = try await requestTask.value + #expect(initialAnswer == expected) + + // Now await the already-answered task from a cancelled task so onCancel invokes withdraw. + let beforeWithdrawals = await server.completedWithdrawalCount + let cancelledWait = Task { + withUnsafeCurrentTask { $0?.cancel() } + return try await server.result( + of: requestTask, withdrawing: request.id, relatedTo: nil, reason: "Too late") + } + let result = try await cancelledWait.value + #expect(result == expected) + try #require(await eventually { await server.completedWithdrawalCount > beforeWithdrawals }) + + let methods = await recorder.methods + #expect(methods.contains(CreateElicitation.name)) + #expect(!methods.contains(CancelledNotification.name)) + + await client.disconnect() + await server.stop() + } + + @Test("connectAnsweringInitialize surfaces responder errors and avoids disconnecting on cancel") + func testConnectAnsweringInitializeErrorHandling() async throws { + // 1. When client.connect fails early, answer is cancelled without issuing a duplicate disconnect. + let failingTransport = MockTransport() + await failingTransport.setFailConnect(true) + let handshakeClient = Client(name: "c", version: "1", configuration: .handshake) + await #expect(throws: MCPError.self) { + try await connectAnsweringInitialize(handshakeClient, over: failingTransport) + } + #expect(await failingTransport.disconnectCount == 1) + + // 2. When the responder fails first (invalid first sent message fails decoding), + // the underlying DecodingError is surfaced instead of MCPError.connectionClosed. + let badTransport = MockTransport() + try await badTransport.send(Data("not-json".utf8), options: .init()) + let badClient = Client(name: "c", version: "1", configuration: .handshake) + do { + try await connectAnsweringInitialize(badClient, over: badTransport) + Issue.record("Expected responder DecodingError") + } catch is DecodingError { + // Expected: surfaced from answer instead of being masked by connectionClosed. + } + await badClient.disconnect() + + // 3. When the caller cancels while initialize is pending, connectAnsweringInitialize + // throws CancellationError and the cancelled responder does not add a second disconnect. + let cancelTransport = MockTransport() + await cancelTransport.setPauseSend(true) + let cancelClient = Client(name: "c", version: "1", configuration: .handshake) + let connectTask = Task { + try await connectAnsweringInitialize(cancelClient, over: cancelTransport) + } + try #require(await eventually { await cancelTransport.isSendPaused }) + connectTask.cancel() + let cancelResult = await outcome(within: .seconds(5)) { try await connectTask.value } + #expect(cancelResult.error is CancellationError, "got \(cancelResult)") + // Only Client.connect's own cleanup disconnects once; the cancelled answer task does not. + #expect(await cancelTransport.disconnectCount == 1) + } + + @Test( + "Deprecated Server.cancelRequest withdraws a pending server request and sends notifications/cancelled", + .timeLimit(.minutes(1))) + @available(*, deprecated, message: "Tests the deprecated Server.cancelRequest shim") + func testDeprecatedServerCancelRequest() async throws { + let server = Server(name: "s", version: "1") + // Before start, cancelRequest throws internalError as in 0.12.1. + await #expect(throws: MCPError.internalError("Server connection not initialized")) { + try await server.cancelRequest("not-connected", reason: "no connection") + } + + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + let recorder = RecordingTransport(serverTransport) + let client = Client( + name: "c", version: "1", + capabilities: .init(elicitation: .init()), configuration: .handshake) + let started = Flag() + let clientHandlerCancelled = Flag() + await client.withElicitationHandler { _ in + await started.set() + do { + try await Task.sleep(for: .seconds(60)) + } catch { + if error is CancellationError { await clientHandlerCancelled.set() } + throw error + } + return CreateElicitation.Result(action: .decline) + } + + try await server.start(transport: recorder) + try await client.connect(transport: clientTransport) + + // 1. Tracked pending server-to-client request: wait for initial send to complete so + // cancelRequest deterministically exercises the post-send withdrawal branch. + let request = CreateElicitation.request(.form(.init(message: "Confirm?", requestedSchema: .init()))) + let pendingTask = try await server.send(request) + try #require(await eventually { await started.isSet }) + try #require(await eventually { await server.inFlightSendCount == 0 }) + + try await server.cancelRequest(request.id, reason: "No longer needed") + let pendingResult = await outcome(within: .seconds(10)) { try await pendingTask.value } + #expect(pendingResult.error is CancellationError, "got \(pendingResult)") + #expect(await eventually { await clientHandlerCancelled.isSet }) + + let sent = await recorder.sent + let matched = sent.first { + $0.objectValue?["method"] == .string(CancelledNotification.name) + && $0.objectValue?["params"]?.objectValue?["requestId"] + == (try? JSONDecoder().decode(Value.self, from: JSONEncoder().encode(request.id))) + } + #expect(matched?.objectValue?["params"]?.objectValue?["reason"] == .string("No longer needed")) + + // 2. Arbitrary untracked ID: sends notifications/cancelled on the connection as in 0.12.1. + try await server.cancelRequest("legacy-id", reason: "Legacy call") + let legacySent = await recorder.sent.first { + $0.objectValue?["method"] == .string(CancelledNotification.name) + && $0.objectValue?["params"]?.objectValue?["requestId"] == .string("legacy-id") + } + #expect(legacySent?.objectValue?["params"]?.objectValue?["reason"] == .string("Legacy call")) + + await client.disconnect() + await server.stop() + } + + @Test( + "Deprecated Server.cancelRequest handles unsent, sending, and already-withdrawn-while-sending phases", + .timeLimit(.minutes(1))) + @available(*, deprecated, message: "Tests the deprecated Server.cancelRequest shim") + func testDeprecatedServerCancelRequestInFlightPhases() async throws { + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + let gated = GatedSendTransport(serverTransport, gatingMethod: CreateElicitation.name) + defer { Task { await gated.release() } } + + let server = Server(name: "s", version: "1") + let client = Client( + name: "c", version: "1", + capabilities: .init(elicitation: .init()), configuration: .handshake) + await client.withElicitationHandler { _ in + try await Task.sleep(for: .seconds(60)) + return CreateElicitation.Result(action: .decline) + } + + try await server.start(transport: gated) + try await client.connect(transport: clientTransport) + + // 1. .unsent phase: cancelRequest removes the unsent entry; neither request nor cancellation is sent. + let registrationGate = AsyncGate() + defer { Task { await registrationGate.release() } } + await server.setBeforeRegisteringOutgoingRequest { + await registrationGate.wait() + } + let unsentRequest = CreateElicitation.request(.form(.init(message: "Unsent?", requestedSchema: .init()))) + let unsentTask = try await server.send(unsentRequest) + try #require(await eventually { await registrationGate.isWaiting }) + #expect(await server.unsentRequestCount == 1) + + try await server.cancelRequest(unsentRequest.id, reason: "before-registration") + #expect(await server.unsentRequestCount == 0) + await registrationGate.release() + let unsentResult = await outcome(within: .seconds(10)) { try await unsentTask.value } + #expect(unsentResult.error is CancellationError, "got \(unsentResult)") + try #require(await eventually { await server.inFlightSendCount == 0 }) + #expect(await !gated.forwardedMethods.contains(CreateElicitation.name)) + #expect(await !gated.forwardedMethods.contains(CancelledNotification.name)) + + // 2. .sending -> .withdrawnWhileSending: cancelRequest defers cancellation until send finishes. + await server.setBeforeRegisteringOutgoingRequest(nil) + let inFlightRequest = CreateElicitation.request(.form(.init(message: "In flight?", requestedSchema: .init()))) + let inFlightTask = try await server.send(inFlightRequest) + try #require(await eventually { await gated.isHeld }) + + try await server.cancelRequest(inFlightRequest.id, reason: "first-cancel") + #expect(await server.pendingWithdrawalCount == 1) + #expect(await !gated.forwardedMethods.contains(CancelledNotification.name)) + + // 3. .withdrawnWhileSending: a second cancelRequest must not send a premature or duplicate cancellation. + try await server.cancelRequest(inFlightRequest.id, reason: "duplicate-cancel") + #expect(await server.pendingWithdrawalCount == 1) + #expect(await !gated.forwardedMethods.contains(CancelledNotification.name)) + + await gated.release() + let inFlightResult = await outcome(within: .seconds(10)) { try await inFlightTask.value } + #expect(inFlightResult.error is CancellationError, "got \(inFlightResult)") + try #require(await eventually { await server.inFlightSendCount == 0 }) + + let requestIndex = try #require(await gated.firstIndex(method: CreateElicitation.name)) + let cancelIndex = try #require(await gated.firstIndex(method: CancelledNotification.name)) + #expect(requestIndex < cancelIndex) + + let cancellations = await gated.forwarded.filter { + $0.objectValue?["method"] == .string(CancelledNotification.name) + } + #expect(cancellations.count == 1) + let expectedID = try JSONDecoder().decode(Value.self, from: JSONEncoder().encode(inFlightRequest.id)) + #expect(cancellations.first?.objectValue?["params"]?.objectValue?["requestId"] == expectedID) + #expect(cancellations.first?.objectValue?["params"]?.objectValue?["reason"] == .string("first-cancel")) + + await client.disconnect() + await server.stop() + } + + @Test( + "A stale failed send from a stopped run does not fail a restarted run's request with the same ID", + .timeLimit(.minutes(1))) + func testStaleFailedSendAfterRestartDoesNotFailNewRunRequest() async throws { + let server = Server(name: "s", version: "1") + let reusedID: ID = .string("reused-id") + + // Run 1: pause the send on gated1, then stop() the server. + let (clientTransport1, serverTransport1) = await InMemoryTransport.createConnectedPair() + let gated1 = GatedSendTransport(serverTransport1, gatingMethod: CreateElicitation.name) + defer { Task { await gated1.release() } } + let client1 = Client( + name: "c1", version: "1", + capabilities: .init(elicitation: .init()), configuration: .handshake) + try await server.start(transport: gated1) + try await client1.connect(transport: clientTransport1) + + let request1 = CreateElicitation.request( + id: reusedID, .form(.init(message: "Run 1", requestedSchema: .init()))) + let task1 = try await server.send(request1) + try #require(await eventually { await gated1.isHeld }) + + await server.stop() + let result1 = await outcome(within: .seconds(10)) { try await task1.value } + #expect(result1.mcpError == .internalError("Server disconnected")) + await client1.disconnect() + + // Run 2: restart the same server and send a new request reusing the same ID. + let (clientTransport2, serverTransport2) = await InMemoryTransport.createConnectedPair() + let client2 = Client( + name: "c2", version: "1", + capabilities: .init(elicitation: .init()), configuration: .handshake) + let run2Started = Flag() + let answerGate = AsyncGate() + defer { Task { await answerGate.release() } } + let expected = CreateElicitation.Result(action: .accept, content: ["run": .int(2)]) + await client2.withElicitationHandler { _ in + await run2Started.set() + await answerGate.wait() + return expected + } + try await server.start(transport: serverTransport2) + try await client2.connect(transport: clientTransport2) + + let request2 = CreateElicitation.request( + id: reusedID, .form(.init(message: "Run 2", requestedSchema: .init()))) + let task2 = try await server.send(request2) + try #require(await eventually { await run2Started.isSet }) + + // Now fail the stale run-1 send: it must not remove or fail run 2's pending request. + await gated1.release(throwing: MCPError.connectionClosed) + try #require(await eventually { await gated1.completedGatedSendCount == 1 }) + try #require(await eventually { await server.inFlightSendCount == 0 }) + + await answerGate.release() + let result2 = try await task2.value + #expect(result2 == expected) + + await client2.disconnect() + await server.stop() + } + + @Test( + "Deprecated Server.cancelRequest sends no cancellation if the request was answered while still sending", + .timeLimit(.minutes(1))) + @available(*, deprecated, message: "Tests the deprecated Server.cancelRequest shim") + func testDeprecatedServerCancelRequestAnsweredWhileSending() async throws { + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + let postGate = PostSendGateTransport(serverTransport, gatingMethod: CreateElicitation.name) + defer { Task { await postGate.release() } } + + let server = Server(name: "s", version: "1") + let client = Client( + name: "c", version: "1", + capabilities: .init(elicitation: .init()), configuration: .handshake) + let expected = CreateElicitation.Result(action: .accept, content: ["ok": .bool(true)]) + await client.withElicitationHandler { _ in expected } + + try await server.start(transport: postGate) + try await client.connect(transport: clientTransport) + + // PostSendGateTransport forwards CreateElicitation to the client and then suspends + // before returning from send(), so the client answers while outgoingRequestPhases[id] + // is still .sending. + let request = CreateElicitation.request(.form(.init(message: "Confirm?", requestedSchema: .init()))) + let pendingTask = try await server.send(request) + try #require(await eventually { await postGate.isHeld }) + let answer = try await pendingTask.value + #expect(answer == expected) + #expect(await server.inFlightSendCount == 1) + + // The request is already answered while its initial send is unwinding: cancelRequest + // must be a no-op and must not fall through to notify(_:). + try await server.cancelRequest(request.id, reason: "answered-while-sending") + + await postGate.release() + try #require(await eventually { await server.inFlightSendCount == 0 }) + #expect(await !postGate.forwardedMethods.contains(CancelledNotification.name)) + + await client.disconnect() + await server.stop() + } +} + +/// Forwards the first outgoing send matching `gatingMethod` to `wrapped`, then +/// pauses before returning from `send(_:options:)` until `release()` is called. +private actor PostSendGateTransport: TransportWrapper { + nonisolated let wrapped: any Transport + private var gatingMethod: String? + private var continuation: CheckedContinuation? + private var released = false + private(set) var forwarded: [Value] = [] + + init(_ wrapped: any Transport, gatingMethod: String) { + self.wrapped = wrapped + self.gatingMethod = gatingMethod + } + + var isHeld: Bool { continuation != nil } + + func send(_ data: Data, options: TransportSendOptions) async throws { + let value = try? JSONDecoder().decode(Value.self, from: data) + if let value { forwarded.append(value) } + try await wrapped.send(data, options: options) + let method = value?.objectValue?["method"]?.stringValue + if let target = gatingMethod, method == target { + gatingMethod = nil + guard !released else { return } + await withCheckedContinuation { continuation = $0 } + } + } + + func release() { + released = true + continuation?.resume() + continuation = nil + } + + var forwardedMethods: [String] { + forwarded.map { $0.objectValue?["method"]?.stringValue ?? ($0.objectValue?["result"] != nil ? "result" : "?") } + } +} + +private actor AsyncGate { + private var continuation: CheckedContinuation? + private var isReleased = false + private(set) var isWaiting = false + + func wait() async { + guard !isReleased else { return } + isWaiting = true + await withCheckedContinuation { continuation = $0 } + } + + func release() { + isReleased = true + continuation?.resume() + continuation = nil + } +} + +private actor TaskHolder { + private var task: Task? + func hold(_ task: Task) { self.task = task } + var isHeld: Bool { task != nil } + func cancel() { task?.cancel() } +} + +/// Wraps a transport and pauses the first outgoing send for each method in +/// `gatingMethods` before forwarding it to `wrapped`, until `release` is +/// called. Records every message and its `TransportSendOptions` forwarded to +/// `wrapped`, in order. +actor GatedSendTransport: TransportWrapper { + private struct GateState { + var armed = true + var continuation: CheckedContinuation? + var releasedResult: Result? + var isHeld: Bool { continuation != nil } + } + + nonisolated let wrapped: any Transport + private var gates: [String: GateState] + private(set) var completedGatedSendCount = 0 + private(set) var forwarded: [Value] = [] + private(set) var forwardedOptions: [TransportSendOptions] = [] + + init(_ wrapped: any Transport, gatingMethod: String) { + self.wrapped = wrapped + self.gates = [gatingMethod: GateState()] + } + + init(_ wrapped: any Transport, gatingMethods: [String]) { + self.wrapped = wrapped + self.gates = Dictionary(uniqueKeysWithValues: gatingMethods.map { ($0, GateState()) }) + } + + var isHeld: Bool { gates.values.contains { $0.isHeld } } + + func isHeld(method: String) -> Bool { gates[method]?.isHeld == true } + + func send(_ data: Data, options: TransportSendOptions) async throws { + let value = try? JSONDecoder().decode(Value.self, from: data) + let method = value?.objectValue?["method"]?.stringValue + if let method, var state = gates[method], state.armed { + state.armed = false + gates[method] = state + defer { completedGatedSendCount += 1 } + if let result = state.releasedResult { + try result.get() + } else { + try await withCheckedThrowingContinuation { continuation in + gates[method]?.continuation = continuation + } + } + if let value { + forwarded.append(value) + forwardedOptions.append(options) + } + try await wrapped.send(data, options: options) + return + } + if let value { + forwarded.append(value) + forwardedOptions.append(options) + } + try await wrapped.send(data, options: options) + } + + func release(method: String, throwing error: (any Swift.Error)? = nil) { + let result: Result = error.map { .failure($0) } ?? .success(()) + guard var state = gates[method] else { return } + state.releasedResult = result + let continuation = state.continuation + state.continuation = nil + gates[method] = state + continuation?.resume(with: result) + } + + func release(throwing error: (any Swift.Error)? = nil) { + for method in Array(gates.keys) { + release(method: method, throwing: error) + } + } + + var forwardedMethods: [String] { + forwarded.map { $0.objectValue?["method"]?.stringValue ?? ($0.objectValue?["result"] != nil ? "result" : "?") } + } + + func firstIndex(method: String) -> Int? { + forwarded.firstIndex { $0.objectValue?["method"]?.stringValue == method } + } + + func options(forMethod method: String) -> TransportSendOptions? { + firstIndex(method: method).map { forwardedOptions[$0] } + } + + func firstResponseIndex(forID id: Value) -> Int? { + forwarded.firstIndex { $0.objectValue?["id"] == id && $0.objectValue?["result"] != nil } + } + + func hasResponse(forID id: Value) -> Bool { + firstResponseIndex(forID: id) != nil + } } private actor BatchGate { @@ -653,7 +1341,7 @@ private actor BatchGate { /// A transport whose HTTP context lookup for one request waits until the /// test releases it. It reports the context lookup, every message the server /// sends and every message the server logs as events. -private actor GatedContextTransport: Transport, HTTPContextProviding { +private actor GatedContextTransport: Transport { nonisolated let logger: Logger nonisolated let events: AsyncStream private nonisolated let eventSink: AsyncStream.Continuation @@ -679,7 +1367,7 @@ private actor GatedContextTransport: Transport, HTTPContextProviding { release() } - func send(_ data: Data) async throws { + func send(_ data: Data, options: TransportSendOptions) async throws { eventSink.yield("sent " + String(decoding: data, as: UTF8.self)) } @@ -695,7 +1383,7 @@ private actor GatedContextTransport: Transport, HTTPContextProviding { gate = nil } - func httpRequestContext(for id: ID) async -> HTTPRequest? { + func httpRequest(for id: ID) async -> HTTPRequest? { guard id == gatedID, !released else { return nil } eventSink.yield("context \(id)") await withCheckedContinuation { gate = $0 } @@ -738,7 +1426,7 @@ private actor ControlledSendTransport: Transport { release() } - func send(_ data: Data) async throws { + func send(_ data: Data, options: TransportSendOptions) async throws { let message = String(decoding: data, as: UTF8.self) if failing(message) { eventSink.yield("failed " + message) diff --git a/Tests/MCPTests/ClientConnectionFailureTests.swift b/Tests/MCPTests/ClientConnectionFailureTests.swift index 673b26ba..f4e683e6 100644 --- a/Tests/MCPTests/ClientConnectionFailureTests.swift +++ b/Tests/MCPTests/ClientConnectionFailureTests.swift @@ -1,5 +1,6 @@ @preconcurrency import Foundation import Logging +import Synchronization import Testing @testable import MCP @@ -30,7 +31,7 @@ private actor ScriptedTransport: Transport { func disconnect() async { continuation.finish() } func receive() -> AsyncThrowingStream { stream } - func send(_ data: Data) async throws { + func send(_ data: Data, options: TransportSendOptions) async throws { let message = try JSONDecoder().decode(Value.self, from: data).objectValue ?? [:] sent.append(message) if let method = message["method"]?.stringValue, let error = failures[method] { throw error } @@ -254,6 +255,70 @@ struct ClientConfigurationCodingTests { #expect(try JSONDecoder().decode(Client.Configuration.self, from: data) == configuration) } } + + @Test("A saved client configuration writes durations in milliseconds") + func savesMilliseconds() throws { + #expect( + try wireString(Client.Configuration()) + == #"{"discoveryTimeoutMs":10000,"maxConcurrentServerRequests":4,"maxContextInclusion":"none","multiRoundTrip":{"isEnabled":true,"maxInputRequests":16,"maxRounds":10},"protocolMode":{"automatic":{}},"strict":false}"# + ) + let withTasks = try wireString(Client.Configuration(tasks: .init())) + #expect( + withTasks.contains( + #""tasks":{"augmentation":"whenRequired","defaultPollIntervalMs":1000,"maximumPollIntervalMs":30000,"minimumPollIntervalMs":100}"# + )) + func saved(_ timeout: Duration?) throws -> String { + try wireString(Client.Configuration(discoveryTimeout: timeout)) + } + #expect(try saved(.seconds(Int64.max)).contains(#""discoveryTimeoutMs":\#(Int.max)"#)) + #expect(try saved(.seconds(-1)).contains(#""discoveryTimeoutMs":0"#)) + } + + @Test("discoveryTimeoutMs null means no timeout; absent means 10 seconds") + func discoveryTimeoutKey() throws { + func load(_ json: String) throws -> Duration? { + try JSONDecoder().decode(Client.Configuration.self, from: Data(json.utf8)).discoveryTimeout + } + #expect(try load(#"{"strict":false,"discoveryTimeoutMs":null}"#) == nil) + #expect(try load(#"{"strict":false}"#) == .seconds(10)) + #expect(try load(#"{"strict":false,"discoveryTimeoutMs":2500}"#) == .milliseconds(2500)) + #expect(try load(#"{"strict":false,"discoveryTimeoutMs":2500.9}"#) == .milliseconds(2500)) + #expect(try load(#"{"strict":false,"discoveryTimeoutMs":0}"#) == .zero) + for invalid in ["-1", #""soon""#, "1e300", "{}"] { + #expect(try load(#"{"strict":false,"discoveryTimeoutMs":\#(invalid)}"#) == .seconds(10), "\(invalid)") + } + #expect(try wireString(Client.Configuration(discoveryTimeout: nil)).contains(#""discoveryTimeoutMs":null"#)) + } + + @Test("A configuration saved with the old duration form still decodes") + func decodesOldDurationForm() throws { + let old = String(decoding: try JSONEncoder().encode(Duration.seconds(2)), as: UTF8.self) + func load(_ json: String) throws -> Duration? { + try JSONDecoder().decode(Client.Configuration.self, from: Data(json.utf8)).discoveryTimeout + } + #expect(try load(#"{"strict":false,"discoveryTimeout":\#(old)}"#) == .seconds(2)) + #expect(try load(#"{"strict":false,"discoveryTimeout":null}"#) == nil) + // The millisecond key wins over the old one, including explicit null. + #expect( + try load(#"{"strict":false,"discoveryTimeoutMs":500,"discoveryTimeout":\#(old)}"#) == .milliseconds(500)) + #expect(try load(#"{"strict":false,"discoveryTimeoutMs":null,"discoveryTimeout":\#(old)}"#) == nil) + let alpha = Data(#"{"strict":false,"discoveryTimeout":\#(old)}"#.utf8) + let resaved = try wireString(JSONDecoder().decode(Client.Configuration.self, from: alpha)) + #expect(resaved.contains(#""discoveryTimeoutMs":2000"#)) + #expect(!resaved.contains(#""discoveryTimeout":"#)) + } + + @Test("A sub-millisecond duration is saved rounded down") + func roundsDown() throws { + let saved = try wireString(Client.Configuration(discoveryTimeout: .microseconds(2999))) + #expect(saved.contains(#""discoveryTimeoutMs":2,"#)) + #expect( + try JSONDecoder().decode(Client.Configuration.self, from: Data(saved.utf8)).discoveryTimeout + == .milliseconds(2)) + // A positive duration is never saved as zero. + let short = try wireString(Client.Configuration(discoveryTimeout: .nanoseconds(1))) + #expect(short.contains(#""discoveryTimeoutMs":1,"#)) + } } @Suite("Outgoing message fields") @@ -264,7 +329,7 @@ struct OutgoingMessageTests { Data( #"{"jsonrpc":"2.0","id":7,"method":" tools/call ","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28"}}}"# .utf8)) - #expect(message.requestID == "7") + #expect(message.requestID == .number(7)) #expect(message.method == " tools/call ") #expect(message.operationKey == "tools/call") #expect(message.protocolVersion == "2026-07-28") @@ -279,7 +344,7 @@ struct OutgoingMessageTests { let cancelled = OutgoingMessage( Data(#"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"r1"}}"#.utf8)) #expect(cancelled.requestID == nil) - #expect(cancelled.cancelledRequestID == "r1") + #expect(cancelled.cancelledRequestID == .string("r1")) let read = OutgoingMessage( Data(#"{"jsonrpc":"2.0","id":1,"method":"resources/read","params":{"uri":"file:///a","name":"x"}}"#.utf8)) #expect(read.nameValue == "file:///a") @@ -331,6 +396,22 @@ struct OutgoingMessageTests { await transport.disconnect() } + @Test("An error with the id \"1\" does not answer request 1: it fails with the status") + func stringIDDoesNotAnswerNumberID() async throws { + let transport = await makeTransport { _ in + reply(400, #"{"jsonrpc":"2.0","id":"1","error":{"code":-32602,"message":"Bad params"}}"#) + } + try await transport.connect() + await #expect { + try await transport.send( + Data(#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"x"}}"#.utf8)) + } throws: { error in + guard case .transportError(let underlying) = error as? MCPError else { return false } + return (underlying as? HTTPStatusError)?.statusCode == 400 + } + await transport.disconnect() + } + @Test("A result on a non-2xx reply is not delivered") func resultOnErrorStatusFails() async throws { let transport = await makeTransport { _ in @@ -560,6 +641,57 @@ struct OutgoingMessageTests { Issue.record("The sign-in of server/discover started after every discovery timeout") } + // Reading a token can need the user too, such as a Keychain item + // behind Face ID: that time is authorization time as well. + @Test("Authorizer time in authorizationHeaders does not count against the discovery timeout") + func headersOutlastDiscoveryTimeout() async throws { + for timeout in Self.discoveryTimeouts { + let attempt = SignInAttempt(timeout: timeout, stage: .headers) + let connecting = Task { try await attempt.connect() } + guard try await attempt.timerWaitsForSignIn() else { + await attempt.abandon(connecting) + continue + } + attempt.authorizer.release() + guard case .returned(let result) = await attempt.outcome(of: connecting) else { + Issue.record("connect did not return a result") + await attempt.client.disconnect() + return + } + #expect(result.protocolVersion == Version.v2026_07_28) + #expect(attempt.authorizer.challenges == 0) + #expect(ChallengedDiscoverProtocol.state.methods(of: attempt.host) == [ServerDiscover.name]) + await attempt.client.disconnect() + return + } + Issue.record("The header building of server/discover started after every discovery timeout") + } + + // So can a requestModifier that reads a credential of its own. + @Test("requestModifier time does not count against the discovery timeout") + func modifierOutlastsDiscoveryTimeout() async throws { + for timeout in Self.discoveryTimeouts { + let attempt = SignInAttempt(timeout: timeout, stage: .modifier) + let connecting = Task { try await attempt.connect() } + guard try await attempt.timerWaitsForSignIn() else { + await attempt.abandon(connecting) + continue + } + attempt.authorizer.release() + guard case .returned(let result) = await attempt.outcome(of: connecting) else { + Issue.record("connect did not return a result") + await attempt.client.disconnect() + return + } + #expect(result.protocolVersion == Version.v2026_07_28) + #expect(attempt.authorizer.challenges == 0) + #expect(ChallengedDiscoverProtocol.state.methods(of: attempt.host) == [ServerDiscover.name]) + await attempt.client.disconnect() + return + } + Issue.record("The requestModifier of server/discover started after every discovery timeout") + } + @Test("The discovery timeout starts again after signing in") func timeoutAfterSignIn() async throws { for timeout in Self.discoveryTimeouts { @@ -657,10 +789,18 @@ struct OutgoingMessageTests { /// Before `connect`, so before the discovery timer starts. let start = ContinuousClock.now - init(timeout: Duration, host suffix: String = "answering.test", succeeds: Bool = true) { + init( + timeout: Duration, host suffix: String = "answering.test", succeeds: Bool = true, + stage: SlowSignInAuthorizer.Stage = .challenge + ) { host = "\(UUID().uuidString).\(suffix)" - authorizer = SlowSignInAuthorizer(succeeds: succeeds) - transport = ChallengedDiscoverProtocol.transport(host: host, authorizer: authorizer) + let authorizer = SlowSignInAuthorizer(succeeds: succeeds, stage: stage) + self.authorizer = authorizer + let signIn: @Sendable (inout URLRequest) async throws -> Void = { _ in + if stage == .modifier { try await authorizer.signIn() } + } + transport = ChallengedDiscoverProtocol.transport( + host: host, authorizer: authorizer, requestModifier: signIn) client = Client( name: "probe", version: "1.0", configuration: .init(protocolMode: .automatic, discoveryTimeout: timeout)) @@ -721,70 +861,88 @@ struct OutgoingMessageTests { /// Signs in on a 401 like a user at a browser, then authorizes every /// request when `succeeds` is `true`. The sign-in ignores cancellation - /// and lasts until ``release()``. - private final class SlowSignInAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { + /// and lasts until ``release()``. With the `.headers` stage the sign-in + /// is instead the first `authorizationHeaders(for:method:)` call, like + /// reading a Keychain item behind Face ID, and no request is challenged. + /// With the `.modifier` stage, the transport's `requestModifier` signs in. + private final class SlowSignInAuthorizer: HTTPClientAuthorizer { + enum Stage { case challenge, headers, modifier } + private struct SignInDenied: LocalizedError { var errorDescription: String? { "User cancelled sign-in" } } - private let lock = NSLock() + private struct State { + var signedIn = false + var challengeCount = 0 + var firstChallenge: ContinuousClock.Instant? + var endedCount = 0 + var released = false + /// Every sign-in waiting for ``release()``. Cancelling `connect` can + /// send `notifications/cancelled`, which is challenged too, so more + /// than one can wait. + var pendingReleases: [CheckedContinuation] = [] + } + + private let state = Mutex(State()) private let succeeds: Bool - private var signedIn = false - private var challengeCount = 0 - private var firstChallenge: ContinuousClock.Instant? - private var endedCount = 0 - private var released = false - /// Every sign-in waiting for ``release()``. Cancelling `connect` can - /// send `notifications/cancelled`, which is challenged too, so more - /// than one can wait. - private var pendingReleases: [CheckedContinuation] = [] - - init(succeeds: Bool = true) { + private let stage: Stage + + init(succeeds: Bool = true, stage: Stage = .challenge) { self.succeeds = succeeds + self.stage = stage } - var challenges: Int { lock.withLock { challengeCount } } + var challenges: Int { state.withLock { $0.challengeCount } } /// When the first sign-in started, if one has. - var firstSignInStart: ContinuousClock.Instant? { lock.withLock { firstChallenge } } + var firstSignInStart: ContinuousClock.Instant? { state.withLock { $0.firstChallenge } } /// Sign-ins that returned or threw. - var signInsEnded: Int { lock.withLock { endedCount } } + var signInsEnded: Int { state.withLock { $0.endedCount } } var maxAuthorizationAttempts: Int { 2 } /// Ends every sign-in, and lets later ones end at once. func release() { - let pending = lock.withLock { - released = true - defer { pendingReleases = [] } - return pendingReleases + let pending = state.withLock { state in + state.released = true + defer { state.pendingReleases = [] } + return state.pendingReleases } for continuation in pending { continuation.resume() } } - func validateEndpointSecurity(for endpoint: URL) throws {} + func prepare(for endpoint: URL, session: URLSession) async throws {} - func authorizationHeaders(for url: URL, method: String) throws -> [String: String] { - lock.withLock { signedIn ? ["Authorization": "Bearer signed-in"] : [:] } + func authorizationHeaders(for url: URL, method: String) async throws -> [String: String] { + if stage == .headers { + try await signIn() + } + return state.withLock { $0.signedIn ? ["Authorization": "Bearer signed-in"] : [:] } + } + + func handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) async throws + -> HTTPChallengeResult + { + state.withLock { $0.challengeCount += 1 } + try await signIn() + return .retry } - func handleChallenge( - statusCode: Int, headers: [String: String], endpoint: URL, operationKey: String?, - session: URLSession - ) async throws -> Bool { - lock.withLock { - challengeCount += 1 - if firstChallenge == nil { firstChallenge = ContinuousClock.now } + /// Waits for ``release()``, then signs in, or throws when `succeeds` is `false`. + func signIn() async throws { + state.withLock { state in + if state.firstChallenge == nil { state.firstChallenge = ContinuousClock.now } } - defer { lock.withLock { endedCount += 1 } } + defer { state.withLock { $0.endedCount += 1 } } + // The continuation is resumed after the lock is released. await withCheckedContinuation { continuation in - let now = lock.withLock { - if !released { pendingReleases.append(continuation) } - return released + let now = state.withLock { state in + if !state.released { state.pendingReleases.append(continuation) } + return state.released } if now { continuation.resume() } } guard succeeds else { throw SignInDenied() } - lock.withLock { signedIn = true } - return true + state.withLock { $0.signedIn = true } } } @@ -801,12 +959,15 @@ struct OutgoingMessageTests { } static let state = State() - static func transport(host: String, authorizer: any HTTPClientAuthorizer) -> HTTPClientTransport { + static func transport( + host: String, authorizer: any HTTPClientAuthorizer, + requestModifier: @escaping @Sendable (inout URLRequest) async throws -> Void = { _ in } + ) -> HTTPClientTransport { let configuration = URLSessionConfiguration.ephemeral configuration.protocolClasses = [ChallengedDiscoverProtocol.self] return HTTPClientTransport( - endpoint: URL(string: "http://\(host)/mcp")!, configuration: configuration, streaming: false, - authorizer: authorizer) + endpoint: URL(string: "https://\(host)/mcp")!, configuration: configuration, streaming: false, + authorizer: authorizer, requestModifier: requestModifier) } override class func canInit(with request: URLRequest) -> Bool { true } diff --git a/Tests/MCPTests/ClientReceiveLoopTerminationTests.swift b/Tests/MCPTests/ClientReceiveLoopTerminationTests.swift index b9902480..0357d55f 100644 --- a/Tests/MCPTests/ClientReceiveLoopTerminationTests.swift +++ b/Tests/MCPTests/ClientReceiveLoopTerminationTests.swift @@ -1,4 +1,5 @@ import Foundation +import Synchronization import Testing @testable import MCP @@ -88,20 +89,19 @@ struct ClientReceiveLoopTerminationTests { let inFlight = try await client.send(Ping.request()) try await transport.waitUntilSent(Ping.name) - let added = BatchTasks() + var tasks: [Task] = [] await #expect(throws: MCPError.connectionClosed) { try await client.withBatch { batch in - await added.append(try await batch.addRequest(Ping.request())) + tasks.append(try await batch.addRequest(Ping.request())) await transport.finishStream() // The request in flight fails once the client has handled the close. _ = await outcome(within: Self.completionLimit) { try await inFlight.value } // Adding to a batch of a closed connection throws. - await added.append(try await batch.addRequest(Ping.request())) + tasks.append(try await batch.addRequest(Ping.request())) } } #expect(await transport.sentBatchCount == 0) - let tasks = await added.tasks #expect(tasks.count == 1) let task = try #require(tasks.first) let result = await outcome(within: Self.completionLimit) { try await task.value } @@ -362,6 +362,70 @@ struct ClientReceiveLoopTerminationTests { await client.disconnect() } + @Test("A stdio input whose read fails fails the request in flight with the read error") + func stdioReadErrorFailsInFlightRequest() async throws { + // The client reads from a TCP socket, which the fake server resets: the client's next + // read fails with ECONNRESET. It writes to a pipe. + final class CloseOnce: Sendable { + private let closed = Mutex(false) + func claim() -> Bool { + closed.withLock { + let was = $0 + $0 = true + return !was + } + } + } + let (clientInput, serverOutput) = try LoopbackTCP.connectedPair() + let serverOutputClosed = CloseOnce() + defer { + _ = close(clientInput) + if serverOutputClosed.claim() { + _ = close(serverOutput) + } + } + let (serverInput, clientOutput) = try FileDescriptor.pipe() + defer { + try? clientOutput.close() + try? serverInput.close() + } + let transport = StdioTransport( + input: FileDescriptor(rawValue: clientInput), output: clientOutput, logger: nil) + let client = Client(name: "TestClient", version: "1.0", configuration: .handshake) + + // Answers initialize, reads notifications/initialized and the ping, then resets the + // connection. Its reads block, so it runs off the cooperative pool. + let server = Task { + try await offThreadPool { + let initialize = try Self.readLine(from: serverInput) + try FileDescriptor(rawValue: serverOutput).writeAll( + try Self.initializeResponse(to: initialize) + Data("\n".utf8)) + _ = try Self.readLine(from: serverInput) + _ = try Self.readLine(from: serverInput) + if serverOutputClosed.claim() { + LoopbackTCP.reset(serverOutput) + } + } + } + + try await client.connect(transport: transport) + let context = try await client.send(Ping.request()) + let served = await outcome(within: Self.completionLimit) { try await server.value } + #expect(!served.didTimeOut && served.error == nil, "the fake server didn't reset the connection") + + let result = await outcome(within: Self.completionLimit) { try await context.value } + #expect(!result.didTimeOut, "the request never completed after the read failed") + // Before the fix the read error ended the stream as end of file: connectionClosed. + guard case .transportError(let error) = result.mcpError else { + Issue.record("Expected transportError(ECONNRESET), got \(result)") + await client.disconnect() + return + } + #expect(error as? Errno == .connectionReset) + + await client.disconnect() + } + @Test("An in-memory peer disconnecting fails the request in flight") func inMemoryPeerDisconnectFailsInFlightRequest() async throws { let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() @@ -404,8 +468,8 @@ struct ClientReceiveLoopTerminationTests { return try JSONEncoder().encode(response) } - /// Reads one newline-terminated message. The server ends of the pipes stay - /// blocking; `StdioTransport` only changes the client ends. + /// Reads one newline-terminated message. The pipes stay blocking: + /// `StdioTransport` doesn't change the flags of its descriptors. private static func readLine(from descriptor: FileDescriptor) throws -> Data { var line = Data() var byte: UInt8 = 0 @@ -417,12 +481,3 @@ struct ClientReceiveLoopTerminationTests { } } } - -/// Collects the tasks returned by `Batch.addRequest(_:)` inside a batch body. -private actor BatchTasks { - private(set) var tasks: [Task] = [] - - func append(_ task: Task) { - tasks.append(task) - } -} diff --git a/Tests/MCPTests/ClientStatelessTests.swift b/Tests/MCPTests/ClientStatelessTests.swift index 09f5f2bd..5ae51986 100644 --- a/Tests/MCPTests/ClientStatelessTests.swift +++ b/Tests/MCPTests/ClientStatelessTests.swift @@ -275,39 +275,21 @@ struct ClientToolHeaderCacheTests { } /// A transport that wraps another one and records the headers the client -/// passes to `send(_:additionalHeaders:)`, by method. -private actor HeaderForwardingTransport: Transport { - nonisolated let logger = Logger(label: "test.header-forwarding") - private let base: any Transport +/// passes in `options.headers`, by method, when there are any. +private actor HeaderForwardingTransport: TransportWrapper { + nonisolated let wrapped: any Transport private(set) var headers: [String: [String: String]] = [:] - init(_ base: any Transport) { - self.base = base + init(_ wrapped: any Transport) { + self.wrapped = wrapped } - func connect() async throws { try await base.connect() } - func disconnect() async { await base.disconnect() } - func send(_ data: Data) async throws { try await base.send(data) } - - func send(_ data: Data, additionalHeaders: [String: String]) async throws { - let method = try JSONDecoder().decode(Value.self, from: data).objectValue?["method"]?.stringValue - headers[method ?? ""] = additionalHeaders - try await base.send(data, additionalHeaders: additionalHeaders) - } - - func receive() -> AsyncThrowingStream { - let base = self.base - return AsyncThrowingStream { continuation in - let task = Task { - do { - for try await data in await base.receive() { continuation.yield(data) } - continuation.finish() - } catch { - continuation.finish(throwing: error) - } - } - continuation.onTermination = { _ in task.cancel() } + func send(_ data: Data, options: TransportSendOptions) async throws { + if !options.headers.isEmpty { + let method = try JSONDecoder().decode(Value.self, from: data).objectValue?["method"]?.stringValue + headers[method ?? ""] = options.headers } + try await wrapped.send(data, options: options) } } @@ -476,7 +458,7 @@ struct ClientDiscoveryNegotiationTests { let transport = HTTPClientTransport( endpoint: endpoint, configuration: configuration, streaming: false) try await transport.connect() - await transport.useStatelessProtocol("2026-07-28") + await transport.didNegotiate(protocolVersion: "2026-07-28") await MockURLProtocol.requestHandlerStorage.setHandler { [endpoint] request in #expect(request.value(forHTTPHeaderField: "Mcp-Session-Id") == nil) diff --git a/Tests/MCPTests/ClientTests.swift b/Tests/MCPTests/ClientTests.swift index 356377cc..5ea7e0a5 100644 --- a/Tests/MCPTests/ClientTests.swift +++ b/Tests/MCPTests/ClientTests.swift @@ -296,8 +296,8 @@ struct ClientTests { let request1 = Ping.request() let request2 = Ping.request() - nonisolated(unsafe) var resultTask1: Task? - nonisolated(unsafe) var resultTask2: Task? + var resultTask1: Task? + var resultTask2: Task? try await client.withBatch { batch in resultTask1 = try await batch.addRequest(request1) @@ -376,7 +376,7 @@ struct ClientTests { let request1 = Ping.request() // Success let request2 = Ping.request() // Error - nonisolated(unsafe) var resultTasks: [Task] = [] + var resultTasks: [Task] = [] try await client.withBatch { batch in resultTasks.append(try await batch.addRequest(request1)) @@ -715,6 +715,93 @@ struct ClientTests { await client.disconnect() } + + /// A strict handshake client connected to `transport`, which answers + /// initialize with `capabilities`. + private func connectStrictClient( + _ transport: MockTransport, serverCapabilities capabilities: Server.Capabilities + ) async throws -> Client { + let client = Client(name: "c", version: "1", configuration: .strictHandshake) + try await connectAnsweringInitialize(client, over: transport, serverCapabilities: capabilities) + return client + } + + @Test( + "Strict client refuses a resource subscription unless the server declares subscribe: true", + arguments: [ + Server.Capabilities(resources: .init(subscribe: false)), + Server.Capabilities(resources: .init(listChanged: true)), + Server.Capabilities(), + ]) + func strictSubscriptionRefused(capabilities: Server.Capabilities) async throws { + let transport = MockTransport() + let client = try await connectStrictClient(transport, serverCapabilities: capabilities) + let refusal = MCPError.methodNotFound("Resource subscription is not supported by the server") + + await #expect(throws: refusal) { try await client.subscribeToResource(uri: "test://a") } + await #expect(throws: refusal) { try await client.unsubscribeFromResource(uri: "test://a") } + // initialize and notifications/initialized only + #expect(await transport.sentData.count == 2) + await client.disconnect() + } + + @Test("Strict client sends a resource subscription when the server declares subscribe: true") + func strictSubscriptionSent() async throws { + let transport = MockTransport() + let client = try await connectStrictClient( + transport, serverCapabilities: .init(resources: .init(subscribe: true))) + + /// Answers message `count`, which must be a `method` request for test://a. + @Sendable func answer(_ method: String, at count: Int) async throws { + try await transport.waitForSentMessages(count: count) + let data = try #require(await transport.sentData.last) + let message = try #require(try JSONDecoder().decode(Value.self, from: data).objectValue) + #expect(message["method"]?.stringValue == method) + #expect(message["params"] == .object(["uri": "test://a"])) + let reply: Value = .object(["jsonrpc": "2.0", "id": try #require(message["id"]), "result": .object([:])]) + await transport.queue(data: try JSONEncoder().encode(reply)) + } + + let subscribed = Task { try await answer(ResourceSubscribe.name, at: 3) } + try await client.subscribeToResource(uri: "test://a") + try await subscribed.value + #expect(await client.subscribedResourceURIs == ["test://a"]) + + let unsubscribed = Task { try await answer(ResourceUnsubscribe.name, at: 4) } + try await client.unsubscribeFromResource(uri: "test://a") + try await unsubscribed.value + #expect(await client.subscribedResourceURIs.isEmpty) + await client.disconnect() + } + + @Test("At 2026-07-28 a strict client refuses subscribe: false and opens no listen stream") + func strictStatelessSubscriptionRefused() async throws { + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + let server = Server(name: "s", version: "1", capabilities: .init(resources: .init(subscribe: false))) + await server.withMethodHandler(ListResources.self) { _ in .init(resources: []) } + try await server.start(transport: serverTransport) + let recording = RecordingTransport(clientTransport) + let client = Client(name: "c", version: "1", configuration: Client.Configuration(strict: true)) + try await client.connect(transport: recording) + #expect(await client.isStateless) + + await #expect(throws: MCPError.methodNotFound("Resource subscription is not supported by the server")) { + try await client.subscribeToResource(uri: "test://a") + } + #expect(await client.subscribedResources.isEmpty) + #expect(await client.notificationStream == nil) + // Not subscribed, so there is nothing to unsubscribe from. + try await client.unsubscribeFromResource(uri: "test://a") + + // A request after both calls: a listen stream opened by either would be sent before it. + _ = try await client.listResources() + let methods = await recording.methods + #expect(methods.contains(ListResources.name)) + #expect(!methods.contains(SubscriptionsListen.name)) + + await client.disconnect() + await server.stop() + } } @Suite("Client undecodable responses", .timeLimit(.minutes(2))) @@ -870,3 +957,73 @@ struct ClientUndecodableResponseTests { await client.disconnect() } } + +@Suite("Client handler names", .timeLimit(.minutes(2))) +struct ClientHandlerNameTests { + // "Kelvin" and "\u{212A}elvin" (KELVIN SIGN): equal as Swift strings, + // different method names on the wire. + private enum KelvinRun: MCP.Method { + static let name = "Kelvin/run" + } + + private struct KelvinNote: MCP.Notification { + static let name = "notifications/Kelvin" + struct Parameters: Hashable, Codable, Sendable { let tag: String } + } + + /// A handshake client connected to `transport`, which answers initialize. + private func connect(_ client: Client, _ transport: MockTransport) async throws { + let answer = Task { + try await transport.waitForSentMessages() + let data = try #require(await transport.sentMessages.last?.data(using: .utf8)) + let request = try JSONDecoder().decode(Request.self, from: data) + try await transport.queue( + response: Initialize.response( + id: request.id, + result: .init( + protocolVersion: Version.latestHandshake, capabilities: .init(), + serverInfo: .init(name: "s", version: "1"), instructions: nil))) + } + _ = try await client.connect(transport: transport) + try await answer.value + } + + @Test("A request handler answers only its method's exact name, not a canonically equivalent one") + func methodHandlersMatchExactly() async throws { + let transport = MockTransport() + let client = Client(name: "c", version: "1", configuration: .handshake) + await client.withMethodHandler(KelvinRun.self) { _ in Empty() } + try await connect(client, transport) + let before = await transport.sentMessages.count + + await transport.queue(data: Data(#"{"jsonrpc":"2.0","id":"sign","method":"\u212Aelvin/run"}"#.utf8)) + await transport.queue(data: Data(#"{"jsonrpc":"2.0","id":"exact","method":"Kelvin/run"}"#.utf8)) + try await transport.waitForSentMessages(count: before + 2, timeout: .seconds(10)) + let sent = await transport.sentMessages + let replies = try sent[before...].map { try JSONDecoder().decode(Value.self, from: Data($0.utf8)) } + let sign = try #require(replies.first { $0.objectValue?["id"] == "sign" }) + let exact = try #require(replies.first { $0.objectValue?["id"] == "exact" }) + #expect(sign.objectValue?["error"]?.objectValue?["code"] == -32601, "\(sign)") + #expect(exact.objectValue?["result"] != nil, "\(exact)") + await client.disconnect() + } + + @Test("A notification handler runs only for its exact name, not a canonically equivalent one") + func notificationHandlersMatchExactly() async throws { + let transport = MockTransport() + let client = Client(name: "c", version: "1", configuration: .handshake) + let notes = AsyncStream.makeStream() + await client.onNotification(KelvinNote.self) { message in notes.continuation.yield(message.params.tag) } + try await connect(client, transport) + + // Notifications are handled in order, so the first one the handler + // sees tells whether the other name reached it. + await transport.queue( + data: Data(#"{"jsonrpc":"2.0","method":"notifications/\u212Aelvin","params":{"tag":"sign"}}"#.utf8)) + await transport.queue( + data: Data(#"{"jsonrpc":"2.0","method":"notifications/Kelvin","params":{"tag":"exact"}}"#.utf8)) + var iterator = notes.stream.makeAsyncIterator() + #expect(await iterator.next() == "exact") + await client.disconnect() + } +} diff --git a/Tests/MCPTests/DataURLTests.swift b/Tests/MCPTests/DataURLTests.swift new file mode 100644 index 00000000..c732b91e --- /dev/null +++ b/Tests/MCPTests/DataURLTests.swift @@ -0,0 +1,308 @@ +import Foundation +import Testing + +@testable import MCP + +@Suite("DataURL") +struct DataURLTests { + /// A `data:` URL, the MIME type it parses to, and its bytes. + struct Parsed: Sendable, CustomTestStringConvertible { + let string: String + let mimeType: String + let bytes: [UInt8] + + init(_ string: String, _ mimeType: String, _ bytes: [UInt8]) { + self.string = string + self.mimeType = mimeType + self.bytes = bytes + } + + init(_ string: String, _ mimeType: String, text: String) { + self.init(string, mimeType, Array(text.utf8)) + } + + var testDescription: String { string } + } + + static let parsed: [Parsed] = [ + // RFC 2397 §4 + Parsed("data:,A%20brief%20note", "text/plain", text: "A brief note"), + Parsed( + "data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw", "image/gif", + Array(Data(base64Encoded: "R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw")!)), + Parsed("data:text/plain;charset=iso-8859-7,%be%d3%be", "text/plain;charset=iso-8859-7", [0xBE, 0xD3, 0xBE]), + Parsed( + "data:application/vnd-xxx-query,select_vcount,fcol_from_fieldtable/local", + "application/vnd-xxx-query", text: "select_vcount,fcol_from_fieldtable/local"), + // Other shapes + Parsed("data:,hello%20world", "text/plain", text: "hello world"), + Parsed("data:;charset=utf-8,hello", "text/plain;charset=utf-8", text: "hello"), + Parsed( + "data:text/plain;charset=iso-8859-7,%CF%84%CE%B5%CF%83%CF%84", "text/plain;charset=iso-8859-7", + [0xCF, 0x84, 0xCE, 0xB5, 0xCF, 0x83, 0xCF, 0x84]), + Parsed("data:text/plain;base64,SGVsbG8=", "text/plain", text: "Hello"), + Parsed("data:application/octet-stream,%FF%00", "application/octet-stream", [0xFF, 0x00]), + Parsed("data:application/octet-stream;base64,/wA=", "application/octet-stream", [0xFF, 0x00]), + Parsed("data:text/plain;charset=utf-8;base64,SGk=", "text/plain;charset=utf-8", text: "Hi"), + Parsed("data:text/plain;base64,", "text/plain", []), + // RFC 2045 §5.1 token characters + Parsed("data:image/svg+xml;base64,PHN2Zy8+", "image/svg+xml", text: ""), + Parsed("data:application/vnd.example-v1+json,%7B%7D", "application/vnd.example-v1+json", text: "{}"), + // Case-insensitive names + Parsed("data:TEXT/PLAIN,hi", "text/plain", text: "hi"), + Parsed("data:text/plain;CharSet=UTF-8;BASE64,aGk=", "text/plain;charset=UTF-8", text: "hi"), + // Payloads starting with combining marks or joiners (UAX #29 GB9) + Parsed("data:,\u{0301}", "text/plain", text: "\u{0301}"), + Parsed("data:text/plain,\u{200D}x", "text/plain", text: "\u{200D}x"), + Parsed("data:,\u{FE0F}", "text/plain", text: "\u{FE0F}"), + ] + + @Test("Parses the RFC 2397 examples and other data: URLs", arguments: parsed) + func parses(_ expected: Parsed) throws { + let url = try #require(DataURL(expected.string)) + #expect(url.mimeType == expected.mimeType) + #expect(url.data == Data(expected.bytes)) + } + + @Test( + "Is not a data: URL", + arguments: [ + "https://example.com", + "data:text/plain", + "dat:,hello", + "", + "data: 3 rows, 2 columns", + "data:text,hi", + "data:text/,hi", + "data:/plain,hi", + "data:text/plain extra,hi", + "data:text/plain;charset=,hi", + "data:text/plain;charset=utf 8,hi", + "data:text/html; charset=utf-8,hi", + "data:text/\u{212A},hi", + "data:text/plain;char\u{017F}et=utf-8,hi", + "data:;ba\u{017F}e64,aGk=", + "data:image/png;name=a.png;base64,AA==", + "DATA:,hi", + ]) + func isNotADataURL(_ string: String) throws { + #expect(DataURL(string) == nil) + let json = try JSONEncoder().encode(string) + #expect(try JSONDecoder().decode(Value.self, from: json) == .string(string)) + } + + @Test( + "Rejects a malformed percent escape", + arguments: ["data:,%", "data:,%F", "data:,%fg", "data:text/plain;charset=iso-8859-7,%be%fg%be"]) + func rejectsMalformedPercentEscape(_ string: String) { + #expect(DataURL(string) == nil) + } + + @Test("Base64 payloads decode leniently") + func base64PayloadsDecodeLeniently() throws { + #expect(DataURL("data:;base64,aGk")?.data == Data("hi".utf8)) + #expect(DataURL("data:;base64,aG k=")?.data == Data("hi".utf8)) + #expect(DataURL("data:;base64,aG\r\nk=")?.data == Data("hi".utf8)) + #expect(DataURL("data:text/plain;base64,SGVsbG8=!") == nil) + #expect(DataURL("data:;base64,====") == nil) + #expect(DataURL("data:;base64,-_-_") == nil) + // Unlike the WHATWG Fetch processor, a base64 payload is not percent-decoded first. + #expect(DataURL("data:;base64,aGk%3D") == nil) + let empty = try #require(DataURL("data:text/plain;base64,")) + #expect(empty.data.isEmpty) + } + + @Test("Keeps ;base64, inside a plain payload and + as itself") + func keepsPlainPayloadAsWritten() throws { + let marker = try #require(DataURL("data:text/plain,hello;base64,world")) + #expect(marker.mimeType == "text/plain") + #expect(marker.data == Data("hello;base64,world".utf8)) + // RFC 2397 uses URL percent-encoding, not form encoding, so `+` is not a space. + #expect(DataURL("data:,a+b%2B")?.data == Data("a+b+".utf8)) + } + + @Test("Keeps charset only for text types") + func keepsCharsetOnlyForTextTypes() { + #expect(DataURL("data:image/png;charset=utf-8;base64,AA==")?.mimeType == "image/png") + #expect(DataURL("data:;charset=utf-8,hi")?.mimeType == "text/plain;charset=utf-8") + } + + @Test("Normalizes the media type at every entry point") + func normalizesMediaType() throws { + let data = Data("hi".utf8) + let upper = DataURL(data: data, mimeType: "TEXT/PLAIN") + let lower = DataURL(data: data, mimeType: "text/plain") + #expect(upper == lower) + #expect(upper.hashValue == lower.hashValue) + #expect(Set([upper, lower]).count == 1) + #expect(DataURL(data: data, mimeType: "text/plain;Charset=UTF-8").mimeType == "text/plain;charset=UTF-8") + #expect(DataURL("data:TEXT/Plain;CHARSET=UTF-8,hi")?.mimeType == "text/plain;charset=UTF-8") + #expect(DataURL(data: data, mimeType: "").mimeType == "text/plain") + #expect(DataURL(data: data, mimeType: "text/html; charset=utf-8").mimeType == "text/html;charset=utf-8") + #expect(DataURL(data: data, mimeType: " ").mimeType == "text/plain") + let decoded = try JSONDecoder().decode(Arguments.self, from: Data(#"{"image":"data:TEXT/PLAIN,hi"}"#.utf8)) + #expect(decoded.image.mimeType == "text/plain") + #expect(decoded.image == lower) + + var url = DataURL(data: data, mimeType: "text/plain") + url.mimeType = "IMAGE/PNG" + #expect(url.mimeType == "image/png") + #expect(url == DataURL(data: data, mimeType: "image/png")) + url.mimeType = "" + #expect(url.mimeType == "text/plain") + // Lowercasing is ASCII-only so non-ASCII characters like U+212A (Kelvin sign) are preserved. + #expect(DataURL(data: data, mimeType: "text/\u{212A}").mimeType == "text/\u{212A}") + #expect(DataURL(data: data, mimeType: "text/plain;\u{212A}=1").mimeType == "text/plain;\u{212A}=1") + } + + @Test("description is the normalized base64 form", arguments: parsed) + func descriptionRoundTrips(_ expected: Parsed) throws { + let url = try #require(DataURL(expected.string)) + #expect(url.description == "data:\(expected.mimeType);base64,\(Data(expected.bytes).base64EncodedString())") + #expect(DataURL(url.description) == url) + } + + @Test("description writes the normalized spelling, not the parsed one") + func descriptionNormalizes() throws { + #expect(String(describing: try #require(DataURL("data:TEXT/Plain,hi"))) == "data:text/plain;base64,aGk=") + #expect(DataURL(data: Data("hi".utf8), mimeType: "TEXT/plain").description == "data:text/plain;base64,aGk=") + } + + @Test("A media type the grammar cannot carry does not parse back, or parses to another value") + func inexpressibleMediaTypeDoesNotRoundTrip() throws { + let charset = DataURL(data: Data([0]), mimeType: "image/png;charset=utf-8") + #expect(DataURL(charset.description) == DataURL(data: Data([0]), mimeType: "image/png")) + let parameter = DataURL(data: Data([0]), mimeType: "image/png;name=a.png") + #expect(DataURL(parameter.description) == nil) + let space = DataURL(data: Data([0]), mimeType: "text/plain;charset=utf 8") + #expect(DataURL(space.description) == nil) + + // A `,` ends the media type early: the rest is read as a percent-encoded payload. + let comma = DataURL(data: Data("hi".utf8), mimeType: "a/b,c") + #expect(comma.description == "data:a/b,c;base64,aGk=") + let reparsed = try #require(DataURL(comma.description)) + #expect(reparsed.mimeType == "a/b") + #expect(reparsed.data == Data("c;base64,aGk=".utf8)) + } + + @Test( + "Whitespace around ; and = is removed, so a Content-Type spelling encodes and parses back", + arguments: ["text/html; charset=utf-8", "TEXT/HTML ; Charset = utf-8", " text/html;\tcharset=utf-8\r\n"]) + func whitespaceAroundSeparatorsRoundTrips(_ mimeType: String) throws { + let data = Data("hi".utf8) + let url = DataURL(data: data, mimeType: mimeType) + #expect(url.mimeType == "text/html;charset=utf-8") + #expect(url == DataURL(data: data, mimeType: "text/html;charset=utf-8")) + #expect(url.description == "data:text/html;charset=utf-8;base64,aGk=") + #expect(DataURL(url.description) == url) + + var set = DataURL(data: data, mimeType: "image/png") + set.mimeType = mimeType + #expect(set.mimeType == "text/html;charset=utf-8") + #expect(set == url) + + let json = #"{"image":"data:text/html;charset=utf-8;base64,aGk="}"# + #expect(try wireString(Arguments(image: url)) == json) + #expect(try JSONDecoder().decode(Arguments.self, from: Data(json.utf8)).image == url) + } + + @Test( + "An empty type part with charset normalizes to text/plain and round-trips", + arguments: [";charset=utf-8", " ; Charset = utf-8 "]) + func emptyTypePartWithCharsetNormalizesToTextPlain(_ mimeType: String) throws { + let data = Data("hi".utf8) + let url = DataURL(data: data, mimeType: mimeType) + #expect(url.mimeType == "text/plain;charset=utf-8") + #expect(url == DataURL(data: data, mimeType: "text/plain;charset=utf-8")) + #expect(url == DataURL("data:;charset=utf-8,hi")) + #expect(url.description == "data:text/plain;charset=utf-8;base64,aGk=") + #expect(DataURL(url.description) == url) + + var mutated = DataURL(data: data, mimeType: "image/png") + mutated.mimeType = mimeType + #expect(mutated.mimeType == "text/plain;charset=utf-8") + #expect(mutated == url) + + let json = #"{"image":"data:text/plain;charset=utf-8;base64,aGk="}"# + #expect(try wireString(Arguments(image: url)) == json) + #expect(try JSONDecoder().decode(Arguments.self, from: Data(json.utf8)).image == url) + } + + @Test( + "Encoding a media type that does not read back throws instead of changing the value", + arguments: [ + "image/png;charset=utf-8", "image/png;name=a.png", ";name=a.png", "text/plain;charset=utf 8", + "text/html; charset=utf 8", "text /html", "a/b,c", "text", "text/\u{212A}", "text/plain;\u{212A}=1", + ]) + func encodingInexpressibleMediaTypeThrows(_ mimeType: String) throws { + let url = DataURL(data: Data("secret".utf8), mimeType: mimeType) + let error = try #require(throws: EncodingError.self) { try JSONEncoder().encode(Arguments(image: url)) } + guard case .invalidValue(let value, let context) = error else { + Issue.record("Expected invalidValue, got \(error)") + return + } + #expect(value as? String == url.mimeType) + #expect(context.codingPath.map(\.stringValue) == ["image"]) + #expect(!String(describing: error).contains(Data("secret".utf8).base64EncodedString())) + } + + struct Arguments: Codable, Equatable { + var image: DataURL + } + + @Test("Codes as a JSON string") + func codesAsJSONString() throws { + let json = #"{"image":"data:image/png;base64,iVBORw=="}"# + let arguments = try JSONDecoder().decode(Arguments.self, from: Data(json.utf8)) + #expect(arguments.image.mimeType == "image/png") + #expect(arguments.image.data == Data([0x89, 0x50, 0x4E, 0x47])) + #expect(try wireString(arguments) == json) + #expect(try JSONDecoder().decode(Arguments.self, from: JSONEncoder().encode(arguments)) == arguments) + } + + @Test("Decoding a string that is not a data: URL throws dataCorrupted") + func decodingNonDataURLThrowsDataCorrupted() throws { + let error = try #require(throws: DecodingError.self) { + try JSONDecoder().decode(Arguments.self, from: Data(#"{"image":"https://x"}"#.utf8)) + } + guard case .dataCorrupted = error else { + Issue.record("Expected dataCorrupted, got \(error)") + return + } + #expect(codingPath(of: error) == ["image"]) + } + + @Test("Decoding a value that is not a string throws typeMismatch") + func decodingNonStringThrowsTypeMismatch() throws { + let error = try #require(throws: DecodingError.self) { + try JSONDecoder().decode(Arguments.self, from: Data(#"{"image":3}"#.utf8)) + } + guard case .typeMismatch = error else { + Issue.record("Expected typeMismatch, got \(error)") + return + } + } + + @Test("Deprecated Data and Value.dataValue shims forward to DataURL") + @available(*, deprecated, message: "Tests the deprecated 0.12.1 DataURL shims") + func deprecatedDataURLShims() throws { + #expect(Data.isDataURL(string: "data:image/png;base64,iVBORw==")) + #expect(!Data.isDataURL(string: "data: 3 rows, 2 columns")) + #expect(!Data.isDataURL(string: "https://example.com")) + + let parsed = try #require(Data.parseDataURL("data:TEXT/Plain;charset=utf-8,hi")) + #expect(parsed.mimeType == "text/plain;charset=utf-8") + #expect(parsed.data == Data("hi".utf8)) + #expect(Data.parseDataURL("not-a-data-url") == nil) + + #expect(Data("hi".utf8).dataURLEncoded() == "data:text/plain;base64,aGk=") + #expect(Data("hi".utf8).dataURLEncoded(mimeType: "image/png") == "data:image/png;base64,aGk=") + + let value: Value = .string("data:image/png;base64,aGk=") + let tuple = try #require(value.dataValue) + #expect(tuple.mimeType == "image/png") + #expect(tuple.1 == Data("hi".utf8)) + #expect(Value.string("hello").dataValue == nil) + #expect(Value.int(42).dataValue == nil) + } +} diff --git a/Tests/MCPTests/ElicitationTests.swift b/Tests/MCPTests/ElicitationTests.swift index 14bf53cb..51aab47a 100644 --- a/Tests/MCPTests/ElicitationTests.swift +++ b/Tests/MCPTests/ElicitationTests.swift @@ -633,4 +633,95 @@ struct ElicitationIntegrationTests { await server.stop() await client.disconnect() } + + @Test( + "Cancelling the task awaiting requestElicitation withdraws the request", + .timeLimit(.minutes(1)), arguments: [false, true]) + func testCancellingRequestElicitationWithdrawsRequest(url: Bool) async throws { + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + let server = Server(name: "ElicitationCancelServer", version: "1.0") + let client = Client( + name: "ElicitationCancelClient", version: "1.0", + capabilities: .init(elicitation: .init(form: .init(), url: .init())), configuration: .handshake) + let started = Flag() + let handlerCancelled = Flag() + await client.withElicitationHandler { _ in + await started.set() + do { + try await Task.sleep(for: .seconds(60)) + } catch { + if error is CancellationError { await handlerCancelled.set() } + throw error + } + return CreateElicitation.Result(action: .decline) + } + try await server.start(transport: serverTransport) + try await client.connect(transport: clientTransport) + + let elicitation = Task { + if url { + try await server.requestElicitation( + message: "Sign in", url: "https://example.com/auth", elicitationId: "e-1") + } else { + try await server.requestElicitation(message: "Your name?", requestedSchema: .init()) + } + } + try #require(await eventually { await started.isSet }) + elicitation.cancel() + + let result = await outcome(within: .seconds(30)) { try await elicitation.value } + #expect(result.error is CancellationError, "got \(result)") + // The client got notifications/cancelled and cancelled its handler. + #expect(await eventually { await handlerCancelled.isSet }) + + await client.disconnect() + await server.stop() + } + + @Test( + "Cancelling a tool call whose handler awaits requestElicitation cancels the client's elicitation", + .timeLimit(.minutes(1))) + func testCancellingToolCallWithdrawsElicitation() async throws { + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + let server = Server(name: "ElicitationCancelServer", version: "1.0", capabilities: .init(tools: .init())) + let toolCancelled = Flag() + await server.withMethodHandler(CallTool.self) { [weak server] _ in + guard let server else { throw MCPError.internalError("The server is gone") } + do { + _ = try await server.requestElicitation(message: "Confirm?", requestedSchema: .init()) + } catch { + if error is CancellationError { await toolCancelled.set() } + throw error + } + return CallTool.Result(content: []) + } + let client = Client( + name: "ElicitationCancelClient", version: "1.0", + capabilities: .init(elicitation: .init()), configuration: .handshake) + let started = Flag() + let handlerCancelled = Flag() + await client.withElicitationHandler { _ in + await started.set() + do { + try await Task.sleep(for: .seconds(60)) + } catch { + if error is CancellationError { await handlerCancelled.set() } + throw error + } + return CreateElicitation.Result(action: .decline) + } + try await server.start(transport: serverTransport) + try await client.connect(transport: clientTransport) + + let context = try await client.send(CallTool.request(.init(name: "confirm"))) + try #require(await eventually { await started.isSet }) + try await client.cancelRequest(context.requestID, reason: "The user closed the chat") + + // The server cancels the tool's handler, which withdraws its elicitation. + #expect(await eventually { await toolCancelled.isSet }) + #expect(await eventually { await handlerCancelled.isSet }) + + await client.disconnect() + await server.stop() + } } diff --git a/Tests/MCPTests/FoundationModelsTests.swift b/Tests/MCPTests/FoundationModelsTests.swift index 6ececf45..543a5dea 100644 --- a/Tests/MCPTests/FoundationModelsTests.swift +++ b/Tests/MCPTests/FoundationModelsTests.swift @@ -190,13 +190,13 @@ import Testing #expect(Value(GeneratedContent(value)) == value) } - @Test("An integral number becomes an int, data becomes its data URL") + @Test("An integral number becomes an int, and a data: URL string stays a string") @available(macOS 26.0, iOS 26.0, visionOS 26.0, watchOS 27.0, *) func valueConversionEdges() throws { #expect(Value(GeneratedContent(Value.double(2))) == .int(2)) #expect(Value(GeneratedContent(kind: .number(1e300))) == .double(1e300)) - let data = Value.data(mimeType: "text/plain", Data("hi".utf8)) - #expect(GeneratedContent(data).kind == .string(Data("hi".utf8).dataURLEncoded(mimeType: "text/plain"))) + #expect(GeneratedContent(Value.string("data:,hi")).kind == .string("data:,hi")) + #expect(Value(GeneratedContent(Value.string("data:,hi"))) == .string("data:,hi")) let object = GeneratedContent(Value.object(["b": 1, "a": 2])) #expect(object.jsonString == #"{"a": 2, "b": 1}"#) } @@ -520,7 +520,7 @@ import Testing /// ``normalized(_:)``. @available(macOS 26.0, iOS 26.0, visionOS 26.0, watchOS 27.0, *) private func converted(_ schema: Value, name: String = "t") throws -> Value { - normalized(try Value.preservingStrings(GenerationSchema(jsonSchema: schema, name: name))) + normalized(try Value(GenerationSchema(jsonSchema: schema, name: name))) } /// The encoding of a generation schema without what changes between OS releases. @@ -1386,7 +1386,7 @@ import Testing @available(macOS 26.0, iOS 26.0, visionOS 26.0, watchOS 27.0, *) func generableRoundTrip(name: String) throws { let original = name == "FMNode" ? FMNode.generationSchema : FMWeatherQuery.generationSchema - let value = try Value.preservingStrings(original) + let value = try Value(original) #expect(try converted(value, name: name) == normalized(value)) } @@ -1397,11 +1397,11 @@ import Testing func resultTextAndDescriptions() throws { let result = CallTool.Result(content: [ .text(text: "First"), - .image(data: "aGk=", mimeType: "image/png"), + .image(Data("hi".utf8), mimeType: "image/png"), .resource(resource: .text("Second", uri: "file:///a.txt")), .resource(resource: .binary(Data("hi".utf8), uri: "file:///b.bin")), .resourceLink(uri: "file:///c.txt", name: "c"), - .audio(data: "aGk=", mimeType: "audio/wav"), + .audio(Data("hi".utf8), mimeType: "audio/wav"), .unknown(type: "custom", .object([:])), ]) #expect( diff --git a/Tests/MCPTests/HTTPClientReliabilityTests.swift b/Tests/MCPTests/HTTPClientReliabilityTests.swift index 4fc39d6c..d29f2918 100644 --- a/Tests/MCPTests/HTTPClientReliabilityTests.swift +++ b/Tests/MCPTests/HTTPClientReliabilityTests.swift @@ -1,5 +1,6 @@ @preconcurrency import Foundation import Logging +import Synchronization import Testing @testable import MCP @@ -30,20 +31,46 @@ struct HTTPClientRetryBoundsTests { #expect(HTTPClientTransport.reconnectDelay(retryInterval: 60_000, consecutiveFailures: 1000) == 60_000) } - @Test("The requestId of notifications/cancelled is read as a routing key") + @Test("Reconnection waits saturate at the cap instead of overflowing Int") + func backoffSaturates() throws { + // 60 s doubled 16 times is past Int32.max, the Int of arm64_32; an + // interval near Int.max overflows a 64-bit Int the same way. + #expect(HTTPClientTransport.reconnectDelay(retryInterval: 60_000, consecutiveFailures: 17) == 60_000) + for interval in [Int.max / 2, Int.max] { + for failures in [2, 17, 64, Int.max] { + #expect( + HTTPClientTransport.reconnectDelay(retryInterval: interval, consecutiveFailures: failures) + == 60_000) + } + } + + // A retry: field at or past Int's range, as the transport reads it. + for field in ["9223372036854775807", "99999999999999999999999"] { + var parser = ServerSentEventParser() + var event: ServerSentEvent? + for byte in "retry: \(field)\n\n".utf8 { event = try parser.consume(byte) ?? event } + let retry = HTTPClientTransport.clampedRetryInterval(try #require(event?.retry)) + #expect(retry == 60_000) + for failures in 0...64 { + #expect(HTTPClientTransport.reconnectDelay(retryInterval: retry, consecutiveFailures: failures) == 60_000) + } + } + } + + @Test("The requestId of notifications/cancelled is read as a typed routing key") func cancelledRequestID() { - func id(_ json: String) -> String? { JSONRPCMessageKind.cancelledRequestID(in: Data(json.utf8)) } - #expect(id(#"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"r1"}}"#) == "r1") - #expect(id(#"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":7}}"#) == "7") + func id(_ json: String) -> ID? { JSONRPCMessageKind.cancelledRequestID(in: Data(json.utf8)) } + #expect(id(#"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"r1"}}"#) == .string("r1")) + #expect(id(#"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":7}}"#) == .number(7)) #expect(id(#"{"jsonrpc":"2.0","method":"notifications/progress","params":{"requestId":"r1"}}"#) == nil) #expect(id(#"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{}}"#) == nil) } @Test("An answer with a method beside its result names the request it answers, as Client reads it") func answeredRequestIDWithMethod() { - func id(_ json: String) -> String? { HTTPClientTransport.answeredRequestID(in: Data(json.utf8)) } - #expect(id(#"{"jsonrpc":"2.0","id":"r1","method":"tools/list","result":{}}"#) == "r1") - #expect(id(#"{"jsonrpc":"2.0","id":7,"method":"m","error":{"code":-32603,"message":"x"}}"#) == "7") + func id(_ json: String) -> ID? { HTTPClientTransport.answeredRequestID(in: Data(json.utf8)) } + #expect(id(#"{"jsonrpc":"2.0","id":"r1","method":"tools/list","result":{}}"#) == .string("r1")) + #expect(id(#"{"jsonrpc":"2.0","id":7,"method":"m","error":{"code":-32603,"message":"x"}}"#) == .number(7)) // It does not read as a response. #expect(id(#"{"jsonrpc":"2.0","id":"r1","method":"m","error":5}"#) == nil) } @@ -155,58 +182,49 @@ struct HTTPClientConnectionLimitTests { } /// An authorizer whose token changes after each challenge it handles. - private final class ChallengeCountingAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { - private let lock = NSLock() - private var token = "old" - private var challenges: [Int] = [] - private var sent: [String?] = [] + private final class ChallengeCountingAuthorizer: HTTPClientAuthorizer, Sendable { + private struct State { + var token = "old" + var challenges: [Int] = [] + var sent: [String?] = [] + } + private let state = Mutex(State()) var maxAuthorizationAttempts: Int { 3 } - var handledChallenges: [Int] { lock.withLock { challenges } } + var handledChallenges: [Int] { state.withLock { $0.challenges } } /// The `Authorization` value of each challenged request. - var sentAuthorizations: [String?] { lock.withLock { sent } } + var sentAuthorizations: [String?] { state.withLock { $0.sent } } - func validateEndpointSecurity(for endpoint: URL) throws {} + func prepare(for endpoint: URL, session: URLSession) async throws {} func authorizationHeaders(for url: URL, method: String) throws -> [String: String] { - lock.withLock { ["Authorization": "Bearer \(token)"] } + state.withLock { ["Authorization": "Bearer \($0.token)"] } } - func handleChallenge( - statusCode: Int, headers: [String: String], endpoint: URL, operationKey: String?, - session: URLSession - ) async throws -> Bool { - lock.withLock { - challenges.append(statusCode) - token = "new" + func handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) async throws + -> HTTPChallengeResult + { + state.withLock { state in + state.sent.append(challenge.sentAuthorization) + state.challenges.append(challenge.statusCode) + state.token = "new" } - return true - } - - func handleChallenge( - statusCode: Int, headers: [String: String], endpoint: URL, operationKey: String?, - sentAuthorization: String?, session: URLSession - ) async throws -> HTTPChallengeResult { - lock.withLock { sent.append(sentAuthorization) } - return HTTPChallengeResult( - retry: try await handleChallenge( - statusCode: statusCode, headers: headers, endpoint: endpoint, operationKey: operationKey, - session: session)) + return .retry } } /// An authorizer that throws `CancellationError` at one stage, as one /// whose authorization flow the user cancelled does. - private final class CancellingAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { - enum Stage: Sendable { case validate, headers, challenge } + private final class CancellingAuthorizer: HTTPClientAuthorizer, Sendable { + enum Stage: Sendable { case prepare, headers, challenge } let stage: Stage init(_ stage: Stage) { self.stage = stage } var maxAuthorizationAttempts: Int { 3 } - func validateEndpointSecurity(for endpoint: URL) throws { - if stage == .validate { throw CancellationError() } + func prepare(for endpoint: URL, session: URLSession) async throws { + if stage == .prepare { throw CancellationError() } } func authorizationHeaders(for url: URL, method: String) throws -> [String: String] { @@ -214,12 +232,11 @@ struct HTTPClientConnectionLimitTests { return ["Authorization": "Bearer t"] } - func handleChallenge( - statusCode: Int, headers: [String: String], endpoint: URL, operationKey: String?, - session: URLSession - ) async throws -> Bool { + func handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) async throws + -> HTTPChallengeResult + { if stage == .challenge { throw CancellationError() } - return false + return .unhandled } } @@ -240,7 +257,7 @@ struct HTTPClientConnectionLimitTests { } /// Yields each message logged at debug level and above to `sink`. - private struct StreamingLogHandler: LogHandler { + struct StreamingLogHandler: LogHandler { let sink: AsyncStream.Continuation var metadata: Logger.Metadata = [:] var logLevel: Logger.Level = .debug @@ -282,8 +299,7 @@ struct HTTPClientConnectionLimitTests { func makeTransport( streaming: Bool = false, sseInitializationTimeout: TimeInterval = 0.05, - authorizer: (any HTTPClientAuthorizer)? = nil, logger: Logger? = nil, - stripsSessionFromGET: Bool = false + authorizer: (any HTTPClientAuthorizer)? = nil, logger: Logger? = nil ) -> (HTTPClientTransport, String) { let key = UUID().uuidString let configuration = URLSessionConfiguration.ephemeral @@ -292,14 +308,7 @@ struct HTTPClientConnectionLimitTests { configuration.httpMaximumConnectionsPerHost = HTTPClientTransport.defaultMaximumConnectionsPerHost let transport = HTTPClientTransport( endpoint: endpoint, configuration: configuration, streaming: streaming, - sseInitializationTimeout: sseInitializationTimeout, authorizer: authorizer, - requestModifier: { request in - var request = request - if stripsSessionFromGET, request.httpMethod == "GET" { - request.setValue(nil, forHTTPHeaderField: "Mcp-Session-Id") - } - return request - }, logger: logger) + sseInitializationTimeout: sseInitializationTimeout, authorizer: authorizer, logger: logger) return (transport, key) } @@ -638,24 +647,35 @@ struct HTTPClientConnectionLimitTests { @Test( "A 404 to a GET without the session ID does not end the session", .timeLimit(.minutes(2))) func getNotFoundWithoutSessionHeader() async throws { - // A proxy-like modifier strips the session ID from GETs. - let (transport, key) = makeTransport( - streaming: true, sseInitializationTimeout: 30, stripsSessionFromGET: true) + // The GET stream stops waiting for a session ID and goes out + // without one; initialize assigns s1 before the GET's 404 arrives. + let (transport, key) = makeTransport(streaming: true, sseInitializationTimeout: 0.05) let requests = RecordedRequests() await IsolatedMockURLProtocol.setHandler(key: key) { request in await requests.append(request) - if request.httpMethod == "POST" { return initializeReply() } - // The first GET ends at once; later ones get a 404. - return await requests.gets.count == 1 ? sse("id: g1\nretry: 10\ndata: \n\n") : sse("", status: 404) + if request.httpMethod == "POST" { + await requests.waitFor(1, "GET") + return initializeReply() + } + guard await requests.gets.count == 1 else { return sse("id: g2\nretry: 10\ndata: \n\n") } + let deadline = ContinuousClock.now + .seconds(5) + while await transport.sessionID == nil, ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(10)) + } + return sse("", status: 404) } try await transport.connect() try await transport.send(Data(#"{"jsonrpc":"2.0","id":"i1","method":"initialize"}"#.utf8)) - // Reported as an expiry, the 404 would end the GET loop after the second GET. - let deadline = ContinuousClock.now + .seconds(5) - while await requests.gets.count < 3 && ContinuousClock.now < deadline { + // Reported as an expiry, the 404 would end the GET loop and the + // session. The next GET follows the default 3 s retry interval. + let deadline = ContinuousClock.now + .seconds(15) + while await requests.gets.count < 2 && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) } - #expect(await requests.gets.count >= 3) + let gets = await requests.gets + #expect(gets.count >= 2) + #expect(gets.first?.value(forHTTPHeaderField: "Mcp-Session-Id") == nil) + #expect(gets.dropFirst().first?.value(forHTTPHeaderField: "Mcp-Session-Id") == "s1") #expect(await transport.sessionID == "s1") await transport.disconnect() } @@ -664,12 +684,12 @@ struct HTTPClientConnectionLimitTests { "A CancellationError from the authorizer is thrown as is", .timeLimit(.minutes(2)), arguments: [ - ("validate", "POST"), ("headers", "POST"), ("challenge", "POST"), + ("prepare", "POST"), ("headers", "POST"), ("challenge", "POST"), ("challenge", "stateless POST"), ("challenge", "resumption GET"), ]) func authorizerCancellation(stage: String, path: String) async throws { let stages: [String: CancellingAuthorizer.Stage] = [ - "validate": .validate, "headers": .headers, "challenge": .challenge, + "prepare": .prepare, "headers": .headers, "challenge": .challenge, ] let (transport, key) = makeTransport(authorizer: CancellingAuthorizer(stages[stage]!)) await IsolatedMockURLProtocol.setHandler(key: key) { request in @@ -707,6 +727,288 @@ struct HTTPClientConnectionLimitTests { #expect(authorizer.sentAuthorizations == ["Bearer old"]) await transport.disconnect() } + + @Test("An actor authorizer authorizes requests and answers challenges") + func actorAuthorizer() async throws { + let authorizer = RenewingActorAuthorizer() + let (transport, key) = makeTransport(authorizer: authorizer) + let requests = RecordedRequests() + await IsolatedMockURLProtocol.setHandler(key: key) { [response] request in + await requests.append(request) + if request.value(forHTTPHeaderField: "Authorization") == "Bearer old" { + return sse("", status: 401, headers: ["WWW-Authenticate": #"Bearer error="invalid_token""#]) + } + return sse("id: e1\ndata: \(response)\n\n") + } + try await transport.connect() + try await transport.send(request) + #expect(try await firstMessage(transport) == response) + + let sent = await requests.all + #expect(sent.map { $0.value(forHTTPHeaderField: "Authorization") } == ["Bearer old", "Bearer new"]) + let challenges = await authorizer.challenges + #expect(challenges.count == 1) + #expect(challenges.first?.statusCode == 401) + #expect(challenges.first?.endpoint == endpoint) + #expect(challenges.first?.operationKey == "tools/call") + #expect(challenges.first?.sentAuthorization == "Bearer old") + #expect(challenges.first?.value(forHeader: "www-authenticate") == #"Bearer error="invalid_token""#) + #expect(await authorizer.responses == 2) + await transport.disconnect() + } + + @Test("An error from prepare fails the request", arguments: ["POST", "resumption GET"]) + func prepareErrorFailsRequest(path: String) async throws { + // The POST of the resumption GET path prepares once, successfully. + let authorizer = FailingPrepareAuthorizer(succeedingCalls: path == "POST" ? 0 : 1) + let (transport, key) = makeTransport(authorizer: authorizer) + let requests = RecordedRequests() + await IsolatedMockURLProtocol.setHandler(key: key) { request in + await requests.append(request) + // The POST's stream ends without its response: the transport + // resumes it with a GET. + return sse("id: e1\nretry: 10\ndata: \n\n") + } + try await transport.connect() + await #expect { + try await transport.send(request) + } throws: { error in + guard case .transportError(let underlying) = error as? MCPError else { return false } + return underlying is FailingPrepareAuthorizer.Failure + } + #expect(await requests.all.map(\.httpMethod) == (path == "POST" ? [] : ["POST"])) + #expect(authorizer.prepareCalls == (path == "POST" ? 1 : 2)) + await transport.disconnect() + } + + /// The error a request to an insecure endpoint fails with when the + /// transport has an authorizer: as before the transport checked the + /// endpoint itself, when the default `prepare(for:session:)` did. + func isInsecureEndpointError(_ error: any Error) -> Bool { + guard case .transportError(let underlying) = error as? MCPError else { return false } + return (underlying as? OAuthAuthorizationError)?.code == .insecureOAuthEndpoint + } + + // An authorizer can't skip the endpoint check, whether it keeps the + // default prepare or implements one that does nothing. + @Test( + "The transport refuses an insecure endpoint before it calls the authorizer", + .timeLimit(.minutes(2)), + arguments: ["default prepare", "no-op prepare"], ["POST", "GET stream"]) + func insecureEndpointRefused(prepare: String, path: String) async throws { + let key = UUID().uuidString + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [IsolatedMockURLProtocol.self] + configuration.httpAdditionalHeaders = [IsolatedMockURLProtocol.sessionKeyHeader: key] + let requests = RecordedRequests() + await IsolatedMockURLProtocol.setHandler(key: key) { request in + await requests.append(request) + return sse("", status: 202) + } + let recording = NoOpPrepareAuthorizer() + let authorizer: any HTTPClientAuthorizer = prepare == "default prepare" ? HeadersOnlyAuthorizer() : recording + let (logs, sink) = AsyncStream.makeStream() + let transport = HTTPClientTransport( + endpoint: URL(string: "http://example.com/mcp")!, configuration: configuration, + streaming: path == "GET stream", sseInitializationTimeout: 0.05, authorizer: authorizer, + logger: Logger(label: "mcp.test.insecure") { _ in StreamingLogHandler(sink: sink) }) + try await transport.connect() + if path == "POST" { + await #expect { + try await transport.send(request) + } throws: { isInsecureEndpointError($0) } + } else { + // The GET stream logs its failure and tries again later. + for await message in logs where message.contains("SSE connection error") { + #expect(message.contains("MCP endpoint must use https or loopback http: http://example.com/mcp")) + break + } + } + #expect(await requests.all.isEmpty) + #expect(recording.calls == 0) + await transport.disconnect() + } + + // The token goes to the request's URL: a requestModifier that points a + // request at cleartext http must not get a token sent there. + @Test( + "A request the requestModifier points at an insecure URL gets no token and is not sent", + .timeLimit(.minutes(2)), arguments: ["POST", "GET stream"]) + func insecureModifiedURLRefused(path: String) async throws { + let key = UUID().uuidString + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [IsolatedMockURLProtocol.self] + configuration.httpAdditionalHeaders = [IsolatedMockURLProtocol.sessionKeyHeader: key] + let requests = RecordedRequests() + await IsolatedMockURLProtocol.setHandler(key: key) { request in + await requests.append(request) + return sse("", status: 202) + } + let authorizer = NoOpPrepareAuthorizer() + let (logs, sink) = AsyncStream.makeStream() + let transport = HTTPClientTransport( + endpoint: endpoint, configuration: configuration, streaming: path == "GET stream", + sseInitializationTimeout: 0.05, authorizer: authorizer, + requestModifier: { request in request.url = URL(string: "http://example.com/mcp") }, + logger: Logger(label: "mcp.test.insecure-modifier") { _ in StreamingLogHandler(sink: sink) }) + try await transport.connect() + if path == "POST" { + await #expect { + try await transport.send(request) + } throws: { isInsecureEndpointError($0) } + } else { + for await message in logs where message.contains("SSE connection error") { + #expect(message.contains("MCP endpoint must use https or loopback http: http://example.com/mcp")) + break + } + } + #expect(await requests.all.isEmpty) + // The endpoint itself is secure, so prepare ran; the headers were + // never asked for. (The GET stream may have tried again meanwhile.) + #expect(authorizer.prepareCalls >= 1) + #expect(authorizer.headerCalls == 0) + await transport.disconnect() + } + + // With no resource named by the configuration or the metadata, the + // token is saved under the endpoint; a requestModifier that changes + // the path must still find it. + @Test("A requestModifier that changes the path keeps the token when the metadata names no resource") + func pathChangingModifierKeepsToken() async throws { + let key = UUID().uuidString + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [IsolatedMockURLProtocol.self] + configuration.httpAdditionalHeaders = [IsolatedMockURLProtocol.sessionKeyHeader: key] + let requests = RecordedRequests() + await IsolatedMockURLProtocol.setHandler(key: key) { [response] request in + await requests.append(request) + guard request.value(forHTTPHeaderField: "Authorization") == "Bearer token-1" else { + return sse("", status: 401, headers: ["WWW-Authenticate": "Bearer"]) + } + return sse("id: e1\ndata: \(response)\n\n") + } + let tokens = RecordingTokenClient() + // MockDiscoveryClient's metadata names no resource. + let authorizer = OAuthAuthorizer( + configuration: OAuthConfiguration( + grantType: .clientCredentials, + authentication: .clientSecretBasic(clientID: "client", clientSecret: "secret")), + urlValidator: MockURLValidator(), discoveryClient: MockDiscoveryClient(), tokenEndpointClient: tokens, + clientRegistrar: MockClientRegistrar(), authCodeFlow: MockAuthCodeFlow()) + let transport = HTTPClientTransport( + endpoint: endpoint, configuration: configuration, streaming: false, authorizer: authorizer, + requestModifier: { request in request.url = URL(string: "http://127.0.0.1:9/v2/rpc") }) + try await transport.connect() + + try await transport.send(request) + #expect(try await firstMessage(transport) == response) + #expect(tokens.calls.count == 1) + #expect(await requests.all.map { $0.value(forHTTPHeaderField: "Authorization") } == [nil, "Bearer token-1"]) + await transport.disconnect() + } + + @Test("The error of an insecure endpoint shows neither its password nor its query") + func insecureEndpointErrorIsRedacted() async throws { + let transport = HTTPClientTransport( + endpoint: URL(string: "http://user:pw-secret@example.com/mcp?token=q-secret")!, + configuration: .ephemeral, streaming: false, authorizer: HeadersOnlyAuthorizer()) + try await transport.connect() + let error = await #expect(throws: MCPError.self) { try await transport.send(request) } + for text in [String(describing: error), error?.localizedDescription ?? "", error?.errorDescription ?? ""] { + #expect(!text.contains("pw-secret"), "\(text)") + #expect(!text.contains("q-secret"), "\(text)") + #expect(text.contains("http://example.com/mcp"), "\(text)") + } + await transport.disconnect() + } + } + + /// An actor conformer: its token changes after each challenge it answers. + private actor RenewingActorAuthorizer: HTTPClientAuthorizer { + nonisolated let maxAuthorizationAttempts = 2 + private var token = "old" + private(set) var challenges: [HTTPAuthorizationChallenge] = [] + private(set) var responses = 0 + + func authorizationHeaders(for url: URL, method: String) -> [String: String] { + ["Authorization": "Bearer \(token)"] + } + + func handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) -> HTTPChallengeResult { + challenges.append(challenge) + token = "new" + return .retry + } + + func didReceiveResponse(headers: [String: String], for url: URL) { + responses += 1 + } + } + + /// Fails every `prepare(for:session:)` after the first `succeedingCalls`. + private final class FailingPrepareAuthorizer: HTTPClientAuthorizer, Sendable { + struct Failure: Error {} + + let maxAuthorizationAttempts = 1 + private let succeedingCalls: Int + private let calls = Mutex(0) + var prepareCalls: Int { calls.withLock { $0 } } + + init(succeedingCalls: Int) { self.succeedingCalls = succeedingCalls } + + func prepare(for endpoint: URL, session: URLSession) async throws { + let call = calls.withLock { count in + count += 1 + return count + } + if call > succeedingCalls { throw Failure() } + } + + func authorizationHeaders(for url: URL, method: String) -> [String: String] { + ["Authorization": "Bearer t"] + } + + func handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) -> HTTPChallengeResult { + .unhandled + } + } + + /// Implements only the requirements without a default. + private struct HeadersOnlyAuthorizer: HTTPClientAuthorizer { + let maxAuthorizationAttempts = 1 + + func authorizationHeaders(for url: URL, method: String) -> [String: String] { + ["Authorization": "Bearer t"] + } + + func handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) -> HTTPChallengeResult { + .unhandled + } + } + + /// Implements `prepare(for:session:)` without checking the endpoint, and + /// counts the calls to each of its methods. + private final class NoOpPrepareAuthorizer: HTTPClientAuthorizer { + let maxAuthorizationAttempts = 1 + private let counts = Mutex<[String: Int]>([:]) + /// The calls to every method. + var calls: Int { counts.withLock { $0.values.reduce(0, +) } } + var prepareCalls: Int { counts.withLock { $0["prepare", default: 0] } } + var headerCalls: Int { counts.withLock { $0["headers", default: 0] } } + + func prepare(for endpoint: URL, session: URLSession) async throws { + counts.withLock { $0["prepare", default: 0] += 1 } + } + + func authorizationHeaders(for url: URL, method: String) -> [String: String] { + counts.withLock { $0["headers", default: 0] += 1 } + return ["Authorization": "Bearer t"] + } + + func handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) -> HTTPChallengeResult { + counts.withLock { $0["challenge", default: 0] += 1 } + return .unhandled + } } extension URLRequest { diff --git a/Tests/MCPTests/HTTPClientResumptionTests.swift b/Tests/MCPTests/HTTPClientResumptionTests.swift index 59f4cf39..dd606b17 100644 --- a/Tests/MCPTests/HTTPClientResumptionTests.swift +++ b/Tests/MCPTests/HTTPClientResumptionTests.swift @@ -292,7 +292,7 @@ import Testing return sse("id: e1\nretry: 10\ndata: \n\n") } try await transport.connect() - await transport.useStatelessProtocol("2026-07-28") + await transport.didNegotiate(protocolVersion: "2026-07-28") try await transport.send(request) let delivered = try await messages(transport, 1) let error = try JSONSerialization.jsonObject(with: Data(delivered[0].utf8)) as? [String: Any] diff --git a/Tests/MCPTests/HTTPClientTransportTests.swift b/Tests/MCPTests/HTTPClientTransportTests.swift index ed16883b..edc9c1d0 100644 --- a/Tests/MCPTests/HTTPClientTransportTests.swift +++ b/Tests/MCPTests/HTTPClientTransportTests.swift @@ -1,5 +1,6 @@ @preconcurrency import Foundation import Logging +import Synchronization import Testing @testable import MCP @@ -39,6 +40,18 @@ import Testing var requestHandler: (@Sendable (URLRequest) async throws -> (HTTPURLResponse, Data))? private var callCounts: [URL: Int] = [:] + /// Whether a 3xx response with a `Location` is reported as a redirect; + /// see ``simulateRedirects()``. + private(set) var redirects = false + + /// Reports the handler's 3xx responses that have a `Location` as + /// redirects, until the handler is cleared. The proposed request keeps + /// every header of the redirected one, as swift-corelibs-foundation's + /// does. Apple platforms only: swift-corelibs-foundation traps when a + /// `URLProtocol` reports a redirect. + func simulateRedirects() { + redirects = true + } func setHandler( _ handler: @Sendable @escaping (URLRequest) async throws -> (HTTPURLResponse, Data) @@ -49,6 +62,7 @@ import Testing func clearHandler() { requestHandler = nil callCounts = [:] + redirects = false } func executeHandler(for request: URLRequest) async throws -> (HTTPURLResponse, Data) { @@ -131,6 +145,21 @@ import Testing private func load() async { do { let (response, data) = try await executeHandler(for: request) + #if !canImport(FoundationNetworking) + if await Self.requestHandlerStorage.redirects, (300..<400).contains(response.statusCode), + let location = response.value(forHTTPHeaderField: "Location"), + let target = URL(string: location, relativeTo: request.url)?.absoluteURL + { + var next = request + next.url = target + // URLSession stops this loading and starts the request + // its delegate returns. + stop.ifLoading(self) { [self] in + client?.urlProtocol(self, wasRedirectedTo: next, redirectResponse: response) + } + return + } + #endif stop.ifLoading(self) { [self] in client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) } stop.ifLoading(self) { [self] in client?.urlProtocol(self, didLoad: data) } stop.ifLoading(self) { [self] in client?.urlProtocolDidFinishLoading(self) } @@ -239,7 +268,8 @@ import Testing } let request = Data(#"{"jsonrpc":"2.0","method":"tools/list","id":7}"#.utf8) - await transport.cancelRequest(.number(7)) + // At a handshake revision the client still sends notifications/cancelled. + #expect(await transport.abandonRequest(.number(7)) == false) await #expect(throws: CancellationError.self) { try await transport.send(request) } #expect(await MockURLProtocol.requestHandlerStorage.callCount(for: testEndpoint) == 0) @@ -248,6 +278,50 @@ import Testing #expect(await MockURLProtocol.requestHandlerStorage.callCount(for: testEndpoint) == 1) } + @Test( + "abandonRequest of id 1 doesn't abort the POST of id \"1\"", .httpClientTransportSetup, + .timeLimit(.minutes(1))) + func testAbandonRequestMatchesTypedID() async throws { + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [MockURLProtocol.self] + let transport = HTTPClientTransport( + endpoint: testEndpoint, configuration: configuration, streaming: false, logger: nil) + try await transport.connect() + defer { Task { await transport.disconnect() } } + + let (started, markStarted) = AsyncStream.makeStream() + let (release, open) = AsyncStream.makeStream() + let answer = Data(#"{"jsonrpc":"2.0","result":{},"id":"1"}"#.utf8) + await MockURLProtocol.requestHandlerStorage.setHandler { [testEndpoint] _ in + markStarted.yield() + for await _ in release { break } + let response = HTTPURLResponse( + url: testEndpoint, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/json"])! + return (response, answer) + } + + let post = Task { + try await transport.send(Data(#"{"jsonrpc":"2.0","method":"tools/list","id":"1"}"#.utf8)) + } + var startedPosts = started.makeAsyncIterator() + await startedPosts.next() + + // Its result says whether Client still sends notifications/cancelled; + // this test checks only which POST the abandonment applies to. + _ = await transport.abandonRequest(.number(1)) + open.finish() + try await post.value + var messages = await transport.receive().makeAsyncIterator() + #expect(try await messages.next() == answer) + + // The abandoned request is the one with the number id. + await #expect(throws: CancellationError.self) { + try await transport.send(Data(#"{"jsonrpc":"2.0","method":"tools/list","id":1}"#.utf8)) + } + #expect(await MockURLProtocol.requestHandlerStorage.callCount(for: testEndpoint) == 1) + } + @Test("Send and Receive Session ID", .httpClientTransportSetup) func testSendAndReceiveSessionID() async throws { let configuration = URLSessionConfiguration.ephemeral @@ -1288,7 +1362,9 @@ import Testing await client.disconnect() } - @Test("Request modifier functionality", .httpClientTransportSetup) + @Test( + "An async requestModifier changes the request; its error fails the request", + .httpClientTransportSetup) func testRequestModifier() async throws { let testEndpoint = URL(string: "https://api.example.com/mcp")! let testToken = "test-bearer-token-12345" @@ -1315,10 +1391,9 @@ import Testing configuration: configuration, streaming: false, requestModifier: { request in - var modifiedRequest = request - modifiedRequest.addValue( - "Bearer \(testToken)", forHTTPHeaderField: "Authorization") - return modifiedRequest + // A modifier may suspend, for example to read a credential. + await Task.yield() + request.addValue("Bearer \(testToken)", forHTTPHeaderField: "Authorization") }, logger: nil ) @@ -1329,6 +1404,25 @@ import Testing try await transport.send(messageData) await transport.disconnect() + + // A modifier that throws fails the request with its error, and + // nothing is sent. + struct CredentialUnavailable: Error {} + let failing = HTTPClientTransport( + endpoint: testEndpoint, + configuration: configuration, + streaming: false, + requestModifier: { _ in throw CredentialUnavailable() }, + logger: nil + ) + try await failing.connect() + await #expect { + try await failing.send(messageData) + } throws: { error in + guard case .transportError(let underlying) = error as? MCPError else { return false } + return underlying is CredentialUnavailable + } + await failing.disconnect() } @Test("OAuth client credentials performs discovery and retries after 401", .httpClientTransportSetup) @@ -2388,7 +2482,7 @@ import Testing let scenario = await MockURLProtocol.requestHandlerStorage .configureOAuthProactiveTokenRefreshWithinWindow() - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let transport = HTTPClientTransport( endpoint: scenario.testEndpoint, configuration: MockResponses.ephemeralConfiguration(), @@ -2407,12 +2501,14 @@ import Testing #expect(receivedFirst == scenario.expectedResponseData) // 200 s later the 300 s token is within its renewal window. - let token = try #require(storage.load()) + let resource = try DefaultOAuthMetadataDiscovery().canonicalResourceURI(from: scenario.testEndpoint) + let token = try #require(storage.load(for: resource)) storage.save( OAuthAccessToken( value: token.value, tokenType: token.tokenType, expiresAt: Date().addingTimeInterval(100), scopes: token.scopes, authorizationServer: token.authorizationServer, - refreshToken: token.refreshToken, clientID: token.clientID)) + refreshToken: token.refreshToken, clientID: token.clientID), + for: resource) try await transport.send(scenario.secondMessageData!) let receivedSecond = try await iterator.next() @@ -2455,6 +2551,1042 @@ import Testing try await transport.send(messageData) await transport.disconnect() } + + // swift-corelibs-foundation traps when a URLProtocol reports a + // redirect; there `HTTPClientTransportRedirectTests` covers it. + #if !canImport(FoundationNetworking) + @Test( + "A redirected POST gets the authorizer's headers for its URL on the same origin, and no credentials on another", + .httpClientTransportSetup, + arguments: [("https://localhost:8080/moved", true), ("https://other.example.com/mcp", false)]) + func testRedirectedPostCredentials(target: String, sameOrigin: Bool) async throws { + let messageData = Data(#"{"jsonrpc":"2.0","method":"tools/list","id":7}"#.utf8) + let responseData = Data(#"{"jsonrpc":"2.0","result":{},"id":7}"#.utf8) + let log = SentRequestLog() + await MockURLProtocol.requestHandlerStorage.simulateRedirects() + await MockURLProtocol.setHandler { [testEndpoint] request in + _ = await log.append(request) + let url = try #require(request.url) + if url == testEndpoint { + return (HTTPURLResponse( + url: url, statusCode: 307, httpVersion: "HTTP/1.1", headerFields: ["Location": target])!, Data()) + } + return (HTTPURLResponse( + url: url, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/json"])!, responseData) + } + let transport = redirectTestTransport(streaming: false) + try await transport.connect() + + try await transport.send(messageData) + var iterator = await transport.receive().makeAsyncIterator() + #expect(try await iterator.next() == responseData) + + let requests = await log.requests + try #require(requests.count == 2) + CredentialHeadersAuthorizer.expectCredentials(in: requests[0], for: testEndpoint, method: "POST") + let targetURL = try #require(URL(string: target)) + #expect(requests[1].url == targetURL) + #expect(requests[1].httpMethod == "POST") + if sameOrigin { + CredentialHeadersAuthorizer.expectCredentials(in: requests[1], for: targetURL, method: "POST") + } else { + CredentialHeadersAuthorizer.expectNoCredentials(in: requests[1]) + } + await transport.disconnect() + } + + @Test( + "A redirected GET stream gets the authorizer's headers for its URL on the same origin, and no credentials on another", + .httpClientTransportSetup, + arguments: [("https://localhost:8080/events", true), ("https://other.example.com/events", false)]) + func testRedirectedGetCredentials(target: String, sameOrigin: Bool) async throws { + let targetURL = try #require(URL(string: target)) + let event = Data(#"{"jsonrpc":"2.0","method":"notifications/message"}"#.utf8) + let log = SentRequestLog() + await MockURLProtocol.requestHandlerStorage.simulateRedirects() + await MockURLProtocol.setHandler { [testEndpoint] request in + _ = await log.append(request) + let url = try #require(request.url) + switch (request.httpMethod, url) { + case ("POST", _): + return (HTTPURLResponse( + url: url, statusCode: 202, httpVersion: "HTTP/1.1", + headerFields: ["Mcp-Session-Id": "session-1"])!, Data()) + case ("GET", testEndpoint): + return (HTTPURLResponse( + url: url, statusCode: 307, httpVersion: "HTTP/1.1", + headerFields: ["Location": target])!, Data()) + default: + return (HTTPURLResponse( + url: url, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "text/event-stream"])!, + Data("id: e1\ndata: ".utf8) + event + Data("\n\n".utf8)) + } + } + let transport = redirectTestTransport(streaming: true) + try await transport.connect() + try await transport.send(Data(#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#.utf8)) + + var iterator = await transport.receive().makeAsyncIterator() + #expect(try await iterator.next() == event) + + let gets = await log.requests.filter { $0.httpMethod == "GET" } + try #require(gets.count >= 2) + CredentialHeadersAuthorizer.expectCredentials(in: gets[0], for: testEndpoint, method: "GET") + #expect(gets[1].url == targetURL) + if sameOrigin { + CredentialHeadersAuthorizer.expectCredentials(in: gets[1], for: targetURL, method: "GET") + } else { + CredentialHeadersAuthorizer.expectNoCredentials(in: gets[1]) + } + #expect(gets[1].value(forHTTPHeaderField: "Mcp-Session-Id") == (sameOrigin ? "session-1" : nil)) + #expect(gets[1].value(forHTTPHeaderField: "Accept") == "text/event-stream") + await transport.disconnect() + } + + /// A transport with a ``CredentialHeadersAuthorizer`` and its + /// `requestModifier`. + private func redirectTestTransport(streaming: Bool) -> HTTPClientTransport { + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [MockURLProtocol.self] + return HTTPClientTransport( + endpoint: testEndpoint, configuration: configuration, streaming: streaming, + sseInitializationTimeout: 1, authorizer: CredentialHeadersAuthorizer(), + requestModifier: CredentialHeadersAuthorizer.modify) + } + #endif + } + + /// Adds `Authorization` and a `DPoP` "proof" that names the method and + /// URL it was made for; its `modify` adds `Proxy-Authorization`, `Cookie` + /// and `X-Custom`, as a `requestModifier`. It throws for a URL whose path + /// is `failingPath`. + struct CredentialHeadersAuthorizer: HTTPClientAuthorizer { + static let authorization = "DPoP access-token" + static let proxyAuthorization = "Basic cHJveHk6cHc=" + static let cookie = "sid=modifier" + + static let modify: @Sendable (inout URLRequest) async throws -> Void = { request in + request.setValue(proxyAuthorization, forHTTPHeaderField: "Proxy-Authorization") + request.setValue(cookie, forHTTPHeaderField: "Cookie") + request.setValue("kept", forHTTPHeaderField: "X-Custom") + } + + static func proof(for method: String, _ url: URL) -> String { "proof for \(method) \(url.absoluteString)" } + + let maxAuthorizationAttempts = 1 + var failingPath: String? + + func authorizationHeaders(for url: URL, method: String) throws -> [String: String] { + if url.path == failingPath { throw URLError(.userAuthenticationRequired) } + return ["Authorization": Self.authorization, "DPoP": Self.proof(for: method, url)] + } + + func handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) -> HTTPChallengeResult { + .unhandled + } + + /// Expects the headers made for `url` and `method` on `request`, and `X-Custom`. + static func expectCredentials( + in request: URLRequest, for url: URL, method: String, sourceLocation: SourceLocation = #_sourceLocation + ) { + expect( + [ + "authorization": authorization, "dpop": proof(for: method, url), + "proxy-authorization": proxyAuthorization, "cookie": cookie, + ], in: request.allHTTPHeaderFields ?? [:], sourceLocation: sourceLocation) + } + + /// Expects none of the credentials on `request`, and `X-Custom`. + static func expectNoCredentials(in request: URLRequest, sourceLocation: SourceLocation = #_sourceLocation) { + expect( + ["authorization": nil, "dpop": nil, "proxy-authorization": nil, "cookie": nil], + in: request.allHTTPHeaderFields ?? [:], sourceLocation: sourceLocation) + } + + /// Expects `credentials` (`nil`: absent) and `X-Custom` in `headers`, + /// whose names are in any case. + static func expect( + _ credentials: [String: String?], in headers: [String: String], sourceLocation: SourceLocation + ) { + let headers = Dictionary(uniqueKeysWithValues: headers.map { ($0.key.lowercased(), $0.value) }) + for (name, value) in credentials { + #expect(headers[name] == value, "\(name)", sourceLocation: sourceLocation) + } + #expect(headers["x-custom"] == "kept", sourceLocation: sourceLocation) + } + } + + // A real URLSession on loopback servers: on swift-corelibs-foundation a + // URLProtocol can't report a redirect. The servers have no TLS, so a + // redirect from https to http is covered by the unit tests of + // HTTPRedirect in OAuthURLValidatorTests. + @Suite("HTTP client transport redirects", .timeLimit(.minutes(1))) + struct HTTPClientTransportRedirectTests { + let message = Data(#"{"jsonrpc":"2.0","method":"tools/list","id":7}"#.utf8) + let response = Data(#"{"jsonrpc":"2.0","result":{},"id":7}"#.utf8) + + /// The first of `logs` that contains `text`, or `nil` when none does + /// within `timeout`. + static func firstLog( + containing text: String, in logs: AsyncStream, within timeout: Duration = .seconds(30) + ) async -> String? { + await withTaskGroup(of: String?.self) { group in + group.addTask { + for await message in logs where message.contains(text) { return message } + return nil + } + group.addTask { + try? await Task.sleep(for: timeout) + return nil + } + let first = await group.next() ?? nil + group.cancelAll() + return first + } + } + + @Test("A redirect to a scheme other than http and https is not followed") + func redirectToOtherScheme() async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + server.routes = ["/mcp": (307, ["Location": "ftp://127.0.0.1:\(server.port)/x"], Data())] + let log = CapturingLogHandler() + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: false, + authorizer: CredentialHeadersAuthorizer(), + logger: Logger(label: "mcp.test.redirect-scheme") { _ in log }) + try await transport.connect() + + let error = await #expect(throws: MCPError.self) { try await transport.send(message) } + guard case .transportError(let underlying) = error else { + Issue.record("Expected transportError, got \(String(describing: error))") + return + } + // As for any redirect that is not followed, the 3xx is the answer. + #expect((underlying as? HTTPStatusError)?.statusCode == 307, "\(underlying)") + #expect(server.requested == ["/mcp"]) + #expect(log.messages.contains("Redirect not followed: its target is not an http or https URL")) + await transport.disconnect() + } + + // The refused hop is never requested, so it needs no listener off the + // machine: `.invalid` never resolves (RFC 6761 §6.4), and a hop the + // transport did follow would fail to connect instead of answering 307. + @Test("A redirect from a loopback host to http on another host is not followed") + func redirectOffLoopbackIsNotFollowed() async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + server.routes = ["/mcp": (307, ["Location": "http://mcp.invalid/x"], Data())] + let log = CapturingLogHandler() + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: false, + logger: Logger(label: "mcp.test.redirect-off-loopback") { _ in log }) + try await transport.connect() + + let error = await #expect(throws: MCPError.self) { try await transport.send(message) } + guard case .transportError(let underlying) = error else { + Issue.record("Expected transportError, got \(String(describing: error))") + return + } + #expect((underlying as? HTTPStatusError)?.statusCode == 307, "\(underlying)") + #expect(server.requested == ["/mcp"]) + #expect(log.messages.contains( + "Redirect not followed: it goes from a loopback host to http on a host that is not a loopback host")) + await transport.disconnect() + } + + @Test("A redirect from loopback http to loopback http on another port is followed, with its body") + func redirectToOtherLoopbackPort() async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + let other = try LoopbackHTTPServer() + defer { other.stop() } + server.routes = ["/mcp": (307, ["Location": "\(other.baseURL)/landed"], Data())] + other.routes = ["/landed": (200, ["Content-Type": "application/json"], response)] + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: false) + try await transport.connect() + + try await transport.send(message) + var iterator = await transport.receive().makeAsyncIterator() + #expect(try await iterator.next() == response) + #expect(other.requests.map(\.path) == ["/landed"]) + #expect(other.requests.first?.body == message) + await transport.disconnect() + } + + @Test( + "A 301, 302 or 303 makes a POST a GET without a body, and a 308 keeps both, with a proof for the hop's method", + arguments: [(301, "GET"), (302, "GET"), (303, "GET"), (308, "POST")]) + func methodOfRedirect(status: Int, method: String) async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + server.routes = [ + "/mcp": (status, ["Location": "/landed"], Data()), + "/landed": (200, ["Content-Type": "application/json"], response), + ] + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: false, + authorizer: CredentialHeadersAuthorizer(), requestModifier: CredentialHeadersAuthorizer.modify) + try await transport.connect() + + try await transport.send(message) + var iterator = await transport.receive().makeAsyncIterator() + #expect(try await iterator.next() == response) + + #expect(server.requested == ["/mcp", "/landed"]) + let landed = try #require(server.requests.last) + #expect(landed.method == method) + #expect(landed.body == (method == "POST" ? message : Data())) + CredentialHeadersAuthorizer.expect( + [ + "authorization": CredentialHeadersAuthorizer.authorization, + "dpop": CredentialHeadersAuthorizer.proof(for: method, URL(string: "\(server.baseURL)/landed")!), + ], in: landed.headers, sourceLocation: #_sourceLocation) + await transport.disconnect() + } + + @Test("A same-origin hop for which the authorizer has no headers carries none, and its 401 is a challenge for the endpoint") + func sameOriginHopWithoutHeaders() async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + server.routes = [ + "/mcp": (307, ["Location": "/landed"], Data()), + "/landed": (401, ["WWW-Authenticate": "DPoP"], Data()), + ] + let authorizer = RecordingRedirectAuthorizer() + let endpoint = URL(string: "\(server.baseURL)/mcp")! + let transport = HTTPClientTransport( + endpoint: endpoint, configuration: .ephemeral, streaming: false, + authorizer: authorizer, requestModifier: CredentialHeadersAuthorizer.modify) + try await transport.connect() + + let error = await #expect(throws: MCPError.self) { try await transport.send(message) } + guard case .transportError(let underlying) = error else { + Issue.record("Expected transportError, got \(String(describing: error))") + return + } + #expect((underlying as? HTTPStatusError)?.statusCode == 401, "\(underlying)") + // Not protectedResourceMismatch: the authorizer handles it, for the endpoint. + let challenge = try #require(authorizer.challenges.first) + #expect(authorizer.challenges.count == 1) + #expect(challenge.statusCode == 401) + #expect(challenge.endpoint == endpoint) + // The redirected hop carried no Authorization, not the first request's token. + #expect(challenge.sentAuthorization == nil) + let landed = try #require(server.requests.last) + #expect(landed.path == "/landed") + CredentialHeadersAuthorizer.expect( + [ + "authorization": nil, "dpop": nil, + "proxy-authorization": CredentialHeadersAuthorizer.proxyAuthorization, + "cookie": CredentialHeadersAuthorizer.cookie, + ], in: landed.headers, sourceLocation: #_sourceLocation) + await transport.disconnect() + } + + @Test("A 401 after a same-origin redirect reports the final hop's Authorization header") + func redirectedChallengeReportsFinalHopAuthorization() async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + server.routes = [ + "/mcp": (307, ["Location": "/landed"], Data()), + "/landed": (401, ["WWW-Authenticate": "Bearer"], Data()), + ] + let authorizer = RecordingRedirectAuthorizer(landedHeaders: ["Authorization": "Bearer rotated"]) + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: false, + authorizer: authorizer) + try await transport.connect() + + _ = await #expect(throws: MCPError.self) { try await transport.send(message) } + let challenge = try #require(authorizer.challenges.first) + #expect(challenge.sentAuthorization == "Bearer rotated") + await transport.disconnect() + } + + @Test("A same-origin redirect to a URL with a fragment fails with a single transportError wrapping invalidResourceURI") + func redirectToFragmentSingleWrapped() async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + server.routes = [ + "/mcp": (307, ["Location": "/landed#frag"], Data()), + "/landed": (200, ["Content-Type": "application/json"], response), + ] + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: false, + authorizer: CredentialHeadersAuthorizer()) + try await transport.connect() + + let error = await #expect(throws: MCPError.self) { try await transport.send(message) } + guard case .transportError(let underlying) = error else { + Issue.record("Expected transportError, got \(String(describing: error))") + return + } + let oauthError = try #require(underlying as? OAuthAuthorizationError) + #expect(oauthError.code == .invalidResourceURI) + #expect(server.requested == ["/mcp"]) + await transport.disconnect() + } + + @Test("A stateful session's Mcp-Session-Id follows a redirect to the same origin only", arguments: [false, true]) + func sessionIDRedirect(crossOrigin: Bool) async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + let other = try LoopbackHTTPServer() + defer { other.stop() } + let landing = crossOrigin ? other : server + let calls = Mutex(0) + server.respond = { request in + let n = calls.withLock { c -> Int in + c += 1 + return c + } + if n == 1 { + return ( + 200, + ["Content-Type": "application/json", "Mcp-Session-Id": "sess-123"], + Data(#"{"jsonrpc":"2.0","result":{},"id":7}"#.utf8) + ) + } + if request.path == "/mcp" { + return (307, ["Location": "\(landing.baseURL)/landed"], Data()) + } + return nil + } + landing.routes["/landed"] = (200, ["Content-Type": "application/json"], response) + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: false) + try await transport.connect() + + // First request establishes the session ID. + try await transport.send(message) + var iterator = await transport.receive().makeAsyncIterator() + #expect(try await iterator.next() == response) + // Second request redirects with Mcp-Session-Id set. + try await transport.send(message) + #expect(try await iterator.next() == response) + + #expect(server.requests[1].headers["mcp-session-id"] == "sess-123") + let landed = try #require(landing.requests.first { $0.path == "/landed" }) + #expect(landed.headers["mcp-session-id"] == (crossOrigin ? nil : "sess-123")) + await transport.disconnect() + } + + @Test("A 404 from a cross-origin redirect hop without Mcp-Session-Id does not expire the session") + func crossOriginRedirect404DoesNotExpireSession() async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + let other = try LoopbackHTTPServer() + defer { other.stop() } + let calls = Mutex(0) + server.respond = { request in + let n = calls.withLock { c -> Int in + c += 1 + return c + } + if n == 1 { + return ( + 200, + ["Content-Type": "application/json", "Mcp-Session-Id": "sess-live"], + Data(#"{"jsonrpc":"2.0","result":{},"id":7}"#.utf8) + ) + } + if n == 2 { + return (307, ["Location": "\(other.baseURL)/missing"], Data()) + } + return (200, ["Content-Type": "application/json"], Data(#"{"jsonrpc":"2.0","result":{},"id":7}"#.utf8)) + } + other.routes["/missing"] = (404, [:], Data()) + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: false) + try await transport.connect() + + // Establish the session. + try await transport.send(message) + var iterator = await transport.receive().makeAsyncIterator() + #expect(try await iterator.next() == response) + #expect(await transport.sessionID == "sess-live") + + // Redirect cross-origin to a 404: Mcp-Session-Id was stripped, so the session stays alive. + let error = await #expect(throws: MCPError.self) { try await transport.send(message) } + guard case .transportError(let underlying) = error else { + Issue.record("Expected transportError, got \(String(describing: error))") + return + } + let statusError = try #require(underlying as? HTTPStatusError) + #expect(statusError.statusCode == 404) + #expect(!statusError.isSessionExpired) + #expect(other.requests.first?.headers["mcp-session-id"] == nil) + #expect(await transport.sessionID == "sess-live") + + // A follow-up request on the original endpoint still sends the live session ID. + try await transport.send(message) + #expect(try await iterator.next() == response) + #expect(server.requests.last?.headers["mcp-session-id"] == "sess-live") + await transport.disconnect() + } + + @Test("A cross-origin 2xx redirect response cannot overwrite or initialize Mcp-Session-Id on POST") + func crossOriginRedirectPostIgnoresForeignSessionID() async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + let other = try LoopbackHTTPServer() + defer { other.stop() } + + // Case 1: existing live session is not overwritten by a foreign origin. + do { + let calls = Mutex(0) + server.respond = { _ in + let n = calls.withLock { c -> Int in + c += 1 + return c + } + if n == 1 { + return (200, ["Content-Type": "application/json", "Mcp-Session-Id": "sess-live"], response) + } + if n == 2 { + return (307, ["Location": "\(other.baseURL)/foreign"], Data()) + } + return (200, ["Content-Type": "application/json"], response) + } + other.routes["/foreign"] = ( + 200, ["Content-Type": "application/json", "Mcp-Session-Id": "sess-foreign"], response + ) + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: false) + try await transport.connect() + var iterator = await transport.receive().makeAsyncIterator() + + try await transport.send(message) + #expect(try await iterator.next() == response) + #expect(await transport.sessionID == "sess-live") + + try await transport.send(message) + #expect(try await iterator.next() == response) + #expect(await transport.sessionID == "sess-live") + + try await transport.send(message) + #expect(try await iterator.next() == response) + #expect(server.requests.last?.headers["mcp-session-id"] == "sess-live") + await transport.disconnect() + } + + // Case 2: unset sessionID stays nil when a cross-origin redirect returns Mcp-Session-Id. + do { + server.respond = nil + server.routes = ["/mcp": (307, ["Location": "\(other.baseURL)/foreign"], Data())] + other.routes["/foreign"] = ( + 200, ["Content-Type": "application/json", "Mcp-Session-Id": "sess-foreign"], response + ) + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: false) + try await transport.connect() + var iterator = await transport.receive().makeAsyncIterator() + + try await transport.send(message) + #expect(try await iterator.next() == response) + #expect(await transport.sessionID == nil) + await transport.disconnect() + } + } + + @Test("A cross-origin 2xx redirect response cannot overwrite Mcp-Session-Id on the GET stream") + func crossOriginRedirectGetStreamIgnoresForeignSessionID() async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + let other = try LoopbackHTTPServer() + defer { other.stop() } + let notification = Data(#"{"jsonrpc":"2.0","method":"notifications/ping"}"#.utf8) + let sseBody = Data("data: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/ping\"}\n\n".utf8) + server.respond = { request in + if request.method == "POST" { + return (200, ["Content-Type": "application/json", "Mcp-Session-Id": "sess-live"], response) + } + return (307, ["Location": "\(other.baseURL)/events"], Data()) + } + other.routes["/events"] = ( + 200, ["Content-Type": "text/event-stream", "Mcp-Session-Id": "sess-foreign-get"], sseBody + ) + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: true) + try await transport.connect() + var iterator = await transport.receive().makeAsyncIterator() + + // POST establishes sess-live, triggering the standalone GET stream which redirects to other. + try await transport.send(message) + var received: [Data] = [] + while received.count < 2, let next = try await iterator.next() { + received.append(next) + } + #expect(received.contains(response)) + #expect(received.contains(notification)) + #expect(other.requests.first?.path == "/events") + #expect(other.requests.first?.headers["mcp-session-id"] == nil) + #expect(await transport.sessionID == "sess-live") + await transport.disconnect() + } + + @Test("The authorizer sees a redirected request's response for the URL that answered it") + func responseURLAfterRedirect() async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + server.routes = [ + "/mcp": (307, ["Location": "/landed"], Data()), + "/landed": (200, ["Content-Type": "application/json", "DPoP-Nonce": "n1"], response), + ] + let authorizer = RecordingRedirectAuthorizer() + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: false, + authorizer: authorizer) + try await transport.connect() + + try await transport.send(message) + var iterator = await transport.receive().makeAsyncIterator() + #expect(try await iterator.next() == response) + + // A DPoP nonce is recorded for the origin of that URL (RFC 9449 §8). + #expect(authorizer.responses.map(\.url) == [URL(string: "\(server.baseURL)/landed")!]) + #expect(authorizer.responses.first?.nonce == "n1") + await transport.disconnect() + } + + // Cookies of the configuration's cookie storage are not request + // headers: URLSession adds those of each hop's URL. Cookies ignore + // the port (RFC 6265 §8.5), so another port on the host gets them, + // and not the Cookie header of the request. + @Test( + "A cookie a redirect sets goes to the next hop from the cookie storage; a request's Cookie doesn't cross origins", + arguments: [false, true]) + func cookieStorageAcrossRedirect(crossOrigin: Bool) async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + let other = try LoopbackHTTPServer() + defer { other.stop() } + let landing = crossOrigin ? other : server + server.routes = [ + "/mcp": (307, ["Location": "\(landing.baseURL)/landed", "Set-Cookie": "stored=1; Path=/"], Data()) + ] + landing.routes["/landed"] = (200, ["Content-Type": "application/json"], response) + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: false, + requestModifier: { request in + // The platforms differ on a request's Cookie next to stored ones on one origin. + if crossOrigin { request.setValue("app=1", forHTTPHeaderField: "Cookie") } + }) + try await transport.connect() + + try await transport.send(message) + var iterator = await transport.receive().makeAsyncIterator() + #expect(try await iterator.next() == response) + + let landed = try #require(landing.requests.first { $0.path == "/landed" }) + #expect(landed.headers["cookie"] == "stored=1") + await transport.disconnect() + } + + @Test("A 307 to the same origin keeps the method and body, with the authorizer's headers for its URL") + func sameOriginRedirect() async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + server.routes = [ + "/mcp": (307, ["Location": "/landed"], Data()), + "/landed": (200, ["Content-Type": "application/json"], response), + ] + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: false, + authorizer: CredentialHeadersAuthorizer(), requestModifier: CredentialHeadersAuthorizer.modify) + try await transport.connect() + + try await transport.send(message) + var iterator = await transport.receive().makeAsyncIterator() + #expect(try await iterator.next() == response) + + #expect(server.requested == ["/mcp", "/landed"]) + let landed = try #require(server.requests.last) + CredentialHeadersAuthorizer.expect( + [ + "authorization": CredentialHeadersAuthorizer.authorization, + "dpop": CredentialHeadersAuthorizer.proof(for: "POST", URL(string: "\(server.baseURL)/landed")!), + "proxy-authorization": CredentialHeadersAuthorizer.proxyAuthorization, + "cookie": CredentialHeadersAuthorizer.cookie, + ], in: landed.headers, sourceLocation: #_sourceLocation) + #expect(landed.body == message) + await transport.disconnect() + } + + @Test("A 401 from another origin that a redirect led to fails at once, naming the redirect target") + func crossOriginChallengeFailsFast() async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + let other = try LoopbackHTTPServer() + defer { other.stop() } + let target = "\(other.baseURL)/landed?sig=q-secret" + // The endpoint asks for a token, then redirects the request that has one. + server.respond = { request in + request.headers["authorization"] == nil + ? (401, ["WWW-Authenticate": "Bearer"], Data()) : (307, ["Location": target], Data()) + } + other.respond = { _ in (401, ["WWW-Authenticate": "Bearer"], Data()) } + let tokens = RecordingTokenClient() + let authorizer = OAuthAuthorizer( + configuration: OAuthConfiguration( + grantType: .clientCredentials, + authentication: .clientSecretBasic(clientID: "client", clientSecret: "secret")), + urlValidator: MockURLValidator(), discoveryClient: MockDiscoveryClient(), tokenEndpointClient: tokens, + clientRegistrar: MockClientRegistrar(), authCodeFlow: MockAuthCodeFlow()) + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: false, + authorizer: authorizer) + try await transport.connect() + + let error = await #expect(throws: MCPError.self) { try await transport.send(message) } + guard case .transportError(let underlying) = error else { + Issue.record("Expected transportError, got \(String(describing: error))") + return + } + let oauthError = try #require(underlying as? OAuthAuthorizationError) + #expect(oauthError.code == .protectedResourceMismatch) + #expect(oauthError.actual == ["\(other.baseURL)/landed"]) + let description = oauthError.errorDescription ?? "" + #expect(description.contains("configure \(other.baseURL)/landed as the endpoint"), "\(description)") + #expect(!description.contains("q-secret"), "\(description)") + // One token, for the first 401; the second came from the other origin. + #expect(tokens.calls.count == 1) + #expect(server.requests.map { $0.headers["authorization"] } == [nil, "Bearer token-1"]) + #expect(other.requests.count == 1) + #expect(other.requests.first?.headers["authorization"] == nil) + await transport.disconnect() + } + + @Test("A 401 after a hop through another origin and back fails at once, without credentials on the way back") + func challengeAfterReturnFailsFast() async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + let other = try LoopbackHTTPServer() + defer { other.stop() } + let back = "\(server.baseURL)/back" + // The endpoint asks for a token, then redirects the request that has + // one away; the other origin sends it back, where it moves on to a + // URL that asks again. + server.respond = { request in + switch (request.path, request.headers["authorization"]) { + case ("/mcp", nil): (401, ["WWW-Authenticate": "Bearer"], Data()) + case ("/mcp", _): (307, ["Location": "\(other.baseURL)/hop"], Data()) + case ("/back", _): (307, ["Location": "/landed"], Data()) + default: (401, ["WWW-Authenticate": "Bearer"], Data()) + } + } + other.respond = { _ in (307, ["Location": back], Data()) } + let tokens = RecordingTokenClient() + let authorizer = OAuthAuthorizer( + configuration: OAuthConfiguration( + grantType: .clientCredentials, + authentication: .clientSecretBasic(clientID: "client", clientSecret: "secret")), + urlValidator: MockURLValidator(), discoveryClient: MockDiscoveryClient(), tokenEndpointClient: tokens, + clientRegistrar: MockClientRegistrar(), authCodeFlow: MockAuthCodeFlow()) + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: false, + authorizer: authorizer, requestModifier: CredentialHeadersAuthorizer.modify) + try await transport.connect() + + let error = await #expect(throws: MCPError.self) { try await transport.send(message) } + guard case .transportError(let underlying) = error else { + Issue.record("Expected transportError, got \(String(describing: error))") + return + } + let oauthError = try #require(underlying as? OAuthAuthorizationError) + #expect(oauthError.code == .protectedResourceMismatch) + #expect(oauthError.actual == ["\(other.baseURL)/hop"]) + let description = oauthError.errorDescription ?? "" + #expect( + description.contains("and from there to \(server.baseURL)/landed, which it reached without credentials"), + "\(description)") + // One token, for the first 401; the hops after the other origin had no credentials. + #expect(tokens.calls.count == 1) + #expect(server.requested == ["/mcp", "/mcp", "/back", "/landed"]) + #expect(other.requested == ["/hop"]) + for hop in [other.requests[0], server.requests[2], server.requests[3]] { + CredentialHeadersAuthorizer.expect( + ["authorization": nil, "dpop": nil, "proxy-authorization": nil, "cookie": nil], + in: hop.headers, sourceLocation: #_sourceLocation) + } + await transport.disconnect() + } + + @Test("A same-origin redirect whose headers the authorizer can't make fails with the authorizer's error") + func redirectWithoutHeadersIsNotFollowed() async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + server.routes = [ + "/mcp": (307, ["Location": "/landed"], Data()), + "/landed": (200, ["Content-Type": "application/json"], response), + ] + let log = CapturingLogHandler() + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: false, + authorizer: CredentialHeadersAuthorizer(failingPath: "/landed"), + logger: Logger(label: "mcp.test.redirect-failure") { _ in log }) + try await transport.connect() + + let error = await #expect(throws: MCPError.self) { try await transport.send(message) } + guard case .transportError(let underlying) = error else { + Issue.record("Expected transportError, got \(String(describing: error))") + return + } + // The authorizer's error, not the 307 it left unanswered. + #expect((underlying as? URLError)?.code == .userAuthenticationRequired, "\(underlying)") + #expect(server.requested == ["/mcp"]) + #expect(log.messages.contains("Redirect not followed: no authorization headers for its target")) + await transport.disconnect() + } + + @Test("A 401 from another origin that a redirect led the GET stream to is not passed to the authorizer") + func crossOriginChallengeOfGETStreamFailsFast() async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + let other = try LoopbackHTTPServer() + defer { other.stop() } + server.respond = { _ in (307, ["Location": "\(other.baseURL)/landed"], Data()) } + other.respond = { _ in (401, ["WWW-Authenticate": "Bearer"], Data()) } + let tokens = RecordingTokenClient() + let authorizer = OAuthAuthorizer( + configuration: OAuthConfiguration( + grantType: .clientCredentials, + authentication: .clientSecretBasic(clientID: "client", clientSecret: "secret")), + urlValidator: MockURLValidator(), discoveryClient: MockDiscoveryClient(), tokenEndpointClient: tokens, + clientRegistrar: MockClientRegistrar(), authCodeFlow: MockAuthCodeFlow()) + let (logs, sink) = AsyncStream.makeStream() + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: true, + sseInitializationTimeout: 0.05, authorizer: authorizer, + logger: Logger(label: "mcp.test.get-redirect") { _ in StreamingLogHandler(sink: sink) }) + try await transport.connect() + + // The GET stream logs its failure and tries again later. + let failure = await Self.firstLog(containing: "SSE connection error", in: logs) + await transport.disconnect() + let message = try #require(failure) + #expect(message.contains("configure \(other.baseURL)/landed as the endpoint"), "\(message)") + #expect(tokens.calls.isEmpty) + #expect(other.requests.allSatisfy { $0.headers["authorization"] == nil }) + } + + @Test("A redirect loop ends after 20 redirects", .timeLimit(.minutes(1))) + func redirectLimit() async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + server.respond = { request in + let hop = Int(request.path.split(separator: "/").last ?? "") ?? 0 + return (307, ["Location": "/hop/\(hop + 1)"], Data()) + } + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/hop/0")!, configuration: .ephemeral, streaming: false, + authorizer: CredentialHeadersAuthorizer()) + try await transport.connect() + + // A URLError of the session is thrown as is. + let error = await #expect(throws: URLError.self) { try await transport.send(message) } + #expect(error?.code == .httpTooManyRedirects) + // The first request and 20 redirects, as on every platform. + #expect(server.requested == (0...20).map { "/hop/\($0)" }) + await transport.disconnect() + } + + @Test("Cancelling a request while the authorizer makes a redirect's headers cancels that call", .timeLimit(.minutes(1))) + func cancelDuringRedirectDecision() async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + server.routes = [ + "/mcp": (307, ["Location": "/landed"], Data()), + "/landed": (200, ["Content-Type": "application/json"], response), + ] + let authorizer = RedirectWaitingAuthorizer() + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: false, + authorizer: authorizer) + try await transport.connect() + + let sending = Task { try await transport.send(message) } + for await _ in authorizer.entered { break } + sending.cancel() + // The call for the redirect sees the cancellation, and the request fails. + for await _ in authorizer.cancelled { break } + await #expect(throws: (any Error).self) { try await sending.value } + #expect(server.requested == ["/mcp"]) + await transport.disconnect() + } + + @Test( + "An Authorization of the configuration follows a redirect to the same origin only", + arguments: [false, true]) + func configurationCredentials(crossOrigin: Bool) async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + let other = try LoopbackHTTPServer() + defer { other.stop() } + let landing = crossOrigin ? other : server + server.routes = ["/mcp": (307, ["Location": "\(landing.baseURL)/landed"], Data())] + landing.routes["/landed"] = (200, ["Content-Type": "application/json"], response) + let configuration = URLSessionConfiguration.ephemeral + // Names in any case. + configuration.httpAdditionalHeaders = [ + "authorization": "Bearer config-token", + "PROXY-AUTHORIZATION": CredentialHeadersAuthorizer.proxyAuthorization, "cookie": "sid=config", + "mcp-session-id": "sess-config", "X-Config": "kept", + ] + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: configuration, streaming: false) + // The caller's configuration is not changed. + #expect(configuration.httpAdditionalHeaders?["authorization"] as? String == "Bearer config-token") + try await transport.connect() + + try await transport.send(message) + var iterator = await transport.receive().makeAsyncIterator() + #expect(try await iterator.next() == response) + + let first = try #require(server.requests.first) + #expect(first.headers["authorization"] == "Bearer config-token") + #expect(first.headers["proxy-authorization"] == CredentialHeadersAuthorizer.proxyAuthorization) + #expect(first.headers["cookie"] == "sid=config") + #expect(first.headers["mcp-session-id"] == "sess-config") + let landed = try #require(landing.requests.first { $0.path == "/landed" }) + #expect(landed.headers["authorization"] == (crossOrigin ? nil : "Bearer config-token")) + #expect(landed.headers["cookie"] == (crossOrigin ? nil : "sid=config")) + #expect(landed.headers["mcp-session-id"] == (crossOrigin ? nil : "sess-config")) + #expect( + landed.headers["proxy-authorization"] == (crossOrigin ? nil : CredentialHeadersAuthorizer.proxyAuthorization)) + #expect(landed.headers["x-config"] == "kept") + await transport.disconnect() + } + + @Test("A request's Authorization wins over the configuration's, also after a redirect") + func requestCredentialWinsOverConfiguration() async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + server.routes = [ + "/mcp": (307, ["Location": "/landed"], Data()), + "/landed": (200, ["Content-Type": "application/json"], response), + ] + let configuration = URLSessionConfiguration.ephemeral + configuration.httpAdditionalHeaders = ["Authorization": "Bearer config-token"] + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: configuration, streaming: false, + requestModifier: { request in + request.setValue("Bearer request-token", forHTTPHeaderField: "Authorization") + }) + try await transport.connect() + + try await transport.send(message) + var iterator = await transport.receive().makeAsyncIterator() + #expect(try await iterator.next() == response) + + #expect(server.requested == ["/mcp", "/landed"]) + #expect(server.requests.map { $0.headers["authorization"] } == ["Bearer request-token", "Bearer request-token"]) + await transport.disconnect() + } + + @Test( + "Without an authorizer, a requestModifier's Authorization and Cookie follow a redirect to the same origin only", + arguments: [false, true]) + func modifierCredentials(crossOrigin: Bool) async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + let other = try LoopbackHTTPServer() + defer { other.stop() } + let landing = crossOrigin ? other : server + server.routes = ["/mcp": (307, ["Location": "\(landing.baseURL)/landed"], Data())] + landing.routes["/landed"] = (200, ["Content-Type": "application/json"], response) + let transport = HTTPClientTransport( + endpoint: URL(string: "\(server.baseURL)/mcp")!, configuration: .ephemeral, streaming: false, + requestModifier: { request in + request.setValue("Bearer user-token", forHTTPHeaderField: "Authorization") + request.setValue(CredentialHeadersAuthorizer.proxyAuthorization, forHTTPHeaderField: "Proxy-Authorization") + request.setValue("sid=user", forHTTPHeaderField: "Cookie") + request.setValue("a-proof", forHTTPHeaderField: "DPoP") + request.setValue("kept", forHTTPHeaderField: "X-Custom") + }) + try await transport.connect() + + try await transport.send(message) + var iterator = await transport.receive().makeAsyncIterator() + #expect(try await iterator.next() == response) + + let landed = try #require(landing.requests.first { $0.path == "/landed" }) + CredentialHeadersAuthorizer.expect( + [ + "authorization": crossOrigin ? nil : "Bearer user-token", + "proxy-authorization": crossOrigin ? nil : CredentialHeadersAuthorizer.proxyAuthorization, + "cookie": crossOrigin ? nil : "sid=user", + "dpop": nil, + ], in: landed.headers, sourceLocation: #_sourceLocation) + await transport.disconnect() + } + } + + /// Authorizes a request to every path but `/landed`, for which it returns + /// `landedHeaders` (default empty, as one whose token expired since the + /// first request); records the challenges, and the responses it sees with + /// their `DPoP-Nonce`. + final class RecordingRedirectAuthorizer: HTTPClientAuthorizer, Sendable { + let maxAuthorizationAttempts = 1 + let landedHeaders: [String: String] + private let state = Mutex<(challenges: [HTTPAuthorizationChallenge], responses: [(url: URL, nonce: String?)])>( + ([], [])) + + init(landedHeaders: [String: String] = [:]) { + self.landedHeaders = landedHeaders + } + + var challenges: [HTTPAuthorizationChallenge] { state.withLock { $0.challenges } } + var responses: [(url: URL, nonce: String?)] { state.withLock { $0.responses } } + + func authorizationHeaders(for url: URL, method: String) -> [String: String] { + guard url.path != "/landed" else { return landedHeaders } + return [ + "Authorization": CredentialHeadersAuthorizer.authorization, + "DPoP": CredentialHeadersAuthorizer.proof(for: method, url), + ] + } + + func didReceiveResponse(headers: [String: String], for url: URL) async { + let nonce = headers.first { $0.key.lowercased() == "dpop-nonce" }?.value + state.withLock { $0.responses.append((url, nonce)) } + } + + func handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) -> HTTPChallengeResult { + state.withLock { $0.challenges.append(challenge) } + return .unhandled + } + } + + /// Authorizes the first request, and waits in the call for a redirect's + /// headers until that call is cancelled. + final class RedirectWaitingAuthorizer: HTTPClientAuthorizer, Sendable { + let maxAuthorizationAttempts = 1 + /// Yields when the call for the redirect starts. + let (entered, enteredContinuation) = AsyncStream.makeStream() + /// Yields when that call is cancelled. + let (cancelled, cancelledContinuation) = AsyncStream.makeStream() + + func authorizationHeaders(for url: URL, method: String) async throws -> [String: String] { + guard url.path == "/landed" else { return ["Authorization": "Bearer t"] } + enteredContinuation.yield() + do { + // Ends only by cancellation. + try await Task.sleep(for: .seconds(3600)) + } catch { + cancelledContinuation.yield() + throw error + } + return ["Authorization": "Bearer t"] + } + + func handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) -> HTTPChallengeResult { + .unhandled + } } /// Opens once; every wait returns after that. @@ -2474,10 +3606,12 @@ import Testing } } - /// An authorizer that suspends in `prepareAuthorization` or in - /// `handleChallenge` until its gate opens, as one refreshing a token does. - final class SuspendingAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { - enum Stage { case prepare, challenge } + /// An authorizer that suspends in `prepare(for:session:)`, in + /// `authorizationHeaders(for:method:)` or in `handleChallenge(_:session:)` + /// until its gate opens, as one refreshing a token or reading the + /// Keychain does. + final class SuspendingAuthorizer: HTTPClientAuthorizer, Sendable { + enum Stage { case prepare, headers, challenge } let maxAuthorizationAttempts = 3 let stage: Stage @@ -2486,26 +3620,78 @@ import Testing init(suspendingIn stage: Stage) { self.stage = stage } - func validateEndpointSecurity(for endpoint: URL) throws {} - func authorizationHeaders(for url: URL, method: String) throws -> [String: String] { - ["Authorization": "Bearer t"] - } - func prepareAuthorization(for endpoint: URL, session: URLSession) async throws { + func prepare(for endpoint: URL, session: URLSession) async throws { guard stage == .prepare else { return } enteredContinuation.yield() await gate.wait() } - func handleChallenge( - statusCode: Int, headers: [String: String], endpoint: URL, operationKey: String?, - session: URLSession - ) async throws -> Bool { - guard stage == .challenge else { return false } + func authorizationHeaders(for url: URL, method: String) async throws -> [String: String] { + if stage == .headers { + enteredContinuation.yield() + await gate.wait() + } + return ["Authorization": "Bearer t"] + } + func handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) async throws + -> HTTPChallengeResult + { + guard stage == .challenge else { return .unhandled } enteredContinuation.yield() await gate.wait() - return true + return .retry + } + } + + /// An actor conformer that suspends its `number`th + /// `authorizationHeaders(for:method:)` call for requests with `method` + /// (any, when `nil`) until its gate opens, as one reading a Keychain item + /// behind Face ID does. + actor HeaderSuspendingAuthorizer: HTTPClientAuthorizer { + nonisolated let maxAuthorizationAttempts = 1 + nonisolated let gate = AuthorizerGate() + /// Yields when the suspending call starts. + nonisolated let entered: AsyncStream + private let enteredContinuation: AsyncStream.Continuation + private let number: Int + private let method: String? + private var calls = 0 + + init(suspendingCall number: Int, method: String? = nil) { + (entered, enteredContinuation) = AsyncStream.makeStream() + self.number = number + self.method = method + } + + func authorizationHeaders(for url: URL, method: String) async -> [String: String] { + if self.method == nil || self.method == method { + calls += 1 + if calls == number { + enteredContinuation.yield() + await gate.wait() + } + } + return ["Authorization": "Bearer t"] + } + + func handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) -> HTTPChallengeResult { + .unhandled } } + /// The requests a mock server or a `requestModifier` saw, in order. + actor SentRequestLog { + private(set) var requests: [URLRequest] = [] + + /// Records `request` and returns how many have been recorded. + func append(_ request: URLRequest) -> Int { + requests.append(request) + return requests.count + } + + var methods: [String?] { requests.map(\.httpMethod) } + var sessionIDs: [String?] { requests.map { $0.value(forHTTPHeaderField: "Mcp-Session-Id") } } + } + /// Never answers and never calls its client. private final class SilentURLProtocol: URLProtocol { override class func canInit(with request: URLRequest) -> Bool { true } @@ -2665,9 +3851,14 @@ import Testing struct HTTPClientTransportSessionTests { let endpoint = URL(string: "http://127.0.0.1:9/mcp")! let request = Data(#"{"jsonrpc":"2.0","id":"r1","method":"tools/list"}"#.utf8) + let notification = Data(#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#.utf8) func makeTransport( + streaming: Bool = false, + sseInitializationTimeout: TimeInterval = 10, + protocolVersion: String = Version.latestHandshake, authorizer: (any HTTPClientAuthorizer)? = nil, + requestModifier: @escaping @Sendable (inout URLRequest) async throws -> Void = { _ in }, _ handler: @escaping @Sendable (URLRequest) async throws -> (HTTPURLResponse, Data) ) async -> HTTPClientTransport { let key = UUID().uuidString @@ -2676,11 +3867,16 @@ import Testing configuration.httpAdditionalHeaders = [IsolatedMockURLProtocol.sessionKeyHeader: key] await IsolatedMockURLProtocol.setHandler(key: key, handler) return HTTPClientTransport( - endpoint: endpoint, configuration: configuration, streaming: false, authorizer: authorizer) + endpoint: endpoint, configuration: configuration, streaming: streaming, + sseInitializationTimeout: sseInitializationTimeout, protocolVersion: protocolVersion, + authorizer: authorizer, requestModifier: requestModifier) } - func reply(_ status: Int) -> (HTTPURLResponse, Data) { - (HTTPURLResponse(url: endpoint, statusCode: status, httpVersion: "HTTP/1.1", headerFields: [:])!, Data()) + func reply(_ status: Int, headers: [String: String] = [:]) -> (HTTPURLResponse, Data) { + ( + HTTPURLResponse(url: endpoint, statusCode: status, httpVersion: "HTTP/1.1", headerFields: headers)!, + Data() + ) } #if canImport(FoundationNetworking) @@ -2716,6 +3912,146 @@ import Testing #expect(result.error is MCPError) } + @Test("disconnect while header building suspends fails the request without sending it") + func disconnectWhileBuildingHeaders() async throws { + let authorizer = SuspendingAuthorizer(suspendingIn: .headers) + let log = SentRequestLog() + let transport = await makeTransport(authorizer: authorizer) { [self] request in + _ = await log.append(request) + return reply(202) + } + try await transport.connect() + let send = Task { [request] in try await transport.send(request) } + for await _ in authorizer.entered { break } + await transport.disconnect() + await authorizer.gate.open() + let result = await outcome(within: .seconds(5)) { try await send.value } + #expect(result.mcpError == .connectionClosed, "\(result)") + #expect(await log.requests.isEmpty) + } + + @Test("A session ID replaced while the authorizer suspends is the one sent") + func sessionReplacedWhileAuthorizerSuspends() async throws { + let authorizer = HeaderSuspendingAuthorizer(suspendingCall: 2) + let log = SentRequestLog() + let transport = await makeTransport(authorizer: authorizer) { [self] request in + // The first reply assigns s1, the second replaces it with s2. + let count = await log.append(request) + return reply(202, headers: count <= 2 ? ["Mcp-Session-Id": "s\(count)"] : [:]) + } + try await transport.connect() + try await transport.send(notification) + let suspended = Task { [notification] in try await transport.send(notification) } + for await _ in authorizer.entered { break } + try await transport.send(notification) + #expect(await transport.sessionID == "s2") + + await authorizer.gate.open() + try await suspended.value + #expect(await log.sessionIDs == [nil, "s1", "s2"]) + await transport.disconnect() + } + + @Test("A session dropped while the requestModifier suspends is not sent") + func sessionDroppedWhileModifierSuspends() async throws { + let gate = AuthorizerGate() + let (entered, enteredContinuation) = AsyncStream.makeStream() + let calls = Counter() + let seen = SentRequestLog() + let log = SentRequestLog() + let transport = await makeTransport( + requestModifier: { request in + _ = await seen.append(request) + await calls.increment() + if await calls.value == 2 { + enteredContinuation.yield() + await gate.wait() + } + } + ) { [self] request in + // The first reply assigns s1; a 404 to the second, which + // carried it, ends the session. + switch await log.append(request) { + case 1: return reply(202, headers: ["Mcp-Session-Id": "s1"]) + case 2: return reply(404) + default: return reply(202) + } + } + try await transport.connect() + try await transport.send(notification) + let suspended = Task { [notification] in try await transport.send(notification) } + for await _ in entered { break } + await #expect { + try await transport.send(notification) + } throws: { error in + guard case .transportError(let status as HTTPStatusError) = error as? MCPError else { return false } + return status.isSessionExpired + } + #expect(await transport.sessionID == nil) + + await gate.open() + try await suspended.value + // The modifier saw the session ID of the moment it ran; the + // request went out without the session that ended meanwhile. + #expect(await seen.sessionIDs == [nil, "s1", "s1"]) + #expect(await log.sessionIDs == [nil, "s1", nil]) + await transport.disconnect() + } + + @Test("The GET stream sets the session ID after the authorizer") + func getStreamSessionIDAfterAuthorizer() async throws { + let authorizer = HeaderSuspendingAuthorizer(suspendingCall: 1, method: "GET") + try await expectGETCarriesReplacedSessionID( + authorizer: authorizer, entered: authorizer.entered, gate: authorizer.gate) + } + + @Test("The GET stream sets the session ID after its requestModifier") + func getStreamSessionIDAfterModifier() async throws { + let gate = AuthorizerGate() + let (entered, enteredContinuation) = AsyncStream.makeStream() + let gets = Counter() + try await expectGETCarriesReplacedSessionID( + requestModifier: { request in + guard request.httpMethod == "GET" else { return } + await gets.increment() + if await gets.value == 1 { + enteredContinuation.yield() + await gate.wait() + } + }, + entered: entered, gate: gate) + } + + /// Opens the GET stream on a session `s1`, holds the GET's header + /// building until `gate` opens (it yields on `entered`), replaces the + /// session ID with `s2` meanwhile, and checks that the GET carries `s2`. + func expectGETCarriesReplacedSessionID( + authorizer: (any HTTPClientAuthorizer)? = nil, + requestModifier: @escaping @Sendable (inout URLRequest) async throws -> Void = { _ in }, + entered: AsyncStream, gate: AuthorizerGate + ) async throws { + let log = SentRequestLog() + let transport = await makeTransport( + streaming: true, authorizer: authorizer, requestModifier: requestModifier + ) { [self] request in + let count = await log.append(request) + // No GET stream: the loop ends after the first GET. + if request.httpMethod == "GET" { return reply(405) } + return reply(202, headers: ["Mcp-Session-Id": count == 1 ? "s1" : "s2"]) + } + try await transport.connect() + try await transport.send(notification) + for await _ in entered { break } + try await transport.send(notification) + #expect(await transport.sessionID == "s2") + + await gate.open() + #expect(await eventually(within: .seconds(10)) { await log.methods.contains("GET") }) + let get = await log.requests.first { $0.httpMethod == "GET" } + #expect(get?.value(forHTTPHeaderField: "Mcp-Session-Id") == "s2") + await transport.disconnect() + } + @Test("connect() after disconnect() throws instead of losing messages") func reconnect() async throws { let transport = await makeTransport { [self] _ in reply(202) } @@ -2726,6 +4062,247 @@ import Testing await #expect(throws: MCPError.self) { try await transport.connect() } } + @Test("A 2026-07-28 server/discover reply with Mcp-Session-Id opens no GET, and the next POST carries no session ID") + func statelessReplySessionID() async throws { + actor Sent { + private(set) var httpMethods: [String] = [] + private(set) var sessionIDs: [String?] = [] + func record(_ request: URLRequest) { + httpMethods.append(request.httpMethod ?? "") + sessionIDs.append(request.value(forHTTPHeaderField: HTTPHeaderName.sessionID)) + } + } + let sent = Sent() + // With a timeout this long, only a session ID ends the GET stream's wait while the + // transport is connected: no didNegotiate here switches the transport. + let transport = await makeTransport(streaming: true, sseInitializationTimeout: 3600) { [endpoint] request in + await sent.record(request) + guard request.httpMethod == "POST", + let body = request.readBody(), + let message = try JSONSerialization.jsonObject(with: body) as? [String: Any], + let id = message["id"] as? Int + else { + return (HTTPURLResponse(url: endpoint, statusCode: 405, httpVersion: "HTTP/1.1", headerFields: [:])!, Data()) + } + let response = HTTPURLResponse( + url: endpoint, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/json", HTTPHeaderName.sessionID: "stray"])! + return (response, Data(#"{"jsonrpc":"2.0","id":\#(id),"result":{"resultType":"complete"}}"#.utf8)) + } + try await transport.connect() + + try await transport.send( + Data( + #"{"jsonrpc":"2.0","id":1,"method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28"}}}"#.utf8)) + #expect(await transport.sessionID == nil) + try await transport.send( + Data( + #"{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28"}}}"#.utf8)) + #expect(await transport.sessionID == nil) + // disconnect() ends the GET stream's wait with the transport closed: it sends no GET. + await transport.disconnect() + + #expect(await sent.httpMethods == ["POST", "POST"]) + #expect(await sent.sessionIDs == [nil, nil]) + } + + @Test("A transport configured for 2026-07-28 ignores Mcp-Session-Id even when the message omits _meta") + func statelessConfiguredTransportIgnoresSessionID() async throws { + actor Sent { + private(set) var httpMethods: [String] = [] + private(set) var sessionIDs: [String?] = [] + func record(_ request: URLRequest) { + httpMethods.append(request.httpMethod ?? "") + sessionIDs.append(request.value(forHTTPHeaderField: HTTPHeaderName.sessionID)) + } + } + let sent = Sent() + let transport = await makeTransport( + streaming: true, sseInitializationTimeout: 0.05, protocolVersion: Version.v2026_07_28 + ) { [endpoint] request in + await sent.record(request) + let response = HTTPURLResponse( + url: endpoint, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/json", HTTPHeaderName.sessionID: "stray"])! + return (response, Data(#"{"jsonrpc":"2.0","id":1,"result":{}}"#.utf8)) + } + try await transport.connect() + + // Message carries no _meta protocolVersion; transport's configured protocolVersion is 2026-07-28. + try await transport.send(Data(#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#.utf8)) + #expect(await transport.sessionID == nil) + // Past sseInitializationTimeout: no standalone GET stream opens for a stateless revision. + try await Task.sleep(for: .milliseconds(100)) + try await transport.send(Data(#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#.utf8)) + #expect(await transport.sessionID == nil) + await transport.disconnect() + + #expect(await sent.httpMethods == ["POST", "POST"]) + #expect(await sent.sessionIDs == [nil, nil]) + } + + @Test("A 2026-07-28 transport falling back to handshake initialize records Mcp-Session-Id and opens GET") + func statelessConfiguredTransportHandshakeFallbackKeepsSessionID() async throws { + actor Recorded { + private(set) var initializedSessionID: String? + private(set) var initializedVersion: String? + private(set) var getSessionID: String? + func recordInitialized(sessionID: String?, version: String?) { + initializedSessionID = sessionID + initializedVersion = version + } + func recordGET(sessionID: String?) { + getSessionID = sessionID + } + } + let recorded = Recorded() + let transport = await makeTransport( + streaming: true, sseInitializationTimeout: 0.05, protocolVersion: Version.v2026_07_28 + ) { [endpoint] request in + if request.httpMethod == "GET" { + await recorded.recordGET(sessionID: request.value(forHTTPHeaderField: HTTPHeaderName.sessionID)) + let response = HTTPURLResponse( + url: endpoint, statusCode: 405, httpVersion: "HTTP/1.1", headerFields: [:])! + return (response, Data()) + } + let body = request.readBody() ?? Data() + let json = (try? JSONSerialization.jsonObject(with: body) as? [String: Any]) ?? [:] + let method = json["method"] as? String + let id = json["id"] + if method == ServerDiscover.name { + let response = HTTPURLResponse( + url: endpoint, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/json"])! + let reply = try JSONSerialization.data(withJSONObject: [ + "jsonrpc": "2.0", "id": id as Any, + "error": ["code": -32601, "message": "Method not found"], + ]) + return (response, reply) + } + if method == Initialize.name { + let response = HTTPURLResponse( + url: endpoint, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/json", HTTPHeaderName.sessionID: "hs-sess"])! + let reply = try JSONSerialization.data(withJSONObject: [ + "jsonrpc": "2.0", "id": id as Any, + "result": [ + "protocolVersion": Version.v2025_11_25, + "capabilities": [String: Any](), + "serverInfo": ["name": "legacy", "version": "1"], + ], + ]) + return (response, reply) + } + if method == InitializedNotification.name { + await recorded.recordInitialized( + sessionID: request.value(forHTTPHeaderField: HTTPHeaderName.sessionID), + version: request.value(forHTTPHeaderField: HTTPHeaderName.protocolVersion)) + let response = HTTPURLResponse( + url: endpoint, statusCode: 202, httpVersion: "HTTP/1.1", headerFields: [:])! + return (response, Data()) + } + let response = HTTPURLResponse( + url: endpoint, statusCode: 202, httpVersion: "HTTP/1.1", headerFields: [:])! + return (response, Data()) + } + let client = Client(name: "c", version: "1", configuration: .init(protocolMode: .automatic)) + try await client.connect(transport: transport) + + #expect(await transport.sessionID == "hs-sess") + #expect(await recorded.initializedSessionID == "hs-sess") + #expect(await recorded.initializedVersion == Version.v2025_11_25) + #expect(await eventually { await recorded.getSessionID == "hs-sess" }) + + await client.disconnect() + } + + @Test("acceptStandaloneStream rejects a late 200 reply after switching to stateless, on 2026-07-28, or disconnecting") + func acceptStandaloneStreamRejectsAfterStatelessOrDisconnect() async throws { + let key = UUID().uuidString + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [IsolatedMockURLProtocol.self] + configuration.httpAdditionalHeaders = [IsolatedMockURLProtocol.sessionKeyHeader: key] + await IsolatedMockURLProtocol.setHandler(key: key) { [endpoint] _ in + let response = HTTPURLResponse( + url: endpoint, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "text/event-stream", HTTPHeaderName.sessionID: "stray"])! + return (response, Data("data: {}\n\n".utf8)) + } + let session = URLSession(configuration: configuration) + let streaming = StreamingSession(configuration: configuration) + defer { + streaming.invalidate(along: session) + } + + func makeReply() async throws -> HTTPClientTransport.EventStreamReply { + let (body, _) = try await session.responseBody(for: URLRequest(url: endpoint), streaming: streaming) + return HTTPClientTransport.EventStreamReply( + stream: body, statusCode: 200, + headers: [HTTPHeaderName.sessionID: "stray"], sessionID: "stray", sentSessionID: nil) + } + + // Case 1: transport switched to stateless while GET was in flight. + let statelessTransport = HTTPClientTransport( + endpoint: endpoint, configuration: configuration, streaming: false) + try await statelessTransport.connect() + await statelessTransport.didNegotiate(protocolVersion: Version.v2026_07_28) + let statelessReply = try await makeReply() + await #expect(throws: CancellationError.self) { + try await statelessTransport.acceptStandaloneStream(statelessReply) + } + #expect(await statelessTransport.sessionID == nil) + await statelessTransport.disconnect() + + // Case 2: transport initialized with 2026-07-28 (before didNegotiate). + let configuredStateless = HTTPClientTransport( + endpoint: endpoint, configuration: configuration, streaming: false, + protocolVersion: Version.v2026_07_28) + try await configuredStateless.connect() + let configuredReply = try await makeReply() + await #expect(throws: CancellationError.self) { + try await configuredStateless.acceptStandaloneStream(configuredReply) + } + #expect(await configuredStateless.sessionID == nil) + await configuredStateless.disconnect() + + // Case 3: transport disconnected while GET was in flight. + let disconnectedTransport = HTTPClientTransport( + endpoint: endpoint, configuration: configuration, streaming: false) + try await disconnectedTransport.connect() + await disconnectedTransport.disconnect() + let disconnectedReply = try await makeReply() + await #expect(throws: CancellationError.self) { + try await disconnectedTransport.acceptStandaloneStream(disconnectedReply) + } + #expect(await disconnectedTransport.sessionID == nil) + } + + @Test("abandonRequest returns true and cancels the POST before didNegotiate on a 2026-07-28 transport") + func abandonRequestReturnsTrueBeforeDidNegotiateOnStatelessTransport() async throws { + let gate = AuthorizerGate() + let (entered, enteredContinuation) = AsyncStream.makeStream() + let transport = await makeTransport( + streaming: false, protocolVersion: Version.v2026_07_28 + ) { [self] _ in + enteredContinuation.yield() + await gate.wait() + return reply(200) + } + try await transport.connect() + + let send = Task { try await transport.send(request) } + for await _ in entered { break } + + // Before didNegotiate, protocolVersion is 2026-07-28 (no sessions), so abandoning + // the request reports true (peer learns via closed POST) and ends the in-flight send. + let handled = await transport.abandonRequest(.string("r1")) + #expect(handled == true) + await gate.open() + let finished = await outcome(within: .seconds(10)) { try await send.value } + #expect(!finished.didTimeOut, "abandoned POST did not finish") + await transport.disconnect() + } + @Test("disconnect() ends a notification's POST that waits for its response") func disconnectEndsNotificationPost() async throws { let gate = AuthorizerGate() diff --git a/Tests/MCPTests/HTTPServerTransportTests.swift b/Tests/MCPTests/HTTPServerTransportTests.swift index 1f593925..e530e270 100644 --- a/Tests/MCPTests/HTTPServerTransportTests.swift +++ b/Tests/MCPTests/HTTPServerTransportTests.swift @@ -1,4 +1,5 @@ import Foundation +import Synchronization import Testing @testable import MCP @@ -100,7 +101,7 @@ private func makeStatefulTransport( ) -> StatefulHTTPServerTransport { StatefulHTTPServerTransport( sessionIDGenerator: sessionIDGenerator, - validationPipeline: StandardValidationPipeline(validators: []) + validators: [] ) } @@ -119,16 +120,16 @@ private func makeAuthenticatedStatefulTransport( challengeScopeProvider: { _, _ in challengeScopes } ) return StatefulHTTPServerTransport( - validationPipeline: StandardValidationPipeline(validators: [ + validators: [ validator, SessionValidator(), - ]) + ] ) } private func makeStatelessTransport() -> StatelessHTTPServerTransport { StatelessHTTPServerTransport( - validationPipeline: StandardValidationPipeline(validators: []) + validators: [] ) } @@ -262,6 +263,79 @@ private func initializeSession( return sid } +/// The JSON-RPC messages an SSE response delivers, in order. +private actor SSEMessages { + private(set) var messages: [Value] = [] + private(set) var firstEventID: String? + private(set) var isFinished = false + private var reader: Task? + + /// Starts reading `response`, which must be an SSE stream. + func read(_ response: HTTPResponse) { + guard case .stream(let stream, _) = response else { return } + reader = Task { + defer { self.markFinished() } + do { + for try await chunk in stream { + for line in String(decoding: chunk, as: UTF8.self).split(separator: "\n") { + if line.hasPrefix("id:") { + self.recordEventID(line.dropFirst(3).trimmingCharacters(in: .whitespaces)) + } else if line.hasPrefix("data: ") { + if let message = try? JSONDecoder().decode(Value.self, from: Data(line.dropFirst(6).utf8)) { + self.append(message) + } + } + } + } + } catch {} + } + } + + private func recordEventID(_ id: String) { + if firstEventID == nil { firstEventID = id } + } + + private func markFinished() { isFinished = true } + + private func append(_ message: Value) { messages.append(message) } + + /// The methods of the messages so far, `"result"` for a response. + var methods: [String] { + messages.map { $0.objectValue?["method"]?.stringValue ?? ($0.objectValue?["result"] != nil ? "result" : "?") } + } + + func first(method: String) -> Value? { + messages.first { $0.objectValue?["method"]?.stringValue == method } + } + + func stop() { reader?.cancel() } +} + +/// A server whose `tools/call` handler asks for elicitation in an +/// unstructured task, which keeps the handler's context, and returns once +/// that task ends. The test cancels the task from outside the handler. +private actor HeldElicitation { + private var task: Task? + + func hold(_ task: Task) { self.task = task } + var isHeld: Bool { task != nil } + func cancel() { task?.cancel() } + + static func makeServer(holding held: HeldElicitation) async -> Server { + let server = Server(name: "s", version: "1", capabilities: .init(tools: .init())) + await server.withMethodHandler(CallTool.self) { [weak server] _ in + guard let server else { throw MCPError.internalError("The server is gone") } + let elicitation = Task { + try await server.requestElicitation(message: "Confirm?", requestedSchema: .init()) + } + await held.hold(elicitation) + _ = try? await elicitation.value + return CallTool.Result(content: []) + } + return server + } +} + // MARK: - StatefulHTTPServerTransport Tests @Suite("StatefulHTTPServerTransport Tests") @@ -643,12 +717,12 @@ struct StatefulHTTPServerTransportTests { "jsonrpc": "2.0", "method": "notifications/progress", "params": ["progressToken": "t", "progress": 1] as [String: Any], ]) - try await transport.send(notification, relatedRequestID: .string(requestID)) + try await transport.send(notification, options: TransportSendOptions(relatedRequestID: .string(requestID))) let serverRequest = try JSONSerialization.data(withJSONObject: [ "jsonrpc": "2.0", "id": "srv-1", "method": "elicitation/create", "params": [:] as [String: Any], ]) - try await transport.send(serverRequest, relatedRequestID: .string(requestID)) + try await transport.send(serverRequest, options: TransportSendOptions(relatedRequestID: .string(requestID))) try await transport.send(makeResponseBody(id: requestID)) let postText = try await postTask.value @@ -694,7 +768,7 @@ struct StatefulHTTPServerTransportTests { "jsonrpc": "2.0", "method": "notifications/message", "params": ["level": "info", "data": "late"] as [String: Any], ]) - try await transport.send(notification, relatedRequestID: .string(requestID)) + try await transport.send(notification, options: TransportSendOptions(relatedRequestID: .string(requestID))) #expect(try await getTask.value.contains("late")) await transport.disconnect() @@ -721,13 +795,13 @@ struct StatefulHTTPServerTransportTests { } break } - await transport.closeSSEStream(forRequestID: requestID) + await transport.closeSSEStream(forRequestID: .string(requestID)) let notification = try JSONSerialization.data(withJSONObject: [ "jsonrpc": "2.0", "method": "notifications/message", "params": ["level": "info", "data": "while-disconnected"] as [String: Any], ]) - try await transport.send(notification, relatedRequestID: .string(requestID)) + try await transport.send(notification, options: TransportSendOptions(relatedRequestID: .string(requestID))) try await transport.send(makeResponseBody(id: requestID)) let resumed = await transport.handleRequest( @@ -890,6 +964,193 @@ struct StatefulHTTPServerTransportTests { #expect(withSession.headers[HTTPHeaderName.sessionID] == nil) } + // MARK: - Validation While the Session Changes + + @Test("A suspending token validator is awaited before the request is handled", .timeLimit(.minutes(1))) + func testSuspendingTokenValidator() async throws { + let gate = ValidationGate() + let transport = makeAuthenticatedStatefulTransport { token, _, _ in + await gate.wait() + return token == "valid" ? .valid(BearerTokenInfo()) : .invalidToken() + } + try await transport.connect() + + let finished = Flag() + let initialize = Task { + let response = await transport.handleRequest( + makeStatefulPOSTRequest(body: makeInitializeBody(), authorization: "Bearer valid")) + await finished.set() + return response + } + #expect(await eventually { await gate.arrivals == 1 }) + + // The transport answers other requests while the token validator suspends. + let unauthenticated = await transport.handleRequest(makeStatefulPOSTRequest(body: makeInitializeBody())) + #expect(unauthenticated.statusCode == 401) + #expect(await finished.isSet == false) + + await gate.open() + let response = await initialize.value + #expect(response.statusCode == 200) + #expect(response.headers[HTTPHeaderName.sessionID] != nil) + await transport.disconnect() + } + + @Test("A DELETE while a POST is being validated ends the POST with 404 and opens no stream", .timeLimit(.minutes(1))) + func testDeleteDuringPostValidation() async throws { + let gate = ValidationGate() + let transport = StatefulHTTPServerTransport(validators: [ + GateValidator(gate) { _, context in context.httpMethod == "POST" && !context.isInitializationRequest }, + SessionValidator(), + ]) + let sessionID = try await initializeSession(transport: transport) + + let post = Task { + await transport.handleRequest(makeStatefulPOSTRequest(body: makeRequestBody(id: "2"), sessionID: sessionID)) + } + #expect(await eventually { await gate.arrivals == 1 }) + let delete = await transport.handleRequest(makeDELETERequest(sessionID: sessionID)) + #expect(delete.statusCode == 200) + + await gate.open() + let response = await post.value + #expect(response.statusCode == 404) + #expect(response.headers[HTTPHeaderName.sessionID] == sessionID) + if case .stream = response { + Issue.record("A POST on a terminated session opened a stream") + } + #expect(await transport.httpRequest(for: .string("2")) == nil) + } + + @Test("Two initialize requests validated at the same time create one session", .timeLimit(.minutes(1))) + func testConcurrentInitializeValidation() async throws { + let gate = ValidationGate() + let transport = StatefulHTTPServerTransport(validators: [ + GateValidator(gate) { _, context in context.isInitializationRequest }, + SessionValidator(), + ]) + try await transport.connect() + + let first = Task { await transport.handleRequest(makeStatefulPOSTRequest(body: makeInitializeBody(id: "1"))) } + let second = Task { await transport.handleRequest(makeStatefulPOSTRequest(body: makeInitializeBody(id: "2"))) } + #expect(await eventually { await gate.arrivals == 2 }) + await gate.open() + let responses = [await first.value, await second.value] + + #expect(responses.map(\.statusCode).sorted() == [200, 400]) + let created = try #require(responses.first { $0.statusCode == 200 }) + let refused = try #require(responses.first { $0.statusCode == 400 }) + #expect(created.headers[HTTPHeaderName.sessionID] != nil) + guard case .error(_, .invalidRequest(let message), _, _, _) = refused else { + Issue.record("Expected an invalid request error, got \(refused)") + return + } + #expect(message == "Bad Request: Session already initialized") + await transport.disconnect() + } + + @Test( + "A request validated while a refused initialize drops the session gets 400 and doesn't reach the server", + .timeLimit(.minutes(1))) + func testRefusedInitializeDuringValidation() async throws { + let gate = ValidationGate() + let transport = StatefulHTTPServerTransport(validators: [ + GateValidator(gate) { _, context in context.httpMethod == "POST" && !context.isInitializationRequest }, + SessionValidator(), + ]) + try await transport.connect() + let initialize = await transport.handleRequest(makeStatefulPOSTRequest(body: makeInitializeBody(id: "1"))) + let sessionID = try #require(initialize.headers[HTTPHeaderName.sessionID]) + + let post = Task { + await transport.handleRequest(makeStatefulPOSTRequest(body: makeRequestBody(id: "2"), sessionID: sessionID)) + } + #expect(await eventually { await gate.arrivals == 1 }) + // The server refuses the initialize: the session is dropped. + try await transport.send(Data(#"{"jsonrpc":"2.0","id":"1","error":{"code":-32603,"message":"refused"}}"#.utf8)) + + await gate.open() + let response = await post.value + #expect(response.statusCode == 400) + guard case .error(_, .invalidRequest(let message), _, _, _) = response else { + Issue.record("Expected an invalid request error, got \(response)") + return + } + #expect(message == "Bad Request: Session not initialized") + + // The server saw the initialize only. + await transport.disconnect() + var received: [Data] = [] + for try await message in await transport.receive() { received.append(message) } + #expect(received.count == 1) + #expect(received.first.map { String(decoding: $0, as: UTF8.self).contains(#""initialize""#) } == true) + } + + @Test("A GET validated while the session terminates gets 404 and registers no stream", .timeLimit(.minutes(1))) + func testGetDuringTermination() async throws { + let gate = ValidationGate() + let transport = StatefulHTTPServerTransport(validators: [GateValidator(gate, method: "GET"), SessionValidator()]) + let sessionID = try await initializeSession(transport: transport) + + let get = Task { await transport.handleRequest(makeGETRequest(sessionID: sessionID)) } + #expect(await eventually { await gate.arrivals == 1 }) + await transport.disconnect() + + await gate.open() + let response = await get.value + #expect(response.statusCode == 404) + if case .stream = response { + Issue.record("A GET on a terminated session registered a stream") + } + } + + @Test("Concurrent DELETEs: one 200, then 404", .timeLimit(.minutes(1))) + func testConcurrentDeletes() async throws { + let gate = ValidationGate() + let transport = StatefulHTTPServerTransport(validators: [GateValidator(gate, method: "DELETE"), SessionValidator()]) + let sessionID = try await initializeSession(transport: transport) + + let first = Task { await transport.handleRequest(makeDELETERequest(sessionID: sessionID)) } + let second = Task { await transport.handleRequest(makeDELETERequest(sessionID: sessionID)) } + #expect(await eventually { await gate.arrivals == 2 }) + await gate.open() + + #expect([await first.value.statusCode, await second.value.statusCode].sorted() == [200, 404]) + } + + @Test("A request whose session changes during every validation run gets 503", .timeLimit(.minutes(1))) + func testSessionChangesDuringEveryValidationRun() async throws { + let gate = ValidationGate() + let transport = StatefulHTTPServerTransport(validators: [GateValidator(gate, method: "GET")]) + try await transport.connect() + + let get = Task { await transport.handleRequest(makeGETRequest(sessionID: "s")) } + #expect(await eventually { await gate.arrivals == 1 }) + // The first run saw no session; an initialize creates one. + let created = await transport.handleRequest(makeStatefulPOSTRequest(body: makeInitializeBody(id: "1"))) + #expect(created.statusCode == 200) + + await gate.releaseOne() + #expect(await eventually { await gate.arrivals == 2 }) + // The second run saw the session; refusing the initialize drops it. + try await transport.send(Data(#"{"jsonrpc":"2.0","id":"1","error":{"code":-32603,"message":"refused"}}"#.utf8)) + + await gate.releaseOne() + #expect(await eventually { await gate.arrivals == 3 }) + // The third run saw no session; another initialize creates one. + let recreated = await transport.handleRequest(makeStatefulPOSTRequest(body: makeInitializeBody(id: "3"))) + #expect(recreated.statusCode == 200) + + await gate.releaseOne() + let response = await get.value + #expect(response.statusCode == 503) + if case .stream = response { + Issue.record("A GET validated against stale session state registered a stream") + } + #expect(await gate.arrivals == 3) + await transport.disconnect() + } + // MARK: - Error Cases @Test("Unsupported method returns 405") @@ -972,7 +1233,7 @@ struct StatefulHTTPServerTransportTests { @Test("An answer without jsonrpc 2.0 gets 400 and reaches the server only once validated") func testInvalidAnswerReachesServerOnceValidated() async throws { let transport = StatefulHTTPServerTransport( - validationPipeline: StandardValidationPipeline(validators: [SessionValidator()])) + validators: [SessionValidator()]) let sessionID = try await initializeSession(transport: transport) let answer = Data(#"{"id":"r1","result":{}}"#.utf8) @@ -1059,6 +1320,463 @@ struct StatefulHTTPServerTransportTests { await server.stop() } + @Test( + "A request to the client withdrawn from outside its handler is cancelled on the handler's stream", + .timeLimit(.minutes(1))) + func testWithdrawalFollowsTheHandlersStream() async throws { + let transport = makeStatefulTransport() + let held = HeldElicitation() + let server = await HeldElicitation.makeServer(holding: held) + try await server.start(transport: transport) + + let initialize = + #"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{"elicitation":{}},"clientInfo":{"name":"c","version":"1"}}}"# + let initResponse = await transport.handleRequest(makeStatefulPOSTRequest(body: Data(initialize.utf8))) + let sessionID = try #require(initResponse.headers[HTTPHeaderName.sessionID]) + _ = try await firstMessage(of: initResponse) { $0.objectValue?["result"] != nil } + _ = await transport.handleRequest( + makeStatefulPOSTRequest( + body: Data(#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#.utf8), sessionID: sessionID)) + + // An open GET stream: a withdrawal routed by no request goes there. + let standalone = SSEMessages() + await standalone.read(await transport.handleRequest(makeGETRequest(sessionID: sessionID))) + let call = SSEMessages() + let body = #"{"jsonrpc":"2.0","id":"call-1","method":"tools/call","params":{"name":"confirm"}}"# + await call.read( + await transport.handleRequest(makeStatefulPOSTRequest(body: Data(body.utf8), sessionID: sessionID))) + #expect(await eventually { await call.first(method: CreateElicitation.name) != nil }) + let elicitationID = try #require(await call.first(method: CreateElicitation.name)?.objectValue?["id"]) + #expect(await eventually { await held.isHeld }) + + // The test task handles no client request. + await held.cancel() + #expect(await eventually { await call.methods.contains("result") }) + #expect(await call.methods == [CreateElicitation.name, CancelledNotification.name, "result"]) + let cancelled = await call.first(method: CancelledNotification.name) + #expect(cancelled?.objectValue?["params"]?.objectValue?["requestId"] == elicitationID) + #expect(await standalone.first(method: CancelledNotification.name) == nil) + + await call.stop() + await standalone.stop() + await server.stop() + } + + @Test( + "Delayed withdrawal send finishes on the handler's stream before the parent response closes it", + .timeLimit(.minutes(1))) + func testDelayedWithdrawalPrecedesParentResponse() async throws { + let transport = makeStatefulTransport() + let gated = GatedSendTransport(transport, gatingMethod: CancelledNotification.name) + defer { Task { await gated.release() } } + let held = HeldElicitation() + let server = await HeldElicitation.makeServer(holding: held) + try await server.start(transport: gated) + + let initialize = + #"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{"elicitation":{}},"clientInfo":{"name":"c","version":"1"}}}"# + let initResponse = await transport.handleRequest(makeStatefulPOSTRequest(body: Data(initialize.utf8))) + let sessionID = try #require(initResponse.headers[HTTPHeaderName.sessionID]) + _ = try await firstMessage(of: initResponse) { $0.objectValue?["result"] != nil } + _ = await transport.handleRequest( + makeStatefulPOSTRequest( + body: Data(#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#.utf8), sessionID: sessionID)) + + let standalone = SSEMessages() + await standalone.read(await transport.handleRequest(makeGETRequest(sessionID: sessionID))) + let call = SSEMessages() + let body = #"{"jsonrpc":"2.0","id":"call-1","method":"tools/call","params":{"name":"confirm"}}"# + await call.read( + await transport.handleRequest(makeStatefulPOSTRequest(body: Data(body.utf8), sessionID: sessionID))) + #expect(await eventually { await call.first(method: CreateElicitation.name) != nil }) + let elicitationID = try #require(await call.first(method: CreateElicitation.name)?.objectValue?["id"]) + #expect(await eventually { await held.isHeld }) + + await held.cancel() + try #require(await eventually { await gated.isHeld }) + + // A ping completes while notifications/cancelled is held at the gate: + // the tools/call handler must not have sent its result and closed the stream. + let pingBody = #"{"jsonrpc":"2.0","id":"sync-ping","method":"ping"}"# + let pingResponse = await transport.handleRequest( + makeStatefulPOSTRequest(body: Data(pingBody.utf8), sessionID: sessionID)) + _ = try await firstMessage(of: pingResponse) { $0.objectValue?["id"] == .string("sync-ping") } + #expect(await call.methods == [CreateElicitation.name]) + + await gated.release() + #expect(await eventually { await call.methods.contains("result") }) + #expect(await call.methods == [CreateElicitation.name, CancelledNotification.name, "result"]) + let cancelled = await call.first(method: CancelledNotification.name) + #expect(cancelled?.objectValue?["params"]?.objectValue?["requestId"] == elicitationID) + #expect(await standalone.first(method: CancelledNotification.name) == nil) + + await call.stop() + await standalone.stop() + await server.stop() + } + + @Test( + "In-flight withdrawal from a tool handler preserves relatedRequestID and waits for the withdrawal send before resuming", + .timeLimit(.minutes(1))) + func testInFlightWithdrawalPreservesRelatedRequestIDAndWaitsBeforeResuming() async throws { + let transport = makeStatefulTransport() + let gated = GatedSendTransport( + transport, gatingMethods: [CreateElicitation.name, CancelledNotification.name]) + defer { Task { await gated.release() } } + + let held = HeldElicitation() + let handlerResumed = Flag() + let server = Server(name: "s", version: "1", capabilities: .init(tools: .init())) + await server.withMethodHandler(CallTool.self) { [weak server] _ in + guard let server else { throw MCPError.internalError("The server is gone") } + let elicitation = Task { + try await server.requestElicitation(message: "Confirm?", requestedSchema: .init()) + } + await held.hold(elicitation) + _ = try? await elicitation.value + await handlerResumed.set() + return CallTool.Result(content: []) + } + try await server.start(transport: gated) + + let initialize = + #"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{"elicitation":{}},"clientInfo":{"name":"c","version":"1"}}}"# + let initResponse = await transport.handleRequest(makeStatefulPOSTRequest(body: Data(initialize.utf8))) + let sessionID = try #require(initResponse.headers[HTTPHeaderName.sessionID]) + _ = try await firstMessage(of: initResponse) { $0.objectValue?["result"] != nil } + _ = await transport.handleRequest( + makeStatefulPOSTRequest( + body: Data(#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#.utf8), sessionID: sessionID)) + + let standalone = SSEMessages() + await standalone.read(await transport.handleRequest(makeGETRequest(sessionID: sessionID))) + let call = SSEMessages() + let body = #"{"jsonrpc":"2.0","id":"call-1","method":"tools/call","params":{"name":"confirm"}}"# + await call.read( + await transport.handleRequest(makeStatefulPOSTRequest(body: Data(body.utf8), sessionID: sessionID))) + + try #require(await eventually { await gated.isHeld(method: CreateElicitation.name) }) + try #require(await eventually { await held.isHeld }) + + // Cancel while the initial requestElicitation send is still in flight. + await held.cancel() + try #require(await eventually { await server.pendingWithdrawalCount == 1 }) + #expect(await !gated.forwardedMethods.contains(CancelledNotification.name)) + #expect(await !handlerResumed.isSet) + + // Release the initial request send: the deferred withdrawal send begins and pauses at the second gate. + await gated.release(method: CreateElicitation.name) + try #require(await eventually { await gated.isHeld(method: CancelledNotification.name) }) + #expect(await eventually { await call.first(method: CreateElicitation.name) != nil }) + let elicitationID = try #require(await call.first(method: CreateElicitation.name)?.objectValue?["id"]) + + // While the deferred withdrawal send is held, the handler must not resume or send its result. + let pingBody = #"{"jsonrpc":"2.0","id":"sync-ping","method":"ping"}"# + let pingResponse = await transport.handleRequest( + makeStatefulPOSTRequest(body: Data(pingBody.utf8), sessionID: sessionID)) + _ = try await firstMessage(of: pingResponse) { $0.objectValue?["id"] == .string("sync-ping") } + #expect(await !handlerResumed.isSet) + #expect(await call.methods == [CreateElicitation.name]) + + // Release the deferred withdrawal send: it carries the parent call's relatedRequestID, + // delivers on the call's stream, and only then does the handler resume and send its result. + await gated.release(method: CancelledNotification.name) + #expect(await eventually { await call.methods.contains("result") }) + try #require(await eventually { await server.inFlightSendCount == 0 }) + #expect(await handlerResumed.isSet) + #expect(await gated.options(forMethod: CancelledNotification.name)?.relatedRequestID == .string("call-1")) + #expect(await call.methods == [CreateElicitation.name, CancelledNotification.name, "result"]) + let cancelled = await call.first(method: CancelledNotification.name) + #expect(cancelled?.objectValue?["params"]?.objectValue?["requestId"] == elicitationID) + #expect(await standalone.first(method: CancelledNotification.name) == nil) + + await call.stop() + await standalone.stop() + await server.stop() + } + + @Test( + "Deprecated Server.cancelRequest invoked outside a tool handler routes notifications/cancelled on the handler's stream", + .timeLimit(.minutes(1))) + @available(*, deprecated, message: "Tests the deprecated Server.cancelRequest shim") + func testDeprecatedServerCancelRequestPreservesOriginatingStream() async throws { + actor RequestIDBox { + private(set) var id: ID? + func set(_ id: ID) { self.id = id } + } + + let transport = makeStatefulTransport() + let idBox = RequestIDBox() + let server = Server(name: "s", version: "1", capabilities: .init(tools: .init())) + await server.withMethodHandler(CallTool.self) { [weak server] _ in + guard let server else { throw MCPError.internalError("The server is gone") } + let request = CreateElicitation.request(.form(.init(message: "Confirm?", requestedSchema: .init()))) + let pendingTask = try await server.send(request) + await idBox.set(request.id) + _ = try? await pendingTask.value + return CallTool.Result(content: []) + } + try await server.start(transport: transport) + + let initialize = + #"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{"elicitation":{}},"clientInfo":{"name":"c","version":"1"}}}"# + let initResponse = await transport.handleRequest(makeStatefulPOSTRequest(body: Data(initialize.utf8))) + let sessionID = try #require(initResponse.headers[HTTPHeaderName.sessionID]) + _ = try await firstMessage(of: initResponse) { $0.objectValue?["result"] != nil } + _ = await transport.handleRequest( + makeStatefulPOSTRequest( + body: Data(#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#.utf8), sessionID: sessionID)) + + let standalone = SSEMessages() + await standalone.read(await transport.handleRequest(makeGETRequest(sessionID: sessionID))) + let call = SSEMessages() + let body = #"{"jsonrpc":"2.0","id":"call-1","method":"tools/call","params":{"name":"confirm"}}"# + await call.read( + await transport.handleRequest(makeStatefulPOSTRequest(body: Data(body.utf8), sessionID: sessionID))) + #expect(await eventually { await call.first(method: CreateElicitation.name) != nil }) + let elicitationJSONID = try #require(await call.first(method: CreateElicitation.name)?.objectValue?["id"]) + try #require(await eventually { await idBox.id != nil }) + try #require(await eventually { await server.inFlightSendCount == 0 }) + let elicitationID = try #require(await idBox.id) + + // Invoked from a detached task with no handler context: must still route on call-1's stream. + try await Task.detached { + try await server.cancelRequest(elicitationID, reason: "outside-handler") + }.value + + #expect(await eventually { await call.methods.contains("result") }) + #expect(await call.methods == [CreateElicitation.name, CancelledNotification.name, "result"]) + let cancelled = await call.first(method: CancelledNotification.name) + #expect(cancelled?.objectValue?["params"]?.objectValue?["requestId"] == elicitationJSONID) + #expect(await standalone.first(method: CancelledNotification.name) == nil) + + await call.stop() + await standalone.stop() + await server.stop() + } + + @Test( + "Deprecated Server.cancelRequest during an in-flight send preserves the originating stream route", + .timeLimit(.minutes(1))) + @available(*, deprecated, message: "Tests the deprecated Server.cancelRequest shim") + func testDeprecatedServerCancelRequestInFlightPreservesOriginatingStream() async throws { + actor RequestIDBox { + private(set) var id: ID? + func set(_ id: ID) { self.id = id } + } + actor MethodGateTransport: TransportWrapper { + nonisolated let wrapped: any Transport + private var gatingMethod: String? + private var continuation: CheckedContinuation? + private var released = false + + init(_ wrapped: any Transport, gatingMethod: String) { + self.wrapped = wrapped + self.gatingMethod = gatingMethod + } + + var isHeld: Bool { continuation != nil } + + func send(_ data: Data, options: TransportSendOptions) async throws { + let method = (try? JSONDecoder().decode(Value.self, from: data))?.objectValue?["method"]?.stringValue + if let target = gatingMethod, method == target { + gatingMethod = nil + if !released { + await withCheckedContinuation { continuation = $0 } + } + } + try await wrapped.send(data, options: options) + } + + func release() { + released = true + continuation?.resume() + continuation = nil + } + } + + let transport = makeStatefulTransport() + let gated = MethodGateTransport(transport, gatingMethod: CreateElicitation.name) + defer { Task { await gated.release() } } + let idBox = RequestIDBox() + let server = Server(name: "s", version: "1", capabilities: .init(tools: .init())) + await server.withMethodHandler(CallTool.self) { [weak server] _ in + guard let server else { throw MCPError.internalError("The server is gone") } + let request = CreateElicitation.request(.form(.init(message: "Confirm?", requestedSchema: .init()))) + let pendingTask = try await server.send(request) + await idBox.set(request.id) + _ = try? await pendingTask.value + return CallTool.Result(content: []) + } + try await server.start(transport: gated) + + let initialize = + #"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{"elicitation":{}},"clientInfo":{"name":"c","version":"1"}}}"# + let initResponse = await transport.handleRequest(makeStatefulPOSTRequest(body: Data(initialize.utf8))) + let sessionID = try #require(initResponse.headers[HTTPHeaderName.sessionID]) + _ = try await firstMessage(of: initResponse) { $0.objectValue?["result"] != nil } + _ = await transport.handleRequest( + makeStatefulPOSTRequest( + body: Data(#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#.utf8), sessionID: sessionID)) + + let standalone = SSEMessages() + await standalone.read(await transport.handleRequest(makeGETRequest(sessionID: sessionID))) + let call = SSEMessages() + let body = #"{"jsonrpc":"2.0","id":"call-1","method":"tools/call","params":{"name":"confirm"}}"# + await call.read( + await transport.handleRequest(makeStatefulPOSTRequest(body: Data(body.utf8), sessionID: sessionID))) + try #require(await eventually { await gated.isHeld }) + try #require(await eventually { await idBox.id != nil }) + let elicitationID = try #require(await idBox.id) + + // Cancel while CreateElicitation is still in flight, from a detached task with no handler context: + // transitions to .withdrawnWhileSending and preserves the originating call-1 stream route. + try await Task.detached { + try await server.cancelRequest(elicitationID, reason: "in-flight-outside-handler") + }.value + #expect(await server.pendingWithdrawalCount == 1) + #expect(await call.first(method: CancelledNotification.name) == nil) + #expect(await standalone.first(method: CancelledNotification.name) == nil) + + await gated.release() + #expect(await eventually { await call.methods.contains("result") }) + #expect(await call.methods == [CreateElicitation.name, CancelledNotification.name, "result"]) + let elicitationJSONID = try #require(await call.first(method: CreateElicitation.name)?.objectValue?["id"]) + let cancelled = await call.first(method: CancelledNotification.name) + #expect(cancelled?.objectValue?["params"]?.objectValue?["requestId"] == elicitationJSONID) + #expect(cancelled?.objectValue?["params"]?.objectValue?["reason"] == .string("in-flight-outside-handler")) + #expect(await standalone.first(method: CancelledNotification.name) == nil) + + await call.stop() + await standalone.stop() + await server.stop() + } + + @Test( + "Parent-request cancellation routes the elicitation withdrawal to the standalone GET stream", + .timeLimit(.minutes(1))) + func testParentCancellationRoutesWithdrawalToGetStream() async throws { + let transport = makeStatefulTransport() + let server = Server(name: "s", version: "1", capabilities: .init(tools: .init())) + let handlerCancelled = Flag() + await server.withMethodHandler(CallTool.self) { [weak server] _ in + guard let server else { throw MCPError.internalError("The server is gone") } + do { + _ = try await server.requestElicitation(message: "Confirm?", requestedSchema: .init()) + } catch is CancellationError { + await handlerCancelled.set() + throw CancellationError() + } + return CallTool.Result(content: []) + } + try await server.start(transport: transport) + + let initialize = + #"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{"elicitation":{}},"clientInfo":{"name":"c","version":"1"}}}"# + let initResponse = await transport.handleRequest(makeStatefulPOSTRequest(body: Data(initialize.utf8))) + let sessionID = try #require(initResponse.headers[HTTPHeaderName.sessionID]) + _ = try await firstMessage(of: initResponse) { $0.objectValue?["result"] != nil } + _ = await transport.handleRequest( + makeStatefulPOSTRequest( + body: Data(#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#.utf8), sessionID: sessionID)) + + let standalone = SSEMessages() + await standalone.read(await transport.handleRequest(makeGETRequest(sessionID: sessionID))) + let call = SSEMessages() + let body = #"{"jsonrpc":"2.0","id":"call-1","method":"tools/call","params":{"name":"confirm"}}"# + await call.read( + await transport.handleRequest(makeStatefulPOSTRequest(body: Data(body.utf8), sessionID: sessionID))) + #expect(await eventually { await call.first(method: CreateElicitation.name) != nil }) + let elicitationID = try #require(await call.first(method: CreateElicitation.name)?.objectValue?["id"]) + + let cancelBody = + #"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"call-1","reason":"User cancelled"}}"# + let cancelResponse = await transport.handleRequest( + makeStatefulPOSTRequest(body: Data(cancelBody.utf8), sessionID: sessionID)) + #expect(cancelResponse.statusCode == 202) + + #expect(await eventually { await handlerCancelled.isSet }) + #expect(await eventually { await call.isFinished }) + #expect(await eventually { await standalone.first(method: CancelledNotification.name) != nil }) + #expect(await call.methods == [CreateElicitation.name]) + let withdrawal = await standalone.first(method: CancelledNotification.name) + #expect(withdrawal?.objectValue?["params"]?.objectValue?["requestId"] == elicitationID) + + await call.stop() + await standalone.stop() + await server.stop() + } + + @Test( + "Parent-request cancellation stores the elicitation withdrawal for GET replay when no GET stream is open", + .timeLimit(.minutes(1))) + func testParentCancellationReplaysWithdrawalWithoutGetStream() async throws { + let transport = makeStatefulTransport() + let server = Server(name: "s", version: "1", capabilities: .init(tools: .init())) + let handlerCancelled = Flag() + await server.withMethodHandler(CallTool.self) { [weak server] _ in + guard let server else { throw MCPError.internalError("The server is gone") } + do { + _ = try await server.requestElicitation(message: "Confirm?", requestedSchema: .init()) + } catch is CancellationError { + await handlerCancelled.set() + throw CancellationError() + } + return CallTool.Result(content: []) + } + try await server.start(transport: transport) + + let initialize = + #"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{"elicitation":{}},"clientInfo":{"name":"c","version":"1"}}}"# + let initResponse = await transport.handleRequest(makeStatefulPOSTRequest(body: Data(initialize.utf8))) + let sessionID = try #require(initResponse.headers[HTTPHeaderName.sessionID]) + _ = try await firstMessage(of: initResponse) { $0.objectValue?["result"] != nil } + _ = await transport.handleRequest( + makeStatefulPOSTRequest( + body: Data(#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#.utf8), sessionID: sessionID)) + + // Open a GET stream only long enough to obtain its priming event ID, then disconnect it. + let initialGet = SSEMessages() + await initialGet.read(await transport.handleRequest(makeGETRequest(sessionID: sessionID))) + #expect(await eventually { await initialGet.firstEventID != nil }) + let primingID = try #require(await initialGet.firstEventID) + await initialGet.stop() + #expect(await eventually { await initialGet.isFinished }) + + let call = SSEMessages() + let body = #"{"jsonrpc":"2.0","id":"call-1","method":"tools/call","params":{"name":"confirm"}}"# + await call.read( + await transport.handleRequest(makeStatefulPOSTRequest(body: Data(body.utf8), sessionID: sessionID))) + #expect(await eventually { await call.first(method: CreateElicitation.name) != nil }) + let elicitationID = try #require(await call.first(method: CreateElicitation.name)?.objectValue?["id"]) + + let cancelBody = + #"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"call-1","reason":"User cancelled"}}"# + let cancelResponse = await transport.handleRequest( + makeStatefulPOSTRequest(body: Data(cancelBody.utf8), sessionID: sessionID)) + #expect(cancelResponse.statusCode == 202) + + #expect(await eventually { await handlerCancelled.isSet }) + #expect(await eventually { await call.isFinished }) + #expect(await eventually { await transport.storedEventIDs.contains { $0.hasPrefix("g_") } }) + #expect(await initialGet.messages.isEmpty) + #expect(await call.methods == [CreateElicitation.name]) + + // Reconnect GET with Last-Event-ID and verify the withdrawal is replayed. + let resumedResponse = await transport.handleRequest( + makeGETRequest(sessionID: sessionID, lastEventID: primingID)) + #expect(resumedResponse.statusCode == 200) + let resumed = SSEMessages() + await resumed.read(resumedResponse) + #expect(await eventually { await resumed.first(method: CancelledNotification.name) != nil }) + let withdrawal = await resumed.first(method: CancelledNotification.name) + #expect(withdrawal?.objectValue?["params"]?.objectValue?["requestId"] == elicitationID) + + await call.stop() + await resumed.stop() + await server.stop() + } + @Test("A request with a result or an error is accepted and reaches the server only when it reads as a response") func testRequestWithAnswerReachesServerAsResponseOnly() async throws { let transport = makeStatefulTransport() @@ -1401,7 +2119,7 @@ struct StatefulHTTPServerTransportTests { let requestID = "cancel-1" let post = await transport.handleRequest( makeStatefulPOSTRequest(body: makeRequestBody(id: requestID), sessionID: sessionID)) - #expect(await transport.httpRequestContext(for: .string(requestID)) != nil) + #expect(await transport.httpRequest(for: .string(requestID)) != nil) let cancel = try JSONSerialization.data(withJSONObject: [ "jsonrpc": "2.0", "method": "notifications/cancelled", @@ -1412,7 +2130,7 @@ struct StatefulHTTPServerTransportTests { #expect(accepted.statusCode == 202) #expect(await readToEnd(post) != nil) - #expect(await transport.httpRequestContext(for: .string(requestID)) == nil) + #expect(await transport.httpRequest(for: .string(requestID)) == nil) // Later related messages go to the GET stream. let get = await transport.handleRequest(makeGETRequest(sessionID: sessionID)) @@ -1432,7 +2150,7 @@ struct StatefulHTTPServerTransportTests { "jsonrpc": "2.0", "method": "notifications/message", "params": ["level": "info", "data": "after-cancel"] as [String: Any], ]) - try await transport.send(notification, relatedRequestID: .string(requestID)) + try await transport.send(notification, options: TransportSendOptions(relatedRequestID: .string(requestID))) #expect(try await getTask.value.contains("after-cancel")) await transport.disconnect() } @@ -1489,31 +2207,205 @@ struct StatefulHTTPServerTransportTests { await transport.disconnect() } + // MARK: - Typed request IDs + + @Test("Requests with ids 1 and \"1\" get their own streams and responses") + func testNumberAndStringIDsAreDistinct() async throws { + let transport = makeStatefulTransport() + let sessionID = try await initializeSession(transport: transport) + + func post(id json: String) async -> HTTPResponse { + await transport.handleRequest( + makeStatefulPOSTRequest( + body: Data(#"{"jsonrpc":"2.0","id":\#(json),"method":"tools/list","params":{}}"#.utf8), + sessionID: sessionID)) + } + let number = await post(id: "1") + let string = await post(id: #""1""#) + #expect(number.statusCode == 200) + #expect(string.statusCode == 200) + #expect(await transport.httpRequest(for: .number(1)) != nil) + #expect(await transport.httpRequest(for: .string("1")) != nil) + + try await transport.send(Data(#"{"jsonrpc":"2.0","id":"1","result":{"answer":"string"}}"#.utf8)) + #expect(await transport.httpRequest(for: .number(1)) != nil) + try await transport.send(Data(#"{"jsonrpc":"2.0","id":1,"result":{"answer":"number"}}"#.utf8)) + + let numberText = try #require(await readToEnd(number)) + let stringText = try #require(await readToEnd(string)) + #expect(numberText.contains(#""answer":"number""#)) + #expect(!numberText.contains(#""answer":"string""#)) + #expect(stringText.contains(#""answer":"string""#)) + #expect(!stringText.contains(#""answer":"number""#)) + await transport.disconnect() + } + + @Test("Requests with canonically equivalent string ids get their own streams and responses") + func testCanonicallyEquivalentIDsAreDistinct() async throws { + let transport = makeStatefulTransport() + let sessionID = try await initializeSession(transport: transport) + + func post(id json: String) async -> HTTPResponse { + await transport.handleRequest( + makeStatefulPOSTRequest( + body: Data(#"{"jsonrpc":"2.0","id":"\#(json)","method":"tools/list","params":{}}"#.utf8), + sessionID: sessionID)) + } + // U+00E9, and e with U+0301: equal as Swift strings, different ids. + let precomposed = await post(id: #"\u00e9"#) + let decomposed = await post(id: #"e\u0301"#) + #expect(precomposed.statusCode == 200) + #expect(decomposed.statusCode == 200) + #expect(await transport.httpRequest(for: .string("\u{E9}")) != nil) + #expect(await transport.httpRequest(for: .string("e\u{301}")) != nil) + + try await transport.send(Data(#"{"jsonrpc":"2.0","id":"e\u0301","result":{"answer":"decomposed"}}"#.utf8)) + #expect(await transport.httpRequest(for: .string("\u{E9}")) != nil) + try await transport.send(Data(#"{"jsonrpc":"2.0","id":"\u00e9","result":{"answer":"precomposed"}}"#.utf8)) + + let precomposedText = try #require(await readToEnd(precomposed)) + let decomposedText = try #require(await readToEnd(decomposed)) + #expect(precomposedText.contains(#""answer":"precomposed""#)) + #expect(!precomposedText.contains(#""answer":"decomposed""#)) + #expect(decomposedText.contains(#""answer":"decomposed""#)) + #expect(!decomposedText.contains(#""answer":"precomposed""#)) + await transport.disconnect() + } + + @Test("A request with the id _GET_stream doesn't replace the standalone stream", .timeLimit(.minutes(1))) + func testRequestIDDoesNotTakeOverStandaloneStream() async throws { + let transport = makeStatefulTransport() + let sessionID = try await initializeSession(transport: transport) + + let get = await transport.handleRequest(makeGETRequest(sessionID: sessionID)) + guard case .stream(let getStream, _) = get else { + Issue.record("Expected .stream response for GET") + return + } + let getTask = Task { + var text = "" + for try await chunk in getStream { + text += String(decoding: chunk, as: UTF8.self) + if text.contains("after-response") { break } + } + return text + } + + let requestID = "_GET_stream" + let post = await transport.handleRequest( + makeStatefulPOSTRequest(body: makeRequestBody(id: requestID), sessionID: sessionID)) + #expect(post.statusCode == 200) + + func notify(_ marker: String) async throws { + try await transport.send( + Data(#"{"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","data":"\#(marker)"}}"#.utf8)) + } + try await notify("before-response") + try await transport.send(makeResponseBody(id: requestID)) + try await notify("after-response") + + let getText = try await getTask.value + #expect(getText.contains("before-response")) + #expect(getText.contains("after-response")) + let postText = try #require(await readToEnd(post)) + #expect(postText.contains(#""tools""#)) + #expect(!postText.contains("before-response")) + await transport.disconnect() + } + + @Test("Event IDs of a string request id are percent-encoded and resume") + func testStringRequestIDEventIDsArePercentEncoded() async throws { + let transport = makeStatefulTransport() + let sessionID = try await initializeSession(transport: transport) + + let requestID = "a_b\nc" + let post = await transport.handleRequest( + makeStatefulPOSTRequest(body: makeRequestBody(id: requestID), sessionID: sessionID)) + guard case .stream(let postStream, _) = post else { + Issue.record("Expected .stream response for POST") + return + } + var iterator = postStream.makeAsyncIterator() + let priming = try #require(try await iterator.next()) + // The request id's LF would end the `id:` line and start another. + let lines = String(decoding: priming, as: UTF8.self).split(separator: "\n") + #expect(lines.allSatisfy { $0.hasPrefix("id: ") || $0.hasPrefix("retry: ") || $0.hasPrefix("data:") }) + let primingID = try #require(primingEventID(priming)) + #expect(primingID.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber || "%_".contains($0)) }) + + await transport.closeSSEStream(forRequestID: .string(requestID)) + #expect(try await iterator.next() == nil) + try await transport.send(makeResponseBody(id: requestID)) + + // Another spelling of the same stream is not an event ID the + // transport made. + let respelled = await transport.handleRequest( + makeGETRequest(sessionID: sessionID, lastEventID: primingID.lowercased())) + #expect(respelled.statusCode == 400) + + let resumed = await transport.handleRequest( + makeGETRequest(sessionID: sessionID, lastEventID: primingID)) + #expect(resumed.statusCode == 200) + #expect(await readToEnd(resumed)?.contains(#""tools""#) == true) + await transport.disconnect() + } + + @Test( + "A request's stream resumes from its priming event ID", + arguments: [ID.number(1), -1, "", "a_b\nc", "é"]) + func testRequestStreamResumes(id: ID) async throws { + let transport = makeStatefulTransport() + let sessionID = try await initializeSession(transport: transport) + let idJSON = String(decoding: try JSONEncoder().encode(id), as: UTF8.self) + + let post = await transport.handleRequest( + makeStatefulPOSTRequest( + body: Data(#"{"jsonrpc":"2.0","id":\#(idJSON),"method":"tools/list","params":{}}"#.utf8), + sessionID: sessionID)) + guard case .stream(let postStream, _) = post else { + Issue.record("Expected .stream response for POST") + return + } + var iterator = postStream.makeAsyncIterator() + let primingID = try #require(try await iterator.next().flatMap(primingEventID)) + await transport.closeSSEStream(forRequestID: id) + #expect(try await iterator.next() == nil) + try await transport.send(Data(#"{"jsonrpc":"2.0","id":\#(idJSON),"result":{"tools":[]}}"#.utf8)) + + let resumed = await transport.handleRequest(makeGETRequest(sessionID: sessionID, lastEventID: primingID)) + #expect(resumed.statusCode == 200) + #expect(await readToEnd(resumed)?.contains(#""tools""#) == true) + await transport.disconnect() + } + @Test("The replay store keeps the newest events only") func testEventStoreCapacity() async throws { let transport = StatefulHTTPServerTransport( - validationPipeline: StandardValidationPipeline(validators: []), eventStoreCapacity: 2) + validators: [], eventStoreCapacity: 2) let sessionID = try await initializeSession(transport: transport) - // No GET stream is open: each message is stored for replay. + // No GET stream is open: each message is stored for replay. Send 4 + // so both `first` and `second` are evicted and `first` has an evicted + // positive counter before `second`. let notification = makeNotificationBody(method: "notifications/tools/list_changed") try await transport.send(notification) let first = try #require(await transport.storedEventIDs.last) try await transport.send(notification) + let second = try #require(await transport.storedEventIDs.last) + try await transport.send(notification) try await transport.send(notification) let eventIDs = await transport.storedEventIDs #expect(eventIDs.count == 2) #expect(!eventIDs.contains(first)) + #expect(!eventIDs.contains(second)) - // Resuming from before a dropped event fails; from the dropped + // Resuming from before a dropped event fails; from the newest dropped // event itself, nothing after it is lost. - let separator = try #require(first.lastIndex(of: "_")) - let prefix = first[.. HTTPResponse? { + if let gate { await gate.wait() } + await log.append(name) + return response + } +} + +@Suite("HTTP request validators") +struct HTTPRequestValidatorTests { + @Test("defaultValidators are the documented validators, in order") + func defaultValidators() throws { + let localhost = OriginValidator.localhost() + + let stateful = StatefulHTTPServerTransport.defaultValidators + #expect( + stateful.map { "\(type(of: $0))" } == [ + "OriginValidator", "AcceptHeaderValidator", "ContentTypeValidator", "ProtocolVersionValidator", + "SessionValidator", + ]) + let statefulOrigin = try #require(stateful.first as? OriginValidator) + #expect(statefulOrigin.allowedHosts == localhost.allowedHosts) + #expect(statefulOrigin.allowedOrigins == localhost.allowedOrigins) + #expect((stateful[1] as? AcceptHeaderValidator)?.mode == .sseRequired) + + let stateless = StatelessHTTPServerTransport.defaultValidators + #expect( + stateless.map { "\(type(of: $0))" } == [ + "OriginValidator", "AcceptHeaderValidator", "ContentTypeValidator", "ProtocolVersionValidator", + ]) + let statelessOrigin = try #require(stateless.first as? OriginValidator) + #expect(statelessOrigin.allowedHosts == localhost.allowedHosts) + #expect(statelessOrigin.allowedOrigins == localhost.allowedOrigins) + #expect((stateless[1] as? AcceptHeaderValidator)?.mode == .jsonOnly) + } + + @Test( + "StandardValidationPipeline awaits its validators in order and stops at the first response", + .timeLimit(.minutes(1))) + func pipelineOrder() async throws { + let log = ValidatorLog() + let gate = ValidationGate() + let pipeline = StandardValidationPipeline(validators: [ + RecordingValidator(name: "first", log: log, gate: gate), + RecordingValidator(name: "second", log: log, response: .error(statusCode: 403, .invalidRequest("no"))), + RecordingValidator(name: "third", log: log), + ]) + let validation = Task { + await pipeline.validate( + HTTPRequest(method: "POST", path: "/mcp"), context: HTTPValidationContext(httpMethod: "POST")) + } + #expect(await eventually { await gate.arrivals == 1 }) + // The second validator waits for the first. + #expect(await log.names.isEmpty) + + await gate.open() + #expect(await validation.value?.statusCode == 403) + #expect(await log.names == ["first", "second"]) + } +} + +// MARK: - Suspension Probes + +/// Records that a job ran. +private final class JobMark: Sendable { + private let state = Mutex(false) + var isSet: Bool { state.withLock { $0 } } + func set() { state.withLock { $0 = true } } +} + +/// Tells whether a call suspends: a job enqueued on the probe's actor +/// before the call can run only while the call is suspended. +private actor SuspensionProbe { + func otherJobRan(during validation: StandardValidationPipeline, request: HTTPRequest) async -> Bool { + let mark = JobMark() + let other = Task { self.run(mark) } + _ = await validation.validateInline(request, context: HTTPValidationContext(httpMethod: request.method)) + let ran = mark.isSet + await other.value + return ran + } + + /// The same through the public, nonisolated `validate`, which leaves + /// the actor. + func otherJobRan(duringPublicValidate validation: StandardValidationPipeline, request: HTTPRequest) async -> Bool { + let mark = JobMark() + let other = Task { self.run(mark) } + _ = await validation.validate(request, context: HTTPValidationContext(httpMethod: request.method)) + let ran = mark.isSet + await other.value + return ran + } + + private func run(_ mark: JobMark) { mark.set() } +} + +extension StatefulHTTPServerTransport { + /// Handles `request`, and tells whether another job on the transport ran + /// meanwhile, which it can only while the handling is suspended. + fileprivate func handleRequestReportingSuspension(_ request: HTTPRequest) async -> (HTTPResponse, suspended: Bool) { + let mark = JobMark() + let other = Task { self.run(mark) } + let response = await handleRequest(request) + let suspended = mark.isSet + await other.value + return (response, suspended) + } + + private func run(_ mark: JobMark) { mark.set() } +} + +extension StatelessHTTPServerTransport { + /// Handles `request`, and tells whether another job on the transport ran + /// meanwhile, which it can only while the handling is suspended. + fileprivate func handleRequestReportingSuspension(_ request: HTTPRequest) async -> (HTTPResponse, suspended: Bool) { + let mark = JobMark() + let other = Task { self.run(mark) } + let response = await handleRequest(request) + let suspended = mark.isSet + await other.value + return (response, suspended) + } + + private func run(_ mark: JobMark) { mark.set() } +} + +@Suite("HTTP request validation without suspension") +struct SynchronousValidationTests { + @Test("The default validators run without suspending, and an async validator suspends") + func pipelineRunsSynchronousValidatorsInline() async { + let probe = SuspensionProbe() + let post = makeStatefulPOSTRequest(body: makeRequestBody(), sessionID: "s") + for defaults in [StatefulHTTPServerTransport.defaultValidators, StatelessHTTPServerTransport.defaultValidators] { + // Nested in a pipeline too: its members run inline as well. + let nested = StandardValidationPipeline(validators: [StandardValidationPipeline(validators: defaults)]) + #expect(await probe.otherJobRan(during: nested, request: post) == false) + // The probe sees the suspension of the public `validate`. + #expect(await probe.otherJobRan(duringPublicValidate: nested, request: post) == true) + } + let bearer = BearerTokenValidator( + resourceMetadataURL: authResourceMetadataURL, resourceIdentifier: authResourceIdentifier, + tokenValidator: { _, _, _ in .valid(BearerTokenInfo()) }) + let withBearer = StandardValidationPipeline(validators: [bearer]) + #expect(await probe.otherJobRan(during: withBearer, request: post) == true) + } + + @Test("With the default validators the stateful transport handles a request without suspending") + func statefulHandlesRequestsAtomically() async throws { + let transport = StatefulHTTPServerTransport() + try await transport.connect() + let (response, suspended) = await transport.handleRequestReportingSuspension( + makeStatefulPOSTRequest(body: makeInitializeBody())) + #expect(response.statusCode == 200) + #expect(suspended == false) + await transport.disconnect() + + // The probe sees a suspension when a validator awaits. + let authenticated = makeAuthenticatedStatefulTransport { _, _, _ in .valid(BearerTokenInfo()) } + try await authenticated.connect() + let (_, awaited) = await authenticated.handleRequestReportingSuspension( + makeStatefulPOSTRequest(body: makeInitializeBody(), authorization: "Bearer t")) + #expect(awaited == true) + await authenticated.disconnect() + } + + @Test("With the default validators the stateless transport handles a notification without suspending") + func statelessHandlesRequestsAtomically() async throws { + let transport = StatelessHTTPServerTransport() + try await transport.connect() + let (response, suspended) = await transport.handleRequestReportingSuspension( + makeStatelessPOSTRequest(body: makeNotificationBody())) + #expect(response.statusCode == 202) + #expect(suspended == false) + await transport.disconnect() + } +} diff --git a/Tests/MCPTests/Helpers/EndableTransport.swift b/Tests/MCPTests/Helpers/EndableTransport.swift index 7dd1e362..4b6bc67f 100644 --- a/Tests/MCPTests/Helpers/EndableTransport.swift +++ b/Tests/MCPTests/Helpers/EndableTransport.swift @@ -45,6 +45,11 @@ actor EndableTransport: Transport { private var buffered: [Data] = [] private var holdsNextDisconnect = false private var heldDisconnect: CheckedContinuation? + private var holdsNextConnect = false + private var heldConnect: CheckedContinuation? + private var onPrepare: (@Sendable () async -> Void)? + private var holdsNextSend = false + private var heldSend: CheckedContinuation? private let encoder = JSONEncoder() private let decoder = JSONDecoder() @@ -63,7 +68,39 @@ actor EndableTransport: Transport { self.continuation = mode == .shared ? continuation : nil } - func connect() async throws {} + func setOnPrepare(_ handler: (@Sendable () async -> Void)?) { + onPrepare = handler + } + + func prepare(servingProtocolVersions versions: [String]) async { + let handler = onPrepare + onPrepare = nil + await handler?() + } + + func connect() async throws { + guard holdsNextConnect else { return } + holdsNextConnect = false + try await withCheckedThrowingContinuation { heldConnect = $0 } + } + + /// Makes the next `connect()` wait until `releaseHeldConnect(throwing:)`. + func holdNextConnect() { + holdsNextConnect = true + } + + /// Whether a `connect()` waits for `releaseHeldConnect(throwing:)`. + var isConnectHeld: Bool { heldConnect != nil } + + /// Ends the held `connect()`: it throws `error` when given, and returns otherwise. + func releaseHeldConnect(throwing error: (any Swift.Error)? = nil) { + if let error { + heldConnect?.resume(throwing: error) + } else { + heldConnect?.resume() + } + heldConnect = nil + } func disconnect() async { disconnectCount += 1 @@ -96,10 +133,28 @@ actor EndableTransport: Transport { } } + /// Makes the next `send(_:options:)` wait until `releaseHeldSend()`, before it records + /// the message. + func holdNextSend() { + holdsNextSend = true + } + + /// Whether a `send(_:options:)` waits for `releaseHeldSend()`. + var isSendHeld: Bool { heldSend != nil } + + func releaseHeldSend() { + heldSend?.resume() + heldSend = nil + } + /// Records the method of each message, the ID of each response, and /// counts batches. Like `StdioTransport` after the server closes its /// output, sending keeps working after the receive stream has ended. - func send(_ data: Data) async throws { + func send(_ data: Data, options: TransportSendOptions) async throws { + if holdsNextSend { + holdsNextSend = false + await withCheckedContinuation { heldSend = $0 } + } if data.first == UInt8(ascii: "[") { sentBatchCount += 1 return diff --git a/Tests/MCPTests/Helpers/LoopbackHTTPServer.swift b/Tests/MCPTests/Helpers/LoopbackHTTPServer.swift new file mode 100644 index 00000000..27b4a18e --- /dev/null +++ b/Tests/MCPTests/Helpers/LoopbackHTTPServer.swift @@ -0,0 +1,208 @@ +import Foundation + +#if canImport(Darwin) + import Darwin +#elseif canImport(Glibc) + import Glibc +#elseif canImport(Musl) + import Musl +#endif + +/// An HTTP/1.1 server answering each path with a fixed response, one request +/// per connection, for tests that need a real `URLSession` (redirects, which +/// swift-corelibs-foundation can't take from a `URLProtocol`). +/// +/// It listens on every IPv4 address on Linux and on 127.0.0.1 on Apple +/// platforms, and records the head of each request. +final class LoopbackHTTPServer: @unchecked Sendable { + typealias Route = (status: Int, headers: [String: String], body: Data) + + /// A request the server read: its method and path, and its headers with + /// lowercased names. + struct Request: Sendable { + let method: String + let path: String + let headers: [String: String] + let body: Data + } + + let port: Int + private let socket: Int32 + private let lock = NSLock() + private var received: [Request] = [] + private var table: [String: Route] = [:] + private var responder: (@Sendable (Request) -> Route?)? + private var stopped = false + + /// The base URL, `http://127.0.0.1:`. + var baseURL: String { "http://127.0.0.1:\(port)" } + /// The paths requested, in order. + var requested: [String] { lock.withLock { received.map(\.path) } } + /// The requests read, in order. + var requests: [Request] { lock.withLock { received } } + var routes: [String: Route] { + get { lock.withLock { table } } + set { lock.withLock { table = newValue } } + } + /// Answers a request before ``routes``, which answer when it returns `nil`. + var respond: (@Sendable (Request) -> Route?)? { + get { lock.withLock { responder } } + set { lock.withLock { responder = newValue } } + } + + init() throws { + #if canImport(Glibc) + let stream = Int32(SOCK_STREAM.rawValue) + #else + let stream = SOCK_STREAM + #endif + let socket = Self.makeSocket(stream) + self.socket = socket + var address = sockaddr_in() + #if canImport(Darwin) + address.sin_len = UInt8(MemoryLayout.size) + address.sin_addr.s_addr = in_addr_t(0x7F00_0001).bigEndian + #else + address.sin_addr = in_addr(s_addr: INADDR_ANY) + #endif + address.sin_family = sa_family_t(AF_INET) + var length = socklen_t(MemoryLayout.size) + let bound = withUnsafeMutablePointer(to: &address) { pointer in + pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { address in + bind(socket, address, length) == 0 && listen(socket, 16) == 0 + && getsockname(socket, address, &length) == 0 + } + } + guard bound else { + _ = close(socket) + throw URLError(.cannotConnectToHost) + } + port = Int(UInt16(bigEndian: address.sin_port)) + let thread = Thread { [self] in serve() } + thread.start() + } + + private static func makeSocket(_ type: Int32) -> Int32 { + #if canImport(Darwin) + Darwin.socket(AF_INET, type, 0) + #elseif canImport(Glibc) + Glibc.socket(AF_INET, type, 0) + #else + Musl.socket(AF_INET, type, 0) + #endif + } + + /// Stops accepting: a connection wakes the blocked `accept`. + func stop() { + lock.withLock { stopped = true } + #if canImport(Glibc) + let wake = Self.makeSocket(Int32(SOCK_STREAM.rawValue)) + #else + let wake = Self.makeSocket(SOCK_STREAM) + #endif + var address = sockaddr_in() + #if canImport(Darwin) + address.sin_len = UInt8(MemoryLayout.size) + #endif + address.sin_family = sa_family_t(AF_INET) + address.sin_port = UInt16(port).bigEndian + address.sin_addr.s_addr = in_addr_t(0x7F00_0001).bigEndian + _ = withUnsafePointer(to: &address) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { + connect(wake, $0, socklen_t(MemoryLayout.size)) + } + } + _ = close(wake) + } + + private func serve() { + defer { _ = close(socket) } + while true { + var connection: Int32 + repeat { + connection = accept(socket, nil, nil) + } while connection < 0 && errno == EINTR + guard connection >= 0, !lock.withLock({ stopped }) else { + if connection >= 0 { _ = close(connection) } + return + } + #if canImport(Darwin) + var noSigPipe: Int32 = 1 + _ = setsockopt( + connection, SOL_SOCKET, SO_NOSIGPIPE, &noSigPipe, socklen_t(MemoryLayout.size)) + #endif + answer(connection) + _ = close(connection) + } + } + + private static func readOnce(_ fd: Int32, into buffer: inout [UInt8], count: Int) -> Int { + while true { + let result = read(fd, &buffer, count) + if result < 0 && errno == EINTR { continue } + return result + } + } + + private static func writeAll(_ data: Data, to fd: Int32) { + data.withUnsafeBytes { raw in + guard let base = raw.baseAddress else { return } + var offset = 0 + while offset < raw.count { + let written: Int + #if canImport(Darwin) + written = write(fd, base.advanced(by: offset), raw.count - offset) + #else + written = send(fd, base.advanced(by: offset), raw.count - offset, Int32(MSG_NOSIGNAL)) + #endif + if written < 0 { + if errno == EINTR { continue } + return + } + if written == 0 { return } + offset += written + } + } + } + + private func answer(_ connection: Int32) { + var data = Data() + var buffer = [UInt8](repeating: 0, count: 4096) + let separator = Data("\r\n\r\n".utf8) + while data.range(of: separator) == nil { + let count = Self.readOnce(connection, into: &buffer, count: buffer.count) + guard count > 0 else { return } + data.append(contentsOf: buffer[.. 0 else { break } + body.append(contentsOf: buffer[.. ((@Sendable (Request) -> Route?)?, Route?) in + received.append(request) + return (self.responder, table[path]) + } + let answer = responder?(request) ?? route ?? (404, [:], Data()) + var head = "HTTP/1.1 \(answer.status) Status\r\nContent-Length: \(answer.body.count)\r\nConnection: close\r\n" + for (name, value) in answer.headers { head += "\(name): \(value)\r\n" } + let response = Data((head + "\r\n").utf8) + answer.body + Self.writeAll(response, to: connection) + } +} diff --git a/Tests/MCPTests/Helpers/LoopbackTCP.swift b/Tests/MCPTests/Helpers/LoopbackTCP.swift new file mode 100644 index 00000000..c74f84f5 --- /dev/null +++ b/Tests/MCPTests/Helpers/LoopbackTCP.swift @@ -0,0 +1,72 @@ +#if canImport(Darwin) + import Darwin +#elseif canImport(Glibc) + import Glibc +#elseif canImport(Musl) + import Musl +#endif + +#if canImport(System) + import System +#else + @preconcurrency import SystemPackage +#endif + +/// TCP sockets on the loopback interface, for tests that need a read to fail: after +/// ``reset(_:)`` on one end, a read on the other fails with `ECONNRESET`. +enum LoopbackTCP { + /// Returns the two ends of a new TCP connection on 127.0.0.1. + static func connectedPair() throws -> (Int32, Int32) { + #if canImport(Glibc) + let stream = Int32(SOCK_STREAM.rawValue) + #else + let stream = SOCK_STREAM + #endif + let listener = socket(AF_INET, stream, 0) + guard listener >= 0 else { throw Errno(rawValue: errno) } + defer { _ = close(listener) } + + var address = sockaddr_in() + #if canImport(Darwin) + address.sin_len = UInt8(MemoryLayout.size) + #endif + address.sin_family = sa_family_t(AF_INET) + address.sin_addr.s_addr = in_addr_t(0x7F00_0001).bigEndian + var length = socklen_t(MemoryLayout.size) + // Port 0: the system picks a free port, which `getsockname` reads back. + try withUnsafeMutablePointer(to: &address) { pointer in + try pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { address in + guard bind(listener, address, length) == 0, listen(listener, 1) == 0, + getsockname(listener, address, &length) == 0 + else { throw Errno(rawValue: errno) } + } + } + + let client = socket(AF_INET, stream, 0) + guard client >= 0 else { throw Errno(rawValue: errno) } + let connected = withUnsafePointer(to: &address) { pointer in + pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { connect(client, $0, length) } + } + guard connected == 0 else { + let error = Errno(rawValue: errno) + _ = close(client) + throw error + } + // The connection is in the listen backlog already, so this returns at once. + let server = accept(listener, nil, nil) + guard server >= 0 else { + let error = Errno(rawValue: errno) + _ = close(client) + throw error + } + return (client, server) + } + + /// Closes `socket` with a reset instead of a normal close (`SO_LINGER` with a zero + /// timeout), so the other end's next read fails with `ECONNRESET`. + static func reset(_ socket: Int32) { + var option = linger(l_onoff: 1, l_linger: 0) + _ = setsockopt(socket, SOL_SOCKET, SO_LINGER, &option, socklen_t(MemoryLayout.size)) + _ = close(socket) + } +} diff --git a/Tests/MCPTests/Helpers/MockTransport.swift b/Tests/MCPTests/Helpers/MockTransport.swift index 08f541e3..f320332f 100644 --- a/Tests/MCPTests/Helpers/MockTransport.swift +++ b/Tests/MCPTests/Helpers/MockTransport.swift @@ -9,7 +9,7 @@ import struct Foundation.POSIXError /// Mock transport for testing actor MockTransport: Transport { - var logger: Logger + nonisolated let logger: Logger let encoder = JSONEncoder() let decoder = JSONDecoder() @@ -27,16 +27,21 @@ actor MockTransport: Transport { } } - private var dataToReceive: [Data] = [] - private(set) var receivedMessages: [String] = [] - - private var dataStreamContinuation: AsyncThrowingStream.Continuation? + /// The stream `receive()` returns on every call. It buffers what + /// `queue(data:)` delivers before anyone reads it. + private let dataStream: AsyncThrowingStream + private let dataStreamContinuation: AsyncThrowingStream.Continuation var shouldFailConnect = false var shouldFailSend = false + private(set) var disconnectCount = 0 + private var shouldPauseSend = false + private var sendGate: CheckedContinuation? + var isSendPaused: Bool { sendGate != nil } init(logger: Logger = Logger(label: "mcp.test.transport")) { self.logger = logger + (dataStream, dataStreamContinuation) = AsyncThrowingStream.makeStream() } public func connect() async throws { @@ -47,37 +52,32 @@ actor MockTransport: Transport { } public func disconnect() async { + disconnectCount += 1 isConnected = false - dataStreamContinuation?.finish() - dataStreamContinuation = nil + if let gate = sendGate { + sendGate = nil + gate.resume(throwing: MCPError.connectionClosed) + } + dataStreamContinuation.finish() } - public func send(_ message: Data) async throws { + /// The `options.relatedRequestID` of each send, in call order. + private(set) var relatedRequestIDs: [ID?] = [] + + public func send(_ message: Data, options: TransportSendOptions) async throws { + if shouldPauseSend { + shouldPauseSend = false + try await withCheckedThrowingContinuation { sendGate = $0 } + } if shouldFailSend { throw MCPError.transportError(POSIXError(.EIO)) } sentData.append(message) - } - - /// Related request IDs passed to `send(_:relatedRequestID:)`, in call order. - private(set) var relatedRequestIDs: [ID?] = [] - - public func send(_ message: Data, relatedRequestID: ID?) async throws { - try await send(message) - relatedRequestIDs.append(relatedRequestID) + relatedRequestIDs.append(options.relatedRequestID) } public func receive() -> AsyncThrowingStream { - return AsyncThrowingStream { continuation in - dataStreamContinuation = continuation - for message in dataToReceive { - continuation.yield(message) - if let string = String(data: message, encoding: .utf8) { - receivedMessages.append(string) - } - } - dataToReceive.removeAll() - } + dataStream } func setFailConnect(_ shouldFail: Bool) { @@ -88,12 +88,12 @@ actor MockTransport: Transport { shouldFailSend = shouldFail } + func setPauseSend(_ shouldPause: Bool) { + shouldPauseSend = shouldPause + } + func queue(data: Data) { - if let continuation = dataStreamContinuation { - continuation.yield(data) - } else { - dataToReceive.append(data) - } + dataStreamContinuation.yield(data) } func queue(request: Request) throws { @@ -139,6 +139,40 @@ actor MockTransport: Transport { func clearMessages() { sentData.removeAll() - dataToReceive.removeAll() } } + +/// Connects `client` over `transport` and answers its `initialize` request +/// at the newest handshake revision, declaring `capabilities` for the server. +func connectAnsweringInitialize( + _ client: Client, over transport: MockTransport, serverCapabilities capabilities: Server.Capabilities = .init() +) async throws { + let answer = Task { + do { + try await transport.waitForSentMessages() + guard let data = await transport.sentData.first else { + throw MCPError.internalError("The client sent no initialize request") + } + let request = try JSONDecoder().decode(Request.self, from: data) + try await transport.queue( + response: Initialize.response( + id: request.id, + result: .init( + protocolVersion: Version.latestHandshake, capabilities: capabilities, + serverInfo: .init(name: "s", version: "1"), instructions: nil))) + } catch { + if !(error is CancellationError) { await transport.disconnect() } + throw error + } + } + do { + try await client.connect(transport: transport) + } catch { + answer.cancel() + if case .failure(let answerError) = await answer.result, !(answerError is CancellationError) { + throw answerError + } + throw error + } + try await answer.value +} diff --git a/Tests/MCPTests/Helpers/RawResult.swift b/Tests/MCPTests/Helpers/RawResult.swift new file mode 100644 index 00000000..75af319c --- /dev/null +++ b/Tests/MCPTests/Helpers/RawResult.swift @@ -0,0 +1,12 @@ +@testable import MCP + +/// The method `M` with a raw `Value` result, so a test server can answer `M` with JSON that +/// `M.Result` refuses, as a peer could send it. +/// +/// Register it with `server.withMethodHandler(RawResult.self) { ... }`; the +/// client still decodes the reply as `M.Result`. +enum RawResult: MCP.Method { + static var name: String { M.name } + typealias Parameters = M.Parameters + typealias Result = Value +} diff --git a/Tests/MCPTests/Helpers/ValidationGate.swift b/Tests/MCPTests/Helpers/ValidationGate.swift new file mode 100644 index 00000000..9d2bf438 --- /dev/null +++ b/Tests/MCPTests/Helpers/ValidationGate.swift @@ -0,0 +1,57 @@ +@testable import MCP + +/// Holds the validators that wait on it until a test lets them through. +/// +/// Each wait counts an arrival, so a test can wait until a request is +/// suspended in its validators before it changes the transport's state. +actor ValidationGate { + private var isOpen = false + private var waiters: [CheckedContinuation] = [] + + /// How many times a validator has waited on the gate. + private(set) var arrivals = 0 + + /// Waits until the gate opens, or until ``releaseOne()`` lets this + /// waiter through. Returns at once while the gate is open. + func wait() async { + arrivals += 1 + guard !isOpen else { return } + await withCheckedContinuation { waiters.append($0) } + } + + /// Lets the oldest waiter through; the gate stays closed. + func releaseOne() { + guard !waiters.isEmpty else { return } + waiters.removeFirst().resume() + } + + /// Lets every waiter through, and every later one. + func open() { + isOpen = true + for waiter in waiters { waiter.resume() } + waiters.removeAll() + } +} + +/// A validator that waits on a ``ValidationGate`` for the requests it +/// applies to, then lets them through. +struct GateValidator: HTTPRequestValidator { + let gate: ValidationGate + let applies: @Sendable (HTTPRequest, HTTPValidationContext) -> Bool + + /// A validator that holds the requests with HTTP method `method`. + init(_ gate: ValidationGate, method: String) { + self.gate = gate + self.applies = { _, context in context.httpMethod == method } + } + + init(_ gate: ValidationGate, applies: @escaping @Sendable (HTTPRequest, HTTPValidationContext) -> Bool) { + self.gate = gate + self.applies = applies + } + + func validate(_ request: HTTPRequest, context: HTTPValidationContext) async -> HTTPResponse? { + if applies(request, context) { await gate.wait() } + return nil + } +} diff --git a/Tests/MCPTests/Helpers/WireExchange.swift b/Tests/MCPTests/Helpers/WireExchange.swift index 7ade71ce..1b5e51f1 100644 --- a/Tests/MCPTests/Helpers/WireExchange.swift +++ b/Tests/MCPTests/Helpers/WireExchange.swift @@ -64,6 +64,29 @@ func wireJSON(_ text: String) throws -> Value { try JSONDecoder().decode(Value.self, from: Data(text.utf8)) } +/// The JSON of `value` as a peer sees it from the server: sorted keys, slashes unescaped. +/// +/// Use it for exact goldens of a single type; `expectWire` checks a subset of a message +/// and treats `1` and `1.0` as equal. +func wireString(_ value: some Encodable) throws -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + return String(decoding: try encoder.encode(value), as: UTF8.self) +} + +/// The coding path of a `DecodingError`, as key names and array indices +/// (`["content", "1", "data"]`); empty for any other error. +func codingPath(of error: any Error) -> [String] { + let context: DecodingError.Context? + switch error as? DecodingError { + case .dataCorrupted(let c), .keyNotFound(_, let c), .typeMismatch(_, let c), .valueNotFound(_, let c): + context = c + default: + context = nil + } + return context?.codingPath.map { $0.intValue.map(String.init) ?? $0.stringValue } ?? [] +} + /// Records an issue unless `actual` contains every member of `expected`. /// /// Objects match when each expected key matches; extra keys in `actual` diff --git a/Tests/MCPTests/IDTests.swift b/Tests/MCPTests/IDTests.swift index 0abf28e6..1debc599 100644 --- a/Tests/MCPTests/IDTests.swift +++ b/Tests/MCPTests/IDTests.swift @@ -1,7 +1,9 @@ import Testing +import struct Foundation.Data import class Foundation.JSONDecoder import class Foundation.JSONEncoder +import class Foundation.NSString import struct Foundation.UUID @testable import MCP @@ -48,4 +50,75 @@ struct IDTests { #expect(Bool(false), "Random ID should be string type") } } + + /// Strings that Swift `String` equality treats as equal, but whose + /// Unicode scalars differ: different JSON-RPC ids. + static let canonicallyEquivalentPairs: [(String, String)] = [ + ("\u{E9}", "e\u{301}"), + ("K", "\u{212A}"), + ("\u{C5}", "\u{212B}"), + ("req-\u{C5}", "req-A\u{30A}"), + ] + + @Test("String ids with different scalars are different ids, also when canonically equivalent") + func canonicallyEquivalentStringsDiffer() { + for (first, second) in Self.canonicallyEquivalentPairs { + #expect(first == second, "the pair must be canonically equivalent") + #expect(ID.string(first) != ID.string(second)) + #expect(Set([ID.string(first), ID.string(second)]).count == 2) + // By assignment: a literal with keys that are equal traps. + var routes: [ID: String] = [:] + routes[.string(first)] = "first" + routes[.string(second)] = "second" + #expect(routes.count == 2) + #expect(routes[.string(first)] == "first") + #expect(routes[.string(second)] == "second") + } + } + + @Test("Equal ids hash alike; a string and a number with the same text differ") + func equalIDsHashAlike() { + let spelled = ID.string("e\u{301}") + let built = ID.string(String(decoding: Array("e\u{301}".utf16), as: UTF16.self)) + #expect(spelled == built) + #expect(spelled.hashValue == built.hashValue) + #expect(ID.string("1") != ID.number(1)) + #expect(Set([ID.string("1"), ID.number(1)]).count == 2) + #expect(ID.number(7) == 7) + #expect(ID.number(7).hashValue == ID.number(7).hashValue) + } + + #if canImport(ObjectiveC) + @Test("A string bridged from NSString hashes like a native one") + func bridgedStringHashesAlike() { + let native = "r\u{E9}q-\u{212A}" + let bridged = NSString(string: native) as String + #expect(ID.string(native) == ID.string(bridged)) + #expect(ID.string(native).hashValue == ID.string(bridged).hashValue) + } + #endif + + @Test("Decoding keeps an id's scalars") + func decodingKeepsScalars() throws { + let decomposed = try JSONDecoder().decode(ID.self, from: Data(#""e\u0301""#.utf8)) + #expect(decomposed == .string("e\u{301}")) + #expect(decomposed != .string("\u{E9}")) + // Compared as bytes: `String` equality would accept "\u{E9}" too. + #expect(try JSONEncoder().encode(decomposed) == Data("\"e\u{301}\"".utf8)) + } + + @Test("ExactString and exactValue(forKey:) match the same scalars only") + func exactStrings() { + for (first, second) in Self.canonicallyEquivalentPairs { + #expect(first.isExactly(first)) + #expect(!first.isExactly(second)) + #expect(ExactString(first) != ExactString(second)) + #expect(Set([ExactString(first), ExactString(second)]).count == 2) + #expect(ExactString(first) == ExactString(String(decoding: Array(first.utf16), as: UTF16.self))) + let stored = [first: "value"] + #expect(stored.exactValue(forKey: first) == "value") + #expect(stored.exactValue(forKey: second) == nil) + } + #expect(!"ab".isExactly("abc")) + } } diff --git a/Tests/MCPTests/InMemoryTransportTests.swift b/Tests/MCPTests/InMemoryTransportTests.swift index 9bb0ccff..62d4948d 100644 --- a/Tests/MCPTests/InMemoryTransportTests.swift +++ b/Tests/MCPTests/InMemoryTransportTests.swift @@ -40,14 +40,14 @@ struct InMemoryTransportTests { } } - @Test("Multiple connect calls are idempotent") + @Test("A second connect() throws") func testMultipleConnectCalls() async throws { let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() - // Connect multiple times should not throw try await clientTransport.connect() - try await clientTransport.connect() // Should be safe - try await clientTransport.connect() // Should be safe + await #expect(throws: MCPError.internalError("Transport already connected")) { + try await clientTransport.connect() + } // Clean up await clientTransport.disconnect() @@ -234,6 +234,53 @@ struct InMemoryTransportTests { receiveTask.cancel() } + @Test("A peer that disconnects before this side connects closes it") + func testPeerDisconnectsBeforeConnect() async throws { + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + + try await serverTransport.connect() + await serverTransport.disconnect() + + // The client never connected; the pair is closed for good. + await #expect(throws: MCPError.internalError("Transport disconnected; create a new transport to reconnect")) { + try await clientTransport.connect() + } + await #expect(throws: MCPError.connectionClosed) { + try await clientTransport.send(Data("message".utf8)) + } + let ended = await outcome(within: .seconds(10)) { + for try await _ in await clientTransport.receive() {} + } + #expect(ended.mcpError == .connectionClosed) + } + + @Test("Disconnected transport pairs break their cycle and deallocate") + func testDisconnectedPairDeallocates() async throws { + weak var weakClient: InMemoryTransport? + weak var weakServer: InMemoryTransport? + + do { + let (client, server) = await InMemoryTransport.createConnectedPair() + weakClient = client + weakServer = server + try await client.connect() + try await server.connect() + await client.disconnect() + } + #expect(weakClient == nil) + #expect(weakServer == nil) + + // Also when disconnected before either side connects. + do { + let (client, server) = await InMemoryTransport.createConnectedPair() + weakClient = client + weakServer = server + await server.disconnect() + } + #expect(weakClient == nil) + #expect(weakServer == nil) + } + @Test("Multiple disconnects are safe") func testMultipleDisconnects() async throws { let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() diff --git a/Tests/MCPTests/MultiRoundTripTests.swift b/Tests/MCPTests/MultiRoundTripTests.swift index 346566c7..9098845e 100644 --- a/Tests/MCPTests/MultiRoundTripTests.swift +++ b/Tests/MCPTests/MultiRoundTripTests.swift @@ -272,6 +272,32 @@ struct RequestStateTests { #expect(reason { try elsewhere.unseal(token, method: CallTool.name, binding: binding, context: alice, now: now) } == "audience") } + @Test("Sealed state is bound to the method, target, and audience by their code points") + func testBindingsMatchExactly() throws { + let protection = try RequestStateProtection(keys: [key]) + // "Kelvin" and "\u{212A}elvin" (KELVIN SIGN): equal as Swift strings, + // different names on the wire. + let (name, sign) = ("Kelvin", "\u{212A}elvin") + let boundary = RequestStateBoundary(protection: protection, audience: name) + let binding = RequestStateBoundary.binding(target: name, arguments: [:]) + let token = try boundary.seal("state", method: "\(name)/run", binding: binding, context: nil) + #expect(try boundary.unseal(token, method: "\(name)/run", binding: { binding }, context: nil).state == "state") + + func reason(_ body: () throws -> RequestStateBoundary.Verified) -> String? { + do { + _ = try body() + return nil + } catch { + return (error as? InvalidRequestState)?.reason + } + } + #expect(reason { try boundary.unseal(token, method: "\(sign)/run", binding: { binding }, context: nil) } == "request binding") + let other = RequestStateBoundary.binding(target: sign, arguments: [:]) + #expect(reason { try boundary.unseal(token, method: "\(name)/run", binding: { other }, context: nil) } == "request binding") + let otherAudience = RequestStateBoundary(protection: protection, audience: sign) + #expect(reason { try otherAudience.unseal(token, method: "\(name)/run", binding: { binding }, context: nil) } == "audience") + } + @Test("Each token has its own id and expiry; the binding is computed only for an authentic token") func testTokenIDs() throws { let boundary = RequestStateBoundary(protection: try RequestStateProtection(keys: [key]), audience: "srv") diff --git a/Tests/MCPTests/NetworkTransportTests.swift b/Tests/MCPTests/NetworkTransportTests.swift index 79202fa4..da0f097f 100644 --- a/Tests/MCPTests/NetworkTransportTests.swift +++ b/Tests/MCPTests/NetworkTransportTests.swift @@ -18,9 +18,28 @@ import Testing private var mockError: Swift.Error? /// Data queue for testing - private var dataToReceive: [Data] = [] + private var dataToReceive: [Received] = [] private var sentData: [Data] = [] + /// One completion of a receive: bytes, the context they belong to, and whether they + /// complete it. + private struct Received { + var data: Data + var context: NWConnection.ContentContext + var isComplete: Bool + } + + /// The context of a TCP stream: one for the whole connection, final, so its completion + /// is the peer's FIN. + static let streamContext = NWConnection.ContentContext(identifier: "stream", isFinal: true) + + /// The number of times `receive` was called + private var receives = 0 + + /// Whether the peer closed the connection: once the queued data is read, a receive + /// reports the close, and the last queued stream chunk completes the stream context. + private var peerClosed = false + /// Send completions held until `completeHeldSends(error:)`, while `holdsSendCompletions` private var holdsSendCompletions = false private var heldSendCompletions: [@Sendable (NWError?) -> Void] = [] @@ -37,9 +56,13 @@ import Testing lock.withLock { mockState } } - /// The state `start()` moves to when the connection is neither cancelled nor failed. - /// Default `.ready`; a non-ready state such as `.waiting` simulates an unreachable peer. - private let startState: NWConnection.State + /// The mock has no path, like a connection that was never started. + var currentPath: NWPath? { nil } + + /// The states `start()` moves through, in order, when the connection is neither cancelled + /// nor failed. Default `.ready`; a `.waiting` state simulates a peer the connection + /// can't reach yet, and a `.failed` one a refused connection. + private let startStates: [NWConnection.State] /// Whether `cancel()` leaves `state` and the handler alone. The real NWConnection reports /// `.cancelled` later, on its queue, not inside `cancel()`. @@ -48,9 +71,15 @@ import Testing /// Whether `cancel()` has been called private var cancelRequested = false - /// Initialize a mock connection + /// Initialize a mock connection that moves to `startState` when started init(startState: NWConnection.State = .ready, defersCancellation: Bool = false) { - self.startState = startState + self.startStates = [startState] + self.defersCancellation = defersCancellation + } + + /// Initialize a mock connection that moves through `startStates` when started + init(startStates: [NWConnection.State], defersCancellation: Bool = false) { + self.startStates = startStates self.defersCancellation = defersCancellation } @@ -62,7 +91,11 @@ import Testing // A cancelled connection cannot be restarted; the real NWConnection reports no further // state, so neither does the mock. A retry must use a fresh connection instead. guard !cancelled else { return } - updateState(error != nil ? state : startState) + if error != nil { + updateState(state) + } else { + for state in startStates { updateState(state) } + } } /// Send data through the connection @@ -97,13 +130,20 @@ import Testing Data?, NWConnection.ContentContext?, Bool, NWError? ) -> Void ) { - let (state, error, data, isLast): (NWConnection.State, Swift.Error?, Data?, Bool) = - lock.withLock { - guard mockState != .cancelled, mockError == nil, !dataToReceive.isEmpty else { + let (state, error, received, closed): + (NWConnection.State, Swift.Error?, Received?, Bool) = lock.withLock { + receives += 1 + guard mockState != .cancelled, mockError == nil else { return (mockState, mockError, nil, false) } - let data = dataToReceive.removeFirst() - return (mockState, mockError, data, dataToReceive.isEmpty) + guard !dataToReceive.isEmpty else { + return (mockState, nil, nil, peerClosed) + } + var received = dataToReceive.removeFirst() + if peerClosed && dataToReceive.isEmpty && received.context === Self.streamContext { + received.isComplete = true + } + return (mockState, nil, received, false) } if state == .cancelled { @@ -114,7 +154,21 @@ import Testing completion(nil, nil, false, error as? NWError) return } - completion(data ?? Data(), nil, isLast, nil) + if closed { + // A graceful close with no more bytes: the stream context completes. + completion(nil, Self.streamContext, true, nil) + return + } + if let received { + completion(received.data, received.context, received.isComplete, nil) + } else { + completion(Data(), nil, false, nil) + } + } + + /// The number of times `receive` was called + var receiveCount: Int { + lock.withLock { receives } } /// Cancel the connection @@ -141,14 +195,29 @@ import Testing updateState(.preparing) } + /// Simulate the connection waiting for a usable path with `error` + func simulateWaiting(_ error: NWError) { + updateState(.waiting(error)) + } + /// Simulate a connection failure func simulateFailure(error: Swift.Error? = nil) { - lock.withLock { mockError = error } - if let nwError = error as? NWError { - updateState(.failed(nwError)) - } else { - updateState(.failed(NWError.posix(POSIXErrorCode(rawValue: 57)!))) + let nwError = (error as? NWError) ?? NWError.posix(POSIXErrorCode(rawValue: 57)!) + let newState = NWConnection.State.failed(nwError) + // Set `mockError` and `mockState` under one lock so `readMessages()` cannot + // observe `mockError`, call `cancel()`, and have `updateState` overwrite `.cancelled`. + let handler = lock.withLock { () -> (@Sendable (NWConnection.State) -> Void)? in + mockError = error + guard mockState != .cancelled else { return nil } + mockState = newState + return _stateUpdateHandler } + handler?(newState) + } + + /// Simulate a graceful close by the peer, after the data already queued + func simulatePeerClose() { + lock.withLock { peerClosed = true } } /// Simulate connection cancellation @@ -166,21 +235,24 @@ import Testing handler?(newState) } - /// Queue data to be received + /// Queue a chunk of the TCP stream to be received func queueDataForReceiving(_ data: Data) { - lock.withLock { dataToReceive.append(data) } + lock.withLock { + dataToReceive.append(Received(data: data, context: Self.streamContext, isComplete: false)) + } } - /// Queue a heartbeat message to be received - func queueHeartbeat() { - // Create a mock heartbeat message that matches the format - let magicBytes: [UInt8] = [0xF0, 0x9F, 0x92, 0x93] // Magic bytes for heartbeat - var data = Data(magicBytes) - let timestamp = UInt64(Date().timeIntervalSinceReferenceDate * 1000) - withUnsafeBytes(of: timestamp) { buffer in - data.append(contentsOf: buffer) + /// Queue a whole message of a message protocol, such as a UDP datagram or a WebSocket + /// message: it arrives in one read that completes `context`. + func queueMessage(_ data: Data, context: NWConnection.ContentContext) { + lock.withLock { + dataToReceive.append(Received(data: data, context: context, isComplete: true)) } - queueDataForReceiving(data) + } + + /// Queue a heartbeat, as a 0.12 peer sends it, to be received + func queueHeartbeat() { + queueDataForReceiving(NetworkTransport.Heartbeat().data) } /// Queue text message to be received @@ -228,36 +300,27 @@ import Testing func add(_ connection: MockNetworkConnection) { lock.withLock { connections.append(connection) } } var count: Int { lock.withLock { connections.count } } var latest: MockNetworkConnection? { lock.withLock { connections.last } } + var all: [MockNetworkConnection] { lock.withLock { connections } } } @Suite("Network Transport Tests", .serialized) struct NetworkTransportTests { @Test("Heartbeat Creation And Parsing") func testHeartbeatCreationAndParsing() { - // Create a heartbeat - let heartbeat = NetworkTransport.Heartbeat() - - // Convert to data and back + // 656 seconds after 2001 is 656,000 ms (0x0A0280), little-endian after the magic bytes. + let heartbeat = NetworkTransport.Heartbeat(timestamp: Date(timeIntervalSinceReferenceDate: 656)) let data = heartbeat.data - let parsed = NetworkTransport.Heartbeat.from(data: data) - - #expect(parsed != nil) - // Time should be very close (within 1 second) - if let parsed = parsed { - let timeDifference = abs(parsed.timestamp.timeIntervalSince(heartbeat.timestamp)) - #expect(timeDifference < 1.0) - } - - // Test invalid data - let invalidData = Data([0x01, 0x02, 0x03]) - #expect(NetworkTransport.Heartbeat.from(data: invalidData) == nil) - #expect(NetworkTransport.Heartbeat.isHeartbeat(invalidData) == false) - #expect(NetworkTransport.Heartbeat.isHeartbeat(data) == true) + #expect(data.count == NetworkTransport.Heartbeat.encodedLength) + #expect(data.count == 12) + #expect(Array(data.prefix(4)) == Array("\u{1F493}".utf8)) + #expect(Array(data.dropFirst(4)) == [0x80, 0x02, 0x0A, 0, 0, 0, 0, 0]) + #expect(NetworkTransport.Heartbeat.isAtStart(of: data)) + #expect(!NetworkTransport.Heartbeat.isAtStart(of: Data([0x01, 0x02, 0x03]))) } @Test("Reconnection Configuration") - func testReconnectionConfiguration() { + func testReconnectionConfiguration() async { // Create custom config let config = NetworkTransport.ReconnectionConfiguration( enabled: true, @@ -282,36 +345,24 @@ import Testing // Test disabled config let disabledConfig = NetworkTransport.ReconnectionConfiguration.disabled #expect(disabledConfig.enabled == false) - } - @Test("Heartbeat Configuration") - func testHeartbeatConfiguration() { - // Create custom config - let config = NetworkTransport.HeartbeatConfiguration( - enabled: true, - interval: 5.0 - ) - - #expect(config.enabled == true) - #expect(config.interval == 5.0) - - // Test default config - let defaultConfig = NetworkTransport.HeartbeatConfiguration.default - #expect(defaultConfig.enabled == true) - #expect(defaultConfig.interval == 15.0) + // `.default` stays enabled; it is not the transport's default. + #expect(NetworkTransport.ReconnectionConfiguration.default.enabled) + #expect(NetworkTransport.ReconnectionConfiguration.default.maxAttempts == 5) - // Test disabled config - let disabledConfig = NetworkTransport.HeartbeatConfiguration.disabled - #expect(disabledConfig.enabled == false) + // The public initializer's defaults + let transport = NetworkTransport( + connection: NWConnection(host: "127.0.0.1", port: 9, using: .tcp)) + #expect(await transport.reconnection == .disabled) + #expect(await transport.connectionTimeout == .seconds(30)) + #expect(await transport.maximumMessageLength == 16 << 20) + #expect(await transport.maximumMessageLength == NetworkTransport.maxMessageLength) } @Test("Connect Success") func testNetworkTransportConnectSuccess() async throws { let mockConnection = MockNetworkConnection() - let transport = NetworkTransport( - mockConnection, - heartbeatConfig: .disabled // Disable heartbeats for simplified testing - ) + let transport = NetworkTransport(mockConnection) try await transport.connect() @@ -326,7 +377,7 @@ import Testing let mockConnection = MockNetworkConnection() let transport = NetworkTransport( mockConnection, - reconnectionConfig: .disabled // Disable reconnection for this test + reconnection: .disabled // Disable reconnection for this test ) // Simulate failure before connecting @@ -351,10 +402,7 @@ import Testing @Test("Send Message") func testNetworkTransportSendMessage() async throws { let mockConnection = MockNetworkConnection() - let transport = NetworkTransport( - mockConnection, - heartbeatConfig: .disabled - ) + let transport = NetworkTransport(mockConnection) try await transport.connect() @@ -379,8 +427,7 @@ import Testing let mockConnection = MockNetworkConnection() let transport = NetworkTransport( mockConnection, - heartbeatConfig: .disabled, - reconnectionConfig: .disabled + reconnection: .disabled ) try await transport.connect() @@ -402,8 +449,32 @@ import Testing await transport.disconnect() } - @Test("A send pending when the transport is disconnected and released throws") - func testPendingSendAfterTransportReleased() async throws { + @Test("A failed send does not start a reconnect") + func testFailedSendDoesNotReconnect() async throws { + let (transport, made) = Self.dialing({ _ in [.ready] }, reconnection: .default) + try await transport.connect() + let first = try #require(made.latest) + + first.holdSendCompletions() + let sent = Task { + await outcome(within: .seconds(30)) { + try await transport.send(Data(#"{"key":"value"}"#.utf8)) + } + } + #expect(await eventually { first.heldSendCount == 1 }) + first.completeHeldSends(error: .posix(.ECONNRESET)) + let result = await sent.value + #expect(result.mcpError == .internalError("Send error: \(NWError.posix(.ECONNRESET))")) + + // A send failure used to reconnect after 500 ms; only the receive loop does now. + #expect(!(await eventually(within: .seconds(1.5)) { made.count > 1 })) + #expect(!first.isCancelRequested) + + await transport.disconnect() + } + + @Test("A send pending at disconnect() throws once the connection completes it, and the transport is then released") + func testPendingSendAtDisconnectThrowsThenTransportIsReleased() async throws { let mockConnection = MockNetworkConnection() weak var weakTransport: NetworkTransport? let sent: Task, Never> @@ -411,12 +482,13 @@ import Testing do { let transport = NetworkTransport( mockConnection, - heartbeatConfig: .disabled, - reconnectionConfig: .disabled + reconnection: .disabled ) weakTransport = transport try await transport.connect() + // The task of the pending send holds the transport until the send returns, + // so the transport can't be released while it is pending. mockConnection.holdSendCompletions() sent = Task { await outcome(within: .seconds(30)) { @@ -435,6 +507,7 @@ import Testing #expect(!result.didTimeOut, "send never finished") #expect(result.mcpError == .internalError("Send error: \(error)")) + // Once the send has returned, nothing keeps the transport alive. let deadline = ContinuousClock.now + .seconds(30) while weakTransport != nil && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(5)) @@ -445,10 +518,7 @@ import Testing @Test("Receive Message") func testNetworkTransportReceiveMessage() async throws { let mockConnection = MockNetworkConnection() - let transport = NetworkTransport( - mockConnection, - heartbeatConfig: .disabled - ) + let transport = NetworkTransport(mockConnection) // Queue a message to be received let message = #"{"key":"value"}"# @@ -472,45 +542,35 @@ import Testing await transport.disconnect() } - @Test("Heartbeat Send and Receive") - func testNetworkTransportHeartbeat() async throws { + @Test("The transport sends only newline-delimited JSON") + func testSendsOnlyNewlineDelimitedJSON() async throws { let mockConnection = MockNetworkConnection() - - // Create transport with rapid heartbeats - let heartbeatConfig = NetworkTransport.HeartbeatConfiguration( - enabled: true, - interval: 0.1 // Short interval for testing - ) - - let transport = NetworkTransport( - mockConnection, - heartbeatConfig: heartbeatConfig - ) - + let transport = NetworkTransport(mockConnection) + // A 0.12 peer's heartbeat on the receive side does not make this side send one. + mockConnection.queueHeartbeat() try await transport.connect() - // The first heartbeat goes out after a 1 second delay - let deadline = ContinuousClock.now + .seconds(30) - while mockConnection.getSentData().isEmpty && ContinuousClock.now < deadline { - try await Task.sleep(for: .milliseconds(5)) + let messages = [ + #"{"jsonrpc":"2.0","id":1,"method":"ping"}"#, + #"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, + ] + for message in messages { + try await transport.send(Data(message.utf8)) } - // Check if heartbeat was sent - let sentData = mockConnection.getSentData() - #expect(sentData.count >= 1, "No heartbeat was sent after \(sentData.count) attempts") - - if let firstSent = sentData.first { - #expect( - NetworkTransport.Heartbeat.isHeartbeat(firstSent), - "Sent data is not a heartbeat") + // 0.12 sent its first heartbeat 1 s after connecting, then every 15 s: watch for + // longer than that first delay for anything besides the messages. + #expect(!(await eventually(within: .seconds(2)) { mockConnection.getSentData().count > messages.count })) + + let sent = mockConnection.getSentData() + #expect(sent.count == messages.count) + for chunk in sent { + #expect(chunk.last == UInt8(ascii: "\n")) + let line = chunk.dropLast() + #expect(!line.contains(UInt8(ascii: "\n"))) + #expect((try? JSONSerialization.jsonObject(with: Data(line))) != nil, "not JSON: \(chunk)") } - // Queue a heartbeat to be received - mockConnection.queueHeartbeat() - - // Wait for heartbeat processing - try await Task.sleep(for: .milliseconds(100)) - await transport.disconnect() } @@ -537,8 +597,7 @@ import Testing let transport = NetworkTransport( mockConnection, - heartbeatConfig: .disabled, - reconnectionConfig: .disabled + reconnection: .disabled ) try await transport.connect() @@ -577,25 +636,61 @@ import Testing splits.append(bytes.map { Data([$0]) }) for chunks in splits { - let mockConnection = MockNetworkConnection() - for chunk in chunks { - mockConnection.queueDataForReceiving(chunk) - } - let transport = NetworkTransport( - mockConnection, - heartbeatConfig: .disabled, - reconnectionConfig: .disabled - ) - try await transport.connect() - let received = try await receiveMessages( - messages.count, from: transport, timeout: .seconds(2)) - await transport.disconnect() - + let received = try await receive(messages.count, fromReads: chunks) #expect(received == messages, "reads of \(chunks.map(\.count)) bytes") if received != messages { break } } } + @Test("Messages and heartbeats one byte per read arrive intact") + func testMessagesAndHeartbeatsOneBytePerRead() async throws { + let messages = [ + #"{"jsonrpc":"2.0","id":1,"method":"ping"}"#, + #"{"jsonrpc":"2.0","method":"notifications/two"}"#, + ] + var bytes = NetworkTransport.Heartbeat().data + bytes.append(Data((messages[0] + "\n").utf8)) + bytes.append(NetworkTransport.Heartbeat(timestamp: Date(timeIntervalSinceReferenceDate: 656)).data) + bytes.append(Data((messages[1] + "\n").utf8)) + bytes.append(NetworkTransport.Heartbeat().data) + + let received = try await receive(messages.count, fromReads: bytes.map { Data([$0]) }) + #expect(received == messages) + } + + @Test("A heartbeat whose timestamp contains 0x0A is skipped") + func testHeartbeatWithNewlineInTimestampIsSkipped() async throws { + let message = #"{"jsonrpc":"2.0","method":"notifications/one"}"# + let heartbeat = NetworkTransport.Heartbeat(timestamp: Date(timeIntervalSinceReferenceDate: 656)).data + let newline = try #require(heartbeat.firstIndex(of: UInt8(ascii: "\n"))) + let bytes = heartbeat + Data((message + "\n").utf8) + + // In one read, and split just after the newline byte of the timestamp + for chunks in [[bytes], [Data(bytes[...newline]), Data(bytes[(newline + 1)...])]] { + let received = try await receive(1, fromReads: chunks) + // Without the skip, the bytes up to the timestamp's 0x0A would arrive as a line. + #expect(received == [message], "reads of \(chunks.map(\.count)) bytes") + } + } + + @Test("A message that starts with U+1F493 at the start of a read is delivered") + func testMessageWithHeartbeatMarkerAtReadStart() async throws { + // The marker inside a message, at the start of the second read: only the start of a + // message is checked for a heartbeat. + let message = #"{"jsonrpc":"2.0","method":"note","params":{"text":"\#u{1F493}\#u{1F493}\#u{1F493}"}}"# + let bytes = Data((message + "\n").utf8) + let marker = try #require(bytes.firstRange(of: Data("\u{1F493}".utf8))).lowerBound + let inside = try await receive( + 1, fromReads: [Data(bytes[.. [String] { + let mockConnection = MockNetworkConnection() + for chunk in chunks { + mockConnection.queueDataForReceiving(chunk) + } + let transport = NetworkTransport(mockConnection) + try await transport.connect() + let received = try await receiveMessages(count, from: transport, timeout: .seconds(2)) + await transport.disconnect() + return received + } + /// Returns the messages `transport` delivers until `count` arrive or `timeout` passes. private func receiveMessages( _ count: Int, @@ -716,44 +811,73 @@ import Testing } } - @Test("Reconnection") - func testNetworkTransportReconnection() async throws { - let mockConnection = MockNetworkConnection() - - // Configure for quick reconnection - let reconnectionConfig = NetworkTransport.ReconnectionConfiguration( - enabled: true, - maxAttempts: 2, - backoffMultiplier: 1.0 - ) - + /// A transport whose connections are mocks: connection `index` (from 0) moves through + /// `states(index)` when started. `made` records every connection, the first included. + private static func dialing( + _ states: @escaping @Sendable (_ index: Int) -> [NWConnection.State], + defersCancellation: Bool = false, + connectionTimeout: Duration = .seconds(30), + reconnection: NetworkTransport.ReconnectionConfiguration = .disabled + ) -> (NetworkTransport, MadeConnections) { + let made = MadeConnections() + let make: @Sendable () -> MockNetworkConnection = { + let connection = MockNetworkConnection( + startStates: states(made.count), defersCancellation: defersCancellation) + made.add(connection) + return connection + } let transport = NetworkTransport( - mockConnection, - heartbeatConfig: .disabled, - reconnectionConfig: reconnectionConfig + first: make(), + makeConnection: make, + connectionTimeout: connectionTimeout, + reconnection: reconnection ) + return (transport, made) + } - try await transport.connect() + /// Collects the messages a stream delivers, so a test can read them after it finished. + private actor Lines { + private(set) var values: [String] = [] + func append(_ data: Data) { values.append(String(decoding: data, as: UTF8.self)) } + } - // Simulate connection failure during operation - mockConnection.simulateFailure(error: NWError.posix(POSIXErrorCode.ECONNRESET)) + /// Whether `error` is `MCPError.transportError` wrapping `expected`. + private static func isTransportError(_ error: (any Error)?, wrapping expected: NWError) -> Bool { + guard case .transportError(let wrapped)? = error as? MCPError else { return false } + return wrapped as? NWError == expected + } - // Wait a bit to ensure failure is processed - try await Task.sleep(for: .milliseconds(100)) + @Test("With reconnection on, a lost connection reconnects on a fresh connection and the stream goes on") + func testNetworkTransportReconnection() async throws { + let (transport, made) = Self.dialing( + { _ in [.ready] }, + reconnection: .init(enabled: true, maxAttempts: 2, backoffMultiplier: 1.0)) + try await transport.connect() + let first = try #require(made.latest) + let stream = await transport.receive() - // Try to send message after failure - should trigger reconnection process - let message = #"{"test":"reconnect"}"#.data(using: .utf8)! + // The receive loop sees the loss and dials a fresh connection after a backoff. + first.simulateFailure(error: NWError.posix(POSIXErrorCode.ECONNRESET)) + #expect(await eventually { made.count == 2 }) + #expect(first.isCancelRequested) - do { - try await transport.send(message) - Issue.record("Expected send to fail after connection lost") - } catch { - // Expected error - #expect(error is MCPError, "Expected MCPError but got \(type(of: error))") + // The fresh connection's messages arrive on the same stream. + let message = #"{"jsonrpc":"2.0","method":"notifications/after"}"# + try #require(made.latest).queueTextMessage(message + "\n") + let result = await outcome(within: .seconds(10)) { () -> Data? in + var iterator = stream.makeAsyncIterator() + return try await iterator.next() } + guard case .returned(let data?) = result else { + Issue.record("No message after reconnecting: \(result)") + await transport.disconnect() + return + } + #expect(String(decoding: data, as: UTF8.self) == message) - // Wait for potential reconnection attempt - try await Task.sleep(for: .milliseconds(600)) + try await transport.send(Data(#"{"k":"v"}"#.utf8)) + #expect(made.latest?.getSentData().count == 1) + #expect(first.getSentData().isEmpty) await transport.disconnect() } @@ -763,8 +887,7 @@ import Testing let mockConnection = MockNetworkConnection() let transport = NetworkTransport( mockConnection, - heartbeatConfig: .disabled, - reconnectionConfig: .disabled + reconnection: .disabled ) try await transport.connect() @@ -788,13 +911,159 @@ import Testing await transport.disconnect() } + @Test("By default a lost connection finishes the stream and a failed connect() is not retried") + func testDefaultDoesNotReconnect() async throws { + // A connection lost after it was ready + let (lost, lostMade) = Self.dialing { _ in [.ready] } + try await lost.connect() + let stream = await lost.receive() + try #require(lostMade.latest).simulateFailure(error: NWError.posix(.ECONNRESET)) + let finished = await outcome(within: .seconds(10)) { for try await _ in stream {} } + #expect(!finished.didTimeOut, "the stream stayed open") + #expect(Self.isTransportError(finished.error, wrapping: .posix(.ECONNRESET))) + #expect(lostMade.count == 1) + #expect(lostMade.latest?.isCancelRequested == true) + await #expect(throws: MCPError.connectionClosed) { + try await lost.send(Data(#"{"k":"v"}"#.utf8)) + } + await lost.disconnect() + + // A connection that fails before it is ready + let (refused, refusedMade) = Self.dialing { _ in [.failed(.posix(.ECONNREFUSED))] } + let result = await outcome(within: .seconds(10)) { try await refused.connect() } + #expect(!result.didTimeOut, "connect() hung") + #expect(result.error as? NWError == .posix(.ECONNREFUSED)) + #expect(refusedMade.count == 1) + #expect(refusedMade.latest?.isCancelRequested == true) + await refused.disconnect() + } + + @Test("A graceful peer close finishes the stream with connectionClosed, also with reconnection on", + arguments: [false, true]) + func testGracefulCloseFinishesStream(withLastMessage: Bool) async throws { + let (transport, made) = Self.dialing({ _ in [.ready] }, reconnection: .default) + let first = try #require(made.latest) + let message = #"{"jsonrpc":"2.0","method":"notifications/last"}"# + // The last bytes arrive with the close (isComplete), or the close comes alone. + if withLastMessage { first.queueTextMessage(message + "\n") } + first.simulatePeerClose() + + try await transport.connect() + let stream = await transport.receive() + let lines = Lines() + let result = await outcome(within: .seconds(10)) { + for try await data in stream { await lines.append(data) } + } + + // Before, a close took the error path, which reconnected and left the stream open. + #expect(!result.didTimeOut, "the stream stayed open") + #expect(result.mcpError == .connectionClosed) + #expect(await lines.values == (withLastMessage ? [message] : [])) + #expect(made.count == 1, "a graceful close dialed a new connection") + #expect(first.isCancelRequested) + await #expect(throws: MCPError.connectionClosed) { + try await transport.send(Data(#"{"k":"v"}"#.utf8)) + } + + await transport.disconnect() + } + + @Test("A message that completes a context that isn't final keeps the stream open; a final one finishes it") + func testMessageContextsAndFinalContext() async throws { + // The framework's own contexts: only a final context's completion is a read close. + #expect(!NWConnection.ContentContext.defaultMessage.isFinal) + #expect(NWConnection.ContentContext.finalMessage.isFinal) + + // As on UDP or WebSocket: each message completes its own context, which isn't final. + let messages = [ + #"{"jsonrpc":"2.0","method":"notifications/one"}"#, + #"{"jsonrpc":"2.0","method":"notifications/two"}"#, + #"{"jsonrpc":"2.0","method":"notifications/three"}"#, + ] + let mockConnection = MockNetworkConnection() + mockConnection.queueMessage( + Data((messages[0] + "\n").utf8), context: NWConnection.ContentContext(identifier: "datagram")) + // An empty message completes its context too, and isn't a close either. + mockConnection.queueMessage(Data(), context: NWConnection.ContentContext(identifier: "empty")) + mockConnection.queueMessage(Data((messages[1] + "\n").utf8), context: .defaultMessage) + mockConnection.queueMessage(Data((messages[2] + "\n").utf8), context: .finalMessage) + + let transport = NetworkTransport(mockConnection) + try await transport.connect() + let stream = await transport.receive() + let lines = Lines() + let result = await outcome(within: .seconds(10)) { + for try await data in stream { await lines.append(data) } + } + + // Before, the first completed message finished the stream. + #expect(!result.didTimeOut, "the final context did not finish the stream") + #expect(await lines.values == messages) + #expect(result.mcpError == .connectionClosed) + #expect(mockConnection.isCancelRequested) + + await transport.disconnect() + } + + @Test("connect() while the receive loop reconnects throws and dials nothing") + func testConnectDuringReconnectThrows() async throws { + // The first connection is lost; the reconnect's connection waits until the test + // makes it ready. + let (transport, made) = Self.dialing( + { index in index == 0 ? [.ready] : [.waiting(.posix(.ENETDOWN))] }, + reconnection: .init(enabled: true, maxAttempts: 5, backoffMultiplier: 1.0)) + try await transport.connect() + let first = try #require(made.latest) + first.simulateFailure(error: NWError.posix(.ECONNRESET)) + #expect(await eventually { made.count == 2 }) + let reconnecting = try #require(made.latest) + + // The transport is still the caller's connection: connect() throws, and dials nothing. + let result = await outcome(within: .seconds(5)) { try await transport.connect() } + #expect(!result.didTimeOut, "connect() hung") + #expect(result.mcpError == .internalError("Transport already connected")) + #expect(made.count == 2) + #expect(!reconnecting.isCancelRequested, "connect() cancelled the reconnect's connection") + + // A send meanwhile throws, without waiting for the reconnect. + await #expect(throws: MCPError.internalError("Transport not connected")) { + try await transport.send(Data(#"{"k":"v"}"#.utf8)) + } + + // Once the reconnect completes, sends go to the new connection. + reconnecting.simulateReady() + #expect( + await eventually { + (try? await transport.send(Data(#"{"k":"v"}"#.utf8))) != nil + }) + #expect(reconnecting.getSentData().count == 1) + + await transport.disconnect() + } + + @Test("disconnect() cancels the receive loop, which reads no more") + func testDisconnectCancelsReceiveLoop() async throws { + // The deferring mock reports no .cancelled, as NWConnection may not in time, so only + // the transport's own state can stop the loop. + let mockConnection = MockNetworkConnection(defersCancellation: true) + let transport = NetworkTransport(mockConnection) + try await transport.connect() + #expect(await eventually { mockConnection.receiveCount > 0 }) + let loop = try #require(await transport.receiveLoopTask) + + await transport.disconnect() + #expect(loop.isCancelled) + let ended = await outcome(within: .seconds(5)) { await loop.value } + #expect(!ended.didTimeOut, "the receive loop kept running after disconnect()") + + let reads = mockConnection.receiveCount + #expect(!(await eventually(within: .milliseconds(500)) { mockConnection.receiveCount > reads })) + } + @Test("Multiple Messages") func testNetworkTransportMultipleMessages() async throws { let mockConnection = MockNetworkConnection() - let transport = NetworkTransport( - mockConnection, - heartbeatConfig: .disabled - ) + let transport = NetworkTransport(mockConnection) // Queue multiple messages let messages = [ @@ -830,10 +1099,7 @@ import Testing @Test("Disconnect During Receive") func testNetworkTransportDisconnectDuringReceive() async throws { let mockConnection = MockNetworkConnection() - let transport = NetworkTransport( - mockConnection, - heartbeatConfig: .disabled - ) + let transport = NetworkTransport(mockConnection) try await transport.connect() @@ -862,10 +1128,7 @@ import Testing @Test("Partial Message Reception") func testPartialMessageReception() async throws { let mockConnection = MockNetworkConnection() - let transport = NetworkTransport( - mockConnection, - heartbeatConfig: .disabled - ) + let transport = NetworkTransport(mockConnection) try await transport.connect() @@ -899,10 +1162,7 @@ import Testing @Test("Large Message Handling") func testLargeMessageHandling() async throws { let mockConnection = MockNetworkConnection() - let transport = NetworkTransport( - mockConnection, - heartbeatConfig: .disabled - ) + let transport = NetworkTransport(mockConnection) try await transport.connect() @@ -928,10 +1188,7 @@ import Testing @Test("Receive buffer releases parsed messages") func testReceiveBufferStaysBounded() async throws { let mockConnection = MockNetworkConnection() - let transport = NetworkTransport( - mockConnection, - heartbeatConfig: .disabled - ) + let transport = NetworkTransport(mockConnection) // Chunks end mid-message, so some reads leave a partial message buffered. let messageCount = 5000 @@ -955,46 +1212,34 @@ import Testing await transport.disconnect() } - @Test("Reconnection Backoff") + @Test("With reconnection on, a failed attempt retries on a fresh connection with backoff") func testReconnectionBackoff() async throws { - let mockConnection = MockNetworkConnection() - let startTime = Date() + // Two refused connections, then one that connects + let (transport, made) = Self.dialing( + { index in index < 2 ? [.failed(.posix(.ECONNREFUSED))] : [.ready] }, + reconnection: .init(enabled: true, maxAttempts: 3, backoffMultiplier: 2.0)) - // Configure for quick reconnection with known backoff - let reconnectionConfig = NetworkTransport.ReconnectionConfiguration( - enabled: true, - maxAttempts: 3, - backoffMultiplier: 2.0 - ) - - let transport = NetworkTransport( - mockConnection, - heartbeatConfig: .disabled, - reconnectionConfig: reconnectionConfig - ) - - try await transport.connect() - - // Simulate failure - mockConnection.simulateFailure(error: NWError.posix(POSIXErrorCode.ECONNRESET)) + let start = ContinuousClock.now + let result = await outcome(within: .seconds(20)) { try await transport.connect() } + let elapsed = ContinuousClock.now - start - // Wait for reconnection attempts - try await Task.sleep(for: .seconds(4)) - - let endTime = Date() - let duration = endTime.timeIntervalSince(startTime) - - // Verify we had enough time for reconnection attempts - #expect(duration >= 3.5) // Should have time for 3 attempts with backoff + #expect(!result.didTimeOut, "connect() hung") + #expect(result.error == nil, "connect() should succeed on the third connection") + #expect(made.count == 3) + #expect(made.all.prefix(2).allSatisfy { $0.isCancelRequested }) + // 0.5 s, then 1.0 s, between the attempts + #expect(elapsed >= .seconds(1.5), "the retries did not back off: \(elapsed)") + try await transport.send(Data(#"{"k":"v"}"#.utf8)) + #expect(made.latest?.getSentData().count == 1) await transport.disconnect() } @Test("connect() retries on a fresh connection instead of restarting the cancelled one") func testConnectRetriesOnFreshConnection() async throws { - // The first connection cannot reach its peer; the fresh one the retry dials can. + // The first connection is refused; the fresh one the retry dials connects. let made = MadeConnections() - let first = MockNetworkConnection(startState: .waiting(.posix(.ECONNREFUSED))) + let first = MockNetworkConnection(startState: .failed(.posix(.ECONNREFUSED))) made.add(first) let transport = NetworkTransport( first: first, @@ -1003,8 +1248,7 @@ import Testing made.add(connection) return connection }, - heartbeatConfig: .disabled, - reconnectionConfig: .init(enabled: true, maxAttempts: 2, backoffMultiplier: 1.0) + reconnection: .init(enabled: true, maxAttempts: 2, backoffMultiplier: 1.0) ) // Restarting the cancelled first connection would report no state, so connect() @@ -1020,44 +1264,273 @@ import Testing await transport.disconnect() } - @Test("connect() to an unreachable endpoint fails within the retry budget instead of hanging") + @Test("A waiting connection uses no attempt") + func testWaitingUsesNoAttempt() async throws { + // One retry in all. The first connection waits three times, then is refused; the + // second waits, then connects. If a wait used an attempt, the budget would run out + // on the first connection. + let waiting = NWConnection.State.waiting(.posix(.ENETDOWN)) + let (transport, made) = Self.dialing( + { index in + index == 0 + ? [waiting, waiting, waiting, .failed(.posix(.ECONNREFUSED))] : [waiting, .ready] + }, + reconnection: .init(enabled: true, maxAttempts: 1, backoffMultiplier: 1.0)) + + let result = await outcome(within: .seconds(10)) { try await transport.connect() } + #expect(!result.didTimeOut, "connect() hung") + #expect(result.error == nil, "connect() should succeed on the second connection") + #expect(made.count == 2) + + await transport.disconnect() + } + + @Test("A waiting connection that becomes ready before the timeout connects") + func testWaitingThenReadyConnects() async throws { + // As while the Local Network prompt is up: the connection waits, then the user allows + // access and NWConnection becomes ready by itself, with reconnection off. + let (transport, made) = Self.dialing { _ in [.waiting(.posix(.ENETDOWN))] } + let first = try #require(made.latest) + + let connecting = Task { + await outcome(within: .seconds(10)) { try await transport.connect() } + } + #expect(await eventually { first.state == .waiting(.posix(.ENETDOWN)) }) + first.simulateReady() + + let result = await connecting.value + #expect(!result.didTimeOut, "connect() hung") + #expect(result.error == nil, "connect() should succeed once the connection is ready") + #expect(made.count == 1) + #expect(!first.isCancelRequested) + try await transport.send(Data(#"{"k":"v"}"#.utf8)) + #expect(first.getSentData().count == 1) + + await transport.disconnect() + } + + @Test("A huge connectionTimeout such as .seconds(Int64.max) does not trap and connects") + func testHugeConnectionTimeoutDoesNotTrap() async throws { + let (transport, made) = Self.dialing( + { _ in [.waiting(.posix(.ENETDOWN))] }, + connectionTimeout: .seconds(Int64.max)) + let first = try #require(made.latest) + + let connecting = Task { + await outcome(within: .seconds(10)) { try await transport.connect() } + } + #expect(await eventually { first.state == .waiting(.posix(.ENETDOWN)) }) + first.simulateReady() + + let result = await connecting.value + #expect(!result.didTimeOut, "connect() hung") + #expect(result.error == nil, "connect() failed: \(result)") + await transport.disconnect() + } + + @Test("Non-finite or huge backoffMultiplier does not trap in Duration.seconds") + func testNonFiniteOrHugeBackoffMultiplierDoesNotTrap() async throws { + // Attempt 1 fails (backoff = 0.5 * multiplier^0 = 0.5s), attempt 2 fails + // (backoff = 0.5 * multiplier^1 = .infinity / 1e300 / NaN), bounded by connectionTimeout. + for multiplier in [Double.infinity, 1e300, Double.nan] { + let (transport, made) = Self.dialing( + { attempt in attempt < 2 ? [.failed(.posix(.ECONNREFUSED))] : [.ready] }, + connectionTimeout: multiplier.isNaN ? .seconds(5) : .milliseconds(1200), + reconnection: .init(enabled: true, maxAttempts: 3, backoffMultiplier: multiplier)) + let result = await outcome(within: .seconds(10)) { try await transport.connect() } + #expect(!result.didTimeOut, "connect() hung for multiplier \(multiplier)") + if multiplier.isNaN { + #expect(result.error == nil, "NaN backoff should clamp to zero and connect: \(result)") + #expect(made.count == 3) + } else { + #expect(result.error is NWError, "Huge backoff should time out cleanly: \(result)") + #expect(made.count == 2) + } + await transport.disconnect() + } + } + + @Test("Repeated empty reads on a non-ready connection cancel it and finish the stream with connectionClosed") + func testEmptyReadsOnNonReadyConnectionExit() async throws { + let mockConnection = MockNetworkConnection() + let transport = NetworkTransport(mockConnection) + try await transport.connect() + let stream = await transport.receive() + + // Transition away from .ready while no data is queued: after consecutive empty reads, + // readMessages() cancels the connection and finishes the stream with connectionClosed. + mockConnection.simulateWaiting(.posix(.ENETDOWN)) + + let ended = await outcome(within: .seconds(10)) { + for try await _ in stream {} + } + #expect(ended.mcpError == .connectionClosed, "Got \(ended)") + #expect(mockConnection.isCancelRequested) + await transport.disconnect() + } + + @Test("connect() to a peer it can't reach throws once connectionTimeout passes") func testNetworkTransportConnectUnreachable() async throws { - // Nothing listens on the discard port, so the connection never reaches .ready. + // Nothing listens on the discard port, so the connection never reaches .ready: it + // waits, or fails at once. let connection = NWConnection(host: "127.0.0.1", port: 9, using: .tcp) let transport = NetworkTransport( connection: connection, - heartbeatConfig: .disabled, - reconnectionConfig: .init(enabled: true, maxAttempts: 2, backoffMultiplier: 1.0) + connectionTimeout: .milliseconds(200) ) let result = await outcome(within: .seconds(20)) { try await transport.connect() } #expect(!result.didTimeOut, "connect() must not hang") - #expect(result.error != nil, "connect() should throw when the peer is unreachable") + #expect(result.error is NWError, "connect() should throw an NWError: \(String(describing: result.error))") await transport.disconnect() } + @Test("On timeout connect() throws the last NWError it saw") + func testTimeoutThrowsLastError() async throws { + let (waited, _) = Self.dialing( + { _ in [.waiting(.posix(.ECONNREFUSED)), .waiting(.posix(.ENETDOWN))] }, + connectionTimeout: .milliseconds(300)) + let waitedResult = await outcome(within: .seconds(10)) { try await waited.connect() } + #expect(!waitedResult.didTimeOut, "connect() hung") + #expect(waitedResult.error as? NWError == .posix(.ENETDOWN)) + await waited.disconnect() + + // With no error seen, ETIMEDOUT + let (preparing, preparingMade) = Self.dialing( + { _ in [.preparing] }, connectionTimeout: .milliseconds(300)) + let preparingResult = await outcome(within: .seconds(10)) { try await preparing.connect() } + #expect(!preparingResult.didTimeOut, "connect() hung") + #expect(preparingResult.error as? NWError == .posix(.ETIMEDOUT)) + #expect(preparingMade.latest?.isCancelRequested == true) + await preparing.disconnect() + } + + @Test("connectionTimeout caps connect() across attempts, waits and backoff") + func testConnectionTimeoutCapsConnect() async throws { + // Two refused connections with a 0.5 s backoff after each, then one that waits for + // good, under a budget of 50 attempts that alone would take far longer. + let timeout = Duration.seconds(2.5) + let (transport, made) = Self.dialing( + { index in + index < 2 + ? [.waiting(.posix(.ENETUNREACH)), .failed(.posix(.ECONNREFUSED))] + : [.waiting(.posix(.ENETDOWN))] + }, + connectionTimeout: timeout, + reconnection: .init(enabled: true, maxAttempts: 50, backoffMultiplier: 1.0)) + + let start = ContinuousClock.now + let result = await outcome(within: .seconds(20)) { try await transport.connect() } + let elapsed = ContinuousClock.now - start + + #expect(!result.didTimeOut, "connect() hung") + #expect(result.error as? NWError == .posix(.ENETDOWN)) + #expect(elapsed >= timeout) + #expect(elapsed < timeout + .seconds(5), "connect() ran past its timeout: \(elapsed)") + #expect(made.count == 3) + #expect(made.all.allSatisfy { $0.isCancelRequested }) + + await transport.disconnect() + } + + @Test("connectionTimeout caps a reconnect from the receive loop, which then finishes the stream") + func testConnectionTimeoutCapsReconnect() async throws { + // The first connection is lost; every later one waits for good. + let timeout = Duration.seconds(1.5) + let (transport, made) = Self.dialing( + { index in index == 0 ? [.ready] : [.waiting(.posix(.ENETDOWN))] }, + connectionTimeout: timeout, + reconnection: .init(enabled: true, maxAttempts: 5, backoffMultiplier: 1.0)) + try await transport.connect() + let first = try #require(made.latest) + let stream = await transport.receive() + + let start = ContinuousClock.now + first.simulateFailure(error: NWError.posix(.ECONNRESET)) + // Before, a reconnect that failed left the stream open, and the client waited forever. + let result = await outcome(within: .seconds(20)) { for try await _ in stream {} } + let elapsed = ContinuousClock.now - start + + #expect(!result.didTimeOut, "the stream stayed open") + #expect(Self.isTransportError(result.error, wrapping: .posix(.ENETDOWN))) + #expect(elapsed >= timeout) + // A waiting connection uses no attempt, so the reconnect dialed one connection. + #expect(made.count == 2) + #expect(made.latest?.isCancelRequested == true) + await #expect(throws: MCPError.connectionClosed) { + try await transport.send(Data(#"{"k":"v"}"#.utf8)) + } + + await transport.disconnect() + } + + @Test("Cancelling a waiting connect() throws CancellationError and cancels the connection") + func testCancellingWaitingConnect() async throws { + let (transport, made) = Self.dialing { _ in [.waiting(.posix(.ENETDOWN))] } + let first = try #require(made.latest) + + let connecting = Task { try await transport.connect() } + #expect(await eventually { first.state == .waiting(.posix(.ENETDOWN)) }) + connecting.cancel() + + let result = await outcome(within: .seconds(10)) { try await connecting.value } + #expect(!result.didTimeOut, "connect() hung after its task was cancelled") + #expect(result.error is CancellationError) + #expect(first.isCancelRequested) + #expect(made.count == 1) + await #expect(throws: MCPError.self) { + try await transport.send(Data(#"{"k":"v"}"#.utf8)) + } + + await transport.disconnect() + } + + @Test("disconnect() during connect() dials nothing more and cancels the connection") + func testDisconnectDuringWaitingConnect() async throws { + // The deferring mock reports no .cancelled, as NWConnection may not in time, so only + // disconnect() itself can end the wait. + let (transport, made) = Self.dialing( + { _ in [.waiting(.posix(.ENETDOWN))] }, defersCancellation: true, + reconnection: .default) + let first = try #require(made.latest) + + let connecting = Task { + await outcome(within: .seconds(20)) { try await transport.connect() } + } + #expect(await eventually { first.state == .waiting(.posix(.ENETDOWN)) }) + await transport.disconnect() + + let result = await outcome(within: .seconds(5)) { await connecting.value } + guard case .returned(let connected) = result else { + Issue.record("connect() kept waiting after disconnect()") + return + } + #expect(connected.mcpError == .connectionClosed) + #expect(first.isCancelRequested) + #expect(made.count == 1) + } + @Test("connect() after a failed connect() dials fresh instead of hanging on the cancelled one") func testConnectAfterFailedConnectDialsFresh() async throws { - // Every connection stays .waiting, so each connect() fails and cancels its connection. + // Every connection is refused, so each connect() fails and cancels its connection. // Like NWConnection, the mocks do not report .cancelled from cancel() itself, so the // transport cannot learn from `state` that the connection was cancelled. let made = MadeConnections() let first = MockNetworkConnection( - startState: .waiting(.posix(.ECONNREFUSED)), defersCancellation: true) + startState: .failed(.posix(.ECONNREFUSED)), defersCancellation: true) made.add(first) let transport = NetworkTransport( first: first, makeConnection: { let connection = MockNetworkConnection( - startState: .waiting(.posix(.ECONNREFUSED)), defersCancellation: true) + startState: .failed(.posix(.ECONNREFUSED)), defersCancellation: true) made.add(connection) return connection }, - heartbeatConfig: .disabled, - reconnectionConfig: .disabled + reconnection: .disabled ) let firstConnect = await outcome(within: .seconds(10)) { try await transport.connect() } @@ -1092,20 +1565,19 @@ import Testing @Test("disconnect() during connect()'s backoff stops it instead of dialing on") func testDisconnectDuringConnectBackoffStops() async throws { - // Every connection stays .waiting, so connect() spends its time in the backoff between + // Every connection is refused, so connect() spends its time in the backoff between // attempts, with a budget far longer than the test's bound. let made = MadeConnections() - let first = MockNetworkConnection(startState: .waiting(.posix(.ECONNREFUSED))) + let first = MockNetworkConnection(startState: .failed(.posix(.ECONNREFUSED))) made.add(first) let transport = NetworkTransport( first: first, makeConnection: { - let connection = MockNetworkConnection(startState: .waiting(.posix(.ECONNREFUSED))) + let connection = MockNetworkConnection(startState: .failed(.posix(.ECONNREFUSED))) made.add(connection) return connection }, - heartbeatConfig: .disabled, - reconnectionConfig: .init(enabled: true, maxAttempts: 50, backoffMultiplier: 2.0) + reconnection: .init(enabled: true, maxAttempts: 50, backoffMultiplier: 2.0) ) let connected = Task { @@ -1130,8 +1602,7 @@ import Testing let mock = MockNetworkConnection(startState: .preparing) let transport = NetworkTransport( mock, - heartbeatConfig: .disabled, - reconnectionConfig: .disabled + reconnection: .disabled ) let connecting = Task { try await transport.connect() } @@ -1159,8 +1630,7 @@ import Testing let mock = MockNetworkConnection(startState: .preparing, defersCancellation: true) let transport = NetworkTransport( mock, - heartbeatConfig: .disabled, - reconnectionConfig: .disabled + reconnection: .disabled ) let connecting = Task { @@ -1178,11 +1648,11 @@ import Testing } } - @Test("connect() after disconnect() on a transport that never connected dials fresh") + @Test("connect() after disconnect() throws and dials nothing") func testConnectAfterDisconnectBeforeConnect() async throws { - // disconnect() cancels the connection even though it was never started, and a - // cancelled connection cannot be started. The deferring mocks report no .cancelled, - // like NWConnection right after cancel(). + // A transport serves one connection: disconnect(), even before connect(), closes it. + // The deferring mock reports no .cancelled, like NWConnection right after cancel(), + // so a connect() that dialed on the cancelled connection would hang. let made = MadeConnections() let first = MockNetworkConnection(defersCancellation: true) made.add(first) @@ -1193,8 +1663,7 @@ import Testing made.add(connection) return connection }, - heartbeatConfig: .disabled, - reconnectionConfig: .disabled + reconnection: .disabled ) await transport.disconnect() @@ -1202,9 +1671,13 @@ import Testing let result = await outcome(within: .seconds(10)) { try await transport.connect() } #expect(!result.didTimeOut, "connect() hung on the connection disconnect() cancelled") - #expect(result.error == nil, "connect() should succeed on a fresh connection") - #expect(made.count == 2) - try await transport.send(Data(#"{"k":"v"}"#.utf8)) + #expect( + result.error as? MCPError + == .internalError("Transport disconnected; create a new transport to reconnect")) + #expect(made.count == 1) + await #expect(throws: MCPError.connectionClosed) { + try await transport.send(Data(#"{"k":"v"}"#.utf8)) + } await transport.disconnect() } @@ -1221,8 +1694,7 @@ import Testing made.add(connection) return connection }, - heartbeatConfig: .disabled, - reconnectionConfig: .disabled + reconnection: .disabled ) let firstConnect = Task { @@ -1249,78 +1721,6 @@ import Testing await transport.disconnect() } - @Test("Heartbeat Failure Handling") - func testHeartbeatFailureHandling() async throws { - let mockConnection = MockNetworkConnection() - - // Create transport with rapid heartbeats - let heartbeatConfig = NetworkTransport.HeartbeatConfiguration( - enabled: true, - interval: 0.1 - ) - - let transport = NetworkTransport( - mockConnection, - heartbeatConfig: heartbeatConfig - ) - - try await transport.connect() - - // Wait for initial heartbeat - let heartbeatDeadline = ContinuousClock.now + .seconds(30) - while mockConnection.getSentData().isEmpty && ContinuousClock.now < heartbeatDeadline { - try await Task.sleep(for: .milliseconds(5)) - } - #expect(mockConnection.getSentData().count >= 1) - - // Simulate failure during heartbeat - mockConnection.simulateFailure(error: NWError.posix(POSIXErrorCode.ECONNRESET)) - - // The transport should react to the failure by cancelling the - // connection before it tries to reconnect - let deadline = ContinuousClock.now + .seconds(30) - while mockConnection.state != .cancelled && ContinuousClock.now < deadline { - try await Task.sleep(for: .milliseconds(50)) - } - #expect(mockConnection.state == .cancelled) - - // Once the connection is lost, the transport should stop sending heartbeats. - // A failed heartbeat retries after 2 seconds, so wait longer than that. - let heartbeatsSent = mockConnection.getSentData().count - try await Task.sleep(for: .seconds(2.5)) - #expect(mockConnection.getSentData().count == heartbeatsSent) - - await transport.disconnect() - } - - @Test("Heartbeats stop when empty reads reveal a failed connection") - func testHeartbeatsStopAfterEmptyReadFailure() async throws { - let mockConnection = MockNetworkConnection() - let transport = NetworkTransport( - mockConnection, - heartbeatConfig: .init(enabled: true, interval: 0.1) - ) - - try await transport.connect() - mockConnection.simulateFailure() - - let deadline = ContinuousClock.now + .seconds(30) - while mockConnection.state != .cancelled && ContinuousClock.now < deadline { - try await Task.sleep(for: .milliseconds(50)) - } - #expect(mockConnection.state == .cancelled) - - await #expect(throws: MCPError.self) { - try await transport.send(Data()) - } - - let heartbeatsSent = mockConnection.getSentData().count - try await Task.sleep(for: .seconds(2.5)) - #expect(mockConnection.getSentData().count == heartbeatsSent) - - await transport.disconnect() - } - @Test("Resource Cleanup") func testResourceCleanup() async throws { weak var weakConnection: MockNetworkConnection? @@ -1330,10 +1730,7 @@ import Testing weakConnection = mockConnection // Create and use transport in a separate scope - let transport = NetworkTransport( - mockConnection, - heartbeatConfig: .disabled - ) + let transport = NetworkTransport(mockConnection) try await transport.connect() await transport.disconnect() @@ -1352,10 +1749,7 @@ import Testing @Test("A message received in many pieces is searched for its newline once") func testLongMessageIsSearchedOnce() async throws { let mockConnection = MockNetworkConnection() - let transport = NetworkTransport( - mockConnection, - heartbeatConfig: .disabled - ) + let transport = NetworkTransport(mockConnection) // A heartbeat, then a message of 1 MiB of text in pieces of 1000 bytes. let message = Data( @@ -1384,10 +1778,7 @@ import Testing @Test("A message longer than 16 MiB ends the receive stream and cancels the connection") func testMessageOverLimitEndsStream() async throws { let mockConnection = MockNetworkConnection() - let transport = NetworkTransport( - mockConnection, - heartbeatConfig: .disabled - ) + let transport = NetworkTransport(mockConnection) // One byte over the limit and no newline: the limit holds before a message ends. let piece = Data(repeating: UInt8(ascii: "a"), count: 1 << 20) @@ -1413,10 +1804,7 @@ import Testing @Test("A message that ends past 16 MiB in the read that completes it ends the receive stream") func testCompletedMessageOverLimitEndsStream() async throws { let mockConnection = MockNetworkConnection() - let transport = NetworkTransport( - mockConnection, - heartbeatConfig: .disabled - ) + let transport = NetworkTransport(mockConnection) // The first read stays under the limit; the second ends the message one byte past // it and carries the next message, which must not be delivered. @@ -1444,10 +1832,7 @@ import Testing @Test("A message of exactly 16 MiB is delivered") func testMessageAtLimitIsDelivered() async throws { let mockConnection = MockNetworkConnection() - let transport = NetworkTransport( - mockConnection, - heartbeatConfig: .disabled - ) + let transport = NetworkTransport(mockConnection) let limit = NetworkTransport.maxMessageLength mockConnection.queueDataForReceiving(Data(repeating: UInt8(ascii: "a"), count: limit)) @@ -1462,13 +1847,12 @@ import Testing await transport.disconnect() } - @Test("With unlimited buffers a message longer than 16 MiB is delivered") - func testUnlimitedBuffersDeliverLongerMessage() async throws { + @Test("With maximumMessageLength Int.max a message longer than 16 MiB is delivered") + func testUnlimitedLengthDeliversLongerMessage() async throws { let mockConnection = MockNetworkConnection() let transport = NetworkTransport( mockConnection, - heartbeatConfig: .disabled, - bufferConfig: .unlimited + maximumMessageLength: Int.max ) let limit = NetworkTransport.maxMessageLength @@ -1485,22 +1869,21 @@ import Testing await transport.disconnect() } - @Test("A buffer size larger than 16 MiB raises the message limit to that size") - func testLargerBufferRaisesMessageLimit() async throws { - let bufferSize = 20 << 20 + @Test("A maximumMessageLength larger than 16 MiB raises the message limit to that length") + func testLargerMaximumRaisesMessageLimit() async throws { + let maximum = 20 << 20 let mockConnection = MockNetworkConnection() let transport = NetworkTransport( mockConnection, - heartbeatConfig: .disabled, - bufferConfig: .init(maxReceiveBufferSize: bufferSize) + maximumMessageLength: maximum ) - // A message longer than 16 MiB but within the buffer size arrives; one longer than - // the buffer size ends the stream. + // A message longer than 16 MiB but within the maximum arrives; one longer than the + // maximum ends the stream. let delivered = NetworkTransport.maxMessageLength + 1 mockConnection.queueDataForReceiving(Data(repeating: UInt8(ascii: "a"), count: delivered)) mockConnection.queueDataForReceiving(Data("\n".utf8)) - mockConnection.queueDataForReceiving(Data(repeating: UInt8(ascii: "b"), count: bufferSize + 1)) + mockConnection.queueDataForReceiving(Data(repeating: UInt8(ascii: "b"), count: maximum + 1)) try await transport.connect() let stream = await transport.receive() @@ -1511,7 +1894,34 @@ import Testing let receivedSizes = await sizes.values #expect(receivedSizes == [delivered]) - #expect(result.mcpError == .internalError(NetworkTransport.messageTooLong(limit: bufferSize))) + #expect(result.mcpError == .internalError(NetworkTransport.messageTooLong(limit: maximum))) + #expect(mockConnection.state == .cancelled) + await transport.disconnect() + } + + @Test("A maximumMessageLength smaller than 16 MiB lowers the message limit to that length") + func testSmallerMaximumLowersMessageLimit() async throws { + let maximum = 100 + let mockConnection = MockNetworkConnection() + let transport = NetworkTransport( + mockConnection, + maximumMessageLength: maximum + ) + + // A message of exactly the maximum arrives; the next, one byte longer, ends the stream. + mockConnection.queueDataForReceiving(Data(repeating: UInt8(ascii: "a"), count: maximum) + Data("\n".utf8)) + mockConnection.queueDataForReceiving( + Data(repeating: UInt8(ascii: "b"), count: maximum + 1) + Data("\n".utf8)) + + try await transport.connect() + let stream = await transport.receive() + let sizes = Messages() + let result = await outcome(within: .seconds(30)) { + for try await message in stream { await sizes.append(message.count) } + } + + #expect(await sizes.values == [maximum]) + #expect(result.mcpError == .internalError("Message longer than 100 bytes")) #expect(mockConnection.state == .cancelled) await transport.disconnect() } diff --git a/Tests/MCPTests/OAuthAuthorizationCodeFlowTests.swift b/Tests/MCPTests/OAuthAuthorizationCodeFlowTests.swift index 86d7bf41..23400092 100644 --- a/Tests/MCPTests/OAuthAuthorizationCodeFlowTests.swift +++ b/Tests/MCPTests/OAuthAuthorizationCodeFlowTests.swift @@ -98,6 +98,50 @@ struct OAuthAuthorizationCodeFlowTests { #expect(!items.contains(where: { $0.name == "scope" })) } + /// A URL that `URLComponents` can't read: an unclosed IPv6 literal, which only a + /// `CFURL` made from raw bytes keeps. `URL(string:)` and `URL(dataRepresentation:)` + /// reject it on every platform, so on Linux there is no such URL. + static func unreadableAuthorizationEndpoint(_ string: String = "https://[::1/authorize") -> URL? { + #if canImport(Darwin) + let bytes = Array(string.utf8) + return CFURLCreateWithBytes( + nil, bytes, bytes.count, CFStringBuiltInEncodings.UTF8.rawValue, nil) as URL? + #else + return nil + #endif + } + + @Test( + "buildURL throws authorizationEndpointInvalid, without the endpoint's secrets, for an endpoint URLComponents can't read", + .enabled( + if: Self.unreadableAuthorizationEndpoint() != nil, + "Only a CFURL on Darwin makes a URL that URLComponents can't read")) + func testBuildURLThrowsForUnreadableEndpoint() throws { + let endpoint = try #require( + Self.unreadableAuthorizationEndpoint("https://user:pw-secret@[::1/authorize?token=q-secret#f-secret")) + try #require(URLComponents(url: endpoint, resolvingAgainstBaseURL: false) == nil) + + let error = #expect(throws: OAuthAuthorizationError.self) { + try flow.buildURL( + authorizationEndpoint: endpoint, + resource: resource, + redirectURI: redirectURI, + clientID: "my-client", + codeChallenge: "abc123", + scopes: nil, + state: "state-xyz", + scopeSerializer: scopeSelector + ) + } + // Errors are logged: a URL that can't be read is named by a placeholder. + #expect(error == .authorizationEndpointInvalid(url: "")) + for text in [error?.errorDescription ?? "", "\(String(describing: error))"] { + for secret in ["pw-secret", "q-secret", "f-secret"] { + #expect(!text.contains(secret), "\(text)") + } + } + } + // MARK: - extractCode @Test("extractCode returns code from valid redirect URL") @@ -151,17 +195,23 @@ struct OAuthAuthorizationCodeFlowTests { } } - @Test("extractCode throws redirect URI mismatch") + @Test("extractCode throws redirect URI mismatch without leaking code or state") func testExtractCodeThrowsRedirectMismatch() { let redirectURL = URL(string: - "https://evil.example.com/callback?code=auth-code-123&state=my-state")! - #expect(throws: OAuthAuthorizationError.self) { + "https://evil.example.com/callback?code=auth-code-secret&state=csrf-state-secret#frag-secret")! + let error = #expect(throws: OAuthAuthorizationError.self) { try flow.extractCode( from: redirectURL, expectedRedirectURI: redirectURI, - expectedState: "my-state" + expectedState: "csrf-state-secret" ) } + #expect(error?.code == .authorizationResponseRedirectMismatch) + let description = error?.errorDescription ?? "" + #expect(description.contains("https://evil.example.com/callback")) + #expect(!description.contains("auth-code-secret"), "\(description)") + #expect(!description.contains("csrf-state-secret"), "\(description)") + #expect(!description.contains("frag-secret"), "\(description)") } @Test("extractCode normalizes host case in redirect URI comparison") diff --git a/Tests/MCPTests/OAuthAuthorizationErrorTests.swift b/Tests/MCPTests/OAuthAuthorizationErrorTests.swift index b052ba51..25d1017f 100644 --- a/Tests/MCPTests/OAuthAuthorizationErrorTests.swift +++ b/Tests/MCPTests/OAuthAuthorizationErrorTests.swift @@ -55,10 +55,34 @@ struct OAuthAuthorizationErrorTests { #expect(failed.statusCode == 400) #expect(failed.oauthError == "invalid_grant") #expect(failed.errorDescription == "Token request failed with status 400 (oauth_error: invalid_grant)") + let statusless = OAuthAuthorizationError.tokenRequestFailed(statusCode: nil, oauthError: nil) + #expect(statusless.code == .tokenRequestFailed) + #expect(statusless.statusCode == nil) + #expect(statusless.errorDescription == "Token request failed with status unknown") let blocked = OAuthAuthorizationError.insecureOAuthEndpoint(context: "Token endpoint", url: "http://a") #expect(blocked.errorDescription == "Token endpoint must use https or loopback http: http://a") } + @Test("The registration and authorization endpoint errors have their own descriptions") + func registrationAndAuthorizationEndpointDescriptions() { + let refused = OAuthAuthorizationError.registrationRequestFailed( + statusCode: 400, oauthError: "invalid_redirect_uri") + #expect(refused.errorDescription == "Client registration failed with status 400 (oauth_error: invalid_redirect_uri)") + let notHTTP = OAuthAuthorizationError.registrationRequestFailed(statusCode: nil, oauthError: nil) + #expect(notHTTP.errorDescription == "Client registration failed with status unknown") + #expect( + OAuthAuthorizationError.registrationResponseInvalid.errorDescription + == "Client registration response is invalid") + #expect( + OAuthAuthorizationError.authorizationEndpointMissing.errorDescription + == "Authorization server metadata is missing authorization_endpoint") + let invalid = OAuthAuthorizationError.authorizationEndpointInvalid(url: "https://as.example/authorize") + #expect(invalid.url == "https://as.example/authorize") + #expect( + invalid.errorDescription + == "Authorization endpoint cannot be made into an authorization request URL: https://as.example/authorize") + } + @Test("A code the SDK does not know has a description") func unknownCode() { let error = OAuthAuthorizationError(code: .init(rawValue: "deviceCodeExpired")) diff --git a/Tests/MCPTests/OAuthAuthorizationTests.swift b/Tests/MCPTests/OAuthAuthorizationTests.swift index bde5889c..9a232195 100644 --- a/Tests/MCPTests/OAuthAuthorizationTests.swift +++ b/Tests/MCPTests/OAuthAuthorizationTests.swift @@ -182,6 +182,172 @@ struct OAuthAuthorizationTests { } } + // MCP 2025-11-25 "Canonical Server URI" and RFC 3986 §6.2.2-6.2.3. + @Test( + "Canonical resource URIs", + arguments: [ + ("https://mcp.example.com/mcp/", "https://mcp.example.com/mcp"), + ("https://mcp.example.com/mcp", "https://mcp.example.com/mcp"), + ("https://mcp.example.com/", "https://mcp.example.com"), + ("https://mcp.example.com", "https://mcp.example.com"), + ("https://mcp.example.com/server/mcp/", "https://mcp.example.com/server/mcp"), + ("https://mcp.example.com:443/mcp", "https://mcp.example.com/mcp"), + ("https://mcp.example.com:443/", "https://mcp.example.com"), + ("http://localhost:80/mcp", "http://localhost/mcp"), + ("http://127.0.0.1:443/mcp", "http://127.0.0.1:443/mcp"), + ("https://mcp.example.com:80/mcp", "https://mcp.example.com:80/mcp"), + ("https://mcp.example.com:8443/mcp", "https://mcp.example.com:8443/mcp"), + ("https://MCP.Example.COM/Mcp", "https://mcp.example.com/Mcp"), + ("HTTPS://mcp.example.com/mcp?tenant=a", "https://mcp.example.com/mcp"), + ("https://user:secret@mcp.example.com/mcp", "https://mcp.example.com/mcp"), + ("https://user@mcp.example.com:443/mcp/", "https://mcp.example.com/mcp"), + ("https://mcp.example.com/a%2fb/%7euser/%e2%82%ac", "https://mcp.example.com/a%2Fb/~user/%E2%82%AC"), + ("https://mcp.example.com/%41%2D%5F", "https://mcp.example.com/A-_"), + ("https://mcp.example.com/a%20b/", "https://mcp.example.com/a%20b"), + ("http://[::1]:80/mcp", "http://[::1]/mcp"), + ("https://mcp.example.com/mcp//", "https://mcp.example.com/mcp"), + ("https://mcp.example.com//", "https://mcp.example.com"), + ("https://mcp.example.com/mcp/../admin", "https://mcp.example.com/admin"), + ("https://mcp.example.com/a/./b/../c/", "https://mcp.example.com/a/c"), + ("https://mcp.example.com/mcp/%2E%2E/admin", "https://mcp.example.com/admin"), + ("https://mcp.example.com/..", "https://mcp.example.com"), + ("https://mcp.example.com/a%2F..%2Fb", "https://mcp.example.com/a%2F..%2Fb"), + ]) + func testCanonicalResourceURIs(_ input: String, _ expected: String) throws { + let canonical = try metadataDiscovery.canonicalResourceURI(from: URL(string: input)!) + #expect(canonical.absoluteString == expected) + // Canonicalizing is idempotent: a key canonicalizes to itself. + #expect(try metadataDiscovery.canonicalResourceURI(from: canonical) == canonical) + } + + @Test("Percent-encoding normalization decodes unreserved characters and keeps a % without two hex digits") + func testPercentEncodingNormalizationKeepsMalformedEscapes() { + #expect(DefaultOAuthMetadataDiscovery.normalizingPercentEncodings(in: "/a%2e%2E") == "/a..") + #expect(DefaultOAuthMetadataDiscovery.normalizingPercentEncodings(in: "/a%2") == "/a%2") + #expect(DefaultOAuthMetadataDiscovery.normalizingPercentEncodings(in: "/a%zz%2f") == "/a%zz%2F") + #expect(DefaultOAuthMetadataDiscovery.normalizingPercentEncodings(in: "/plain") == "/plain") + } + + // RFC 3986 §5.2.4 and its examples (§5.4). + @Test( + "Dot segments are removed as RFC 3986 removes them", + arguments: [ + ("/a/b/c/./../../g", "/a/g"), ("mid/content=5/../6", "mid/6"), ("/../a", "/a"), + ("/a/..", "/"), ("/a/.", "/a/"), ("/.hidden/..x", "/.hidden/..x"), ("/mcp", "/mcp"), + ]) + func testRemovingDotSegments(_ path: String, _ expected: String) { + #expect(DefaultOAuthMetadataDiscovery.removingDotSegments(from: path) == expected) + } + + // RFC 3986 §6.2.2.1: only ASCII letters are lowercased, in the host's + // encoded (punycode) form. + @Test("An internationalized host gives one canonical URI in its Unicode and punycode spellings") + func testCanonicalResourceURIOfInternationalizedHost() throws { + let spellings = [ + "https://Bücher.Example/mcp", "https://BÜCHER.example/mcp", "https://xn--bcher-kva.example/mcp", + "https://XN--BCHER-KVA.EXAMPLE/mcp", + ] + let keys = try Set(spellings.map { try metadataDiscovery.canonicalResourceURI(from: URL(string: $0)!) }) + #expect(keys.map(\.absoluteString) == ["https://xn--bcher-kva.example/mcp"]) + } + + // User information, a query and a fragment can carry a password or a + // token; errors are logged, so they show none of them. + @Test( + "An endpoint error names the URL without user information, query or fragment", + arguments: [ + "http://user:pw-secret@example.com/mcp?token=q-secret", + "https://user:pw-secret@mcp.example.com/mcp?token=q-secret#f-secret", + "https://mcp.example.com/mcp#access_token=f-secret", + ]) + func testEndpointErrorsAreRedacted(endpoint: String) { + let error = #expect(throws: OAuthAuthorizationError.self) { + try OAuthURLValidator().validateHTTPSOrLoopback(URL(string: endpoint)!, context: "MCP endpoint") + } + for text in [error?.errorDescription ?? "", error?.url ?? "", error?.detail ?? "", "\(String(describing: error))"] { + #expect(!text.contains("pw-secret"), "\(text)") + #expect(!text.contains("q-secret"), "\(text)") + #expect(!text.contains("f-secret"), "\(text)") + } + let description = error?.errorDescription ?? "" + #expect(description.contains("example.com/mcp")) + } + + @Test("Discovery URLs and the fallback issuer carry no user information") + func testDiscoveryURLsDropUserInformation() throws { + let endpoint = URL(string: "https://user:pw-secret@mcp.example.com/a%2Fb")! + #expect( + metadataDiscovery.protectedResourceMetadataURLs(for: endpoint).map(\.absoluteString) == [ + "https://mcp.example.com/.well-known/oauth-protected-resource/a%2Fb", + "https://mcp.example.com/.well-known/oauth-protected-resource", + ]) + #expect(try metadataDiscovery.authorizationServerFallbackIssuer(from: endpoint).absoluteString == "https://mcp.example.com") + let issuer = URL(string: "https://user:pw-secret@auth.example.com/tenant")! + let asURLs = metadataDiscovery.authorizationServerMetadataURLs(for: issuer).map(\.absoluteString) + #expect(asURLs == [ + "https://auth.example.com/.well-known/oauth-authorization-server/tenant", + "https://auth.example.com/.well-known/openid-configuration/tenant", + "https://auth.example.com/tenant/.well-known/openid-configuration", + ]) + #expect(asURLs.allSatisfy { !$0.contains("pw-secret") && !$0.contains("user") }) + } + + @Test("Protected resource matching collapses dot segments and %2e%2e directly without pre-canonicalization") + func testDirectProtectedResourceMatchesCollapsesDotSegments() { + let resource = URL(string: "https://mcp.example.com/mcp")! + #expect(!metadataDiscovery.protectedResourceMatches( + resource: resource, endpoint: URL(string: "https://mcp.example.com/mcp/../admin")!)) + #expect(!metadataDiscovery.protectedResourceMatches( + resource: resource, endpoint: URL(string: "https://mcp.example.com/mcp/%2e%2e/admin")!)) + #expect(!metadataDiscovery.protectedResourceMatches( + resource: resource, endpoint: URL(string: "https://mcp.example.com/mcp/%2E%2E/admin")!)) + #expect(metadataDiscovery.protectedResourceMatches( + resource: resource, endpoint: URL(string: "https://mcp.example.com/mcp/./sub")!)) + #expect(metadataDiscovery.protectedResourceMatches( + resource: URL(string: "https://mcp.example.com/mcp/./")!, + endpoint: URL(string: "https://mcp.example.com/mcp/sub")!)) + } + + @Test("Hostless https:/// URIs are rejected by canonicalResourceURI, discovery URLs, and protectedResourceMatches") + func testHostlessHTTPSRejected() { + let hostless = URL(string: "https:///mcp")! + #expect(throws: OAuthAuthorizationError.self) { + _ = try metadataDiscovery.canonicalResourceURI(from: hostless) + } + #expect(metadataDiscovery.protectedResourceMetadataURLs(for: hostless).isEmpty) + #expect(metadataDiscovery.authorizationServerMetadataURLs(for: hostless).isEmpty) + #expect(!metadataDiscovery.protectedResourceMatches(resource: hostless, endpoint: hostless)) + #expect(!DefaultOAuthMetadataDiscovery.isSecureOAuthScheme(scheme: "https", host: "")) + } + + // RFC 9728 §3.3: the authorizer compares the metadata's resource with the + // endpoint after canonicalizing both. + @Test( + "A metadata resource matches the endpoint in any spelling of the same canonical URI", + arguments: [ + ("https://mcp.example.com/mcp/", "https://mcp.example.com/mcp", true), + ("https://mcp.example.com:443/mcp", "https://mcp.example.com/mcp", true), + ("HTTPS://MCP.EXAMPLE.COM/mcp", "https://mcp.example.com/mcp", true), + ("https://mcp.example.com/mcp", "https://mcp.example.com:443/mcp/", true), + ("https://mcp.example.com/", "https://mcp.example.com/mcp", true), + ("https://mcp.example.com:8443/mcp", "https://mcp.example.com/mcp", false), + ("https://mcp.example.com/mcp/", "https://mcp.example.com/mcp2", false), + // %2F is not a path separator. + ("https://mcp.example.com/a%2Fb", "https://mcp.example.com/a/b/mcp", false), + ("https://mcp.example.com/mcp", "https://mcp.example.com/mcp%2Fadmin", false), + ("https://mcp.example.com/a%2fb", "https://mcp.example.com/a%2Fb/mcp", true), + // Dot segments are removed before the prefix match. + ("https://mcp.example.com/mcp/", "https://mcp.example.com/mcp/../admin", false), + ("https://mcp.example.com/mcp", "https://mcp.example.com/mcp/./tools", true), + ]) + func testCanonicalProtectedResourceMatching(resource: String, endpoint: String, matches: Bool) throws { + let canonicalResource = try metadataDiscovery.canonicalResourceURI(from: URL(string: resource)!) + let canonicalEndpoint = try metadataDiscovery.canonicalResourceURI(from: URL(string: endpoint)!) + #expect( + metadataDiscovery.protectedResourceMatches(resource: canonicalResource, endpoint: canonicalEndpoint) + == matches) + } + @Test("Protected resource matching allows same-origin parent resource") func testProtectedResourceMatchingParentResource() { let resource = URL(string: "https://mcp.example.com")! @@ -269,6 +435,97 @@ struct OAuthAuthorizationTests { } } + /// The `iat` and `exp` claims of an assertion, decoded as JSON integers. + private struct NumericDateClaims: Decodable, Equatable { + let iat: Int64 + let exp: Int64 + } + + private static func makeAssertion(issuedAt: Date, expiresIn: TimeInterval) throws -> String { + try OAuthConfiguration.makePrivateKeyJWTAssertion( + clientID: "test-client", + tokenEndpoint: URL(string: "https://auth.example.com/token")!, + privateKeyPEM: testPrivateKeyPEM, + issuedAt: issuedAt, + expiresIn: expiresIn + ) + } + + /// The decoded `iat` and `exp` claims, and the payload JSON text. + private static func numericDateClaims(of assertion: String) throws -> (NumericDateClaims, String) { + let parts = assertion.split(separator: ".") + try #require(parts.count == 3) + let payload = try #require(decodeBase64URL(parts[1])) + let claims = try JSONDecoder().decode(NumericDateClaims.self, from: payload) + return (claims, String(decoding: payload, as: UTF8.self)) + } + + private static func isInvalidLifetime(_ error: any Error, _ lifetime: TimeInterval) -> Bool { + guard case .invalidLifetime(let reported) = error as? OAuthConfiguration.PrivateKeyJWTAssertionError + else { return false } + return reported == lifetime || (reported.isNaN && lifetime.isNaN) + } + + @Test( + "private_key_jwt helper rejects a lifetime that is not finite or not an Int64", + arguments: [ + TimeInterval.infinity, -.infinity, .nan, 1e300, .greatestFiniteMagnitude, 1e19, + ]) + func testPrivateKeyJWTAssertionRejectsUnrepresentableLifetime(lifetime: TimeInterval) { + #expect { + _ = try Self.makeAssertion(issuedAt: Date(timeIntervalSince1970: 1_700_000_000), expiresIn: lifetime) + } throws: { error in + Self.isInvalidLifetime(error, lifetime) + } + } + + @Test("private_key_jwt helper rejects a lifetime whose exp overflows Int64") + func testPrivateKeyJWTAssertionRejectsOverflowingExpiration() throws { + // 2^59 + 2^58 seconds: a multiple of 128, so `Date` keeps it exactly. + let issuedAt = Date(timeIntervalSince1970: 864_691_128_455_135_232) + + // 7 × 2^60 seconds: iat + lifetime still fits in Int64. + let (claims, _) = try Self.numericDateClaims( + of: Self.makeAssertion(issuedAt: issuedAt, expiresIn: 8_070_450_532_247_928_832)) + #expect(claims == NumericDateClaims(iat: 864_691_128_455_135_232, exp: 8_935_141_660_703_064_064)) + + // 15 × 2^59 seconds is an Int64, but iat + lifetime is not. + let lifetime: TimeInterval = 8_646_911_284_337_852_416 + #expect { + _ = try Self.makeAssertion(issuedAt: issuedAt, expiresIn: lifetime) + } throws: { error in + Self.isInvalidLifetime(error, lifetime) + } + } + + // The error's value is the TimeInterval, not the Date: describing a NaN + // date traps on Linux. + @Test( + "private_key_jwt helper rejects an issuedAt without an Int64 NumericDate", + arguments: [TimeInterval.infinity, -.infinity, .nan, 1e300, -1e300, 1e19]) + func testPrivateKeyJWTAssertionRejectsUnrepresentableIssuedAt(seconds: TimeInterval) { + #expect { + _ = try Self.makeAssertion(issuedAt: Date(timeIntervalSince1970: seconds), expiresIn: 300) + } throws: { error in + guard case .invalidValue(let value, _) = error as? EncodingError else { return false } + return value is TimeInterval + } + } + + // 2038-01-19T03:14:08Z (one second past Int32.max, where a 32-bit `Int` + // such as watchOS's overflows) and 2100-01-01T00:00:00Z. + @Test( + "private_key_jwt helper writes iat and exp after 2038-01-19 as Int64 JSON numbers", + arguments: [Int64(2_147_483_648), 4_102_444_800]) + func testPrivateKeyJWTAssertionNumericDatesAfter2038(issuedAt: Int64) throws { + let assertion = try Self.makeAssertion( + issuedAt: Date(timeIntervalSince1970: TimeInterval(issuedAt)), expiresIn: 300.9) + let (claims, payload) = try Self.numericDateClaims(of: assertion) + #expect(claims == NumericDateClaims(iat: issuedAt, exp: issuedAt + 300)) + #expect(payload.contains(#""iat":\#(issuedAt)"#), "\(payload)") + #expect(payload.contains(#""exp":\#(issuedAt + 300)"#), "\(payload)") + } + // MARK: - WWW-Authenticate Parser Edge Cases @Test("Parse Bearer returns nil when WWW-Authenticate header is absent") @@ -465,113 +722,181 @@ struct OAuthAuthorizationTests { #expect(!isValid, "Whitespace-only token_type must not be accepted as Bearer") } - // MARK: - InMemoryTokenStorage + // MARK: - InMemoryOAuthTokenStorage - @Test("InMemoryTokenStorage save and load round-trip") + private static func storedToken(_ value: String, scopes: Set = []) -> OAuthAccessToken { + OAuthAccessToken( + value: value, tokenType: "Bearer", expiresAt: nil, scopes: scopes, authorizationServer: nil, + refreshToken: nil) + } + + @Test("InMemoryOAuthTokenStorage save and load round-trip") func testTokenStorageSaveAndLoad() { - let storage = InMemoryTokenStorage() - #expect(storage.load() == nil) - - let token = OAuthAccessToken( - value: "access-123", - tokenType: "Bearer", - expiresAt: nil, - scopes: ["read"], - authorizationServer: nil, - refreshToken: nil - ) - storage.save(token) + let resource = URL(string: "https://mcp.example.com/mcp")! + let storage = InMemoryOAuthTokenStorage() + #expect(storage.load(for: resource) == nil) + + storage.save(Self.storedToken("access-123", scopes: ["read"]), for: resource) - let loaded = storage.load() + let loaded = storage.load(for: resource) #expect(loaded?.value == "access-123") #expect(loaded?.tokenType == "Bearer") #expect(loaded?.scopes == Set(["read"])) } - @Test("InMemoryTokenStorage clear removes stored token") + @Test("InMemoryOAuthTokenStorage clear removes stored token") func testTokenStorageClear() { - let storage = InMemoryTokenStorage() - let token = OAuthAccessToken( - value: "access-456", - tokenType: "Bearer", - expiresAt: nil, - scopes: [], - authorizationServer: nil, - refreshToken: nil - ) - storage.save(token) - #expect(storage.load() != nil) + let resource = URL(string: "https://mcp.example.com/mcp")! + let storage = InMemoryOAuthTokenStorage() + storage.save(Self.storedToken("access-456"), for: resource) + #expect(storage.load(for: resource) != nil) - storage.clear() - #expect(storage.load() == nil) + storage.clear(for: resource) + #expect(storage.load(for: resource) == nil) } - @Test("InMemoryTokenStorage save overwrites previous token") + @Test("InMemoryOAuthTokenStorage save overwrites previous token") func testTokenStorageSaveOverwrites() { - let storage = InMemoryTokenStorage() - let first = OAuthAccessToken( - value: "first", - tokenType: "Bearer", - expiresAt: nil, - scopes: [], - authorizationServer: nil, - refreshToken: nil - ) - let second = OAuthAccessToken( - value: "second", - tokenType: "Bearer", - expiresAt: nil, - scopes: [], - authorizationServer: nil, - refreshToken: nil - ) - storage.save(first) - storage.save(second) + let resource = URL(string: "https://mcp.example.com/mcp")! + let storage = InMemoryOAuthTokenStorage() + storage.save(Self.storedToken("first"), for: resource) + storage.save(Self.storedToken("second"), for: resource) - #expect(storage.load()?.value == "second") + #expect(storage.load(for: resource)?.value == "second") + } + + @Test("In-memory storage keeps one token per resource") + func testTokenStorageKeepsOneTokenPerResource() { + let a = URL(string: "https://a.example.com/mcp")! + let b = URL(string: "https://b.example.com/mcp")! + let storage = InMemoryOAuthTokenStorage() + storage.save(Self.storedToken("token-a"), for: a) + storage.save(Self.storedToken("token-b"), for: b) + + #expect(storage.load(for: a)?.value == "token-a") + #expect(storage.load(for: b)?.value == "token-b") + #expect(storage.load(for: URL(string: "https://c.example.com/mcp")!) == nil) + } + + @Test("Clearing one resource leaves the others") + func testTokenStorageClearsOneResource() { + let a = URL(string: "https://a.example.com/mcp")! + let b = URL(string: "https://b.example.com/mcp")! + let storage = InMemoryOAuthTokenStorage() + storage.save(Self.storedToken("token-a"), for: a) + storage.save(Self.storedToken("token-b"), for: b) + + storage.clear(for: a) + // Clearing a resource without a token is not an error. + storage.clear(for: URL(string: "https://c.example.com/mcp")!) + + #expect(storage.load(for: a) == nil) + #expect(storage.load(for: b)?.value == "token-b") + } + + @Test("In-memory token storage is safe from several tasks") + func testTokenStorageIsThreadSafe() async { + let storage = InMemoryOAuthTokenStorage() + let resources = [URL(string: "https://a.example.com/mcp")!, URL(string: "https://b.example.com/mcp")!] + await withTaskGroup(of: Void.self) { group in + for index in 0..<200 { + group.addTask { + let resource = resources[index % 2] + if index.isMultiple(of: 3) { + storage.clear(for: resource) + } else { + storage.save(Self.storedToken("\(index)"), for: resource) + } + _ = storage.load(for: resource) + } + } + } + // Each resource keeps only tokens saved for it. + for (offset, resource) in resources.enumerated() { + if let value = storage.load(for: resource)?.value { + #expect(Int(value).map { $0 % 2 } == offset) + } + } + } + + /// Keeps tokens as JSON, as a store backed by the Keychain does. + private actor JSONTokenStorage: OAuthTokenStorage { + private var stored: [URL: Data] = [:] + + func save(_ token: OAuthAccessToken, for resource: URL) throws { + stored[resource] = try JSONEncoder().encode(token) + } + + func load(for resource: URL) throws -> OAuthAccessToken? { + try stored[resource].map { try JSONDecoder().decode(OAuthAccessToken.self, from: $0) } + } + + func clear(for resource: URL) { + stored[resource] = nil + } + } + + @Test("An actor conforms to OAuthTokenStorage") + func testActorTokenStorage() async throws { + let resource = URL(string: "https://mcp.example.com/mcp")! + let storage: any OAuthTokenStorage = JSONTokenStorage() + try await storage.save(Self.storedToken("access-789", scopes: ["read"]), for: resource) + let loaded = try await storage.load(for: resource) + #expect(loaded?.value == "access-789") + #expect(loaded?.scopes == ["read"]) + try await storage.clear(for: resource) + #expect(try await storage.load(for: resource) == nil) + + // The authorizer takes it, and finds a token stored for its endpoint. + try await storage.save(Self.storedToken("persisted"), for: resource) + let authorizer = OAuthAuthorizer( + configuration: OAuthConfiguration(authentication: .none(clientID: "client")), tokenStorage: storage) + let headers = try await authorizer.authorizationHeaders(for: resource, method: "POST") + #expect(headers["Authorization"] == "Bearer persisted") } // MARK: - Proactive Token Refresh - @Test("prepareAuthorization does nothing when proactiveRefreshWindowSeconds is zero") + @Test("prepare does nothing when proactiveRefreshWindowSeconds is zero") func testPrepareAuthorizationSkipsWhenWindowIsZero() async throws { - let storage = InMemoryTokenStorage() + let endpoint = URL(string: "https://example.com/mcp")! + let storage = InMemoryOAuthTokenStorage() // Token expires in 50 s — within a large proactive window but not within the 30 s default skew. - storage.save(OAuthAccessToken( - value: "original-token", - tokenType: "Bearer", - expiresAt: Date().addingTimeInterval(50), - scopes: [], - authorizationServer: nil, - refreshToken: "some-refresh-token" - )) + storage.save( + OAuthAccessToken( + value: "original-token", + tokenType: "Bearer", + expiresAt: Date().addingTimeInterval(50), + scopes: [], + authorizationServer: nil, + refreshToken: "some-refresh-token" + ), for: endpoint) let config = OAuthConfiguration( authentication: .none(clientID: "client"), proactiveRefreshWindowSeconds: 0 ) let authorizer = OAuthAuthorizer(configuration: config, tokenStorage: storage) - try await authorizer.prepareAuthorization( - for: URL(string: "https://example.com/mcp")!, - session: .shared - ) + try await authorizer.prepare(for: endpoint, session: .shared) // Token must be unchanged — proactive refresh is disabled. - #expect(storage.load()?.value == "original-token") + #expect(storage.load(for: endpoint)?.value == "original-token") } - @Test("prepareAuthorization does nothing without cached authorization server metadata") + @Test("prepare does nothing without cached authorization server metadata") func testPrepareAuthorizationSkipsWithoutCachedASMetadata() async throws { - let storage = InMemoryTokenStorage() + let endpoint = URL(string: "https://example.com/mcp")! + let storage = InMemoryOAuthTokenStorage() // Token expires in 50 s — within the 400 s proactive window. - storage.save(OAuthAccessToken( - value: "original-token", - tokenType: "Bearer", - expiresAt: Date().addingTimeInterval(50), - scopes: [], - authorizationServer: nil, - refreshToken: "some-refresh-token" - )) + storage.save( + OAuthAccessToken( + value: "original-token", + tokenType: "Bearer", + expiresAt: Date().addingTimeInterval(50), + scopes: [], + authorizationServer: nil, + refreshToken: "some-refresh-token" + ), for: endpoint) let config = OAuthConfiguration( authentication: .none(clientID: "client"), proactiveRefreshWindowSeconds: 400 @@ -579,13 +904,10 @@ struct OAuthAuthorizationTests { // No handleChallenge call → authorizationServerMetadata remains nil. let authorizer = OAuthAuthorizer(configuration: config, tokenStorage: storage) - try await authorizer.prepareAuthorization( - for: URL(string: "https://example.com/mcp")!, - session: .shared - ) + try await authorizer.prepare(for: endpoint, session: .shared) // Token must be unchanged — refresh requires cached AS metadata. - #expect(storage.load()?.value == "original-token") + #expect(storage.load(for: endpoint)?.value == "original-token") } // MARK: - WWW-Authenticate Bare Scheme Detection @@ -662,38 +984,38 @@ struct OAuthAuthorizationTests { } @Test("BearerTokenValidator allows valid token with nil audience (opaque token)") - func testBearerValidatorNilAudienceAllows() { + func testBearerValidatorNilAudienceAllows() async { let validator = makeBearerValidator { _, _, _ in .valid(BearerTokenInfo(audience: nil)) } - let result = validator.validate(makeRequest(authorization: "Bearer tok"), context: makeContext()) + let result = await validator.validate(makeRequest(authorization: "Bearer tok"), context: makeContext()) #expect(result == nil) } @Test("BearerTokenValidator allows token with matching audience") - func testBearerValidatorMatchingAudienceAllows() { + func testBearerValidatorMatchingAudienceAllows() async { let validator = makeBearerValidator { _, _, _ in .valid(BearerTokenInfo(audience: ["https://api.example.com"])) } - let result = validator.validate(makeRequest(authorization: "Bearer tok"), context: makeContext()) + let result = await validator.validate(makeRequest(authorization: "Bearer tok"), context: makeContext()) #expect(result == nil) } @Test("BearerTokenValidator allows token when one aud entry matches") - func testBearerValidatorOneOfMultipleAudienceMatches() { + func testBearerValidatorOneOfMultipleAudienceMatches() async { let validator = makeBearerValidator { _, _, _ in .valid(BearerTokenInfo(audience: ["https://other.example.com", "https://api.example.com"])) } - let result = validator.validate(makeRequest(authorization: "Bearer tok"), context: makeContext()) + let result = await validator.validate(makeRequest(authorization: "Bearer tok"), context: makeContext()) #expect(result == nil) } @Test("BearerTokenValidator returns 401 invalid_token when audience does not match") - func testBearerValidatorAudienceMismatchReturns401() { + func testBearerValidatorAudienceMismatchReturns401() async { let validator = makeBearerValidator { _, _, _ in .valid(BearerTokenInfo(audience: ["https://other.example.com"])) } - let result = validator.validate(makeRequest(authorization: "Bearer tok"), context: makeContext()) + let result = await validator.validate(makeRequest(authorization: "Bearer tok"), context: makeContext()) #expect(result?.statusCode == 401) let challenge = result?.headers[HTTPHeaderName.wwwAuthenticate] #expect(challenge?.contains("error=\"invalid_token\"") == true) @@ -701,12 +1023,12 @@ struct OAuthAuthorizationTests { } @Test("BearerTokenValidator returns 401 invalid_token when token is expired") - func testBearerValidatorExpiredTokenReturns401() { + func testBearerValidatorExpiredTokenReturns401() async { let pastDate = Date(timeIntervalSinceNow: -3600) let validator = makeBearerValidator { _, _, _ in .valid(BearerTokenInfo(expiresAt: pastDate)) } - let result = validator.validate(makeRequest(authorization: "Bearer tok"), context: makeContext()) + let result = await validator.validate(makeRequest(authorization: "Bearer tok"), context: makeContext()) #expect(result?.statusCode == 401) let challenge = result?.headers[HTTPHeaderName.wwwAuthenticate] #expect(challenge?.contains("error=\"invalid_token\"") == true) @@ -714,23 +1036,23 @@ struct OAuthAuthorizationTests { } @Test("BearerTokenValidator allows token that has not yet expired") - func testBearerValidatorNonExpiredTokenAllows() { + func testBearerValidatorNonExpiredTokenAllows() async { let futureDate = Date(timeIntervalSinceNow: 3600) let validator = makeBearerValidator { _, _, _ in .valid(BearerTokenInfo(expiresAt: futureDate)) } - let result = validator.validate(makeRequest(authorization: "Bearer tok"), context: makeContext()) + let result = await validator.validate(makeRequest(authorization: "Bearer tok"), context: makeContext()) #expect(result == nil) } @Test("BearerTokenValidator checks expiry before audience") - func testBearerValidatorExpiryCheckedBeforeAudience() { + func testBearerValidatorExpiryCheckedBeforeAudience() async { let pastDate = Date(timeIntervalSinceNow: -1) let validator = makeBearerValidator { _, _, _ in // Expired token but matching audience — expiry should win .valid(BearerTokenInfo(audience: ["https://api.example.com"], expiresAt: pastDate)) } - let result = validator.validate(makeRequest(authorization: "Bearer tok"), context: makeContext()) + let result = await validator.validate(makeRequest(authorization: "Bearer tok"), context: makeContext()) #expect(result?.statusCode == 401) let challenge = result?.headers[HTTPHeaderName.wwwAuthenticate] #expect(challenge?.contains("Token has expired") == true) diff --git a/Tests/MCPTests/OAuthAuthorizerStateTests.swift b/Tests/MCPTests/OAuthAuthorizerStateTests.swift index ecf34400..9507d440 100644 --- a/Tests/MCPTests/OAuthAuthorizerStateTests.swift +++ b/Tests/MCPTests/OAuthAuthorizerStateTests.swift @@ -1,4 +1,5 @@ @preconcurrency import Foundation +import Synchronization import Testing @testable import MCP @@ -17,22 +18,36 @@ final class RecordingTokenClient: OAuthTokenRequesting, @unchecked Sendable { let grantType: String? let refreshToken: String? let scope: String? + /// The `resource` parameter (RFC 8707 §2). + let resource: String? } private let lock = NSLock() private var recorded: [Call] = [] private var issued = 0 + /// The tokens are `-1`, `-2`, ... + let prefix: String /// Grant types answered with HTTP 400 `invalid_grant`. var refusedGrants: Set = [] /// An HTTP status, without an `error` member, that refresh requests get. var refreshStatus: Int? + /// Refuses refresh requests whose `resource` equals this string with HTTP 400 `invalid_target`. + var refusedRefreshResource: String? + /// Token type returned in responses (default `"Bearer"`). + var tokenType = "Bearer" var expiresIn = 3600 var delay: Duration = .zero /// Answers without `refresh_token`, as RFC 6749 §6 allows. var omitsRefreshToken = false + /// Awaited before each answer, after the call is recorded. + var beforeAnswer: (@Sendable () async -> Void)? var calls: [Call] { lock.withLock { recorded } } + init(prefix: String = "token") { + self.prefix = prefix + } + func request( parameters: inout [String: String], endpoint: URL, @@ -45,19 +60,25 @@ final class RecordingTokenClient: OAuthTokenRequesting, @unchecked Sendable { recorded.append( Call( endpoint: endpoint, grantType: grant, refreshToken: parameters[OAuthParameterName.refreshToken], - scope: parameters[OAuthParameterName.scope])) + scope: parameters[OAuthParameterName.scope], resource: parameters[OAuthParameterName.resource])) issued += 1 return issued } if delay > .zero { try await Task.sleep(for: delay) } + if let beforeAnswer { await beforeAnswer() } if grant == "refresh_token", let refreshStatus { throw OAuthAuthorizationError.tokenRequestFailed(statusCode: refreshStatus, oauthError: nil) } + if grant == "refresh_token", let refusedRefreshResource, + parameters[OAuthParameterName.resource] == refusedRefreshResource + { + throw OAuthAuthorizationError.tokenRequestFailed(statusCode: 400, oauthError: "invalid_target") + } if let grant, refusedGrants.contains(grant) { throw OAuthAuthorizationError.tokenRequestFailed(statusCode: 400, oauthError: "invalid_grant") } return OAuthTokenResponse( - accessToken: "token-\(number)", tokenType: "Bearer", expiresIn: expiresIn, scope: nil, + accessToken: "\(prefix)-\(number)", tokenType: tokenType, expiresIn: expiresIn, scope: nil, refreshToken: omitsRefreshToken ? nil : "refresh-\(number)") } } @@ -143,6 +164,84 @@ final class FlakyClientRegistrar: OAuthClientRegistering, @unchecked Sendable { struct UserCancelledAuthorization: Error {} +/// A token storage that is an actor, as one backed by the Keychain may be. +/// One `load(for:)` can be held after it has read the token, the next +/// `clear(for:)` can be held before it clears, and the operations named in +/// `failing` throw. +actor ControllableTokenStorage: OAuthTokenStorage { + struct Failure: Error, Equatable { + let operation: String + } + + private var tokens: [URL: OAuthAccessToken] = [:] + private var loads = 0 + private var heldLoad: Int? + private var heldContinuation: CheckedContinuation? + private var failing: Set = [] + private var failingLoadResources: Set = [] + private var holdsNextClear = false + private var heldClear: CheckedContinuation? + + /// Whether a `clear(for:)` is held, waiting for `releaseClear()`. + var isHoldingClear: Bool { heldClear != nil } + + /// Holds the next `clear(for:)`, before it clears. + func holdNextClear() { holdsNextClear = true } + + /// Lets the held `clear(for:)` clear. + func releaseClear() { + heldClear?.resume() + heldClear = nil + } + + /// Whether a `load(for:)` is held, waiting for `releaseLoad()`. + var isHoldingLoad: Bool { heldContinuation != nil } + + /// Holds the `number`th `load(for:)` from now, after it has read the token. + func holdLoad(_ number: Int) { heldLoad = loads + number } + + /// Lets the held `load(for:)` return the token it read. + func releaseLoad() { + heldContinuation?.resume() + heldContinuation = nil + } + + /// Makes the named operations (`load`, `save`, `clear`) throw ``Failure``. + func fail(_ operations: Set) { failing = operations } + + /// Makes `load(for:)` throw ``Failure`` for the given resources only. + func failLoad(for resources: Set) { failingLoadResources = resources } + + /// The stored token, read without counting as a `load(for:)`. + func token(for resource: URL) -> OAuthAccessToken? { tokens[resource] } + + func load(for resource: URL) async throws -> OAuthAccessToken? { + if failing.contains("load") || failingLoadResources.contains(resource) { + throw Failure(operation: "load") + } + loads += 1 + let token = tokens[resource] + if loads == heldLoad { + await withCheckedContinuation { heldContinuation = $0 } + } + return token + } + + func save(_ token: OAuthAccessToken, for resource: URL) throws { + if failing.contains("save") { throw Failure(operation: "save") } + tokens[resource] = token + } + + func clear(for resource: URL) async throws { + if failing.contains("clear") { throw Failure(operation: "clear") } + if holdsNextClear { + holdsNextClear = false + await withCheckedContinuation { heldClear = $0 } + } + tokens[resource] = nil + } +} + /// Waits until `condition` holds, for at most `limit`. private func waitUntil(within limit: Duration = .seconds(5), _ condition: () -> Bool) async throws { let deadline = ContinuousClock.now + limit @@ -178,7 +277,7 @@ struct OAuthAuthorizerStateTests { func makeAuthorizer( discovery: MockDiscoveryClient, tokens: RecordingTokenClient, - storage: TokenStorage = InMemoryTokenStorage(), + storage: any OAuthTokenStorage = InMemoryOAuthTokenStorage(), overrides: OAuthConfiguration.EndpointOverrides = .none, grantType: OAuthConfiguration.GrantType = .clientCredentials, authentication: OAuthConfiguration.TokenEndpointAuthentication = .clientSecretBasic( @@ -206,25 +305,28 @@ struct OAuthAuthorizerStateTests { return discovery } - func challenge(_ authorizer: OAuthAuthorizer, status: Int = 401, headers: [String: String]? = nil) async throws -> Bool { + func challenge( + _ authorizer: OAuthAuthorizer, status: Int = 401, headers: [String: String]? = nil, endpoint: URL? = nil + ) async throws -> Bool { try await authorizer.handleChallenge( - statusCode: status, headers: headers ?? challenge, endpoint: endpoint, operationKey: "tools/call", - session: .shared) + statusCode: status, headers: headers ?? challenge, endpoint: endpoint ?? self.endpoint, + operationKey: "tools/call", session: .shared) } /// A challenge for a request sent with `sent` as its `Authorization` value. func challenge( - _ authorizer: OAuthAuthorizer, sent: String?, status: Int = 401, headers: [String: String]? = nil + _ authorizer: OAuthAuthorizer, sent: String?, status: Int = 401, headers: [String: String]? = nil, + endpoint: URL? = nil ) async throws -> Bool { try await authorizer.handleChallenge( - statusCode: status, headers: headers ?? challenge, endpoint: endpoint, operationKey: "tools/call", - sentAuthorization: sent, session: .shared - ).retry + statusCode: status, headers: headers ?? challenge, endpoint: endpoint ?? self.endpoint, + operationKey: "tools/call", sentAuthorization: sent, session: .shared + ).shouldRetry } @Test("A 401 for a token another challenge already refreshed retries with the new token") func lateChallengeKeepsRefreshedToken() async throws { - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let tokens = RecordingTokenClient() let authorizer = makeAuthorizer(discovery: discovery(listing: serverA), tokens: tokens, storage: storage) #expect(try await challenge(authorizer, sent: nil)) @@ -233,13 +335,13 @@ struct OAuthAuthorizerStateTests { // A request sent with token-1 before the refresh gets its 401 now. #expect(try await challenge(authorizer, sent: "Bearer token-1")) #expect(tokens.calls.map(\.grantType) == ["client_credentials", "refresh_token"]) - #expect(storage.load()?.value == "token-2") - #expect(storage.load()?.refreshToken == "refresh-2") + #expect(storage.load(for: endpoint)?.value == "token-2") + #expect(storage.load(for: endpoint)?.refreshToken == "refresh-2") } @Test("A refreshed token rejected later is refreshed again after the resource metadata is read") func refreshedTokenIsRefreshedAgain() async throws { - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let discovery = discovery(listing: serverA) let tokens = RecordingTokenClient() let authorizer = makeAuthorizer(discovery: discovery, tokens: tokens, storage: storage) @@ -251,24 +353,24 @@ struct OAuthAuthorizerStateTests { #expect(discovery.fetchProtectedResourceMetadataCallCount == fetches + 1) #expect(tokens.calls.map(\.grantType) == ["client_credentials", "refresh_token", "refresh_token"]) #expect(tokens.calls.last?.refreshToken == "refresh-2") - #expect(storage.load()?.value == "token-3") + #expect(storage.load(for: endpoint)?.value == "token-3") } @Test("A refresh response without a refresh token keeps the previous one (RFC 6749 section 6)") func refreshWithoutRefreshTokenKeepsIt() async throws { - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let tokens = RecordingTokenClient() let authorizer = makeAuthorizer(discovery: discovery(listing: serverA), tokens: tokens, storage: storage) #expect(try await challenge(authorizer, sent: nil, headers: ["WWW-Authenticate": #"Bearer scope="files:read""#])) - let previous = try #require(storage.load()) + let previous = try #require(storage.load(for: endpoint)) #expect(previous.scopes == ["files:read"]) tokens.omitsRefreshToken = true #expect(try await challenge(authorizer, sent: "Bearer token-1")) // refresh - #expect(storage.load()?.value == "token-2") - #expect(storage.load()?.refreshToken == "refresh-1") + #expect(storage.load(for: endpoint)?.value == "token-2") + #expect(storage.load(for: endpoint)?.refreshToken == "refresh-1") // Neither the refresh request nor the response names a scope: the // token keeps the scopes granted before. - #expect(storage.load()?.scopes == previous.scopes) + #expect(storage.load(for: endpoint)?.scopes == previous.scopes) // The kept refresh token refreshes again instead of a new grant. #expect(try await challenge(authorizer, sent: "Bearer token-2")) @@ -278,11 +380,11 @@ struct OAuthAuthorizerStateTests { @Test("A transient failure to read the authorization server metadata keeps the stored tokens") func transientServerMetadataFailureKeepsToken() async throws { - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() storage.save( OAuthAccessToken( value: "persisted", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(-60), scopes: [], - authorizationServer: serverA, refreshToken: "persisted-refresh")) + authorizationServer: serverA, refreshToken: "persisted-refresh"), for: endpoint) let discovery = discovery(listing: serverA) discovery.authorizationServerMetadataError = OAuthMetadataUnavailable(url: serverA, reason: "HTTP 503") let tokens = RecordingTokenClient() @@ -291,8 +393,8 @@ struct OAuthAuthorizerStateTests { await #expect(throws: OAuthMetadataUnavailable.self) { _ = try await challenge(authorizer, sent: "Bearer persisted") } - #expect(storage.load()?.value == "persisted") - #expect(storage.load()?.refreshToken == "persisted-refresh") + #expect(storage.load(for: endpoint)?.value == "persisted") + #expect(storage.load(for: endpoint)?.refreshToken == "persisted-refresh") #expect(tokens.calls.isEmpty) // Once the server answers, the token is refreshed. @@ -303,7 +405,7 @@ struct OAuthAuthorizerStateTests { @Test("A timed-out or rate-limited refresh keeps the stored tokens", arguments: [408, 429]) func throttledRefreshKeepsTokens(status: Int) async throws { - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let tokens = RecordingTokenClient() let authorizer = makeAuthorizer(discovery: discovery(listing: serverA), tokens: tokens, storage: storage) #expect(try await challenge(authorizer, sent: nil)) @@ -311,7 +413,7 @@ struct OAuthAuthorizerStateTests { await #expect(throws: OAuthAuthorizationError.self) { _ = try await challenge(authorizer, sent: "Bearer token-1") } - #expect(storage.load()?.refreshToken == "refresh-1") + #expect(storage.load(for: endpoint)?.refreshToken == "refresh-1") #expect(tokens.calls.map(\.grantType) == ["client_credentials", "refresh_token"]) } @@ -346,11 +448,11 @@ struct OAuthAuthorizerStateTests { "Concurrent 403 step-ups for a token whose step-up the user cancelled ask once and fail", .timeLimit(.minutes(2))) func waitersShareCancelledStepUp() async throws { - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() storage.save( OAuthAccessToken( value: "narrow", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(3600), scopes: ["read"], - authorizationServer: nil, refreshToken: nil)) + authorizationServer: nil, refreshToken: nil), for: endpoint) let flow = GatedAuthCodeFlow() flow.error = UserCancelledAuthorization() let authorizer = makeAuthorizer( @@ -373,7 +475,7 @@ struct OAuthAuthorizerStateTests { await #expect(throws: UserCancelledAuthorization.self) { _ = try await task.value } } #expect(flow.performCount == 1) - #expect(storage.load()?.value == "narrow") + #expect(storage.load(for: endpoint)?.value == "narrow") } @Test("Concurrent 403 step-ups for the same scopes run one token request", .timeLimit(.minutes(2))) @@ -392,7 +494,7 @@ struct OAuthAuthorizerStateTests { for try await handled in group { #expect(handled) } } #expect(tokens.calls.count == 2) - #expect(try authorizer.authorizationHeaders(for: endpoint, method: "POST")["Authorization"] == "Bearer token-2") + #expect(try await authorizer.authorizationHeaders(for: endpoint, method: "POST")["Authorization"] == "Bearer token-2") } @Test("A registration that failed is tried again by the next challenge") @@ -450,7 +552,7 @@ struct OAuthAuthorizerStateTests { #expect(try await first.value) await observer.value #expect(flow.performCount == 1) - #expect(try authorizer.authorizationHeaders(for: endpoint, method: "POST")["Authorization"] == "Bearer token-1") + #expect(try await authorizer.authorizationHeaders(for: endpoint, method: "POST")["Authorization"] == "Bearer token-1") } @Test("A 401 refreshes at the token's server before reading the resource metadata again") @@ -464,7 +566,7 @@ struct OAuthAuthorizerStateTests { #expect(try await challenge(authorizer)) #expect(tokens.calls.map(\.grantType) == ["client_credentials", "refresh_token"]) #expect(discovery.fetchProtectedResourceMetadataCallCount == fetches) - #expect(try authorizer.authorizationHeaders(for: endpoint, method: "POST")["Authorization"] == "Bearer token-2") + #expect(try await authorizer.authorizationHeaders(for: endpoint, method: "POST")["Authorization"] == "Bearer token-2") } @Test("A transient failure to read the metadata keeps the token's server; nothing goes to the MCP origin") @@ -503,7 +605,7 @@ struct OAuthAuthorizerStateTests { @Test("With a configured authorization server, a 401 keeps the token when the resource lists another server") func configuredServerKeepsTokenOn401() async throws { - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let discovery = discovery(listing: serverA) let tokens = RecordingTokenClient() let authorizer = makeAuthorizer( @@ -519,12 +621,12 @@ struct OAuthAuthorizerStateTests { #expect(try await challenge(authorizer, sent: "Bearer token-2")) #expect(tokens.calls.map(\.grantType) == ["client_credentials", "refresh_token", "refresh_token"]) #expect(tokens.calls.allSatisfy { $0.endpoint.host == serverA.host }) - #expect(storage.load()?.value == "token-3") + #expect(storage.load(for: endpoint)?.value == "token-3") } @Test("With a configured authorization server, a 403 step-up keeps the token and its scopes") func configuredServerKeepsTokenOnStepUp() async throws { - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let discovery = discovery(listing: serverA) let tokens = RecordingTokenClient() let authorizer = makeAuthorizer( @@ -544,7 +646,7 @@ struct OAuthAuthorizerStateTests { let requested = tokens.calls.last?.scope?.split(separator: " ").map(String.init) ?? [] #expect(Set(requested) == ["read", "admin"]) #expect(tokens.calls.last?.endpoint.host == serverA.host) - #expect(storage.load()?.value == "token-1") + #expect(storage.load(for: endpoint)?.value == "token-1") } @Test("A new authorization server drops the stored token, so its refresh token never reaches that server") @@ -564,15 +666,15 @@ struct OAuthAuthorizerStateTests { ] tokens.refusedGrants = ["client_credentials"] await #expect(throws: (any Error).self) { _ = try await challenge(authorizer, status: 403, headers: moved) } - #expect(try authorizer.authorizationHeaders(for: endpoint, method: "POST")["Authorization"] == nil) + #expect(try await authorizer.authorizationHeaders(for: endpoint, method: "POST")["Authorization"] == nil) - try await authorizer.prepareAuthorization(for: endpoint, session: .shared) + try await authorizer.prepare(for: endpoint, session: .shared) #expect(!tokens.calls.contains { $0.grantType == "refresh_token" }) } @Test("A token without a recorded server is not refreshed at a discovered one") func unboundTokenIsNotRefreshed() async throws { - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let discovery = discovery(listing: serverA) let tokens = RecordingTokenClient() let authorizer = makeAuthorizer(discovery: discovery, tokens: tokens, storage: storage) @@ -580,8 +682,8 @@ struct OAuthAuthorizerStateTests { storage.save( OAuthAccessToken( value: "old", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(10), scopes: [], - authorizationServer: nil, refreshToken: "old-refresh")) - try await authorizer.prepareAuthorization(for: endpoint, session: .shared) + authorizationServer: nil, refreshToken: "old-refresh"), for: endpoint) + try await authorizer.prepare(for: endpoint, session: .shared) #expect(tokens.calls.map(\.grantType) == ["client_credentials"]) // With a configured server, the token belongs to it. @@ -592,8 +694,8 @@ struct OAuthAuthorizerStateTests { storage.save( OAuthAccessToken( value: "old", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(10), scopes: [], - authorizationServer: nil, refreshToken: "old-refresh")) - try await configured.prepareAuthorization(for: endpoint, session: .shared) + authorizationServer: nil, refreshToken: "old-refresh"), for: endpoint) + try await configured.prepare(for: endpoint, session: .shared) #expect(tokens.calls.last?.grantType == "refresh_token") #expect(discovery.lastTrustedIssuer == serverA) } @@ -614,15 +716,15 @@ struct OAuthAuthorizerStateTests { @Test("Concurrent proactive refreshes run one refresh") func concurrentRefreshes() async throws { - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let tokens = RecordingTokenClient() let authorizer = makeAuthorizer(discovery: discovery(listing: serverA), tokens: tokens, storage: storage) #expect(try await challenge(authorizer)) - storage.save(aged(try #require(storage.load()), expiringIn: 40)) + storage.save(aged(try #require(storage.load(for: endpoint)), expiringIn: 40), for: endpoint) tokens.delay = .milliseconds(50) try await withThrowingTaskGroup(of: Void.self) { group in for _ in 0..<10 { - group.addTask { try await authorizer.prepareAuthorization(for: endpoint, session: .shared) } + group.addTask { try await authorizer.prepare(for: endpoint, session: .shared) } } try await group.waitForAll() } @@ -631,102 +733,1407 @@ struct OAuthAuthorizerStateTests { @Test("A token issued for less than the window is refreshed halfway, not on every request") func shortLivedTokenRefresh() async throws { - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let tokens = RecordingTokenClient() tokens.expiresIn = 50 let authorizer = makeAuthorizer(discovery: discovery(listing: serverA), tokens: tokens, storage: storage) #expect(try await challenge(authorizer)) for _ in 0..<5 { - try await authorizer.prepareAuthorization(for: endpoint, session: .shared) + try await authorizer.prepare(for: endpoint, session: .shared) } #expect(tokens.calls.map(\.grantType) == ["client_credentials"]) // Sent until 30 s before it expires: renewed when 40 s are left. - storage.save(aged(try #require(storage.load()), expiringIn: 39)) + storage.save(aged(try #require(storage.load(for: endpoint)), expiringIn: 39), for: endpoint) for _ in 0..<5 { - try await authorizer.prepareAuthorization(for: endpoint, session: .shared) + try await authorizer.prepare(for: endpoint, session: .shared) } #expect(tokens.calls.map(\.grantType) == ["client_credentials", "refresh_token"]) - #expect(storage.load()?.value == "token-2") + #expect(storage.load(for: endpoint)?.value == "token-2") // A token that is never sent is left to the 401 path. tokens.expiresIn = 30 - storage.save(aged(try #require(storage.load()), expiringIn: 39)) - try await authorizer.prepareAuthorization(for: endpoint, session: .shared) - #expect(storage.load()?.value == "token-3") + storage.save(aged(try #require(storage.load(for: endpoint)), expiringIn: 39), for: endpoint) + try await authorizer.prepare(for: endpoint, session: .shared) + #expect(storage.load(for: endpoint)?.value == "token-3") for _ in 0..<5 { - try await authorizer.prepareAuthorization(for: endpoint, session: .shared) + try await authorizer.prepare(for: endpoint, session: .shared) } #expect(tokens.calls.count == 3) } @Test("A failed proactive refresh is tried once per token") func failedRefreshTriedOnce() async throws { - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let tokens = RecordingTokenClient() let authorizer = makeAuthorizer(discovery: discovery(listing: serverA), tokens: tokens, storage: storage) #expect(try await challenge(authorizer)) - storage.save(aged(try #require(storage.load()), expiringIn: 40)) + storage.save(aged(try #require(storage.load(for: endpoint)), expiringIn: 40), for: endpoint) tokens.refusedGrants = ["refresh_token"] for _ in 0..<5 { - try await authorizer.prepareAuthorization(for: endpoint, session: .shared) + try await authorizer.prepare(for: endpoint, session: .shared) } #expect(tokens.calls.map(\.grantType) == ["client_credentials", "refresh_token"]) - #expect(storage.load()?.value == "token-1") + #expect(storage.load(for: endpoint)?.value == "token-1") // A new token is tried again. tokens.refusedGrants = [] #expect(try await challenge(authorizer, sent: "Bearer token-1")) - let renewed = try #require(storage.load()) - storage.save(aged(renewed, expiringIn: 40)) - try await authorizer.prepareAuthorization(for: endpoint, session: .shared) + let renewed = try #require(storage.load(for: endpoint)) + storage.save(aged(renewed, expiringIn: 40), for: endpoint) + try await authorizer.prepare(for: endpoint, session: .shared) #expect(tokens.calls.last?.grantType == "refresh_token") - #expect(storage.load()?.value != renewed.value) + #expect(storage.load(for: endpoint)?.value != renewed.value) } @Test("A cancelled proactive refresh is tried again by the next request", .timeLimit(.minutes(2))) func cancelledRefreshTriedAgain() async throws { - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let tokens = RecordingTokenClient() let authorizer = makeAuthorizer(discovery: discovery(listing: serverA), tokens: tokens, storage: storage) #expect(try await challenge(authorizer)) - storage.save(aged(try #require(storage.load()), expiringIn: 40)) + storage.save(aged(try #require(storage.load(for: endpoint)), expiringIn: 40), for: endpoint) // The refresh waits until its request is cancelled. tokens.delay = .seconds(60) - let cancelled = Task { try await authorizer.prepareAuthorization(for: endpoint, session: .shared) } + let cancelled = Task { try await authorizer.prepare(for: endpoint, session: .shared) } let deadline = ContinuousClock.now + .seconds(10) while tokens.calls.count < 2 && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) } cancelled.cancel() _ = await cancelled.result - #expect(storage.load()?.value == "token-1") + #expect(storage.load(for: endpoint)?.value == "token-1") tokens.delay = .zero - try await authorizer.prepareAuthorization(for: endpoint, session: .shared) + try await authorizer.prepare(for: endpoint, session: .shared) #expect(tokens.calls.map(\.grantType) == ["client_credentials", "refresh_token", "refresh_token"]) - #expect(storage.load()?.value == "token-3") + #expect(storage.load(for: endpoint)?.value == "token-3") } - @Test("In-memory token storage is safe from several tasks") - func storageIsThreadSafe() async { - let storage = InMemoryTokenStorage() - await withTaskGroup(of: Void.self) { group in - for index in 0..<200 { - group.addTask { - if index.isMultiple(of: 3) { - storage.clear() - } else { - storage.save( - OAuthAccessToken( - value: "\(index)", tokenType: "Bearer", expiresAt: nil, scopes: [], - authorizationServer: nil, refreshToken: nil)) - } - _ = storage.load() - } + @Test("prepare validates the endpoint and ignores a failed renewal") + func prepareValidatesAndIgnoresFailedRenewal() async throws { + let storage = InMemoryOAuthTokenStorage() + let tokens = RecordingTokenClient() + let validator = MockURLValidator() + let authorizer = makeAuthorizer( + discovery: discovery(listing: serverA), tokens: tokens, storage: storage, urlValidator: validator) + #expect(try await challenge(authorizer)) + storage.save(aged(try #require(storage.load(for: endpoint)), expiringIn: 40), for: endpoint) + tokens.refusedGrants = ["refresh_token"] + let checks = validator.validateHTTPSOrLoopbackCallCount + + try await authorizer.prepare(for: endpoint, session: .shared) + #expect(validator.validateHTTPSOrLoopbackCallCount == checks + 1) + #expect(tokens.calls.map(\.grantType) == ["client_credentials", "refresh_token"]) + #expect(storage.load(for: endpoint)?.value == "token-1") + + // An endpoint the validator refuses fails before any renewal. + validator.shouldThrow = OAuthAuthorizationError.insecureOAuthEndpoint( + context: "MCP endpoint", url: endpoint.absoluteString) + await #expect { + try await authorizer.prepare(for: endpoint, session: .shared) + } throws: { ($0 as? OAuthAuthorizationError)?.code == .insecureOAuthEndpoint } + #expect(tokens.calls.count == 2) + } + + // MARK: - Token storage + + /// A valid Bearer token from `server`. + func storedToken(_ value: String, server: URL?, refreshToken: String? = nil) -> OAuthAccessToken { + OAuthAccessToken( + value: value, tokenType: "Bearer", expiresAt: Date().addingTimeInterval(3600), scopes: [], + authorizationServer: server, refreshToken: refreshToken) + } + + /// Discovery whose protected resource metadata names `resource`. + func discovery(listing server: URL, resource: URL?) -> MockDiscoveryClient { + let discovery = discovery(listing: server) + discovery.protectedResourceMetadataResult = OAuthProtectedResourceMetadata( + resource: resource?.absoluteString, authorizationServers: [server], scopesSupported: nil) + return discovery + } + + @Test("Throwing storage fails the request with its error") + func throwingStorage() async throws { + let storage = ControllableTokenStorage() + let tokens = RecordingTokenClient() + let authorizer = makeAuthorizer(discovery: discovery(listing: serverA), tokens: tokens, storage: storage) + + await storage.fail(["load"]) + await #expect(throws: ControllableTokenStorage.Failure(operation: "load")) { + try await authorizer.authorizationHeaders(for: endpoint, method: "POST") + } + await #expect(throws: ControllableTokenStorage.Failure(operation: "load")) { + try await challenge(authorizer, sent: nil) + } + await #expect(throws: ControllableTokenStorage.Failure(operation: "load")) { + try await authorizer.prepare(for: endpoint, session: .shared) + } + + // A token the storage can't save fails the challenge. It is not + // remembered: the next challenge runs the flow again. + await storage.fail(["save"]) + await #expect(throws: ControllableTokenStorage.Failure(operation: "save")) { + try await challenge(authorizer, sent: nil) + } + #expect(tokens.calls.count == 1) + await storage.fail([]) + #expect(try await challenge(authorizer, sent: nil)) + #expect(tokens.calls.count == 2) + #expect(await storage.token(for: endpoint)?.value == "token-2") + } + + @Test("A token that a proactive renewal can't save is kept, and prepare doesn't fail") + func failedSaveInPrepareIsIgnored() async throws { + let storage = ControllableTokenStorage() + let tokens = RecordingTokenClient() + let authorizer = makeAuthorizer(discovery: discovery(listing: serverA), tokens: tokens, storage: storage) + #expect(try await challenge(authorizer)) + let stored = aged(try #require(await storage.token(for: endpoint)), expiringIn: 40) + try await storage.save(stored, for: endpoint) + + await storage.fail(["save"]) + try await authorizer.prepare(for: endpoint, session: .shared) + #expect(tokens.calls.map(\.grantType) == ["client_credentials", "refresh_token"]) + #expect(await storage.token(for: endpoint)?.value == "token-1") + } + + @Test("A challenge waiting behind one whose save failed fails with the storage error", .timeLimit(.minutes(2))) + func waiterSharesFailedSave() async throws { + let storage = ControllableTokenStorage() + let flow = GatedAuthCodeFlow() + let authorizer = makeAuthorizer( + discovery: discovery(listing: serverA), tokens: RecordingTokenClient(), storage: storage, + grantType: .authorizationCode, authCodeFlow: flow) + await storage.fail(["save"]) + var entered = flow.entered.makeAsyncIterator() + + let first = Task { try await challenge(authorizer, sent: nil) } + await entered.next() + let waiting = Task { try await challenge(authorizer, sent: nil) } + try await waitUntil { authorizer.gate.waiterCount == 1 } + flow.release() + + for task in [first, waiting] { + await #expect(throws: ControllableTokenStorage.Failure(operation: "save")) { _ = try await task.value } + } + // The user signed in once. + #expect(flow.performCount == 1) + } + + @Test("A token the storage can't clear fails the request") + func failedClearFailsRequest() async throws { + let storage = ControllableTokenStorage() + let tokens = RecordingTokenClient() + let authorizer = makeAuthorizer(discovery: discovery(listing: serverA), tokens: tokens, storage: storage) + #expect(try await challenge(authorizer)) + await storage.fail(["clear"]) + + // A 401 whose refresh is refused clears the token before a new grant. + tokens.refusedGrants = ["refresh_token"] + await #expect(throws: ControllableTokenStorage.Failure(operation: "clear")) { + try await challenge(authorizer, sent: "Bearer token-1") + } + #expect(tokens.calls.map(\.grantType) == ["client_credentials", "refresh_token"]) + + // A token from another authorization server is cleared before any request carries it. + try await storage.save(storedToken("foreign", server: serverB), for: endpoint) + await #expect(throws: ControllableTokenStorage.Failure(operation: "clear")) { + try await authorizer.authorizationHeaders(for: endpoint, method: "POST") + } + #expect(await storage.token(for: endpoint)?.value == "foreign") + } + + let insufficientScope = ["WWW-Authenticate": #"Bearer error="insufficient_scope", scope="admin""#] + + /// Starts `authorizationHeaders` for a stored token of server B, which + /// `authorizer` (of server A) clears, and holds it in the clear between + /// its compare and its clear. Then starts a 403 step-up and returns once + /// its save of `token-2` waits for that clear. + func startClearRacingSave(_ authorizer: OAuthAuthorizer, storage: ControllableTokenStorage) async throws + -> (headers: Task<[String: String], any Error>, stepUp: Task) + { + try await storage.save(storedToken("foreign", server: serverB), for: endpoint) + // The first load reads the token to inspect; the second, the compare + // of the compare-then-clear, is held. + await storage.holdLoad(2) + let headers = Task { try await authorizer.authorizationHeaders(for: endpoint, method: "POST") } + #expect(await eventually(within: .seconds(10)) { await storage.isHoldingLoad }) + let stepUp = Task { [self] in + try await challenge(authorizer, sent: "Bearer foreign", status: 403, headers: insufficientScope) + } + #expect(await eventually(within: .seconds(10)) { authorizer.tokens.writes.waiterCount == 1 }) + return (headers, stepUp) + } + + @Test("A clear racing a save keeps the saved token", .timeLimit(.minutes(2))) + func clearRacingSave() async throws { + let storage = ControllableTokenStorage() + let tokens = RecordingTokenClient() + let authorizer = makeAuthorizer(discovery: discovery(listing: serverA), tokens: tokens, storage: storage) + #expect(try await challenge(authorizer)) + let race = try await startClearRacingSave(authorizer, storage: storage) + + await storage.releaseLoad() + #expect(try await race.headers.value.isEmpty) + #expect(try await race.stepUp.value) + // The clear removed the token it compared, and the save landed after it. + #expect(await storage.token(for: endpoint)?.value == "token-2") + #expect(tokens.calls.count == 2) + } + + @Test("A save waits for a clear in progress and is not skipped when cancelled", .timeLimit(.minutes(2))) + func cancelledSaveWaitsForClear() async throws { + let storage = ControllableTokenStorage() + let tokens = RecordingTokenClient() + let authorizer = makeAuthorizer(discovery: discovery(listing: serverA), tokens: tokens, storage: storage) + #expect(try await challenge(authorizer)) + let race = try await startClearRacingSave(authorizer, storage: storage) + + // The token endpoint has issued token-2: cancelling the challenge + // must not lose it. + race.stepUp.cancel() + #expect(authorizer.tokens.writes.waiterCount == 1) + await storage.releaseLoad() + #expect(try await race.headers.value.isEmpty) + _ = await race.stepUp.result + #expect(await storage.token(for: endpoint)?.value == "token-2") + #expect(authorizer.tokens.writes.waiterCount == 0) + } + + @Test("Two authorizers for different servers share one storage") + func authorizersShareStorage() async throws { + let storage = InMemoryOAuthTokenStorage() + let endpointA = URL(string: "https://a.example.com/mcp")! + let endpointB = URL(string: "https://b.example.com/mcp")! + let tokensA = RecordingTokenClient(prefix: "a-token") + let tokensB = RecordingTokenClient(prefix: "b-token") + let authorizerA = makeAuthorizer(discovery: discovery(listing: serverA), tokens: tokensA, storage: storage) + let authorizerB = makeAuthorizer(discovery: discovery(listing: serverB), tokens: tokensB, storage: storage) + + #expect(try await challenge(authorizerA, endpoint: endpointA)) + #expect(try await challenge(authorizerB, endpoint: endpointB)) + #expect(storage.load(for: endpointA)?.value == "a-token-1") + #expect(storage.load(for: endpointB)?.value == "b-token-1") + #expect( + try await authorizerA.authorizationHeaders(for: endpointA, method: "POST")["Authorization"] + == "Bearer a-token-1") + #expect( + try await authorizerB.authorizationHeaders(for: endpointB, method: "POST")["Authorization"] + == "Bearer b-token-1") + + // A 401 that A can't answer clears A's token and leaves B's. + tokensA.refusedGrants = ["refresh_token", "client_credentials"] + await #expect(throws: OAuthAuthorizationError.self) { + try await challenge(authorizerA, sent: "Bearer a-token-1", endpoint: endpointA) + } + #expect(storage.load(for: endpointA) == nil) + #expect(storage.load(for: endpointB)?.value == "b-token-1") + #expect(try await authorizerA.authorizationHeaders(for: endpointA, method: "POST").isEmpty) + #expect( + try await authorizerB.authorizationHeaders(for: endpointB, method: "POST")["Authorization"] + == "Bearer b-token-1") + #expect(tokensB.calls.count == 1) + } + + @Test("A token saved under the metadata's resource is found after a relaunch") + func tokenFoundUnderMetadataResource() async throws { + let storage = InMemoryOAuthTokenStorage() + let resource = URL(string: "https://mcp.example.com")! + let tokens = RecordingTokenClient() + let first = makeAuthorizer( + discovery: discovery(listing: serverA, resource: resource), tokens: tokens, storage: storage) + #expect(try await challenge(first)) + #expect(storage.load(for: resource)?.value == "token-1") + #expect(storage.load(for: endpoint) == nil) + + // A new launch: the authorizer has not read the metadata yet, so the + // first request goes out without a token. + let relaunched = makeAuthorizer( + discovery: discovery(listing: serverA, resource: resource), tokens: tokens, storage: storage) + #expect(try await relaunched.authorizationHeaders(for: endpoint, method: "POST").isEmpty) + // Its 401 reads the metadata, finds the token under the resource it + // names, and retries with it: no new token request. + #expect(try await challenge(relaunched, sent: nil)) + #expect(tokens.calls.count == 1) + #expect( + try await relaunched.authorizationHeaders(for: endpoint, method: "POST")["Authorization"] + == "Bearer token-1") + } + + @Test("A token rejected under the endpoint's key is cleared when the metadata's key holds a usable one") + func supersededTokenIsCleared() async throws { + let storage = InMemoryOAuthTokenStorage() + let resource = URL(string: "https://mcp.example.com")! + storage.save(storedToken("old", server: serverA, refreshToken: "refresh-old"), for: endpoint) + storage.save(storedToken("new", server: serverA), for: resource) + let tokens = RecordingTokenClient() + let authorizer = makeAuthorizer( + discovery: discovery(listing: serverA, resource: resource), tokens: tokens, storage: storage) + // Before discovery, the key is the endpoint. + #expect( + try await authorizer.authorizationHeaders(for: endpoint, method: "POST")["Authorization"] == "Bearer old") + + #expect(try await challenge(authorizer, sent: "Bearer old")) + #expect(tokens.calls.isEmpty) + #expect(storage.load(for: endpoint) == nil) + #expect(storage.load(for: resource)?.value == "new") + #expect( + try await authorizer.authorizationHeaders(for: endpoint, method: "POST")["Authorization"] == "Bearer new") + } + + @Test("Without a token under the metadata's key, the rejected token's refresh token is tried for that key") + func supersededTokenIsRefreshed() async throws { + let storage = InMemoryOAuthTokenStorage() + let resource = URL(string: "https://mcp.example.com")! + storage.save(storedToken("old", server: serverA, refreshToken: "refresh-old"), for: endpoint) + let tokens = RecordingTokenClient() + let authorizer = makeAuthorizer( + discovery: discovery(listing: serverA, resource: resource), tokens: tokens, storage: storage) + + #expect(try await challenge(authorizer, sent: "Bearer old")) + #expect(tokens.calls.map(\.grantType) == ["refresh_token"]) + #expect(tokens.calls.first?.refreshToken == "refresh-old") + #expect(tokens.calls.first?.resource == resource.absoluteString) + #expect(storage.load(for: resource)?.value == "token-1") + #expect(storage.load(for: endpoint) == nil) + } + + /// An authorizer whose metadata names `https://mcp.example.com`, so the key + /// changes from the endpoint to it at the first discovery, with `old` + /// stored under the endpoint. + func keyChange( + old: OAuthAccessToken, storage: any OAuthTokenStorage, tokens: RecordingTokenClient, + discovery: MockDiscoveryClient? = nil, overrides: OAuthConfiguration.EndpointOverrides = .none + ) async throws -> OAuthAuthorizer { + try await storage.save(old, for: endpoint) + return makeAuthorizer( + discovery: discovery ?? self.discovery(listing: serverA, resource: metadataResource), tokens: tokens, + storage: storage, overrides: overrides) + } + + let metadataResource = URL(string: "https://mcp.example.com")! + + @Test("The token under the old key is kept when the challenge fails: unavailable server metadata, and recovers on retry") + func supersededKeptWhenMetadataUnavailable() async throws { + let storage = InMemoryOAuthTokenStorage() + let discovery = discovery(listing: serverA, resource: metadataResource) + discovery.authorizationServerMetadataError = OAuthMetadataUnavailable(url: serverA, reason: "HTTP 503") + let tokens = RecordingTokenClient() + let authorizer = try await keyChange( + old: storedToken("old", server: serverA, refreshToken: "refresh-old"), storage: storage, tokens: tokens, + discovery: discovery) + + await #expect(throws: OAuthMetadataUnavailable.self) { try await challenge(authorizer, sent: "Bearer old") } + #expect(storage.load(for: endpoint)?.refreshToken == "refresh-old") + #expect(tokens.calls.isEmpty) + + // Once server metadata is reachable again, the follow-up challenge + // refreshes the superseded token for the new key and clears the old one. + discovery.authorizationServerMetadataError = nil + #expect(try await challenge(authorizer, sent: "Bearer old")) + #expect(tokens.calls.map(\.grantType) == ["refresh_token"]) + #expect(tokens.calls.first?.refreshToken == "refresh-old") + #expect(tokens.calls.first?.resource == metadataResource.absoluteString) + #expect(storage.load(for: metadataResource)?.value == "token-1") + #expect(storage.load(for: endpoint) == nil) + } + + @Test("The token under the old key is kept when the challenge fails: a refresh answered with 5xx, and recovers on retry") + func supersededKeptWhenRefreshFails() async throws { + let storage = InMemoryOAuthTokenStorage() + let tokens = RecordingTokenClient() + tokens.refreshStatus = 503 + let authorizer = try await keyChange( + old: storedToken("old", server: serverA, refreshToken: "refresh-old"), storage: storage, tokens: tokens) + + await #expect(throws: OAuthAuthorizationError.self) { try await challenge(authorizer, sent: "Bearer old") } + #expect(tokens.calls.map(\.refreshToken) == ["refresh-old"]) + #expect(storage.load(for: endpoint)?.refreshToken == "refresh-old") + #expect(storage.load(for: metadataResource) == nil) + + // Once the transient 5xx clears, the follow-up challenge still refreshes + // the superseded token and cleans up the old key. + tokens.refreshStatus = nil + #expect(try await challenge(authorizer, sent: "Bearer old")) + #expect(tokens.calls.map(\.grantType) == ["refresh_token", "refresh_token"]) + #expect(tokens.calls.last?.refreshToken == "refresh-old") + #expect(tokens.calls.last?.resource == metadataResource.absoluteString) + #expect(storage.load(for: metadataResource)?.value == "token-2") + #expect(storage.load(for: endpoint) == nil) + } + + @Test("The token under the old key is cleared before a new grant") + func supersededClearedBeforeGrant() async throws { + let storage = InMemoryOAuthTokenStorage() + let tokens = RecordingTokenClient() + // No refresh token: nothing to refresh, so the challenge runs a grant. + let authorizer = try await keyChange(old: storedToken("old", server: serverA), storage: storage, tokens: tokens) + + #expect(try await challenge(authorizer, sent: "Bearer old")) + #expect(tokens.calls.map(\.grantType) == ["client_credentials"]) + #expect(storage.load(for: endpoint) == nil) + #expect(storage.load(for: metadataResource)?.value == "token-1") + } + + @Test("After a failed refresh, the token found under a new key is refreshed too") + func newKeyTokenRefreshedAfterFailedRefresh() async throws { + let storage = InMemoryOAuthTokenStorage() + let tokens = RecordingTokenClient() + let discovery = discovery(listing: serverA) + let authorizer = makeAuthorizer(discovery: discovery, tokens: tokens, storage: storage) + #expect(try await challenge(authorizer)) // token-1, under the endpoint + + // The server's metadata now names another resource, under which an + // expired token with its own refresh token is stored. + discovery.protectedResourceMetadataResult = OAuthProtectedResourceMetadata( + resource: metadataResource.absoluteString, authorizationServers: [serverA], scopesSupported: nil) + storage.save( + OAuthAccessToken( + value: "persisted", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(-60), scopes: [], + authorizationServer: serverA, refreshToken: "refresh-persisted"), + for: metadataResource) + // token-1's refresh is refused; the next one isn't. + tokens.refusedGrants = ["refresh_token"] + tokens.beforeAnswer = { [tokens] in + if tokens.calls.count == 3 { tokens.refusedGrants = [] } + } + + #expect(try await challenge(authorizer, sent: "Bearer token-1")) + #expect(tokens.calls.map(\.refreshToken) == [nil, "refresh-1", "refresh-persisted"]) + #expect(tokens.calls.last?.resource == metadataResource.absoluteString) + #expect(storage.load(for: metadataResource)?.value == "token-3") + #expect(storage.load(for: endpoint) == nil) + } + + @Test("A token saved again under the old key meanwhile is not cleared", .timeLimit(.minutes(2))) + func resavedOldKeyTokenIsKept() async throws { + let storage = InMemoryOAuthTokenStorage() + let tokens = RecordingTokenClient() + let (answered, answer) = AsyncStream.makeStream() + tokens.beforeAnswer = { for await _ in answered {} } + let authorizer = try await keyChange( + old: storedToken("old", server: serverA, refreshToken: "refresh-old"), storage: storage, tokens: tokens) + + // While the old token's refresh is on its way, another writer saves a + // new token under the old key. + let challenged = Task { try await challenge(authorizer, sent: "Bearer old") } + try await waitUntil { tokens.calls.count == 1 } + storage.save(storedToken("resaved", server: serverA), for: endpoint) + answer.finish() + + #expect(try await challenged.value) + #expect(storage.load(for: metadataResource)?.value == "token-1") + #expect(storage.load(for: endpoint)?.value == "resaved") + } + + @Test("A storage error clearing the old key's token doesn't fail a request that has a usable token") + func supersededClearIsBestEffort() async throws { + let storage = ControllableTokenStorage() + try await storage.save(storedToken("new", server: serverA), for: metadataResource) + let tokens = RecordingTokenClient() + let authorizer = try await keyChange(old: storedToken("old", server: serverA), storage: storage, tokens: tokens) + await storage.fail(["clear"]) + + #expect(try await challenge(authorizer, sent: "Bearer old")) + #expect(tokens.calls.isEmpty) + #expect(await storage.token(for: endpoint)?.value == "old") + #expect( + try await authorizer.authorizationHeaders(for: endpoint, method: "POST")["Authorization"] == "Bearer new") + } + + @Test( + "With a configured authorization server, a token under the metadata's key is used only when that server issued it", + arguments: ["configured server", "listed server"]) + func tokenUnderMetadataKeyWithConfiguredServer(issuer: String) async throws { + let storage = InMemoryOAuthTokenStorage() + // The metadata lists A; the application configures B. + storage.save(storedToken("stored", server: issuer == "configured server" ? serverB : serverA), for: metadataResource) + let tokens = RecordingTokenClient() + let authorizer = makeAuthorizer( + discovery: discovery(listing: serverA, resource: metadataResource), tokens: tokens, storage: storage, + overrides: .init(authorizationServerURL: serverB)) + + #expect(try await challenge(authorizer, sent: nil)) + if issuer == "configured server" { + #expect(tokens.calls.isEmpty) + #expect(storage.load(for: metadataResource)?.value == "stored") + } else { + #expect(tokens.calls.map(\.grantType) == ["client_credentials"]) + #expect(storage.load(for: metadataResource)?.value == "token-1") + } + } + + @Test("A 403 step-up at the first discovery uses the old key's scopes, and clears the old key") + func stepUpAtKeyChange() async throws { + let storage = InMemoryOAuthTokenStorage() + let tokens = RecordingTokenClient() + let narrow = OAuthAccessToken( + value: "narrow", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(3600), scopes: ["read"], + authorizationServer: serverA, refreshToken: nil) + let authorizer = try await keyChange(old: narrow, storage: storage, tokens: tokens) + + #expect(try await challenge(authorizer, sent: "Bearer narrow", status: 403, headers: insufficientScope)) + let scope = try #require(tokens.calls.last?.scope) + #expect(Set(scope.split(separator: " ").map(String.init)) == ["read", "admin"]) + #expect(tokens.calls.last?.resource == metadataResource.absoluteString) + #expect(storage.load(for: endpoint) == nil) + #expect(storage.load(for: metadataResource)?.value == "token-1") + } + + @Test("A 403 step-up at the first discovery retries with a usable token under the metadata's key") + func stepUpAtKeyChangeFindsToken() async throws { + let storage = InMemoryOAuthTokenStorage() + let tokens = RecordingTokenClient() + storage.save( + OAuthAccessToken( + value: "wide", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(3600), + scopes: ["read", "admin"], authorizationServer: serverA, refreshToken: nil), + for: metadataResource) + let authorizer = try await keyChange(old: storedToken("narrow", server: serverA), storage: storage, tokens: tokens) + + #expect(try await challenge(authorizer, sent: "Bearer narrow", status: 403, headers: insufficientScope)) + #expect(tokens.calls.isEmpty) + #expect(storage.load(for: endpoint) == nil) + } + + @Test("A 403 step-up at a key change preserves the superseded token when elevation fails, and clears it once elevation succeeds") + func stepUpAtKeyChangeKeepsSupersededTokenWhenAcquisitionFails() async throws { + let storage = InMemoryOAuthTokenStorage() + let tokens = RecordingTokenClient() + tokens.refusedGrants = ["client_credentials"] + let narrow = OAuthAccessToken( + value: "narrow", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(3600), scopes: ["read"], + authorizationServer: serverA, refreshToken: "refresh-narrow") + let authorizer = try await keyChange(old: narrow, storage: storage, tokens: tokens) + + await #expect(throws: OAuthAuthorizationError.self) { + _ = try await challenge(authorizer, sent: "Bearer narrow", status: 403, headers: insufficientScope) + } + // Step-up failed: the valid narrower token stays in storage. + #expect(storage.load(for: endpoint)?.value == "narrow") + #expect(storage.load(for: endpoint)?.refreshToken == "refresh-narrow") + + // When step-up succeeds on retry, it still unions the narrower token's scopes and clears the old key. + tokens.refusedGrants = [] + #expect(try await challenge(authorizer, sent: "Bearer narrow", status: 403, headers: insufficientScope)) + let scope = try #require(tokens.calls.last?.scope) + #expect(Set(scope.split(separator: " ").map(String.init)) == ["read", "admin"]) + #expect(storage.load(for: endpoint) == nil) + #expect(storage.load(for: metadataResource)?.value == "token-2") + } + + @Test("A 403 retry after a transient key-change failure still rejects an unissued token under the new key") + func stepUpRetryAfterKeyChangeIgnoresUnissuedToken() async throws { + let storage = InMemoryOAuthTokenStorage() + // Pre-existing token under metadataResource has no recorded authorizationServer: + // it must not be accepted as a usable token on key-change recovery. + storage.save( + OAuthAccessToken( + value: "unissued-wide", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(3600), + scopes: ["read", "admin"], authorizationServer: nil, refreshToken: nil), + for: metadataResource) + let tokens = RecordingTokenClient() + tokens.refusedGrants = ["client_credentials"] + let narrow = OAuthAccessToken( + value: "narrow", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(3600), scopes: ["read"], + authorizationServer: serverA, refreshToken: nil) + let authorizer = try await keyChange(old: narrow, storage: storage, tokens: tokens) + + // First 403 discovers metadataResource, records pendingSuperseded, and fails elevation. + await #expect(throws: OAuthAuthorizationError.self) { + _ = try await challenge(authorizer, sent: "Bearer narrow", status: 403, headers: insufficientScope) + } + #expect(storage.load(for: endpoint)?.value == "narrow") + + // Follow-up 403 sees keyChanged == false but recovers superseded: must still reject unissued-wide + // and acquire a fresh token with union scopes ["read", "admin"]. + tokens.refusedGrants = [] + #expect(try await challenge(authorizer, sent: "Bearer narrow", status: 403, headers: insufficientScope)) + #expect(tokens.calls.count == 2) + let scope = try #require(tokens.calls.last?.scope) + #expect(Set(scope.split(separator: " ").map(String.init)) == ["read", "admin"]) + #expect(storage.load(for: metadataResource)?.value == "token-2") + #expect(storage.load(for: endpoint) == nil) + } + + @Test("A storage error reloading the pending superseded old key does not block 401 or 403 recovery") + func pendingSupersededLoadErrorDoesNotBlockRecovery() async throws { + // 401 path + do { + let storage = ControllableTokenStorage() + let discovery = discovery(listing: serverA, resource: metadataResource) + discovery.authorizationServerMetadataError = OAuthMetadataUnavailable(url: serverA, reason: "HTTP 503") + let tokens = RecordingTokenClient() + let authorizer = try await keyChange( + old: storedToken("old", server: serverA, refreshToken: "refresh-old"), storage: storage, + tokens: tokens, discovery: discovery) + await #expect(throws: OAuthMetadataUnavailable.self) { + _ = try await challenge(authorizer, sent: "Bearer old") } + + // Old key storage now fails on load; follow-up 401 must still recover via a fresh grant. + discovery.authorizationServerMetadataError = nil + await storage.failLoad(for: [endpoint]) + #expect(try await challenge(authorizer, sent: "Bearer old")) + #expect(tokens.calls.map(\.grantType) == ["client_credentials"]) + #expect(await storage.token(for: metadataResource)?.value == "token-1") } + + // 403 path + do { + let storage = ControllableTokenStorage() + let tokens = RecordingTokenClient() + tokens.refusedGrants = ["client_credentials"] + let narrow = OAuthAccessToken( + value: "narrow", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(3600), scopes: ["read"], + authorizationServer: serverA, refreshToken: nil) + let authorizer = try await keyChange(old: narrow, storage: storage, tokens: tokens) + await #expect(throws: OAuthAuthorizationError.self) { + _ = try await challenge(authorizer, sent: "Bearer narrow", status: 403, headers: insufficientScope) + } + + // Old key storage now fails on load; follow-up 403 must still recover via step-up. + tokens.refusedGrants = [] + await storage.failLoad(for: [endpoint]) + #expect(try await challenge(authorizer, sent: "Bearer narrow", status: 403, headers: insufficientScope)) + #expect(await storage.token(for: metadataResource)?.value == "token-2") + } + } + + @Test("A foreign-issuer token is rejected when protectedResourceMetadata is cached while selectedAuthorizationServer is nil") + func foreignIssuerTokenRejectedBeforeSelectionWhenMetadataCached() async throws { + let storage = InMemoryOAuthTokenStorage() + storage.save(storedToken("foreign", server: serverB), for: metadataResource) + let discovery = discovery(listing: serverA, resource: metadataResource) + discovery.authorizationServerMetadataError = OAuthMetadataUnavailable(url: serverA, reason: "HTTP 503") + let tokens = RecordingTokenClient() + let authorizer = try await keyChange( + old: storedToken("old", server: serverA, refreshToken: "refresh-old"), storage: storage, tokens: tokens, + discovery: discovery) + + // First challenge caches protectedResourceMetadata (serverA) while selectedAuthorizationServer stays nil. + await #expect(throws: OAuthMetadataUnavailable.self) { try await challenge(authorizer, sent: "Bearer old") } + let headers = try await authorizer.authorizationHeaders(for: endpoint, method: "POST") + #expect(headers.isEmpty) + #expect(storage.load(for: metadataResource) == nil) + } + + @Test("A foreign-issuer token is rejected against endpointOverrides.authorizationServerURL before first discovery") + func foreignIssuerTokenRejectedByConfiguredServerBeforeDiscovery() async throws { + let storage = InMemoryOAuthTokenStorage() + storage.save(storedToken("foreign", server: serverB), for: endpoint) + let tokens = RecordingTokenClient() + let authorizer = makeAuthorizer( + discovery: discovery(listing: serverA), tokens: tokens, storage: storage, + overrides: .init(authorizationServerURL: serverA)) + + let headers = try await authorizer.authorizationHeaders(for: endpoint, method: "POST") + #expect(headers.isEmpty) + #expect(storage.load(for: endpoint) == nil) + } + + @Test("Cached Bearer tokens are not reused when resource metadata requires DPoP") + func bearerTokenNotReusedWhenMetadataRequiresDPoP() async throws { + // 1. Key change without DPoP configured: must throw dpopRequired instead of reusing Bearer. + do { + let storage = InMemoryOAuthTokenStorage() + storage.save(storedToken("bearer-stored", server: serverA), for: metadataResource) + let discovery = discovery(listing: serverA, resource: metadataResource) + discovery.protectedResourceMetadataResult = OAuthProtectedResourceMetadata( + resource: metadataResource.absoluteString, authorizationServers: [serverA], scopesSupported: nil, + dpopBoundAccessTokensRequired: true) + let tokens = RecordingTokenClient() + let authorizer = makeAuthorizer(discovery: discovery, tokens: tokens, storage: storage) + + let error = await #expect(throws: OAuthAuthorizationError.self) { + _ = try await challenge(authorizer, sent: nil) + } + #expect(error?.code == .dpopRequired) + } + + // 2. Cached metadata requiring DPoP: authorizationHeaders returns [:] without deleting a refreshable Bearer token. + do { + let storage = InMemoryOAuthTokenStorage() + let discovery = discovery(listing: serverA, resource: metadataResource) + discovery.protectedResourceMetadataResult = OAuthProtectedResourceMetadata( + resource: metadataResource.absoluteString, authorizationServers: [serverA], scopesSupported: nil, + dpopBoundAccessTokensRequired: true) + discovery.authorizationServerMetadataError = OAuthMetadataUnavailable(url: serverA, reason: "HTTP 503") + let tokens = RecordingTokenClient() + let authorizer = try await keyChange( + old: storedToken("old", server: serverA, refreshToken: "refresh-old"), storage: storage, tokens: tokens, + discovery: discovery) + await #expect(throws: OAuthMetadataUnavailable.self) { + _ = try await challenge(authorizer, sent: "Bearer old") + } + + storage.save(storedToken("bearer-refreshable", server: serverA, refreshToken: "r1"), for: metadataResource) + let headers = try await authorizer.authorizationHeaders(for: endpoint, method: "POST") + #expect(headers.isEmpty) + #expect(storage.load(for: metadataResource)?.refreshToken == "r1") + } + + // 3. Key change with DPoP configured: skips Bearer token and acquires a DPoP-bound token. + do { + let storage = InMemoryOAuthTokenStorage() + storage.save(storedToken("bearer-stored", server: serverA), for: metadataResource) + let discovery = discovery(listing: serverA, resource: metadataResource) + discovery.protectedResourceMetadataResult = OAuthProtectedResourceMetadata( + resource: metadataResource.absoluteString, authorizationServers: [serverA], scopesSupported: nil, + dpopBoundAccessTokensRequired: true) + let tokens = RecordingTokenClient() + tokens.tokenType = "DPoP" + let authorizer = OAuthAuthorizer( + configuration: OAuthConfiguration( + grantType: .clientCredentials, + authentication: .clientSecretBasic(clientID: "client", clientSecret: "secret"), + dpop: .init()), + tokenStorage: storage, + urlValidator: MockURLValidator(), + discoveryClient: discovery, + tokenEndpointClient: tokens, + clientRegistrar: MockClientRegistrar(), + authCodeFlow: MockAuthCodeFlow()) + + #expect(try await challenge(authorizer, sent: nil)) + #expect(tokens.calls.map(\.grantType) == ["client_credentials"]) + #expect(storage.load(for: metadataResource)?.isDPoPBound == true) + } + } + + @Test("401 key-change refresh ignores an unusable stored token and refreshes the superseded token") + func keyChangeRefreshIgnoresUnusableStoredToken() async throws { + let storage = InMemoryOAuthTokenStorage() + // Foreign-issuer token under the new key has a refresh token, but is unusable for serverA. + storage.save(storedToken("foreign", server: serverB, refreshToken: "refresh-foreign"), for: metadataResource) + let tokens = RecordingTokenClient() + let authorizer = try await keyChange( + old: storedToken("old", server: serverA, refreshToken: "refresh-old"), storage: storage, tokens: tokens) + + #expect(try await challenge(authorizer, sent: "Bearer old")) + #expect(tokens.calls.map(\.grantType) == ["refresh_token"]) + #expect(tokens.calls.map(\.refreshToken) == ["refresh-old"]) + #expect(tokens.calls.first?.resource == metadataResource.absoluteString) + #expect(storage.load(for: metadataResource)?.value == "token-1") + #expect(storage.load(for: endpoint) == nil) + } + + @Test("Unparseable authorization server URLs never match each other") + func unparseableAuthorizationServerURLsDoNotMatch() async throws { + let storage = InMemoryOAuthTokenStorage() + storage.save( + storedToken("bad", server: URL(string: "ftp://bad-a.example.com")!), for: metadataResource) + let discovery = discovery(listing: serverA, resource: metadataResource) + discovery.protectedResourceMetadataResult = OAuthProtectedResourceMetadata( + resource: metadataResource.absoluteString, + authorizationServers: [URL(string: "ftp://bad-b.example.com")!, URL(string: "https:///empty-host")!, serverA], + scopesSupported: nil) + let tokens = RecordingTokenClient() + let authorizer = makeAuthorizer(discovery: discovery, tokens: tokens, storage: storage) + + #expect(try await challenge(authorizer, sent: nil)) + // Must not treat nil == nil as a match for the stored token. + #expect(tokens.calls.map(\.grantType) == ["client_credentials"]) + #expect(storage.load(for: metadataResource)?.value == "token-1") + } + + @Test("A refresh refused for the old resource is retried once discovery updates the resource key") + func triedRefreshRetriesWhenResourceChanges() async throws { + let storage = InMemoryOAuthTokenStorage() + let tokens = RecordingTokenClient() + let discovery = discovery(listing: serverA) + let authorizer = makeAuthorizer(discovery: discovery, tokens: tokens, storage: storage) + #expect(try await challenge(authorizer)) // token-1 under endpoint, caches asMetadata + + // Server now advertises metadataResource; refresh for the old endpoint fails with 400 invalid_target. + discovery.protectedResourceMetadataResult = OAuthProtectedResourceMetadata( + resource: metadataResource.absoluteString, authorizationServers: [serverA], scopesSupported: nil) + tokens.refusedRefreshResource = endpoint.absoluteString + + #expect(try await challenge(authorizer, sent: "Bearer token-1")) + #expect(tokens.calls.map(\.grantType) == ["client_credentials", "refresh_token", "refresh_token"]) + #expect(tokens.calls[1].resource == endpoint.absoluteString) + #expect(tokens.calls[2].resource == metadataResource.absoluteString) + #expect(tokens.calls[2].refreshToken == "refresh-1") + #expect(storage.load(for: metadataResource)?.value == "token-3") + #expect(storage.load(for: endpoint) == nil) + } + + @Test("prepare recomputes canonicalResource after waiting on the gate across a concurrent key change", .timeLimit(.minutes(1))) + func prepareRecomputesCanonicalResourceAfterGate() async throws { + let storage = ControllableTokenStorage() + let tokens = RecordingTokenClient() + let discovery = discovery(listing: serverA) + let authorizer = OAuthAuthorizer( + configuration: OAuthConfiguration( + grantType: .clientCredentials, + authentication: .clientSecretBasic(clientID: "client", clientSecret: "secret"), + proactiveRefreshWindowSeconds: 60), + tokenStorage: storage, + urlValidator: MockURLValidator(), + discoveryClient: discovery, + tokenEndpointClient: tokens, + clientRegistrar: MockClientRegistrar(), + authCodeFlow: MockAuthCodeFlow()) + #expect(try await challenge(authorizer)) // caches asMetadata under endpoint + let expiring = OAuthAccessToken( + value: "expiring", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(20), scopes: [], + authorizationServer: serverA, refreshToken: "refresh-expiring") + try await storage.save(expiring, for: endpoint) + + // Next challenge attempts pre-discovery refresh for `endpoint` (which suspends + // before metadata changes), then discovers `metadataResource`, saves a fresh token + // there, and fails clear on `endpoint` so the expiring token remains at the old key. + discovery.protectedResourceMetadataResult = OAuthProtectedResourceMetadata( + resource: metadataResource.absoluteString, authorizationServers: [serverA], scopesSupported: nil) + tokens.refusedRefreshResource = endpoint.absoluteString + await storage.fail(["clear"]) + let (entered, enter) = AsyncStream.makeStream() + let (released, release) = AsyncStream.makeStream() + tokens.beforeAnswer = { [tokens] in + if tokens.calls.count == 2 { + enter.yield() + for await _ in released {} + } + } + + let migrating = Task { try await challenge(authorizer, sent: "Bearer expiring") } + for await _ in entered { break } + // `migrating` holds the gate and protectedResourceMetadata is still `nil`, so + // `prepare` computes `endpoint` pre-gate and queues on the gate. + let preparing = Task { try await authorizer.prepare(for: endpoint, session: .shared) } + try await waitUntil { authorizer.gate.waiterCount == 1 } + release.finish() + + #expect(try await migrating.value) + try await preparing.value + // Post-gate `prepare` reloads `metadataResource` (fresh token-3), not stale `endpoint`. + #expect(tokens.calls.map(\.grantType) == ["client_credentials", "refresh_token", "refresh_token"]) + #expect(await storage.token(for: metadataResource)?.value == "token-3") + } + + @Test("A failed tokens.save does not clear proactivelyRenewedToken and hammer the token endpoint") + func failedSavePreservesProactiveRenewalGuard() async throws { + let storage = ControllableTokenStorage() + let tokens = RecordingTokenClient() + let authorizer = OAuthAuthorizer( + configuration: OAuthConfiguration( + grantType: .clientCredentials, + authentication: .clientSecretBasic(clientID: "client", clientSecret: "secret"), + proactiveRefreshWindowSeconds: 60), + tokenStorage: storage, + urlValidator: MockURLValidator(), + discoveryClient: discovery(listing: serverA), + tokenEndpointClient: tokens, + clientRegistrar: MockClientRegistrar(), + authCodeFlow: MockAuthCodeFlow()) + #expect(try await challenge(authorizer)) // caches asMetadata + let expiring = OAuthAccessToken( + value: "expiring", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(20), scopes: [], + authorizationServer: serverA, refreshToken: "refresh-expiring") + try await storage.save(expiring, for: endpoint) + + await storage.fail(["save"]) + try await authorizer.prepare(for: endpoint, session: .shared) + try await authorizer.prepare(for: endpoint, session: .shared) + // First prepare tried refresh once (save threw and was swallowed); second prepare must not retry. + #expect(tokens.calls.map(\.grantType) == ["client_credentials", "refresh_token"]) + } + + @Test( + "A token under the metadata's key is used only when a server the metadata lists issued it", + arguments: ["another server", "no server"]) + func tokenUnderMetadataKeyFromUnlistedServer(issuer: String) async throws { + let storage = InMemoryOAuthTokenStorage() + let resource = URL(string: "https://mcp.example.com")! + storage.save(storedToken("stored", server: issuer == "another server" ? serverB : nil), for: resource) + let tokens = RecordingTokenClient() + let authorizer = makeAuthorizer( + discovery: discovery(listing: serverA, resource: resource), tokens: tokens, storage: storage) + + #expect(try await challenge(authorizer, sent: nil)) + #expect(tokens.calls.map(\.grantType) == ["client_credentials"]) + #expect(storage.load(for: resource)?.value == "token-1") + } + + @Test("A 403 retry after a loadPendingSuperseded storage error still rejects an unissued token under the new key") + func stepUpRetryAfterPendingSupersededLoadErrorRejectsUnissuedToken() async throws { + let storage = ControllableTokenStorage() + try await storage.save( + OAuthAccessToken( + value: "unissued-wide", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(3600), + scopes: ["read", "admin"], authorizationServer: nil, refreshToken: nil), + for: metadataResource) + let tokens = RecordingTokenClient() + tokens.refusedGrants = ["client_credentials"] + let narrow = OAuthAccessToken( + value: "narrow", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(3600), scopes: ["read"], + authorizationServer: serverA, refreshToken: nil) + let authorizer = try await keyChange(old: narrow, storage: storage, tokens: tokens) + + // First 403 discovers metadataResource, records pendingKeyChangeResource and pendingSuperseded, then fails. + await #expect(throws: OAuthAuthorizationError.self) { + _ = try await challenge(authorizer, sent: "Bearer narrow", status: 403, headers: insufficientScope) + } + // authorizationHeaders must not send the unvalidated pre-existing token while migration is unfinished. + #expect(try await authorizer.authorizationHeaders(for: endpoint, method: "POST").isEmpty) + + // Loading the old key now fails, dropping pendingSuperseded; retry must still reject unissued-wide. + tokens.refusedGrants = [] + await storage.failLoad(for: [endpoint]) + #expect(try await challenge(authorizer, sent: "Bearer narrow", status: 403, headers: insufficientScope)) + #expect(tokens.calls.count == 2) + #expect(await storage.token(for: metadataResource)?.value == "token-2") + } + + @Test("A 403 retry when the old key had no token still rejects an unissued token under the new key") + func stepUpRetryWithoutOldTokenRejectsUnissuedToken() async throws { + let storage = InMemoryOAuthTokenStorage() + storage.save( + OAuthAccessToken( + value: "unissued-wide", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(3600), + scopes: ["read", "admin"], authorizationServer: nil, refreshToken: nil), + for: metadataResource) + let tokens = RecordingTokenClient() + tokens.refusedGrants = ["client_credentials"] + let authorizer = makeAuthorizer( + discovery: discovery(listing: serverA, resource: metadataResource), tokens: tokens, storage: storage) + + // First 403 discovers metadataResource with no old token under endpoint and fails elevation. + await #expect(throws: OAuthAuthorizationError.self) { + _ = try await challenge(authorizer, sent: nil, status: 403, headers: insufficientScope) + } + #expect(try await authorizer.authorizationHeaders(for: endpoint, method: "POST").isEmpty) + + // Follow-up 403 must still reject unissued-wide and acquire a fresh token. + tokens.refusedGrants = [] + #expect(try await challenge(authorizer, sent: nil, status: 403, headers: insufficientScope)) + #expect(tokens.calls.count == 2) + #expect(storage.load(for: metadataResource)?.value == "token-2") + } + + @Test("A 401 retry after OAuthMetadataUnavailable still rejects an unissued token under the new key") + func unauthorizedRetryAfterMetadataUnavailableRejectsUnissuedToken() async throws { + let storage = InMemoryOAuthTokenStorage() + storage.save( + OAuthAccessToken( + value: "unissued-new", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(3600), + scopes: ["read"], authorizationServer: nil, refreshToken: nil), + for: metadataResource) + let discovery = discovery(listing: serverA, resource: metadataResource) + discovery.authorizationServerMetadataError = OAuthMetadataUnavailable(url: serverA, reason: "HTTP 503") + let tokens = RecordingTokenClient() + let authorizer = try await keyChange( + old: storedToken("old", server: serverA, refreshToken: "refresh-old"), storage: storage, tokens: tokens, + discovery: discovery) + + // First 401 discovers metadataResource, rejects unissued-new, and fails resolving AS metadata + // before tokens.clear runs, leaving unissued-new stored under metadataResource. + await #expect(throws: OAuthMetadataUnavailable.self) { + _ = try await challenge(authorizer, sent: "Bearer old") + } + #expect(storage.load(for: metadataResource)?.value == "unissued-new") + #expect(try await authorizer.authorizationHeaders(for: endpoint, method: "POST").isEmpty) + + // AS metadata recovers; follow-up 401 must not early-return unissued-new at line 709 and must + // refresh old (or acquire a fresh token) instead. + discovery.authorizationServerMetadataError = nil + #expect(try await challenge(authorizer, sent: "Bearer old")) + #expect(tokens.calls.map(\.grantType) == ["refresh_token"]) + #expect(storage.load(for: metadataResource)?.value == "token-1") + } + + @Test("pendingKeyChangeResource is set atomically when protectedResourceMetadata is published") + func metadataPublishSetsPendingKeyChangeAtomically() async throws { + final class ObservingScopeSelector: OAuthScopeSelecting, Sendable { + private let hook = Mutex<(@Sendable () -> Void)?>(nil) + func setHook(_ hook: @escaping @Sendable () -> Void) { self.hook.withLock { $0 = hook } } + func selectScopes(challengeScope: String?, scopesSupported: [String]?) -> Set? { + let current = hook.withLock { $0 } + current?() + return DefaultOAuthScopeSelector().selectScopes( + challengeScope: challengeScope, scopesSupported: scopesSupported) + } + func parseScopeString(_ scope: String) -> Set { + DefaultOAuthScopeSelector().parseScopeString(scope) + } + func serialize(_ scopes: Set) -> String? { + DefaultOAuthScopeSelector().serialize(scopes) + } + } + + let storage = InMemoryOAuthTokenStorage() + let unissued = OAuthAccessToken( + value: "unissued-wide", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(3600), + scopes: ["read", "admin"], authorizationServer: nil, refreshToken: nil) + storage.save(unissued, for: metadataResource) + + let selector = ObservingScopeSelector() + let discovery = discovery(listing: serverA, resource: metadataResource) + let tokens = RecordingTokenClient() + let authorizer = OAuthAuthorizer( + configuration: OAuthConfiguration( + grantType: .clientCredentials, + authentication: .clientSecretBasic(clientID: "client", clientSecret: "secret")), + tokenStorage: storage, + scopeSelector: selector, + urlValidator: MockURLValidator(), + discoveryClient: discovery, + tokenEndpointClient: tokens, + clientRegistrar: MockClientRegistrar(), + authCodeFlow: MockAuthCodeFlow()) + + // Inside selectScopes on the 403 path, discoverProtectedResourceMetadata has already + // published protectedResourceMetadata, while answerChallenge has not reached its + // post-discovery keyChanged check yet. The unissued token under metadataResource must + // already be rejected as unvalidated. + final class Observation: Sendable { + let rejected = Mutex(nil) + } + let observation = Observation() + selector.setHook { + let isRejected = authorizer.isUnvalidatedAfterKeyChange(unissued, for: metadataResource) + observation.rejected.withLock { $0 = isRejected } + } + + #expect(try await challenge(authorizer, sent: nil, status: 403, headers: insufficientScope)) + #expect(observation.rejected.withLock { $0 } == true) + #expect(storage.load(for: metadataResource)?.value == "token-1") + } + + @Test("authorizationHeaders rejects an unissued token loaded before a concurrent key change finishes") + func authorizationHeadersRejectsUnissuedTokenLoadedAcrossKeyChangeCompletion() async throws { + let storage = ControllableTokenStorage() + try await storage.save( + OAuthAccessToken( + value: "unissued-wide", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(3600), + scopes: ["read", "admin"], authorizationServer: nil, refreshToken: nil), + for: metadataResource) + let tokens = RecordingTokenClient() + tokens.refusedGrants = ["client_credentials"] + let authorizer = makeAuthorizer( + discovery: discovery(listing: serverA, resource: metadataResource), tokens: tokens, storage: storage) + + // First 403 publishes metadataResource and sets pendingKeyChangeResource, then fails. + await #expect(throws: OAuthAuthorizationError.self) { + _ = try await challenge(authorizer, sent: nil, status: 403, headers: insufficientScope) + } + + // Hold authorizationHeaders right after tokens.load reads the pre-existing unissued token. + await storage.holdLoad(1) + let headersTask = Task { + try await authorizer.authorizationHeaders(for: endpoint, method: "POST") + } + try #require(await eventually { await storage.isHoldingLoad }) + + // Complete the key change while headersTask is suspended, saving a validated token and + // clearing pendingKeyChangeResource to nil. + tokens.refusedGrants = [] + #expect(try await challenge(authorizer, sent: nil, status: 403, headers: insufficientScope)) + #expect(await storage.token(for: metadataResource)?.value == "token-2") + + // Resume headersTask with the stale unissued token it loaded before completion. + await storage.releaseLoad() + let headers = try await headersTask.value + #expect(headers.isEmpty) + } + + @Test("Foreign-issuer and wrong-DPoP-key superseded tokens are neither refreshed on 401 nor merged on 403") + func ineligibleSupersededTokensAreNotRefreshedOrMerged() async throws { + let dpop = OAuthConfiguration.DPoP() + let otherDPoP = OAuthConfiguration.DPoP() + + // 401: foreign-issuer superseded token is not refreshed. + do { + let storage = InMemoryOAuthTokenStorage() + let tokens = RecordingTokenClient() + let foreign = storedToken("foreign", server: serverB, refreshToken: "refresh-foreign") + let authorizer = try await keyChange(old: foreign, storage: storage, tokens: tokens) + + #expect(try await challenge(authorizer, sent: "Bearer foreign")) + #expect(tokens.calls.map(\.grantType) == ["client_credentials"]) + #expect(storage.load(for: metadataResource)?.value == "token-1") + } + + // 401: wrong-DPoP-key superseded token is not refreshed. + do { + let storage = InMemoryOAuthTokenStorage() + let wrongKeyToken = OAuthAccessToken( + value: "wrong-key", tokenType: "DPoP", expiresAt: Date().addingTimeInterval(3600), scopes: ["read"], + authorizationServer: serverA, refreshToken: "refresh-wrong-key", + keyThumbprint: otherDPoP.keyThumbprint) + storage.save(wrongKeyToken, for: endpoint) + let tokens = RecordingTokenClient() + tokens.tokenType = "DPoP" + let authorizer = OAuthAuthorizer( + configuration: OAuthConfiguration( + grantType: .clientCredentials, + authentication: .clientSecretBasic(clientID: "client", clientSecret: "secret"), + dpop: dpop), + tokenStorage: storage, + urlValidator: MockURLValidator(), + discoveryClient: discovery(listing: serverA, resource: metadataResource), + tokenEndpointClient: tokens, + clientRegistrar: MockClientRegistrar(), + authCodeFlow: MockAuthCodeFlow()) + + #expect(try await challenge(authorizer, sent: "DPoP wrong-key")) + #expect(tokens.calls.map(\.grantType) == ["client_credentials"]) + #expect(storage.load(for: metadataResource)?.value == "token-1") + } + + // 403: foreign-issuer superseded token scopes are not merged into upgradedScopes. + do { + let storage = InMemoryOAuthTokenStorage() + let tokens = RecordingTokenClient() + let foreign = OAuthAccessToken( + value: "foreign", tokenType: "Bearer", expiresAt: Date().addingTimeInterval(3600), + scopes: ["secret-scope"], authorizationServer: serverB, refreshToken: nil) + let authorizer = try await keyChange(old: foreign, storage: storage, tokens: tokens) + + #expect(try await challenge(authorizer, sent: "Bearer foreign", status: 403, headers: insufficientScope)) + let scope = try #require(tokens.calls.last?.scope) + #expect(Set(scope.split(separator: " ").map(String.init)) == ["admin"]) + } + + // 403: wrong-DPoP-key superseded token scopes are not merged into upgradedScopes. + do { + let storage = InMemoryOAuthTokenStorage() + let wrongKeyToken = OAuthAccessToken( + value: "wrong-key", tokenType: "DPoP", expiresAt: Date().addingTimeInterval(3600), + scopes: ["secret-scope"], authorizationServer: serverA, refreshToken: nil, + keyThumbprint: otherDPoP.keyThumbprint) + storage.save(wrongKeyToken, for: endpoint) + let tokens = RecordingTokenClient() + tokens.tokenType = "DPoP" + let authorizer = OAuthAuthorizer( + configuration: OAuthConfiguration( + grantType: .clientCredentials, + authentication: .clientSecretBasic(clientID: "client", clientSecret: "secret"), + dpop: dpop), + tokenStorage: storage, + urlValidator: MockURLValidator(), + discoveryClient: discovery(listing: serverA, resource: metadataResource), + tokenEndpointClient: tokens, + clientRegistrar: MockClientRegistrar(), + authCodeFlow: MockAuthCodeFlow()) + + #expect(try await challenge(authorizer, sent: "DPoP wrong-key", status: 403, headers: insufficientScope)) + let scope = try #require(tokens.calls.last?.scope) + #expect(Set(scope.split(separator: " ").map(String.init)) == ["admin"]) + } + } + + @Test("DPoP nonce fast path is skipped when the stored token is from another authorization server") + func dpopNonceFastPathSkipsForeignAuthorizationServerToken() async throws { + let dpop = OAuthConfiguration.DPoP() + let storage = InMemoryOAuthTokenStorage() + let foreignDPoP = OAuthAccessToken( + value: "foreign-dpop", tokenType: "DPoP", expiresAt: Date().addingTimeInterval(3600), scopes: [], + authorizationServer: serverB, refreshToken: nil, keyThumbprint: dpop.keyThumbprint) + storage.save(foreignDPoP, for: endpoint) + let tokens = RecordingTokenClient() + tokens.tokenType = "DPoP" + let authorizer = OAuthAuthorizer( + configuration: OAuthConfiguration( + grantType: .clientCredentials, + authentication: .clientSecretBasic(clientID: "client", clientSecret: "secret"), + endpointOverrides: .init(authorizationServerURL: serverA), + dpop: dpop), + tokenStorage: storage, + urlValidator: MockURLValidator(), + discoveryClient: discovery(listing: serverA), + tokenEndpointClient: tokens, + clientRegistrar: MockClientRegistrar(), + authCodeFlow: MockAuthCodeFlow()) + + let result = try await authorizer.handleChallenge( + HTTPAuthorizationChallenge( + statusCode: 401, + headers: [ + "WWW-Authenticate": #"DPoP error="use_dpop_nonce""#, + "DPoP-Nonce": "fresh-nonce", + ], + endpoint: endpoint, + sentAuthorization: "DPoP foreign-dpop"), + session: .shared) + #expect(result == .retry) + #expect(!result.isDPoPNonceRetry) + #expect(tokens.calls.map(\.grantType) == ["client_credentials"]) + #expect(storage.load(for: endpoint)?.value == "token-1") + } + + @Test("Whitespace-padded metadata.resource is trimmed in canonicalResource(for:)") + func whitespacePaddedMetadataResourceIsTrimmed() async throws { + let storage = InMemoryOAuthTokenStorage() + let discovery = discovery(listing: serverA, resource: metadataResource) + discovery.protectedResourceMetadataResult = OAuthProtectedResourceMetadata( + resource: " \(metadataResource.absoluteString) \n", + authorizationServers: [serverA], + scopesSupported: nil) + let tokens = RecordingTokenClient() + let authorizer = makeAuthorizer(discovery: discovery, tokens: tokens, storage: storage) + + #expect(try await challenge(authorizer, sent: nil)) + #expect(tokens.calls.first?.resource == metadataResource.absoluteString) + #expect(storage.load(for: metadataResource)?.value == "token-1") + #expect(storage.load(for: endpoint) == nil) + } + + @Test( + "Tokens are stored under the resource the token request named", + arguments: ["configured resource", "metadata resource", "endpoint"]) + func tokensStoredUnderRequestedResource(source: String) async throws { + let resource = URL(string: "https://mcp.example.com")! + let storage = InMemoryOAuthTokenStorage() + let tokens = RecordingTokenClient() + let authorizer = makeAuthorizer( + discovery: discovery(listing: serverA, resource: source == "metadata resource" ? resource : nil), + tokens: tokens, storage: storage, + overrides: source == "configured resource" ? .init(resource: resource) : .none) + #expect(try await challenge(authorizer)) + + let expected = source == "endpoint" ? endpoint : resource + #expect(tokens.calls.last?.resource == expected.absoluteString) + #expect(storage.load(for: expected)?.value == "token-1") + #expect(storage.load(for: source == "endpoint" ? resource : endpoint) == nil) + } + + @Test( + "Metadata naming the endpoint in another spelling matches it, and the canonical form is sent and stored", + arguments: [ + "https://mcp.example.com/mcp/", "https://mcp.example.com:443/mcp", "HTTPS://MCP.EXAMPLE.COM/mcp", + "https://user:secret@mcp.example.com/mcp", + ]) + func metadataResourceIsCanonicalized(resource: String) async throws { + let storage = InMemoryOAuthTokenStorage() + let tokens = RecordingTokenClient() + let authorizer = makeAuthorizer( + discovery: discovery(listing: serverA, resource: URL(string: resource)!), tokens: tokens, + storage: storage) + #expect(try await challenge(authorizer)) + #expect(tokens.calls.map(\.resource) == ["https://mcp.example.com/mcp"]) + #expect(storage.load(for: endpoint)?.value == "token-1") + #expect( + try await authorizer.authorizationHeaders(for: endpoint, method: "POST")["Authorization"] + == "Bearer token-1") + } + + @Test("An endpoint with a trailing slash and a default port is stored under its canonical form") + func endpointIsCanonicalized() async throws { + let storage = InMemoryOAuthTokenStorage() + let tokens = RecordingTokenClient() + let spelled = URL(string: "https://MCP.example.com:443/mcp/")! + let authorizer = makeAuthorizer(discovery: discovery(listing: serverA), tokens: tokens, storage: storage) + #expect(try await challenge(authorizer, endpoint: spelled)) + #expect(tokens.calls.map(\.resource) == ["https://mcp.example.com/mcp"]) + #expect(storage.load(for: endpoint)?.value == "token-1") + // Either spelling finds the token. + for url in [spelled, endpoint] { + #expect(try await authorizer.authorizationHeaders(for: url, method: "POST")["Authorization"] == "Bearer token-1") + } + } + + @Test("Without a named resource, a URL on the endpoint's origin uses the endpoint's token") + func unnamedResourceCoversEndpointOrigin() async throws { + let storage = InMemoryOAuthTokenStorage() + let tokens = RecordingTokenClient() + // The metadata names no resource, as a 2025-03-26 server's fallback. + let authorizer = makeAuthorizer(discovery: discovery(listing: serverA), tokens: tokens, storage: storage) + #expect(try await challenge(authorizer)) + #expect(storage.load(for: endpoint)?.value == "token-1") + + // A requestModifier gave the request another path (and a query). + let moved = URL(string: "https://mcp.example.com/v2/rpc?tenant=a")! + #expect(try await authorizer.authorizationHeaders(for: moved, method: "POST")["Authorization"] == "Bearer token-1") + #expect(tokens.calls.count == 1) + // Another origin is another server. + await #expect { + try await authorizer.authorizationHeaders(for: URL(string: "https://other.example.com/mcp")!, method: "POST") + } throws: { ($0 as? OAuthAuthorizationError)?.code == .protectedResourceMismatch } + } + + /// Moves the resource of `discovery` to server B, after a challenge has + /// stored token-1 from server A. + func moveToServerB(_ discovery: MockDiscoveryClient, tokens: RecordingTokenClient) { + discovery.protectedResourceMetadataResult = OAuthProtectedResourceMetadata( + resource: nil, authorizationServers: [serverB], scopesSupported: nil) + discovery.authorizationServerMetadataResult = asMetadata(serverB) + // token-1's refresh at A is refused, so the challenge reads the metadata again. + tokens.refusedGrants = ["refresh_token"] + } + + let serverC = URL(string: "https://c.example.com")! + + @Test( + "While a switch of authorization server clears the old token, tokens are still checked against the old server", + .timeLimit(.minutes(2))) + func serverSwitchClearsBeforeDroppingSelection() async throws { + let storage = ControllableTokenStorage() + let tokens = RecordingTokenClient() + let discovery = discovery(listing: serverA) + let authorizer = makeAuthorizer(discovery: discovery, tokens: tokens, storage: storage) + #expect(try await challenge(authorizer)) + moveToServerB(discovery, tokens: tokens) + await storage.holdNextClear() + + let switching = Task { try await challenge(authorizer, sent: "Bearer token-1") } + #expect(await eventually(within: .seconds(10)) { await storage.isHoldingClear }) + // A token from a third server lands meanwhile. It is not attached: it + // is from another server than the selected one, so its clear waits + // behind the held one. + try await storage.save(storedToken("c-token", server: serverC), for: endpoint) + let headers = Task { try await authorizer.authorizationHeaders(for: endpoint, method: "POST") } + #expect(await eventually(within: .seconds(10)) { authorizer.tokens.writes.waiterCount == 1 }) + await storage.releaseClear() + + #expect(try await headers.value.isEmpty) + #expect(try await switching.value) + #expect(await storage.token(for: endpoint)?.authorizationServer == serverB) + } + + @Test("A switch of authorization server whose clear fails keeps the old server selected") + func serverSwitchFailedClearKeepsSelection() async throws { + let storage = ControllableTokenStorage() + let tokens = RecordingTokenClient() + let discovery = discovery(listing: serverA) + let authorizer = makeAuthorizer(discovery: discovery, tokens: tokens, storage: storage) + #expect(try await challenge(authorizer)) + moveToServerB(discovery, tokens: tokens) + + await storage.fail(["clear"]) + await #expect(throws: ControllableTokenStorage.Failure(operation: "clear")) { + try await challenge(authorizer, sent: "Bearer token-1") + } + await storage.fail([]) + // Tokens are still checked against A: one from another server is cleared, not attached. + try await storage.save(storedToken("c-token", server: serverC), for: endpoint) + #expect(try await authorizer.authorizationHeaders(for: endpoint, method: "POST").isEmpty) + #expect(await storage.token(for: endpoint) == nil) + + // The next challenge for a rejected token reads the metadata again and makes the switch. + try await storage.save(storedToken("a-token", server: serverA), for: endpoint) + #expect(try await challenge(authorizer, sent: "Bearer a-token")) + #expect(await storage.token(for: endpoint)?.authorizationServer == serverB) + } + + @Test("No token is attached to a URL outside the resource") + func noTokenOutsideResource() async throws { + let other = URL(string: "https://other.example.com/mcp")! + let storage = InMemoryOAuthTokenStorage() + let authorizer = makeAuthorizer( + discovery: discovery(listing: serverA, resource: URL(string: "https://mcp.example.com")!), + tokens: RecordingTokenClient(), storage: storage) + // Before discovery, another URL is its own resource, without a token. + #expect(try await authorizer.authorizationHeaders(for: other, method: "POST").isEmpty) + + #expect(try await challenge(authorizer)) + #expect(!(try await authorizer.authorizationHeaders(for: endpoint, method: "POST")).isEmpty) + await #expect { + try await authorizer.authorizationHeaders(for: other, method: "POST") + } throws: { ($0 as? OAuthAuthorizationError)?.code == .protectedResourceMismatch } } } @@ -737,3 +2144,126 @@ private func aged(_ token: OAuthAccessToken, expiringIn seconds: TimeInterval) - scopes: token.scopes, authorizationServer: token.authorizationServer, refreshToken: token.refreshToken, clientID: token.clientID) } + +/// Records which gate bodies ran, in which order, and how many at once. +private actor GateRecorder { + private(set) var order: [Int] = [] + private(set) var mostActive = 0 + private var active = 0 + + func enter(_ index: Int) { + order.append(index) + active += 1 + mostActive = max(mostActive, active) + } + + func leave() { active -= 1 } +} + +/// Takes `gate` in a task that holds it until `release` is called. +private func hold(_ gate: AsyncGate) async -> (task: Task, release: @Sendable () -> Void) { + let (entered, enteredSink) = AsyncStream.makeStream() + let (released, releaseSink) = AsyncStream.makeStream() + let task = Task { + try await gate.run { + enteredSink.yield() + for await _ in released {} + } + } + var iterator = entered.makeAsyncIterator() + await iterator.next() + return (task, { releaseSink.finish() }) +} + +@Suite("AsyncGate") +struct AsyncGateTests { + @Test("The gate runs bodies one at a time, in arrival order", .timeLimit(.minutes(2))) + func runsInArrivalOrder() async throws { + let gate = AsyncGate() + let recorder = GateRecorder() + let holder = await hold(gate) + var waiters: [Task] = [] + for index in 1...5 { + waiters.append( + Task { + try await gate.run { + await recorder.enter(index) + await Task.yield() + await recorder.leave() + } + }) + // Enqueue the next one only after this one waits, so the + // arrival order is the index order. + try await waitUntil { gate.waiterCount == index } + } + holder.release() + try await holder.task.value + for waiter in waiters { try await waiter.value } + + #expect(await recorder.order == [1, 2, 3, 4, 5]) + #expect(await recorder.mostActive == 1) + #expect(gate.waiterCount == 0) + } + + @Test("Concurrent bodies never overlap", .timeLimit(.minutes(2))) + func concurrentBodiesDoNotOverlap() async throws { + let gate = AsyncGate() + let recorder = GateRecorder() + try await withThrowingTaskGroup(of: Void.self) { group in + for index in 0..<100 { + group.addTask { + try await gate.run(ignoringCancellation: index.isMultiple(of: 2)) { + await recorder.enter(index) + await Task.yield() + await recorder.leave() + } + } + } + try await group.waitForAll() + } + #expect(await recorder.order.count == 100) + #expect(await recorder.mostActive == 1) + #expect(gate.waiterCount == 0) + } + + @Test("A cancelled waiter leaves the queue and throws CancellationError", .timeLimit(.minutes(2))) + func cancelledWaiterThrows() async throws { + let gate = AsyncGate() + let recorder = GateRecorder() + let holder = await hold(gate) + let waiter = Task { try await gate.run { await recorder.enter(1) } } + try await waitUntil { gate.waiterCount == 1 } + + waiter.cancel() + // The cancellation handler runs inside cancel(): the waiter has + // left the queue while the holder still has the gate. + #expect(gate.waiterCount == 0) + await #expect(throws: CancellationError.self) { try await waiter.value } + + holder.release() + try await holder.task.value + #expect(await recorder.order.isEmpty) + let value = try await gate.run { 42 } + #expect(value == 42) + } + + @Test("A waiter that ignores cancellation still runs its body", .timeLimit(.minutes(2))) + func waiterIgnoringCancellationRuns() async throws { + let gate = AsyncGate() + let holder = await hold(gate) + let waiter = Task { try await gate.run(ignoringCancellation: true) { Task.isCancelled } } + try await waitUntil { gate.waiterCount == 1 } + + waiter.cancel() + #expect(gate.waiterCount == 1) + + holder.release() + try await holder.task.value + // The body ran, and it sees the cancellation. + let sawCancellation = try await waiter.value + #expect(sawCancellation) + #expect(gate.waiterCount == 0) + let value = try await gate.run { 42 } + #expect(value == 42) + } +} diff --git a/Tests/MCPTests/OAuthAuthorizerTests.swift b/Tests/MCPTests/OAuthAuthorizerTests.swift index f03557a9..8e6f7568 100644 --- a/Tests/MCPTests/OAuthAuthorizerTests.swift +++ b/Tests/MCPTests/OAuthAuthorizerTests.swift @@ -1,4 +1,5 @@ @preconcurrency import Foundation +import Synchronization import Testing @testable import MCP @@ -9,25 +10,46 @@ import Testing // MARK: - Mock Implementations -final class MockURLValidator: OAuthURLValidating, @unchecked Sendable { - var validateHTTPSOrLoopbackCallCount = 0 - var validateAuthorizationServerCallCount = 0 - var validateRedirectURICallCount = 0 - var shouldThrow: Error? +/// Counts the validator calls of concurrent challenges; `shouldThrow` fails each check. +final class MockURLValidator: OAuthURLValidating, Sendable { + private struct Counts { + var https = 0 + var authorizationServer = 0 + var redirectURI = 0 + var error: (any Error)? + } + private let counts = Mutex(Counts()) + + var validateHTTPSOrLoopbackCallCount: Int { counts.withLock { $0.https } } + var validateAuthorizationServerCallCount: Int { counts.withLock { $0.authorizationServer } } + var validateRedirectURICallCount: Int { counts.withLock { $0.redirectURI } } + var shouldThrow: (any Error)? { + get { counts.withLock { $0.error } } + set { counts.withLock { $0.error = newValue } } + } func validateHTTPSOrLoopback(_ url: URL, context: String) throws { - validateHTTPSOrLoopbackCallCount += 1 - if let error = shouldThrow { throw error } + let error = counts.withLock { counts in + counts.https += 1 + return counts.error + } + if let error { throw error } } func validateAuthorizationServer(_ url: URL, context: String) throws { - validateAuthorizationServerCallCount += 1 - if let error = shouldThrow { throw error } + let error = counts.withLock { counts in + counts.authorizationServer += 1 + return counts.error + } + if let error { throw error } } func validateRedirectURI(_ url: URL) throws { - validateRedirectURICallCount += 1 - if let error = shouldThrow { throw error } + let error = counts.withLock { counts in + counts.redirectURI += 1 + return counts.error + } + if let error { throw error } } func isPrivateIPHost(_ host: String) -> Bool { false } @@ -229,27 +251,43 @@ struct OAuthAuthorizerTests { ) } - // MARK: - validateEndpointSecurity + // MARK: - Component protocols - @Test("validateEndpointSecurity calls urlValidator") - func testValidateEndpointSecurityCallsURLValidator() throws { + @Test("The OAuth component protocols are Sendable") + func componentProtocolsAreSendable() async { + // Compiles only while both protocols refine Sendable: the child + // tasks capture the existentials, as concurrent challenges do. + let selector: any OAuthScopeSelecting = DefaultOAuthScopeSelector() + let parser: any OAuthWWWAuthenticateParsing = DefaultOAuthWWWAuthenticateParser() + let results = await withTaskGroup(of: String?.self) { group in + group.addTask { selector.serialize(["write", "read"]) } + group.addTask { parser.parseBearer(from: ["WWW-Authenticate": #"Bearer scope="read write""#])?.scope } + return await group.reduce(into: [String?]()) { $0.append($1) } + } + #expect(results == ["read write", "read write"]) + } + + // MARK: - prepare(for:session:) + + @Test("prepare checks the endpoint with urlValidator") + func testPrepareCallsURLValidator() async throws { let validator = MockURLValidator() let authorizer = makeAuthorizer(urlValidator: validator) - try authorizer.validateEndpointSecurity(for: endpoint) + try await authorizer.prepare(for: endpoint, session: .shared) #expect(validator.validateHTTPSOrLoopbackCallCount == 1) } - @Test("validateEndpointSecurity propagates validation error") - func testValidateEndpointSecurityPropagatesError() { + @Test("prepare propagates a validation error") + func testPreparePropagatesValidationError() async { let validator = MockURLValidator() validator.shouldThrow = OAuthAuthorizationError.insecureOAuthEndpoint( context: "test", url: "http://example.com") let authorizer = makeAuthorizer(urlValidator: validator) - #expect(throws: OAuthAuthorizationError.self) { - try authorizer.validateEndpointSecurity(for: endpoint) + await #expect(throws: OAuthAuthorizationError.self) { + try await authorizer.prepare(for: endpoint, session: .shared) } } @@ -346,6 +384,49 @@ struct OAuthAuthorizerTests { #expect(tokenClient.capturedParameters?["code"] == "mock-auth-code") } + @Test("The authorization_code grant without an authorization_endpoint throws authorizationEndpointMissing") + func testHandleChallenge401AuthorizationCodeWithoutAuthorizationEndpoint() async throws { + let discovery = MockDiscoveryClient() + let server = discovery.authorizationServerMetadataResult.server + discovery.authorizationServerMetadataResult.metadata = OAuthAuthorizationServerMetadata( + issuer: server, + authorizationEndpoint: nil, + tokenEndpoint: URL(string: "https://auth.example.com/token"), + registrationEndpoint: nil, + codeChallengeMethodsSupported: ["S256"], + tokenEndpointAuthMethodsSupported: nil, + clientIDMetadataDocumentSupported: nil + ) + let authCodeFlow = MockAuthCodeFlow() + let tokenClient = MockTokenClient() + let authorizer = OAuthAuthorizer( + configuration: OAuthConfiguration( + grantType: .authorizationCode, + authentication: .none(clientID: "my-client"), + authorizationRedirectURI: URL(string: "https://app.example.com/callback")! + ), + urlValidator: MockURLValidator(), + discoveryClient: discovery, + tokenEndpointClient: tokenClient, + clientRegistrar: MockClientRegistrar(), + authCodeFlow: authCodeFlow + ) + + let error = await #expect(throws: OAuthAuthorizationError.self) { + try await authorizer.handleChallenge( + statusCode: 401, + headers: headers401, + endpoint: endpoint, + operationKey: nil, + session: .shared + ) + } + + #expect(error == .authorizationEndpointMissing) + #expect(authCodeFlow.buildURLCallCount == 0) + #expect(tokenClient.requestCallCount == 0) + } + // MARK: - handleChallenge (403) @Test("handleChallenge 403 returns false for non-insufficient_scope error") @@ -434,7 +515,7 @@ struct OAuthAuthorizerTests { @Test("handleChallenge persists the DCR-assigned clientID on the saved token") func testHandleChallengePersistsDCRClientIDOnToken() async throws { let assignedClientID = "dcr-assigned-client-id" - let tokenStorage = InMemoryTokenStorage() + let tokenStorage = InMemoryOAuthTokenStorage() let registrar = MockClientRegistrar() registrar.registrationResult = ( response: OAuthClientRegistrationResponse( @@ -469,7 +550,7 @@ struct OAuthAuthorizerTests { #expect(handled == true) #expect(registrar.registerCallCount == 1) - #expect(tokenStorage.load()?.clientID == assignedClientID) + #expect(tokenStorage.load(for: endpoint)?.clientID == assignedClientID) } // MARK: - Refused authorization servers @@ -739,3 +820,133 @@ struct OAuthAuthorizerTests { #expect(registrar.lastAllowingLoopback == allowsLoopback) } } + +#if swift(>=6.1) + // The `resource` parameter as a token request carries it, through the + // SDK's own discovery and token endpoint clients (RFC 8707 §2). + @Suite("OAuthAuthorizer resource parameter on the wire") + struct OAuthResourceParameterWireTests { + /// The bodies of the token requests, in order. + actor TokenRequestBodies { + private(set) var all: [String] = [] + func append(_ body: String) { all.append(body) } + } + + /// The body of `request`, which a URLProtocol may see as a stream. + static func body(of request: URLRequest) -> String { + var body = request.httpBody ?? Data() + if body.isEmpty, let stream = request.httpBodyStream { + stream.open() + defer { stream.close() } + var buffer = [UInt8](repeating: 0, count: 4096) + while stream.hasBytesAvailable { + let count = stream.read(&buffer, maxLength: buffer.count) + guard count > 0 else { break } + body.append(buffer, count: count) + } + } + return String(decoding: body, as: UTF8.self) + } + + /// Answers a 401 for `endpoint` with an authorizer that uses the SDK's + /// own discovery and token endpoint clients, against metadata naming + /// `metadataResource`; returns the form parameters of the one token + /// request, as sent. + static func tokenRequestParameters( + endpoint: URL, metadataResource: String?, storage: InMemoryOAuthTokenStorage, + metadataDiscovery: any OAuthMetadataDiscovering = DefaultOAuthMetadataDiscovery() + ) async throws -> [String] { + let (session, key) = makeIsolatedSession() + let bodies = TokenRequestBodies() + let resourceMember = metadataResource.map { #""resource":"\#($0)","# } ?? "" + await IsolatedMockURLProtocol.setHandler(key: key) { request in + let url = try #require(request.url) + func reply(_ json: String) -> (HTTPURLResponse, Data) { + ( + HTTPURLResponse( + url: url, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/json"])!, Data(json.utf8) + ) + } + switch (url.host, url.path) { + case ("mcp.example.com", let path) where path.hasPrefix("/.well-known/oauth-protected-resource"): + return reply(#"{\#(resourceMember)"authorization_servers":["https://auth.example.com"]}"#) + case ("auth.example.com", "/.well-known/oauth-authorization-server"): + return reply( + #"{"issuer":"https://auth.example.com","token_endpoint":"https://auth.example.com/token","code_challenge_methods_supported":["S256"]}"# + ) + case ("auth.example.com", "/token"): + await bodies.append(Self.body(of: request)) + return reply(#"{"access_token":"wire-token","token_type":"Bearer","expires_in":3600}"#) + default: + return (HTTPURLResponse(url: url, statusCode: 404, httpVersion: "HTTP/1.1", headerFields: nil)!, Data()) + } + } + let authorizer = OAuthAuthorizer( + configuration: OAuthConfiguration( + grantType: .clientCredentials, + authentication: .clientSecretBasic(clientID: "client", clientSecret: "secret")), + tokenStorage: storage, metadataDiscovery: metadataDiscovery) + + let result = try await authorizer.handleChallenge( + HTTPAuthorizationChallenge(statusCode: 401, headers: ["WWW-Authenticate": "Bearer"], endpoint: endpoint), + session: session) + #expect(result == .retry) + let sent = await bodies.all + #expect(sent.count == 1) + return try #require(sent.first).split(separator: "&").map(String.init) + } + + @Test( + "A token request names the canonical resource, whatever the metadata's spelling", + arguments: ["https://mcp.example.com/mcp", "https://MCP.example.com:443/mcp/", nil]) + func tokenRequestResource(metadataResource: String?) async throws { + let storage = InMemoryOAuthTokenStorage() + let endpoint = URL(string: "https://mcp.example.com/mcp")! + let parameters = try await Self.tokenRequestParameters( + endpoint: endpoint, metadataResource: metadataResource, storage: storage) + // The form body, as sent: the `resource` is percent-encoded with + // nothing after it. + #expect(parameters.contains("resource=https%3A%2F%2Fmcp.example.com%2Fmcp"), "\(parameters)") + #expect(storage.load(for: endpoint)?.value == "wire-token") + } + + /// Keeps the trailing slash of a resource whose slash is significant, + /// on top of the default. + struct TrailingSlashDiscovery: OAuthMetadataDiscovering { + let base = DefaultOAuthMetadataDiscovery() + + func protectedResourceMetadataURLs(for endpoint: URL) -> [URL] { + base.protectedResourceMetadataURLs(for: endpoint) + } + func authorizationServerMetadataURLs(for issuer: URL) -> [URL] { + base.authorizationServerMetadataURLs(for: issuer) + } + func canonicalResourceURI(from endpoint: URL) throws -> URL { + let canonical = try base.canonicalResourceURI(from: endpoint) + guard endpoint.path.count > 1, endpoint.absoluteString.hasSuffix("/") else { return canonical } + return URL(string: canonical.absoluteString + "/")! + } + func authorizationServerFallbackIssuer(from endpoint: URL) throws -> URL { + try base.authorizationServerFallbackIssuer(from: endpoint) + } + func protectedResourceMatches(resource: URL, endpoint: URL) -> Bool { + base.protectedResourceMatches(resource: resource, endpoint: endpoint) + } + } + + // The documented opt-out for a server whose trailing slash is + // significant: a wrapping OAuthMetadataDiscovering. + @Test("A metadata discovery that wraps the default can keep a significant trailing slash") + func trailingSlashOptOut() async throws { + let storage = InMemoryOAuthTokenStorage() + let endpoint = URL(string: "https://mcp.example.com/mcp/")! + let parameters = try await Self.tokenRequestParameters( + endpoint: endpoint, metadataResource: "https://mcp.example.com/mcp/", storage: storage, + metadataDiscovery: TrailingSlashDiscovery()) + #expect(parameters.contains("resource=https%3A%2F%2Fmcp.example.com%2Fmcp%2F"), "\(parameters)") + #expect(storage.load(for: endpoint)?.value == "wire-token") + #expect(storage.load(for: URL(string: "https://mcp.example.com/mcp")!) == nil) + } + } +#endif diff --git a/Tests/MCPTests/OAuthClientRegistrarTests.swift b/Tests/MCPTests/OAuthClientRegistrarTests.swift index 4b7dc2a0..d4a29d3b 100644 --- a/Tests/MCPTests/OAuthClientRegistrarTests.swift +++ b/Tests/MCPTests/OAuthClientRegistrarTests.swift @@ -153,7 +153,7 @@ import Testing #expect(resultValue.updatedAuthentication == expected) } - @Test("Throws on 4xx registration response") + @Test("A 4xx registration response throws registrationRequestFailed with its OAuth error") func testRegisterThrowsOn4xx() async throws { let errorBody = try JSONSerialization.data( withJSONObject: ["error": "invalid_client_metadata"]) @@ -166,7 +166,7 @@ import Testing } let config = makeConfig(authentication: .none(clientID: "")) - await #expect(throws: OAuthAuthorizationError.self) { + let error = await #expect(throws: OAuthAuthorizationError.self) { try await registrar.register( configuration: config, asMetadata: makeASMetadata(registrationEndpoint: registrationEndpoint), @@ -174,9 +174,10 @@ import Testing session: session ) } + #expect(error == .registrationRequestFailed(statusCode: 400, oauthError: "invalid_client_metadata")) } - @Test("Throws tokenRequestFailed on non-2xx non-4xx response") + @Test("A 5xx registration response throws registrationRequestFailed with its status") func testRegisterThrowsOn5xx() async throws { let (session, key) = makeIsolatedSession() await IsolatedMockURLProtocol.setHandler(key: key) { _ in @@ -195,7 +196,44 @@ import Testing session: session ) } - #expect(error == .tokenRequestFailed(statusCode: 503, oauthError: nil)) + #expect(error == .registrationRequestFailed(statusCode: 503, oauthError: nil)) + } + + @Test("An unreadable registration response throws registrationResponseInvalid") + func testRegisterThrowsOnUnreadableResponse() async throws { + // No client_id: not a client information response (RFC 7591 §3.2.1). + let body = try JSONSerialization.data(withJSONObject: ["client_secret": "registration-secret"]) + let (session, key) = makeIsolatedSession() + await IsolatedMockURLProtocol.setHandler(key: key) { _ in + let response = HTTPURLResponse( + url: self.registrationEndpoint, statusCode: 201, + httpVersion: nil, headerFields: nil)! + return (response, body) + } + + let error = await #expect(throws: OAuthAuthorizationError.self) { + try await registrar.register( + configuration: makeConfig(authentication: .none(clientID: "")), + asMetadata: makeASMetadata(registrationEndpoint: registrationEndpoint), + allowingLoopback: false, + session: session + ) + } + #expect(error == .registrationResponseInvalid) + #expect(error?.localizedDescription.contains("registration-secret") == false) + } + + @Test("A registration response that is not HTTP throws registrationRequestFailed without a status") + func testRegisterThrowsOnNonHTTPResponse() async throws { + let error = await #expect(throws: OAuthAuthorizationError.self) { + try await registrar.register( + configuration: makeConfig(authentication: .none(clientID: "")), + asMetadata: makeASMetadata(registrationEndpoint: registrationEndpoint), + allowingLoopback: false, + session: NonHTTPResponseURLProtocol.makeSession() + ) + } + #expect(error == .registrationRequestFailed(statusCode: nil, oauthError: nil)) } // MARK: - Loopback registration endpoints diff --git a/Tests/MCPTests/OAuthComponentTestHelpers.swift b/Tests/MCPTests/OAuthComponentTestHelpers.swift index 7d49fb11..9719b866 100644 --- a/Tests/MCPTests/OAuthComponentTestHelpers.swift +++ b/Tests/MCPTests/OAuthComponentTestHelpers.swift @@ -96,4 +96,36 @@ return (IsolatedMockURLProtocol.makeSession(key: key), key) } + // MARK: - Responses that are not HTTP + + /// Answers every request with a `URLResponse` that is not an `HTTPURLResponse`, and a + /// `{}` body. It keeps no state, so suites can use it concurrently. + final class NonHTTPResponseURLProtocol: URLProtocol { + /// A session whose every request gets a response that is not HTTP. + static func makeSession() -> URLSession { + let config = URLSessionConfiguration.ephemeral + config.protocolClasses = [NonHTTPResponseURLProtocol.self] + return URLSession(configuration: config) + } + + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + /// Ends the client calls at `stopLoading()`: see ``URLProtocolStop``. + private let stop = URLProtocolStop() + + override func startLoading() { + let body = Data("{}".utf8) + let response = URLResponse( + url: request.url!, mimeType: "application/json", + expectedContentLength: body.count, textEncodingName: nil) + stop.ifLoading(self) { [self] in client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) } + stop.ifLoading(self) { [self] in client?.urlProtocol(self, didLoad: body) } + stop.ifLoading(self) { [self] in client?.urlProtocolDidFinishLoading(self) } + } + + override func stopLoading() { + stop.stop() + } + } + #endif diff --git a/Tests/MCPTests/OAuthDPoPTests.swift b/Tests/MCPTests/OAuthDPoPTests.swift index bebb96c8..32500ade 100644 --- a/Tests/MCPTests/OAuthDPoPTests.swift +++ b/Tests/MCPTests/OAuthDPoPTests.swift @@ -1,5 +1,6 @@ @preconcurrency import Foundation import Crypto +import Synchronization import Testing @testable import MCP @@ -72,7 +73,7 @@ private func accessTokenHash(_ token: String) -> String { private func dpopAuthorizer( dpop: OAuthConfiguration.DPoP? = .init(), - tokenStorage: TokenStorage = InMemoryTokenStorage(), + tokenStorage: any OAuthTokenStorage = InMemoryOAuthTokenStorage(), discovery: MockDiscoveryClient = MockDiscoveryClient(), tokenClient: any OAuthTokenRequesting = MockTokenClient() ) -> OAuthAuthorizer { @@ -109,8 +110,8 @@ struct DPoPProofTests { let signer = DPoPProofSigner(configuration: .init()) @Test("A proof is an ES256 dpop+jwt signed by the key in its jwk header") - func structure() throws { - let proof = try DecodedProof( + func structure() async throws { + let proof = try await DecodedProof( signer.proof( method: "post", url: URL(string: "HTTPS://MCP.example.com/mcp?tenant=a#frag")!, accessToken: "token-1", server: .resourceServer)) @@ -131,62 +132,127 @@ struct DPoPProofTests { } @Test("Every proof has a new jti; a token request proof has no ath") - func freshProofs() throws { - let first = try DecodedProof( + func freshProofs() async throws { + let first = try await DecodedProof( signer.proof(method: "POST", url: tokenEndpoint, accessToken: nil, server: .authorizationServer)) - let second = try DecodedProof( + let second = try await DecodedProof( signer.proof(method: "POST", url: tokenEndpoint, accessToken: nil, server: .authorizationServer)) #expect(first.claims["jti"] as? String != second.claims["jti"] as? String) #expect(first.claims["ath"] == nil) } @Test("Nonces apply per origin and per server kind") - func nonces() throws { + func nonces() async throws { signer.recordNonce( from: ["dpop-nonce": "n-rs"], for: URL(string: "https://mcp.example.com/other")!, server: .resourceServer) - func nonce(_ url: URL, _ server: DPoPProofSigner.ServerKind) throws -> String? { - try DecodedProof(signer.proof(method: "GET", url: url, accessToken: nil, server: server)) + func nonce(_ url: URL, _ server: DPoPProofSigner.ServerKind) async throws -> String? { + try await DecodedProof(signer.proof(method: "GET", url: url, accessToken: nil, server: server)) .claims["nonce"] as? String } - #expect(try nonce(endpoint, .resourceServer) == "n-rs") - #expect(try nonce(endpoint, .authorizationServer) == nil) - #expect(try nonce(URL(string: "https://mcp.example.com:8443/mcp")!, .resourceServer) == nil) + #expect(try await nonce(endpoint, .resourceServer) == "n-rs") + #expect(try await nonce(URL(string: "https://MCP.EXAMPLE.COM:443/v2")!, .resourceServer) == "n-rs") + #expect(try await nonce(endpoint, .authorizationServer) == nil) + #expect(try await nonce(URL(string: "https://mcp.example.com:8443/mcp")!, .resourceServer) == nil) + + // Recording under an explicit default port matches the implicit-port origin and vice versa. + signer.recordNonce( + from: ["DPoP-Nonce": "n-port443"], for: URL(string: "https://redirect.example.com:443/v2")!, + server: .resourceServer) + #expect(try await nonce(URL(string: "https://redirect.example.com/mcp")!, .resourceServer) == "n-port443") + signer.recordNonce( + from: ["DPoP-Nonce": "n-port80"], for: URL(string: "http://127.0.0.1:80/v2")!, + server: .resourceServer) + #expect(try await nonce(URL(string: "http://127.0.0.1/mcp")!, .resourceServer) == "n-port80") + } + + @Test("Nonces can be recorded and read from several tasks at once") + func concurrentNonces() async throws { + let signer = self.signer + @Sendable func server(_ number: Int) -> URL { URL(string: "https://server-\(number).example.com/mcp")! } + await withTaskGroup(of: Void.self) { group in + for index in 0..<200 { + group.addTask { + signer.setNonce("n-\(index)", for: server(index % 4), server: .resourceServer) + _ = signer.nonce(for: server((index + 1) % 4), server: .resourceServer) + } + } + } + // Each origin keeps one of the nonces recorded for it. + for number in 0..<4 { + let nonce = try #require(signer.nonce(for: server(number), server: .resourceServer)) + let index = try #require(Int(nonce.dropFirst("n-".count))) + #expect(index % 4 == number) + } } @Test("htu drops user information") - func targetDropsUserInfo() throws { - let proof = try DecodedProof( + func targetDropsUserInfo() async throws { + let proof = try await DecodedProof( signer.proof( method: "POST", url: URL(string: "https://user:secret@mcp.example.com/mcp?a=1")!, accessToken: nil, server: .resourceServer)) #expect(proof.claims["htu"] as? String == "https://mcp.example.com/mcp") } - /// Signs with a key it holds, as a hardware-backed key would. - private struct ExternalKey: DPoPSigningKey { + // 2100-01-01T00:00:00Z: past 2038-01-19, where a 32-bit `Int` such as + // watchOS's overflows. + @Test("A proof made after 2038-01-19 carries its iat as an Int64 JSON number") + func issuedAtAfter2038() async throws { + let compact = try await signer.proof( + method: "POST", url: endpoint, accessToken: nil, server: .resourceServer, + now: Date(timeIntervalSince1970: 4_102_444_800)) + let parts = compact.split(separator: ".").map(String.init) + try #require(parts.count == 3) + let claims = try #require(DecodedProof.decode(parts[1])) + struct IssuedAt: Decodable { let iat: Int64 } + #expect(try JSONDecoder().decode(IssuedAt.self, from: claims).iat == 4_102_444_800) + #expect(String(decoding: claims, as: UTF8.self).contains(#""iat":4102444800"#)) + } + + // The error's value is the TimeInterval, not the Date: describing a NaN + // date traps on Linux. + @Test("A clock without an Int64 NumericDate fails the proof", arguments: [TimeInterval.infinity, .nan, 1e19]) + func clockWithoutNumericDate(seconds: TimeInterval) async { + await #expect { + _ = try await signer.proof( + method: "POST", url: endpoint, accessToken: nil, server: .resourceServer, + now: Date(timeIntervalSince1970: seconds)) + } throws: { error in + guard case .invalidValue(let value, _) = error as? EncodingError else { return false } + return value is TimeInterval + } + } + + /// Signs with a key it holds, as a hardware-backed key would: it + /// suspends before it signs, and throws `failure` when set. + struct ExternalKey: DPoPSigningKey { + struct KeyUnavailable: Error {} + let wrapped = P256.Signing.PrivateKey() let signatures = Counter() + var fails = false var publicKey: P256.Signing.PublicKey { wrapped.publicKey } - func signature(for data: Data) throws -> P256.Signing.ECDSASignature { + func signature(for data: Data) async throws -> P256.Signing.ECDSASignature { + await Task.yield() + if fails { throw KeyUnavailable() } signatures.increment() return try wrapped.signature(for: data) } } - final class Counter: @unchecked Sendable { - private let lock = NSLock() - private var count = 0 - var value: Int { lock.withLock { count } } - func increment() { lock.withLock { count += 1 } } + final class Counter: Sendable { + private let count = Mutex(0) + var value: Int { count.withLock { $0 } } + func increment() { count.withLock { $0 += 1 } } } - @Test("A DPoPSigningKey signs proofs and names the thumbprint") - func externalKey() throws { + @Test("A key that signs asynchronously signs proofs and names the thumbprint") + func externalKey() async throws { let key = ExternalKey() let configuration = OAuthConfiguration.DPoP(key: key) let signer = DPoPProofSigner(configuration: configuration) - let proof = try DecodedProof( + let proof = try await DecodedProof( signer.proof(method: "POST", url: endpoint, accessToken: nil, server: .resourceServer)) #expect(try proof.verifies()) #expect(key.signatures.value == 1) @@ -195,6 +261,80 @@ struct DPoPProofTests { #expect(signer.thumbprint == configuration.keyThumbprint) } + @Test("A signing error fails the request") + func signingErrorFailsRequest() async throws { + let dpop = OAuthConfiguration.DPoP(key: ExternalKey(fails: true)) + let storage = InMemoryOAuthTokenStorage() + storage.save( + OAuthAccessToken( + value: "bound", tokenType: "DPoP", expiresAt: nil, scopes: [], authorizationServer: nil, + refreshToken: nil, keyThumbprint: dpop.keyThumbprint), for: endpoint) + let authorizer = dpopAuthorizer(dpop: dpop, tokenStorage: storage) + await #expect(throws: ExternalKey.KeyUnavailable.self) { + try await authorizer.authorizationHeaders(for: endpoint, method: "POST") + } + + // Through the transport: the request fails with the key's error and + // is not sent. + let key = UUID().uuidString + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [IsolatedMockURLProtocol.self] + configuration.httpAdditionalHeaders = [IsolatedMockURLProtocol.sessionKeyHeader: key] + let sent = Recorder() + await IsolatedMockURLProtocol.setHandler(key: key) { request in + await sent.append(request) + return (HTTPURLResponse(url: endpoint, statusCode: 202, httpVersion: "HTTP/1.1", headerFields: [:])!, Data()) + } + let transport = HTTPClientTransport( + endpoint: endpoint, configuration: configuration, streaming: false, authorizer: authorizer) + try await transport.connect() + await #expect { + try await transport.send(Data(#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#.utf8)) + } throws: { error in + guard case .transportError(let underlying) = error as? MCPError else { return false } + return underlying is ExternalKey.KeyUnavailable + } + #expect(await sent.values.isEmpty) + await transport.disconnect() + } + + @Test("HTTPChallengeResult static members") + func challengeResultStaticMembers() { + #expect(HTTPChallengeResult.retry == HTTPChallengeResult(shouldRetry: true, isDPoPNonceRetry: false)) + #expect( + HTTPChallengeResult.retryWithDPoPNonce == HTTPChallengeResult(shouldRetry: true, isDPoPNonceRetry: true)) + #expect(HTTPChallengeResult.unhandled == HTTPChallengeResult(shouldRetry: false, isDPoPNonceRetry: false)) + #expect(HTTPChallengeResult(shouldRetry: false, isDPoPNonceRetry: true) == .unhandled) + } + + @Test("A challenge's description and mirror name no header value and no sent token") + func challengeDescriptionIsRedacted() { + let challenge = HTTPAuthorizationChallenge( + statusCode: 401, + headers: ["WWW-Authenticate": #"Bearer error="invalid_token""#, "DPoP-Nonce": "nonce-value"], + endpoint: URL(string: "https://user:password@mcp.example.com/mcp?key=query-secret#frag-secret")!, + operationKey: "tools/call", sentAuthorization: "Bearer secret") + // dump(_:) and debuggers read the mirror, not the description. + var dumped = "" + dump(challenge, to: &dumped) + let mirror = Mirror(reflecting: challenge) + #expect(mirror.children.map(\.label) == ["statusCode", "endpoint", "operationKey", "headers"]) + let mirrored = mirror.children.map { "\($0.label ?? ""): \($0.value)" }.joined(separator: "\n") + for text in [String(describing: challenge), String(reflecting: challenge), "\(challenge)", dumped, mirrored] { + #expect(!text.contains("secret"), "\(text)") + #expect(!text.contains("invalid_token"), "\(text)") + #expect(!text.contains("nonce-value"), "\(text)") + #expect(!text.contains("password"), "\(text)") + #expect(text.contains("WWW-Authenticate"), "\(text)") + #expect(text.contains("DPoP-Nonce"), "\(text)") + #expect(text.contains("401"), "\(text)") + #expect(text.contains("tools/call"), "\(text)") + } + // The values stay readable from the properties. + #expect(challenge.value(forHeader: "www-authenticate") == #"Bearer error="invalid_token""#) + #expect(challenge.sentAuthorization == "Bearer secret") + } + @Test("The thumbprint is the RFC 7638 hash of the canonical JWK") func thumbprint() throws { let configuration = OAuthConfiguration.DPoP() @@ -263,7 +403,7 @@ struct DPoPAuthorizerTests { statusCode: 401, headers: headers401, endpoint: endpoint, session: .shared)) #expect(tokenClient.capturedDPoP != nil) - let headers = try authorizer.authorizationHeaders(for: endpoint, method: "GET") + let headers = try await authorizer.authorizationHeaders(for: endpoint, method: "GET") #expect(headers[HTTPHeaderName.authorization] == "DPoP dpop-token") let proof = try DecodedProof(try #require(headers[HTTPHeaderName.dpop])) #expect(proof.claims["htm"] as? String == "GET") @@ -274,11 +414,11 @@ struct DPoPAuthorizerTests { @Test("The stored token records the key thumbprint") func storesThumbprint() async throws { let dpop = OAuthConfiguration.DPoP() - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let authorizer = dpopAuthorizer(dpop: dpop, tokenStorage: storage, tokenClient: dpopTokenClient()) _ = try await authorizer.handleChallenge( statusCode: 401, headers: headers401, endpoint: endpoint, session: .shared) - let token = try #require(storage.load()) + let token = try #require(storage.load(for: endpoint)) #expect(token.isDPoPBound) #expect(token.keyThumbprint == dpop.keyThumbprint) } @@ -288,7 +428,7 @@ struct DPoPAuthorizerTests { let authorizer = dpopAuthorizer(tokenClient: MockTokenClient()) _ = try await authorizer.handleChallenge( statusCode: 401, headers: headers401, endpoint: endpoint, session: .shared) - let headers = try authorizer.authorizationHeaders(for: endpoint, method: "POST") + let headers = try await authorizer.authorizationHeaders(for: endpoint, method: "POST") #expect(headers == [HTTPHeaderName.authorization: "Bearer mock-access-token"]) } @@ -296,7 +436,7 @@ struct DPoPAuthorizerTests { func bearerForDPoPResource() async { let discovery = MockDiscoveryClient() discovery.protectedResourceMetadataResult.dpopBoundAccessTokensRequired = true - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let tokenClient = MockTokenClient() let authorizer = dpopAuthorizer(tokenStorage: storage, discovery: discovery, tokenClient: tokenClient) let error = await authorizationError { @@ -305,7 +445,7 @@ struct DPoPAuthorizerTests { } #expect(error?.code == .dpopRequired) #expect(tokenClient.requestCallCount == 1) - #expect(storage.load() == nil) + #expect(storage.load(for: endpoint) == nil) } @Test("A refresh that returns Bearer for a DPoP-required resource falls back to a full grant") @@ -331,12 +471,12 @@ struct DPoPAuthorizerTests { let discovery = MockDiscoveryClient() discovery.protectedResourceMetadataResult.dpopBoundAccessTokensRequired = true let dpop = OAuthConfiguration.DPoP() - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() storage.save( OAuthAccessToken( value: "stale", tokenType: "DPoP", expiresAt: nil, scopes: [], authorizationServer: URL(string: "https://auth.example.com")!, refreshToken: "rt-1", - keyThumbprint: dpop.keyThumbprint)) + keyThumbprint: dpop.keyThumbprint), for: endpoint) let tokenClient = RefreshThenGrantClient() let authorizer = dpopAuthorizer(dpop: dpop, tokenStorage: storage, discovery: discovery, tokenClient: tokenClient) @@ -344,67 +484,69 @@ struct DPoPAuthorizerTests { statusCode: 401, headers: headers401, endpoint: endpoint, session: .shared) #expect(retried) #expect(tokenClient.grants == ["refresh_token", "client_credentials"]) - #expect(storage.load()?.value == "token-client_credentials") - #expect(storage.load()?.isDPoPBound == true) + #expect(storage.load(for: endpoint)?.value == "token-client_credentials") + #expect(storage.load(for: endpoint)?.isDPoPBound == true) // When the full grant also returns Bearer, the stale refresh token is still cleared. storage.save( OAuthAccessToken( value: "stale-2", tokenType: "DPoP", expiresAt: nil, scopes: [], authorizationServer: URL(string: "https://auth.example.com")!, refreshToken: "rt-2", - keyThumbprint: dpop.keyThumbprint)) + keyThumbprint: dpop.keyThumbprint), for: endpoint) tokenClient.grantTokenType = "Bearer" let error = await authorizationError { _ = try await authorizer.handleChallenge( statusCode: 401, headers: headers401, endpoint: endpoint, session: .shared) } #expect(error?.errorDescription == OAuthAuthorizationError.dpopRequired.errorDescription) - #expect(storage.load() == nil) + #expect(storage.load(for: endpoint) == nil) } @Test("A stored token bound to another key is discarded") - func otherKey() throws { - let storage = InMemoryTokenStorage() + func otherKey() async throws { + let storage = InMemoryOAuthTokenStorage() storage.save(OAuthAccessToken( value: "old", tokenType: "DPoP", expiresAt: nil, scopes: [], authorizationServer: nil, - refreshToken: nil, keyThumbprint: "another-key")) + refreshToken: nil, keyThumbprint: "another-key"), for: endpoint) let authorizer = dpopAuthorizer(tokenStorage: storage) - #expect(try authorizer.authorizationHeaders(for: endpoint, method: "POST").isEmpty) - #expect(storage.load() == nil) + #expect(try await authorizer.authorizationHeaders(for: endpoint, method: "POST").isEmpty) + #expect(storage.load(for: endpoint) == nil) } - /// Returns `first` from the first `load()` and `later` afterwards, as a + /// Returns `first` from the first `load(for:)` and `later` afterwards, as a /// storage that a challenge saves `later` into meanwhile. - private final class ReplacedTokenStorage: TokenStorage, @unchecked Sendable { - private let lock = NSLock() - private var loads = 0 - private var cleared = 0 - private var token: OAuthAccessToken? + private final class ReplacedTokenStorage: OAuthTokenStorage { + private struct State { + var loads = 0 + var cleared = 0 + var token: OAuthAccessToken? + } + private let state: Mutex private let first: OAuthAccessToken - var clears: Int { lock.withLock { cleared } } + var clears: Int { state.withLock { $0.cleared } } init(first: OAuthAccessToken, later: OAuthAccessToken) { self.first = first - token = later + state = Mutex(State(token: later)) } - func save(_ token: OAuthAccessToken) { lock.withLock { self.token = token } } - func load() -> OAuthAccessToken? { - lock.withLock { - loads += 1 - return loads == 1 ? first : token + func save(_ token: OAuthAccessToken, for resource: URL) { state.withLock { $0.token = token } } + func load(for resource: URL) -> OAuthAccessToken? { + state.withLock { state in + state.loads += 1 + return state.loads == 1 ? first : state.token } } - func clear() { - lock.withLock { - cleared += 1 - token = nil + func clear(for resource: URL) { + state.withLock { state in + state.cleared += 1 + state.token = nil } } } @Test("A token saved after the inspected one was loaded is not discarded") - func otherKeyReplacedMeanwhile() throws { + func otherKeyReplacedMeanwhile() async throws { let dpop = OAuthConfiguration.DPoP() let storage = ReplacedTokenStorage( first: OAuthAccessToken( @@ -414,43 +556,43 @@ struct DPoPAuthorizerTests { value: "new", tokenType: "DPoP", expiresAt: nil, scopes: [], authorizationServer: nil, refreshToken: nil, keyThumbprint: dpop.keyThumbprint)) let authorizer = dpopAuthorizer(dpop: dpop, tokenStorage: storage) - #expect(try authorizer.authorizationHeaders(for: endpoint, method: "POST").isEmpty) + #expect(try await authorizer.authorizationHeaders(for: endpoint, method: "POST").isEmpty) #expect(storage.clears == 0) - #expect(storage.load()?.value == "new") + #expect(storage.load(for: endpoint)?.value == "new") #expect( - try authorizer.authorizationHeaders(for: endpoint, method: "POST")[HTTPHeaderName.authorization] + try await authorizer.authorizationHeaders(for: endpoint, method: "POST")[HTTPHeaderName.authorization] == "DPoP new") } @Test("Without DPoP configured, a DPoP-bound stored token is discarded") - func boundTokenWithoutDPoP() throws { - let storage = InMemoryTokenStorage() + func boundTokenWithoutDPoP() async throws { + let storage = InMemoryOAuthTokenStorage() storage.save(OAuthAccessToken( value: "old", tokenType: "DPoP", expiresAt: nil, scopes: [], authorizationServer: nil, - refreshToken: nil, keyThumbprint: "k")) + refreshToken: nil, keyThumbprint: "k"), for: endpoint) let authorizer = dpopAuthorizer(dpop: nil, tokenStorage: storage) - #expect(try authorizer.authorizationHeaders(for: endpoint, method: "POST").isEmpty) + #expect(try await authorizer.authorizationHeaders(for: endpoint, method: "POST").isEmpty) } @Test("An expired token bound to another key is discarded") - func expiredTokenOfOtherKey() throws { - let storage = InMemoryTokenStorage() + func expiredTokenOfOtherKey() async throws { + let storage = InMemoryOAuthTokenStorage() storage.save(OAuthAccessToken( value: "old", tokenType: "DPoP", expiresAt: Date().addingTimeInterval(-60), scopes: [], - authorizationServer: nil, refreshToken: "rt-other-key", keyThumbprint: "another-key")) + authorizationServer: nil, refreshToken: "rt-other-key", keyThumbprint: "another-key"), for: endpoint) let authorizer = dpopAuthorizer(tokenStorage: storage) - #expect(try authorizer.authorizationHeaders(for: endpoint, method: "POST").isEmpty) - #expect(storage.load() == nil) + #expect(try await authorizer.authorizationHeaders(for: endpoint, method: "POST").isEmpty) + #expect(storage.load(for: endpoint) == nil) } @Test("The refresh token of a token bound to another key is not used (RFC 9449 section 5)") func refreshTokenOfOtherKey() async throws { let dpop = OAuthConfiguration.DPoP() - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() storage.save(OAuthAccessToken( value: "old", tokenType: "DPoP", expiresAt: Date().addingTimeInterval(-60), scopes: [], authorizationServer: URL(string: "https://auth.example.com")!, refreshToken: "rt-other-key", - keyThumbprint: "another-key")) + keyThumbprint: "another-key"), for: endpoint) let tokenClient = dpopTokenClient() let authorizer = dpopAuthorizer(dpop: dpop, tokenStorage: storage, tokenClient: tokenClient) #expect(try await authorizer.handleChallenge( @@ -458,7 +600,7 @@ struct DPoPAuthorizerTests { #expect(tokenClient.requestCallCount == 1) #expect(tokenClient.capturedParameters?[OAuthParameterName.grantType] == OAuthGrantTypeValue.clientCredentials) #expect(tokenClient.capturedParameters?[OAuthParameterName.refreshToken] == nil) - let token = try #require(storage.load()) + let token = try #require(storage.load(for: endpoint)) #expect(token.value == "dpop-token") #expect(token.keyThumbprint == dpop.keyThumbprint) } @@ -466,28 +608,28 @@ struct DPoPAuthorizerTests { @Test("A DPoP-bound token is refreshed with a proof of its key and stays bound to it") func refreshBoundToken() async throws { let dpop = OAuthConfiguration.DPoP() - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() storage.save(OAuthAccessToken( value: "old", tokenType: "DPoP", expiresAt: Date().addingTimeInterval(-60), scopes: [], authorizationServer: URL(string: "https://auth.example.com")!, refreshToken: "rt-1", - keyThumbprint: dpop.keyThumbprint)) + keyThumbprint: dpop.keyThumbprint), for: endpoint) let tokenClient = dpopTokenClient("refreshed") let authorizer = dpopAuthorizer(dpop: dpop, tokenStorage: storage, tokenClient: tokenClient) let result = try await authorizer.handleChallenge( statusCode: 401, headers: headers401, endpoint: endpoint, operationKey: nil, sentAuthorization: "DPoP old", session: .shared) - #expect(result == HTTPChallengeResult(retry: true)) + #expect(result == .retry) #expect(tokenClient.requestCallCount == 1) #expect(tokenClient.capturedParameters?[OAuthParameterName.grantType] == OAuthGrantTypeValue.refreshToken) #expect(tokenClient.capturedParameters?[OAuthParameterName.refreshToken] == "rt-1") #expect(tokenClient.capturedDPoP?.thumbprint == dpop.keyThumbprint) - let token = try #require(storage.load()) + let token = try #require(storage.load(for: endpoint)) #expect(token.value == "refreshed") #expect(token.isDPoPBound) #expect(token.keyThumbprint == dpop.keyThumbprint) #expect(token.refreshToken == "rt-1") - let headers = try authorizer.authorizationHeaders(for: endpoint, method: "POST") + let headers = try await authorizer.authorizationHeaders(for: endpoint, method: "POST") #expect(headers[HTTPHeaderName.authorization] == "DPoP refreshed") let proof = try DecodedProof(try #require(headers[HTTPHeaderName.dpop])) #expect(proof.claims["ath"] as? String == accessTokenHash("refreshed")) @@ -495,19 +637,19 @@ struct DPoPAuthorizerTests { @Test("use_dpop_nonce for a token bound to another key is not a nonce retry") func resourceNonceForOtherKey() async throws { - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() storage.save(OAuthAccessToken( value: "old", tokenType: "DPoP", expiresAt: nil, scopes: [], authorizationServer: nil, - refreshToken: nil, keyThumbprint: "another-key")) + refreshToken: nil, keyThumbprint: "another-key"), for: endpoint) let tokenClient = dpopTokenClient() let authorizer = dpopAuthorizer(tokenStorage: storage, tokenClient: tokenClient) let result = try await authorizer.handleChallenge( statusCode: 401, headers: ["WWW-Authenticate": #"DPoP error="use_dpop_nonce""#, "DPoP-Nonce": "rs-nonce-1"], endpoint: endpoint, operationKey: nil, sentAuthorization: "DPoP old", session: .shared) - #expect(result == HTTPChallengeResult(retry: true, isDPoPNonceRetry: false)) + #expect(result == .retry) #expect(tokenClient.requestCallCount == 1) - #expect(storage.load()?.value == "dpop-token") + #expect(storage.load(for: endpoint)?.value == "dpop-token") } @Test("Of a Bearer and a DPoP challenge, the one for the scheme the request used is answered") @@ -515,17 +657,17 @@ struct DPoPAuthorizerTests { // RFC 9449 §7.2: the error is in the challenge of the scheme used. func stepUp(sent scheme: String, tokenType: String, challenge: String) async throws -> Set? { let dpop = OAuthConfiguration.DPoP() - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() storage.save(OAuthAccessToken( value: "old", tokenType: tokenType, expiresAt: nil, scopes: ["read"], authorizationServer: nil, refreshToken: nil, - keyThumbprint: tokenType == "DPoP" ? dpop.keyThumbprint : nil)) + keyThumbprint: tokenType == "DPoP" ? dpop.keyThumbprint : nil), for: endpoint) let tokenClient = dpopTokenClient() let authorizer = dpopAuthorizer(dpop: dpop, tokenStorage: storage, tokenClient: tokenClient) let result = try await authorizer.handleChallenge( statusCode: 403, headers: ["WWW-Authenticate": challenge], endpoint: endpoint, operationKey: nil, sentAuthorization: "\(scheme) old", session: .shared) - guard result.retry else { return nil } + guard result.shouldRetry else { return nil } return tokenClient.capturedParameters?[OAuthParameterName.scope].map { Set($0.split(separator: " ").map(String.init)) } @@ -580,7 +722,7 @@ struct DPoPAuthorizerTests { statusCode: 401, headers: challenge, endpoint: endpoint, session: .shared)) #expect(tokenClient.requestCallCount == 1) - let headers = try authorizer.authorizationHeaders(for: endpoint, method: "POST") + let headers = try await authorizer.authorizationHeaders(for: endpoint, method: "POST") #expect(headers[HTTPHeaderName.authorization] == "DPoP dpop-token") let proof = try DecodedProof(try #require(headers[HTTPHeaderName.dpop])) #expect(proof.claims["nonce"] as? String == "rs-nonce-1") @@ -592,14 +734,23 @@ struct DPoPAuthorizerTests { _ = try await authorizer.handleChallenge( statusCode: 401, headers: headers401, endpoint: endpoint, session: .shared) let other = URL(string: "https://edge.example.com/mcp")! - authorizer.didReceiveResponse(headers: ["dpop-nonce": "edge-nonce"], for: other) + await authorizer.didReceiveResponse(headers: ["dpop-nonce": "edge-nonce"], for: other) - func nonce(_ url: URL) throws -> String? { - let headers = try authorizer.authorizationHeaders(for: url, method: "POST") + func nonce(_ url: URL) async throws -> String? { + let headers = try await authorizer.authorizationHeaders(for: url, method: "POST") return try DecodedProof(try #require(headers[HTTPHeaderName.dpop])).claims["nonce"] as? String } - #expect(try nonce(other) == "edge-nonce") - #expect(try nonce(endpoint) == nil) + // The other origin's nonce is not used for the endpoint's origin. + #expect(try await nonce(endpoint) == nil) + await authorizer.didReceiveResponse( + headers: ["dpop-nonce": "mcp-nonce"], for: URL(string: "https://mcp.example.com/other")!) + #expect(try await nonce(endpoint) == "mcp-nonce") + // The token belongs to the endpoint's resource: no token, and no + // proof, for a request to another origin, which the metadata (naming + // no resource) leaves to the endpoint's server alone. + await #expect { + try await authorizer.authorizationHeaders(for: other, method: "POST") + } throws: { ($0 as? OAuthAuthorizationError)?.code == .protectedResourceMismatch } } @Test("token_type is trimmed once: a padded DPoP answer is stored as DPoP-bound") @@ -612,11 +763,11 @@ struct DPoPAuthorizerTests { let tokenClient = MockTokenClient() tokenClient.tokenResponse = decoded let dpop = OAuthConfiguration.DPoP() - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let authorizer = dpopAuthorizer(dpop: dpop, tokenStorage: storage, tokenClient: tokenClient) _ = try await authorizer.handleChallenge( statusCode: 401, headers: headers401, endpoint: endpoint, session: .shared) - let token = try #require(storage.load()) + let token = try #require(storage.load(for: endpoint)) #expect(token.isDPoPBound) #expect(token.keyThumbprint == dpop.keyThumbprint) } @@ -632,7 +783,7 @@ struct DPoPAuthorizerTests { statusCode: 401, headers: challenge, endpoint: endpoint, session: .shared)) #expect(tokenClient.requestCallCount == 1) let proof = try DecodedProof( - try #require(try authorizer.authorizationHeaders(for: endpoint, method: "POST")[HTTPHeaderName.dpop])) + try #require(try await authorizer.authorizationHeaders(for: endpoint, method: "POST")[HTTPHeaderName.dpop])) #expect(proof.claims["nonce"] as? String == "rs-nonce-1") } @@ -650,10 +801,10 @@ struct DPoPAuthorizerTests { headers: ["WWW-Authenticate": "DPoP error=\"\(error)\"", "DPoP-Nonce": "rs-nonce-1"], endpoint: endpoint, operationKey: nil, sentAuthorization: "DPoP dpop-token", session: .shared) } - #expect(try await challenge("vendor_nonce") == HTTPChallengeResult(retry: true, isDPoPNonceRetry: true)) + #expect(try await challenge("vendor_nonce") == .retryWithDPoPNonce) #expect(tokenClient.requestCallCount == 1) // The parser reads it as invalid_token: the token is replaced. - #expect(try await challenge("use_dpop_nonce") == HTTPChallengeResult(retry: true, isDPoPNonceRetry: false)) + #expect(try await challenge("use_dpop_nonce") == .retry) #expect(tokenClient.requestCallCount == 2) } @@ -665,7 +816,7 @@ struct DPoPAuthorizerTests { statusCode: 401, headers: ["WWW-Authenticate": #"DPoP error="use_dpop_nonce""#, "DPoP-Nonce": "rs-nonce-1"], endpoint: endpoint, operationKey: nil, sentAuthorization: nil, session: .shared) - #expect(result == HTTPChallengeResult(retry: true, isDPoPNonceRetry: false)) + #expect(result == .retry) #expect(tokenClient.requestCallCount == 1) } @@ -801,54 +952,53 @@ struct DPoPAuthorizerTests { } /// Returns fixed headers and records the requests they were made for. - private final class RecordingAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { - private let lock = NSLock() - private var _requests: [(url: URL, method: String)] = [] - var requests: [(url: URL, method: String)] { - lock.lock() - defer { lock.unlock() } - return _requests - } + private final class RecordingAuthorizer: HTTPClientAuthorizer, Sendable { + private let recorded = Mutex<[(url: URL, method: String)]>([]) + var requests: [(url: URL, method: String)] { recorded.withLock { $0 } } let maxAuthorizationAttempts = 1 - func validateEndpointSecurity(for endpoint: URL) throws {} + func prepare(for endpoint: URL, session: URLSession) async throws {} func authorizationHeaders(for url: URL, method: String) throws -> [String: String] { - lock.lock() - _requests.append((url, method)) - lock.unlock() + recorded.withLock { $0.append((url, method)) } return ["Authorization": "DPoP t", "DPoP": "proof-for-\(method)"] } - func handleChallenge( - statusCode: Int, headers: [String: String], endpoint: URL, operationKey: String?, - session: URLSession - ) async throws -> Bool { false } + func handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) async throws + -> HTTPChallengeResult + { .unhandled } } - /// Accepts every challenge, as an authorizer that has a token and a nonce does. - private final class NonceAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { + /// Accepts every challenge, as an authorizer that has a token and a nonce + /// does. A `401` `use_dpop_nonce` with a `DPoP-Nonce` header is a nonce + /// retry (RFC 9449 §9). + private final class NonceAuthorizer: HTTPClientAuthorizer, Sendable { + private struct State { + var challenges = 0 + var responses: [URL] = [] + } let maxAuthorizationAttempts: Int - private let lock = NSLock() - private var challengeCount = 0 - private var responseURLs: [URL] = [] - var challenges: Int { lock.withLock { challengeCount } } - var responses: [URL] { lock.withLock { responseURLs } } + private let state = Mutex(State()) + var challenges: Int { state.withLock { $0.challenges } } + var responses: [URL] { state.withLock { $0.responses } } init(maxAuthorizationAttempts: Int = 5) { self.maxAuthorizationAttempts = maxAuthorizationAttempts } - func validateEndpointSecurity(for endpoint: URL) throws {} + func prepare(for endpoint: URL, session: URLSession) async throws {} func authorizationHeaders(for url: URL, method: String) throws -> [String: String] { ["Authorization": "DPoP t", "DPoP": "proof"] } - func handleChallenge( - statusCode: Int, headers: [String: String], endpoint: URL, operationKey: String?, - session: URLSession - ) async throws -> Bool { - lock.withLock { challengeCount += 1 } - return true + func handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) async throws + -> HTTPChallengeResult + { + state.withLock { $0.challenges += 1 } + let error = DefaultOAuthWWWAuthenticateParser() + .parseChallenge(scheme: "DPoP", from: challenge.headers)?.error + let hasNonce = !(challenge.value(forHeader: "DPoP-Nonce") ?? "").isEmpty + return challenge.statusCode == 401 && error == "use_dpop_nonce" && hasNonce + ? .retryWithDPoPNonce : .retry } - func didReceiveResponse(headers: [String: String], for url: URL) { - lock.withLock { responseURLs.append(url) } + func didReceiveResponse(headers: [String: String], for url: URL) async { + state.withLock { $0.responses.append(url) } } } @@ -862,19 +1012,14 @@ struct DPoPAuthorizerTests { self.nonceRetry = nonceRetry } - func validateEndpointSecurity(for endpoint: URL) throws {} + func prepare(for endpoint: URL, session: URLSession) async throws {} func authorizationHeaders(for url: URL, method: String) throws -> [String: String] { ["Authorization": "DPoP t", "DPoP": "proof"] } - func handleChallenge( - statusCode: Int, headers: [String: String], endpoint: URL, operationKey: String?, - session: URLSession - ) async throws -> Bool { true } - func handleChallenge( - statusCode: Int, headers: [String: String], endpoint: URL, operationKey: String?, - sentAuthorization: String?, session: URLSession - ) async throws -> HTTPChallengeResult { - HTTPChallengeResult(retry: true, isDPoPNonceRetry: nonceRetry) + func handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) async throws + -> HTTPChallengeResult + { + HTTPChallengeResult(shouldRetry: true, isDPoPNonceRetry: nonceRetry) } } @@ -950,26 +1095,6 @@ struct DPoPAuthorizerTests { await transport.disconnect() } - @Test("By default, a retried use_dpop_nonce with a DPoP-Nonce header is a nonce retry") - func defaultNonceClassification() async throws { - let authorizer = NonceAuthorizer() - func result(_ status: Int, _ headers: [String: String]) async throws -> HTTPChallengeResult { - try await authorizer.handleChallenge( - statusCode: status, headers: headers, endpoint: endpoint, operationKey: nil, - sentAuthorization: "DPoP t", session: .shared) - } - let nonce = #"DPoP error="use_dpop_nonce""# - #expect( - try await result(401, ["WWW-Authenticate": nonce, "DPoP-Nonce": "n"]) - == HTTPChallengeResult(retry: true, isDPoPNonceRetry: true)) - #expect( - try await result(401, ["WWW-Authenticate": nonce]) - == HTTPChallengeResult(retry: true, isDPoPNonceRetry: false)) - #expect( - try await result(403, ["WWW-Authenticate": nonce, "DPoP-Nonce": "n"]) - == HTTPChallengeResult(retry: true, isDPoPNonceRetry: false)) - } - @Test("A retry the authorizer reports as a nonce retry does not use up an authorization attempt") func authorizerReportsNonceRetry() async throws { let (configuration, sent) = await mockSession { request, count in @@ -1143,10 +1268,8 @@ struct DPoPAuthorizerTests { endpoint: endpoint, configuration: configuration, streaming: false, authorizer: authorizer, requestModifier: { request in - var request = request request.url = URL(string: "https://mcp.example.com/mcp?tenant=a")! request.setValue("Bearer from-modifier", forHTTPHeaderField: "Authorization") - return request }) try await transport.connect() try await transport.send(Data(#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#.utf8)) diff --git a/Tests/MCPTests/OAuthDiscoveryClientTests.swift b/Tests/MCPTests/OAuthDiscoveryClientTests.swift index a5ef79e7..014b8c90 100644 --- a/Tests/MCPTests/OAuthDiscoveryClientTests.swift +++ b/Tests/MCPTests/OAuthDiscoveryClientTests.swift @@ -318,7 +318,7 @@ import Testing } return (HTTPURLResponse(url: request.url!, statusCode: 404, httpVersion: nil, headerFields: nil)!, Data()) } - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let authorizer = OAuthAuthorizer( configuration: OAuthConfiguration( grantType: .clientCredentials, @@ -331,7 +331,7 @@ import Testing let retried = try await authorizer.handleChallenge( statusCode: 401, headers: ["WWW-Authenticate": "Bearer"], endpoint: mcpEndpoint, session: session) #expect(retried) - #expect(storage.load()?.value == "override-token") + #expect(storage.load(for: mcpEndpoint)?.value == "override-token") } @Test("A loopback candidate is refused without a request unless loopback is allowed") diff --git a/Tests/MCPTests/OAuthIssuerTests.swift b/Tests/MCPTests/OAuthIssuerTests.swift index bd33ca18..49fdaab5 100644 --- a/Tests/MCPTests/OAuthIssuerTests.swift +++ b/Tests/MCPTests/OAuthIssuerTests.swift @@ -157,7 +157,7 @@ struct OAuthIssuerTests { _ = try await authorizer.handleChallenge( statusCode: 401, headers: headers401, endpoint: endpoint, session: .shared) #expect(registrar.registerCallCount == 1) - #expect((try authorizer.authorizationHeaders(for: endpoint, method: "POST"))[HTTPHeaderName.authorization] != nil) + #expect((try await authorizer.authorizationHeaders(for: endpoint, method: "POST"))[HTTPHeaderName.authorization] != nil) // The same 401 again, but the metadata now names another server. let second = URL(string: "https://auth2.example.com")! diff --git a/Tests/MCPTests/OAuthJWTBearerTests.swift b/Tests/MCPTests/OAuthJWTBearerTests.swift index f535876a..d6343492 100644 --- a/Tests/MCPTests/OAuthJWTBearerTests.swift +++ b/Tests/MCPTests/OAuthJWTBearerTests.swift @@ -57,7 +57,7 @@ private func jwtBearerAuthorizer( discovery: MockDiscoveryClient = MockDiscoveryClient(), tokenClient: any OAuthTokenRequesting = MockTokenClient(), registrar: MockClientRegistrar = MockClientRegistrar(), - storage: TokenStorage = InMemoryTokenStorage() + storage: any OAuthTokenStorage = InMemoryOAuthTokenStorage() ) -> OAuthAuthorizer { OAuthAuthorizer( configuration: configuration, tokenStorage: storage, urlValidator: MockURLValidator(), @@ -109,7 +109,7 @@ struct OAuthJWTBearerGrantTests { #expect(context.resource == endpoint) #expect(context.tokenEndpoint == URL(string: "https://auth.example.com/token")!) #expect(context.requestedScopes == ["read", "write"]) - #expect((try authorizer.authorizationHeaders(for: endpoint, method: "POST"))[HTTPHeaderName.authorization] == "Bearer mock-access-token") + #expect((try await authorizer.authorizationHeaders(for: endpoint, method: "POST"))[HTTPHeaderName.authorization] == "Bearer mock-access-token") } @Test("Every token request gets a new assertion") @@ -327,6 +327,17 @@ struct OAuthJWTBearerGrantTests { } } + @Test("A response that is not HTTP fails without a status") + func nonHTTPResponse() async throws { + let error = await #expect(throws: OAuthAuthorizationError.self) { + _ = try await OAuthTokenExchange.exchange( + request, tokenEndpoint: idpToken, authentication: .none(clientID: "c"), + session: NonHTTPResponseURLProtocol.makeSession()) + } + // Every property is compared: statusCode is nil, not -1. + #expect(error == .tokenRequestFailed) + } + @Test("Insecure and private endpoints are refused before any request") func endpointChecks() async throws { let (session, key) = makeIsolatedSession() @@ -447,7 +458,7 @@ struct OAuthJWTBearerGrantTests { ), ( "https://idp.example.com", "https://idp.example.com/token#top", false, - .invalidResourceURI("Invalid Token exchange endpoint: https://idp.example.com/token#top") + .invalidResourceURI("Invalid Token exchange endpoint: https://idp.example.com/token") ), ( "https://idp.example.com", "http://10.0.0.1/token", false, @@ -491,7 +502,7 @@ struct OAuthJWTBearerGrantTests { ( "https://idp.example.com/#top", OAuthAuthorizationError.invalidResourceURI( - "Invalid Authorization server issuer: https://idp.example.com/#top") + "Invalid Authorization server issuer: https://idp.example.com/") ), ( "http://idp.example.com", @@ -578,7 +589,7 @@ struct OAuthJWTBearerGrantTests { configuration: configuration(pinned: URL(string: "https://auth.example.com")!)) #expect(try await authorizer.handleChallenge( statusCode: 401, headers: headers401, endpoint: endpoint, session: session)) - #expect((try authorizer.authorizationHeaders(for: endpoint, method: "POST"))[HTTPHeaderName.authorization] == "Bearer mcp-token") + #expect((try await authorizer.authorizationHeaders(for: endpoint, method: "POST"))[HTTPHeaderName.authorization] == "Bearer mcp-token") let sent = await requests.values let paths = sent.map(\.0) @@ -786,7 +797,7 @@ struct OAuthJWTBearerDestinationTests { func proactiveReacquisition() async throws { let calls = Recorder() let tokenClient = MockTokenClient() - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let authorizer = jwtBearerAuthorizer( .init( grantType: .jwtBearer, authentication: .none(clientID: ""), @@ -797,8 +808,8 @@ struct OAuthJWTBearerDestinationTests { }), tokenClient: tokenClient, storage: storage) #expect(try await authorizer.handleChallenge(statusCode: 401, headers: headers401, endpoint: endpoint, session: .shared)) - storage.save(aged(try #require(storage.load()), expiringIn: 40)) - try await authorizer.prepareAuthorization(for: endpoint, session: .shared) + storage.save(aged(try #require(storage.load(for: endpoint)), expiringIn: 40), for: endpoint) + try await authorizer.prepare(for: endpoint, session: .shared) #expect(await calls.values.count == 2) #expect(tokenClient.requestCallCount == 2) } @@ -807,7 +818,7 @@ struct OAuthJWTBearerDestinationTests { func reissuedTokenRenewedAgain() async throws { // MockTokenClient issues `mock-access-token` every time. let tokenClient = MockTokenClient() - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let authorizer = jwtBearerAuthorizer( .init( grantType: .jwtBearer, authentication: .none(clientID: ""), @@ -816,11 +827,11 @@ struct OAuthJWTBearerDestinationTests { tokenClient: tokenClient, storage: storage) #expect(try await authorizer.handleChallenge(statusCode: 401, headers: headers401, endpoint: endpoint, session: .shared)) for renewals in 1...2 { - storage.save(aged(try #require(storage.load()), expiringIn: 40)) - try await authorizer.prepareAuthorization(for: endpoint, session: .shared) + storage.save(aged(try #require(storage.load(for: endpoint)), expiringIn: 40), for: endpoint) + try await authorizer.prepare(for: endpoint, session: .shared) #expect(tokenClient.requestCallCount == 1 + renewals) } - #expect(storage.load()?.value == "mock-access-token") + #expect(storage.load(for: endpoint)?.value == "mock-access-token") } @Test("A configured token endpoint renews a token whose server metadata has none") @@ -835,7 +846,7 @@ struct OAuthJWTBearerDestinationTests { clientIDMetadataDocumentSupported: nil) ) let tokenClient = MockTokenClient() - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let authorizer = jwtBearerAuthorizer( .init( grantType: .jwtBearer, authentication: .none(clientID: ""), @@ -843,8 +854,8 @@ struct OAuthJWTBearerDestinationTests { assertionProvider: { _, _ in "jwt" }), discovery: discovery, tokenClient: tokenClient, storage: storage) #expect(try await authorizer.handleChallenge(statusCode: 401, headers: headers401, endpoint: endpoint, session: .shared)) - storage.save(aged(try #require(storage.load()), expiringIn: 40)) - try await authorizer.prepareAuthorization(for: endpoint, session: .shared) + storage.save(aged(try #require(storage.load(for: endpoint)), expiringIn: 40), for: endpoint) + try await authorizer.prepare(for: endpoint, session: .shared) #expect(tokenClient.requestCallCount == 2) } @@ -852,7 +863,7 @@ struct OAuthJWTBearerDestinationTests { func cancelledRenewalTriedAgain() async throws { let calls = Recorder() let tokenClient = MockTokenClient() - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let authorizer = jwtBearerAuthorizer( .init( grantType: .jwtBearer, authentication: .none(clientID: ""), @@ -868,11 +879,11 @@ struct OAuthJWTBearerDestinationTests { }), tokenClient: tokenClient, storage: storage) #expect(try await authorizer.handleChallenge(statusCode: 401, headers: headers401, endpoint: endpoint, session: .shared)) - storage.save(aged(try #require(storage.load()), expiringIn: 40)) - let cancelled = Task { try await authorizer.prepareAuthorization(for: endpoint, session: .shared) } + storage.save(aged(try #require(storage.load(for: endpoint)), expiringIn: 40), for: endpoint) + let cancelled = Task { try await authorizer.prepare(for: endpoint, session: .shared) } _ = await cancelled.result #expect(tokenClient.requestCallCount == 1) - try await authorizer.prepareAuthorization(for: endpoint, session: .shared) + try await authorizer.prepare(for: endpoint, session: .shared) #expect(await calls.values.count == 3) #expect(tokenClient.requestCallCount == 2) } @@ -894,7 +905,7 @@ struct OAuthJWTBearerDestinationTests { tokenClient: tokenClient) #expect(try await authorizer.handleChallenge(statusCode: 401, headers: headers401, endpoint: endpoint, session: .shared)) for _ in 0..<5 { - try await authorizer.prepareAuthorization(for: endpoint, session: .shared) + try await authorizer.prepare(for: endpoint, session: .shared) } #expect(await calls.values.count == 1) #expect(tokenClient.requestCallCount == 1) @@ -904,7 +915,7 @@ struct OAuthJWTBearerDestinationTests { func failedReacquisitionTriedOnce() async throws { let grant = "urn:ietf:params:oauth:grant-type:jwt-bearer" let tokens = RecordingTokenClient() - let storage = InMemoryTokenStorage() + let storage = InMemoryOAuthTokenStorage() let authorizer = jwtBearerAuthorizer( .init( grantType: .jwtBearer, authentication: .none(clientID: ""), @@ -912,17 +923,17 @@ struct OAuthJWTBearerDestinationTests { assertionProvider: { _, _ in "jwt" }), tokenClient: tokens, storage: storage) #expect(try await authorizer.handleChallenge(statusCode: 401, headers: headers401, endpoint: endpoint, session: .shared)) - let token = try #require(storage.load()) + let token = try #require(storage.load(for: endpoint)) storage.save( OAuthAccessToken( value: token.value, tokenType: token.tokenType, expiresAt: Date().addingTimeInterval(40), - scopes: token.scopes, authorizationServer: token.authorizationServer, refreshToken: nil)) + scopes: token.scopes, authorizationServer: token.authorizationServer, refreshToken: nil), for: endpoint) tokens.refusedGrants = [grant] for _ in 0..<5 { - try await authorizer.prepareAuthorization(for: endpoint, session: .shared) + try await authorizer.prepare(for: endpoint, session: .shared) } #expect(tokens.calls.map(\.grantType) == [grant, grant]) - #expect(storage.load()?.value == token.value) + #expect(storage.load(for: endpoint)?.value == token.value) } @Test("The identity provider's token endpoint is discovered once") diff --git a/Tests/MCPTests/OAuthTokenEndpointClientTests.swift b/Tests/MCPTests/OAuthTokenEndpointClientTests.swift index 43d0944a..2e7053ca 100644 --- a/Tests/MCPTests/OAuthTokenEndpointClientTests.swift +++ b/Tests/MCPTests/OAuthTokenEndpointClientTests.swift @@ -149,6 +149,46 @@ import Testing } } + @Test( + "An unreadable token response throws tokenResponseInvalid", + arguments: ["not json", #"{"token_type":"Bearer","refresh_token":"refresh-secret"}"#]) + func testRequestThrowsForUnreadableResponse(body: String) async throws { + let (session, key) = makeIsolatedSession() + await IsolatedMockURLProtocol.setHandler(key: key) { _ in + let response = HTTPURLResponse( + url: self.tokenEndpoint, statusCode: 200, + httpVersion: nil, headerFields: nil)! + return (response, Data(body.utf8)) + } + + var params = ["grant_type": "client_credentials"] + let error = await #expect(throws: OAuthAuthorizationError.self) { + try await client.request( + parameters: ¶ms, + endpoint: tokenEndpoint, + authentication: .none(clientID: "client-id"), + session: session + ) + } + #expect(error == .tokenResponseInvalid) + #expect(error?.localizedDescription.contains("refresh-secret") == false) + } + + @Test("A token response that is not HTTP throws tokenRequestFailed without a status") + func testRequestThrowsForNonHTTPResponse() async throws { + var params = ["grant_type": "client_credentials"] + let error = await #expect(throws: OAuthAuthorizationError.self) { + try await client.request( + parameters: ¶ms, + endpoint: tokenEndpoint, + authentication: .none(clientID: "client-id"), + session: NonHTTPResponseURLProtocol.makeSession() + ) + } + // Every property is compared: statusCode is nil, not -1. + #expect(error == .tokenRequestFailed) + } + // MARK: - Form Encoding @Test("Sends parameters as form-encoded POST body") diff --git a/Tests/MCPTests/OAuthURLValidatorTests.swift b/Tests/MCPTests/OAuthURLValidatorTests.swift index 41c05fbf..d944d16b 100644 --- a/Tests/MCPTests/OAuthURLValidatorTests.swift +++ b/Tests/MCPTests/OAuthURLValidatorTests.swift @@ -1,4 +1,6 @@ import Foundation +import Logging +import Synchronization import Testing @testable import MCP @@ -418,6 +420,472 @@ struct OAuthURLValidatorTests { #expect(!guardDelegate.allows(from: https, to: URL(string: "http://127.0.0.1:3000/metadata")!)) } + // MARK: - Credentials across redirects + + /// A POST to `url` with credentials in any case of their names, and + /// other headers. + private static func credentialedRequest(_ url: String) -> URLRequest { + var request = URLRequest(url: URL(string: url)!) + request.httpMethod = "POST" + request.httpBody = Data("{}".utf8) + request.setValue("Bearer t", forHTTPHeaderField: "authorization") + request.setValue("Basic cHJveHk6cHc=", forHTTPHeaderField: "PROXY-AUTHORIZATION") + request.setValue("proof", forHTTPHeaderField: "dpop") + request.setValue("sid=1", forHTTPHeaderField: "cookie") + request.setValue("s1", forHTTPHeaderField: "mcp-session-id") + for (name, value) in otherHeaders { request.setValue(value, forHTTPHeaderField: name) } + return request + } + + private static let otherHeaders = [ + "Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "MCP-Protocol-Version": "2025-11-25", "X-Custom": "kept", + ] + + /// `headers` with lowercased names: swift-corelibs-foundation rewrites them. + private static func lowercased(_ headers: [String: String]?) -> [String: String] { + Dictionary(uniqueKeysWithValues: (headers ?? [:]).map { ($0.key.lowercased(), $0.value) }) + } + + // The Fetch standard, curl, Go and Python requests: credentials follow a + // redirect to the same scheme, host and port only. + @Test( + "A redirect keeps Authorization, Proxy-Authorization, Cookie and Mcp-Session-Id on the same origin only, and never DPoP", + arguments: [ + ("https://mcp.example.com/mcp", "https://mcp.example.com/mcp/", true), + ("https://mcp.example.com/mcp", "https://MCP.example.com:443/v2/mcp", true), + ("http://127.0.0.1:3000/mcp", "http://127.0.0.1:3000/other", true), + ("https://mcp.example.com/mcp", "https://other.example.com/mcp", false), + ("https://mcp.example.com/mcp", "https://mcp.example.com:8443/mcp", false), + ("https://mcp.example.com/mcp", "http://mcp.example.com/mcp", false), + ("http://127.0.0.1:3000/mcp", "https://127.0.0.1:3000/mcp", false), + ("http://mcp.example.com/mcp", "https://mcp.example.com/mcp", false), + ]) + func testRedirectCredentials(from first: String, to target: String, sameOrigin: Bool) { + let original = Self.credentialedRequest(first) + // URLSession on Apple platforms proposes the redirect without + // Authorization and Proxy-Authorization; they are put back. + for proposesCredentials in [true, false] { + var proposed = original + proposed.url = URL(string: target)! + if !proposesCredentials { + proposed.setValue(nil, forHTTPHeaderField: "Authorization") + proposed.setValue(nil, forHTTPHeaderField: "Proxy-Authorization") + } + var chain = HTTPRedirectChain() + let (followed, isSameOrigin) = HTTPRedirect.request( + redirectedTo: proposed, original: original, from: original.url, chain: &chain) + #expect(isSameOrigin == sameOrigin) + #expect(chain.leftOrigin == (sameOrigin ? nil : URL(string: target)!)) + #expect(followed.value(forHTTPHeaderField: "Authorization") == (sameOrigin ? "Bearer t" : nil)) + #expect( + followed.value(forHTTPHeaderField: "Proxy-Authorization") == (sameOrigin ? "Basic cHJveHk6cHc=" : nil)) + #expect(followed.value(forHTTPHeaderField: "Cookie") == (sameOrigin ? "sid=1" : nil)) + #expect(followed.value(forHTTPHeaderField: "Mcp-Session-Id") == (sameOrigin ? "s1" : nil)) + #expect(followed.value(forHTTPHeaderField: "DPoP") == nil) + var expected = Self.lowercased(Self.otherHeaders) + if sameOrigin { + expected["authorization"] = "Bearer t" + expected["proxy-authorization"] = "Basic cHJveHk6cHc=" + expected["cookie"] = "sid=1" + expected["mcp-session-id"] = "s1" + } + #expect(Self.lowercased(followed.allHTTPHeaderFields) == expected) + #expect(followed.url == URL(string: target)!) + #expect(followed.httpMethod == "POST") + #expect(followed.httpBody == original.httpBody) + } + } + + @Test("The credentials of a configuration's additional headers are taken out of a copy") + func testSeparatingConfigurationCredentials() throws { + let configuration = URLSessionConfiguration.ephemeral + configuration.httpAdditionalHeaders = [ + "authorization": "Bearer t", "Proxy-Authorization": "Basic cHJveHk6cHc=", "DPOP": "proof", + "COOKIE": "sid=1", "Mcp-Session-Id": "s1", "X-Custom": "kept", + ] + let (separated, credentials) = HTTPRedirect.separatingCredentials(of: configuration) + #expect(separated !== configuration) + #expect(Self.lowercased(credentials) == [ + "authorization": "Bearer t", "proxy-authorization": "Basic cHJveHk6cHc=", "dpop": "proof", + "cookie": "sid=1", "mcp-session-id": "s1", + ]) + #expect(separated.httpAdditionalHeaders?.count == 1) + #expect(separated.httpAdditionalHeaders?["X-Custom"] as? String == "kept") + #expect(configuration.httpAdditionalHeaders?.count == 6) + + // A request's own header wins. + var request = URLRequest(url: URL(string: "https://mcp.example.com/mcp")!) + request.setValue("Bearer request", forHTTPHeaderField: "Authorization") + HTTPRedirect.addingCredentials(credentials, to: &request) + #expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer request") + #expect(request.value(forHTTPHeaderField: "Proxy-Authorization") == "Basic cHJveHk6cHc=") + #expect(request.value(forHTTPHeaderField: "DPoP") == "proof") + #expect(request.value(forHTTPHeaderField: "Cookie") == "sid=1") + #expect(request.value(forHTTPHeaderField: "Mcp-Session-Id") == "s1") + + let plain = URLSessionConfiguration.ephemeral + plain.httpAdditionalHeaders = ["X-Custom": "kept"] + let unchanged = HTTPRedirect.separatingCredentials(of: plain) + #expect(unchanged.configuration === plain) + #expect(unchanged.credentials.isEmpty) + } + + @Test("A chain that left the origin doesn't get the credentials back when it returns") + func testRedirectBackToOriginHasNoCredentials() { + let original = Self.credentialedRequest("https://mcp.example.com/mcp") + var chain = HTTPRedirectChain() + var proposed = original + proposed.url = URL(string: "https://other.example.com/hop")! + let (away, awaySameOrigin) = HTTPRedirect.request( + redirectedTo: proposed, original: original, from: original.url, chain: &chain) + #expect(!awaySameOrigin) + #expect(away.value(forHTTPHeaderField: "Authorization") == nil) + #expect(away.value(forHTTPHeaderField: "Mcp-Session-Id") == nil) + #expect(chain.leftOrigin == URL(string: "https://other.example.com/hop")!) + + // Back on the origin, from a hop that is on it too: still none. + for source in ["https://other.example.com/hop", "https://mcp.example.com/back"] { + proposed = away + proposed.url = URL(string: "https://mcp.example.com/landed")! + let (back, backSameOrigin) = HTTPRedirect.request( + redirectedTo: proposed, original: original, from: URL(string: source)!, chain: &chain) + #expect(!backSameOrigin, "\(source)") + #expect(back.value(forHTTPHeaderField: "Authorization") == nil) + #expect(back.value(forHTTPHeaderField: "Proxy-Authorization") == nil) + #expect(back.value(forHTTPHeaderField: "Cookie") == nil) + #expect(back.value(forHTTPHeaderField: "Mcp-Session-Id") == nil) + #expect(chain.leftOrigin == URL(string: "https://other.example.com/hop")!) + } + + // A hop from another origin is one away from it, whatever the chain recorded. + var fresh = HTTPRedirectChain() + let (fromOther, fromOtherSameOrigin) = HTTPRedirect.request( + redirectedTo: proposed, original: original, from: URL(string: "https://other.example.com/hop")!, + chain: &fresh) + #expect(!fromOtherSameOrigin) + #expect(fromOther.value(forHTTPHeaderField: "Authorization") == nil) + #expect(fromOther.value(forHTTPHeaderField: "Mcp-Session-Id") == nil) + #expect(fresh.leftOrigin != nil) + } + + // What swift-corelibs-foundation proposes, except that 307 and 308 keep + // the body, which it drops (RFC 9110 §15.4.8, §15.4.9). + @Test( + "The proposed redirect of a POST keeps its method, body and representation headers for 307 and 308 only, and strips Host", + arguments: [ + (307, "POST", true), (308, "POST", true), (301, "GET", false), (302, "GET", false), + (303, "GET", false), + ]) + func testProposedRedirect(status: Int, method: String, keepsBody: Bool) throws { + var request = Self.credentialedRequest("https://mcp.example.com/mcp") + request.setValue("mcp.example.com", forHTTPHeaderField: "Host") + request.setValue("2", forHTTPHeaderField: "Content-Length") + request.setValue("gzip", forHTTPHeaderField: "Content-Encoding") + request.setValue("en", forHTTPHeaderField: "Content-Language") + request.setValue("/orig", forHTTPHeaderField: "Content-Location") + let response = HTTPURLResponse( + url: request.url!, statusCode: status, httpVersion: "HTTP/1.1", headerFields: ["Location": "/v2/mcp"])! + let proposed = try #require(HTTPRedirect.proposedRequest(after: request, response: response)) + #expect(proposed.url == URL(string: "https://mcp.example.com/v2/mcp")) + #expect(proposed.httpMethod == method) + #expect(proposed.httpBody == (keepsBody ? request.httpBody : nil)) + #expect(proposed.value(forHTTPHeaderField: "Host") == nil) + for header in ["Content-Type", "Content-Length", "Content-Encoding", "Content-Language", "Content-Location"] { + if keepsBody { + #expect(proposed.value(forHTTPHeaderField: header) != nil, "\(status) \(header)") + } else { + #expect(proposed.value(forHTTPHeaderField: header) == nil, "\(status) \(header)") + } + } + } + + @Test("A 303 redirect preserves HEAD instead of rewriting it to GET") + func testProposedRedirectPreservesHEADOn303() throws { + var request = URLRequest(url: URL(string: "https://mcp.example.com/mcp")!) + request.httpMethod = "HEAD" + request.setValue("mcp.example.com", forHTTPHeaderField: "Host") + let response = HTTPURLResponse( + url: request.url!, statusCode: 303, httpVersion: "HTTP/1.1", headerFields: ["Location": "/v2/mcp"])! + let proposed = try #require(HTTPRedirect.proposedRequest(after: request, response: response)) + #expect(proposed.httpMethod == "HEAD") + #expect(proposed.value(forHTTPHeaderField: "Host") == nil) + } + + @Test("A 300, 304, 305, 306 or a 3xx without Location proposes no redirect") + func testNoProposedRedirect() { + let request = Self.credentialedRequest("https://mcp.example.com/mcp") + for (status, headers) in [ + (300, ["Location": "/a"]), (304, ["Location": "/a"]), (305, ["Location": "/a"]), + (306, ["Location": "/a"]), (307, [:]), + ] { + let response = HTTPURLResponse( + url: request.url!, statusCode: status, httpVersion: "HTTP/1.1", headerFields: headers)! + #expect(HTTPRedirect.proposedRequest(after: request, response: response) == nil, "\(status)") + } + } + + // The Fetch standard's HTTP-redirect fetch, step 6; no remote-to-loopback + // hop; no https to http downgrade (even on loopback); and no hop from a + // loopback host to non-loopback http. The loopback servers of the transport + // tests have no TLS, so the https hops are tested here only. + @Test( + "A redirect to another scheme, to loopback from remote, from https to http, or from loopback to remote http is refused", + arguments: [ + ("https://mcp.example.com/mcp", "ftp://example.com/x", true), + ("https://mcp.example.com/mcp", "data:,x", true), + ("https://mcp.example.com/mcp", "file:///etc/hosts", true), + ("http://127.0.0.1:3000/mcp", "ws://127.0.0.1:3000/mcp", true), + ("https://mcp.example.com/mcp", "https:///mcp", true), + ("https://mcp.example.com/mcp", "http://mcp.example.com/mcp", true), + ("https://mcp.example.com/mcp", "HTTP://other.example.com/mcp", true), + ("https://mcp.example.com/mcp", "http://10.0.0.5/mcp", true), + ("https://mcp.example.com/mcp", "http://127.0.0.1:3000/mcp", true), + ("https://mcp.example.com/mcp", "http://localhost/mcp", true), + ("https://mcp.example.com/mcp", "http://[::1]:8080/mcp", true), + ("https://mcp.example.com/mcp", "https://127.0.0.1:3000/mcp", true), + ("https://mcp.example.com/mcp", "https://localhost/mcp", true), + ("https://mcp.example.com/mcp", "https://sub.localhost/mcp", true), + ("http://mcp.example.com/mcp", "http://127.0.0.1:3000/mcp", true), + // Non-canonical loopback and unspecified spellings are refused from remote hosts. + ("https://mcp.example.com/mcp", "https://127.1:8443/mcp", true), + ("https://mcp.example.com/mcp", "https://2130706433:8443/mcp", true), + ("https://mcp.example.com/mcp", "https://0177.0.0.1:8443/mcp", true), + ("https://mcp.example.com/mcp", "https://0x7f000001:8443/mcp", true), + ("https://mcp.example.com/mcp", "https://127.0.0.1.:8443/mcp", true), + ("https://mcp.example.com/mcp", "https://0.0.0.0:8443/mcp", true), + ("https://mcp.example.com/mcp", "https://[::]:8443/mcp", true), + ("http://mcp.example.com/mcp", "http://127.1:3000/mcp", true), + ("http://mcp.example.com/mcp", "http://2130706433:3000/mcp", true), + ("http://mcp.example.com/mcp", "http://0177.0.0.1:3000/mcp", true), + ("http://mcp.example.com/mcp", "http://0x7f000001:3000/mcp", true), + ("http://mcp.example.com/mcp", "http://127.0.0.1.:3000/mcp", true), + ("http://mcp.example.com/mcp", "http://0.0.0.0:3000/mcp", true), + ("http://mcp.example.com/mcp", "http://[::]:3000/mcp", true), + // Non-canonical loopback sources cannot redirect to remote cleartext http. + ("http://127.1:3000/mcp", "http://other.example.com/mcp", true), + ("http://2130706433:3000/mcp", "http://other.example.com/mcp", true), + ("http://0177.0.0.1:3000/mcp", "http://other.example.com/mcp", true), + ("http://0x7f000001:3000/mcp", "http://other.example.com/mcp", true), + ("http://127.0.0.1.:3000/mcp", "http://other.example.com/mcp", true), + ("http://0.0.0.0:3000/mcp", "http://other.example.com/mcp", true), + ("http://[::]:3000/mcp", "http://other.example.com/mcp", true), + // RFC 1918 private-network targets remain allowed for MCP requests. + ("https://mcp.example.com/mcp", "https://10.0.0.5/mcp", false), + ("http://mcp.example.com/mcp", "http://10.0.0.5/mcp", false), + ("https://localhost:8443/mcp", "http://localhost:3000/mcp", true), + ("https://127.0.0.1:8443/mcp", "http://127.0.0.1:3000/mcp", true), + ("https://localhost:8443/mcp", "https://127.0.0.1:8443/mcp", false), + ("https://mcp.example.com/mcp", "https://other.example.com/mcp", false), + ("https://mcp.example.com/mcp", "HTTPS://other.example.com/mcp", false), + ("http://127.0.0.1:3000/mcp", "http://other.example.com/mcp", true), + ("http://localhost:3000/mcp", "http://10.0.0.5/mcp", true), + ("http://[::1]:3000/mcp", "http://other.example.com/mcp", true), + ("http://127.0.0.2:3000/mcp", "http://other.example.com/mcp", true), + ("http://mcp.localhost:3000/mcp", "http://other.example.com/mcp", true), + ("http://127.0.0.1:3000/mcp", "http://127.0.0.1:4000/mcp", false), + ("http://127.0.0.1:3000/mcp", "http://localhost:4000/mcp", false), + ("http://127.0.0.1:3000/mcp", "https://127.0.0.1:4000/mcp", false), + ("http://127.0.0.1:3000/mcp", "https://other.example.com/mcp", false), + ("http://mcp.example.com/mcp", "http://other.example.com/mcp", false), + ]) + func testRedirectRefusal(from source: String, to target: String, refused: Bool) { + #expect((HTTPRedirect.refusal(of: URL(string: target)!, from: URL(string: source)!) != nil) == refused) + } + + @Test( + "Non-canonical IPv4 and embedded IPv6 loopback and unspecified literals are classified as local hosts", + arguments: [ + "127.1", "2130706433", "0177.0.0.1", "0x7f000001", "127.0.0.1.", "0.0.0.0", "0", "::", "[::]", + "[::ffff:0177.0.0.1]", "[::ffff:127.1]", "[::ffff:127.0.0.1.]", "[::ffff:0.0.0.0]", + "[::ffff:2130706433]", "[::ffff:0x7f000001]", "[64:ff9b::127.1]", + ]) + func testNonCanonicalLoopbackAndUnspecifiedHosts(host: String) { + #expect(OAuthURLValidator.isLoopbackOrUnspecifiedHost(host)) + // Non-loopback private and public hosts are not misclassified. + #expect(!OAuthURLValidator.isLoopbackOrUnspecifiedHost("10.0.0.5")) + #expect(!OAuthURLValidator.isLoopbackOrUnspecifiedHost("192.168.1.1")) + #expect(!OAuthURLValidator.isLoopbackOrUnspecifiedHost("[::ffff:10.0.0.1]")) + #expect(!OAuthURLValidator.isLoopbackOrUnspecifiedHost("[::ffff:1]")) + #expect(!OAuthURLValidator.isLoopbackOrUnspecifiedHost("example.com")) + } + + @Test("The client's policy follows no refused redirect, logs it, and doesn't ask the authorizer") + func testClientRedirectsRefuse() async { + let asked = Mutex(0) + let log = CapturingLogHandler() + let redirects = HTTPClientRedirects( + authorize: { _, _ in + asked.withLock { $0 += 1 } + return ["Authorization": "DPoP fresh"] + }, logger: Logger(label: "redirects", factory: { _ in log })) + for target in ["ftp://mcp.example.com/x", "http://mcp.example.com/mcp", "https://127.0.0.1:3000/mcp"] { + let original = Self.credentialedRequest("https://mcp.example.com/mcp") + var proposed = original + proposed.url = URL(string: target)! + let response = HTTPURLResponse( + url: original.url!, statusCode: 307, httpVersion: "HTTP/1.1", headerFields: ["Location": target])! + var chain = HTTPRedirectChain() + let followed = await redirects.request(redirectedTo: proposed, by: response, original: original, chain: &chain) + #expect(followed == nil, "\(target)") + #expect(chain.failure == nil) + } + #expect(asked.withLock { $0 } == 0) + #expect(log.messages == [ + "Redirect not followed: its target is not an http or https URL", + "Redirect not followed: it goes from https to http", + "Redirect not followed: it goes to a loopback host from a host that is not a loopback host", + ]) + } + + @Test("A same-origin hop for which the authorizer has no headers carries no Authorization and no DPoP") + func testClientRedirectsWithoutHeadersForTarget() async { + let original = Self.credentialedRequest("https://mcp.example.com/mcp") + let redirects = HTTPClientRedirects(authorize: { _, _ in [:] }) + var proposed = original + proposed.url = URL(string: "https://mcp.example.com/v2")! + let response = HTTPURLResponse( + url: original.url!, statusCode: 307, httpVersion: "HTTP/1.1", headerFields: [:])! + var chain = HTTPRedirectChain() + let followed = await redirects.request(redirectedTo: proposed, by: response, original: original, chain: &chain) + #expect(followed != nil) + // Never the first request's token, so never `DPoP ` without a proof (RFC 9449 §7.1). + #expect(followed?.value(forHTTPHeaderField: "Authorization") == nil) + #expect(followed?.value(forHTTPHeaderField: "DPoP") == nil) + #expect(followed?.value(forHTTPHeaderField: "Proxy-Authorization") == "Basic cHJveHk6cHc=") + #expect(followed?.value(forHTTPHeaderField: "Cookie") == "sid=1") + #expect(followed?.value(forHTTPHeaderField: "Mcp-Session-Id") == "s1") + #expect(chain.leftOrigin == nil && chain.failure == nil) + #expect(chain.sentAuthorization == .some(nil)) + } + + @Test("A same-origin redirect gets the authorizer's headers for its URL; a failure stops it") + func testClientRedirectsAuthorizeSameOrigin() async { + let original = Self.credentialedRequest("https://mcp.example.com/mcp") + let asked = Mutex<[String]>([]) + let log = CapturingLogHandler() + let redirects = HTTPClientRedirects( + authorize: { url, method in + asked.withLock { $0.append("\(method) \(url.absoluteString)") } + guard url.path != "/refused" else { throw URLError(.userAuthenticationRequired) } + return ["Authorization": "DPoP fresh", "DPoP": "proof for \(method) \(url.absoluteString)"] + }, logger: Logger(label: "redirects", factory: { _ in log })) + func redirect(to target: String, chain: inout HTTPRedirectChain) async -> URLRequest? { + var proposed = original + proposed.url = URL(string: target)! + let response = HTTPURLResponse( + url: original.url!, statusCode: 307, httpVersion: "HTTP/1.1", headerFields: ["Location": target])! + return await redirects.request(redirectedTo: proposed, by: response, original: original, chain: &chain) + } + + var chain = HTTPRedirectChain() + let same = await redirect(to: "https://mcp.example.com/v2", chain: &chain) + #expect(same?.value(forHTTPHeaderField: "Authorization") == "DPoP fresh") + #expect(same?.value(forHTTPHeaderField: "DPoP") == "proof for POST https://mcp.example.com/v2") + #expect(same?.value(forHTTPHeaderField: "Proxy-Authorization") == "Basic cHJveHk6cHc=") + #expect(same?.value(forHTTPHeaderField: "Cookie") == "sid=1") + #expect(same?.value(forHTTPHeaderField: "Mcp-Session-Id") == "s1") + #expect(chain.leftOrigin == nil && chain.failure == nil) + #expect(chain.sentAuthorization == .some("DPoP fresh")) + // Another origin: no credentials, and the authorizer is not asked. + chain = HTTPRedirectChain() + let other = await redirect(to: "https://other.example.com/v2", chain: &chain) + #expect(other != nil) + #expect(other?.value(forHTTPHeaderField: "Authorization") == nil) + #expect(other?.value(forHTTPHeaderField: "Mcp-Session-Id") == nil) + #expect(other?.value(forHTTPHeaderField: "DPoP") == nil) + #expect(chain.leftOrigin == URL(string: "https://other.example.com/v2")!) + #expect(chain.sentAuthorization == .some(nil)) + // A failure stops the redirect, is recorded for the transport, and logged. + #expect(log.messages.isEmpty) + chain = HTTPRedirectChain() + #expect(await redirect(to: "https://mcp.example.com/refused", chain: &chain) == nil) + #expect((chain.failure as? URLError)?.code == .userAuthenticationRequired) + #expect(log.messages == ["Redirect not followed: no authorization headers for its target"]) + #expect(asked.withLock { $0 } == ["POST https://mcp.example.com/v2", "POST https://mcp.example.com/refused"]) + + // Without an authorizer the credentials stay, and DPoP goes. + let plain = HTTPClientRedirects(authorize: nil) + var proposed = original + proposed.url = URL(string: "https://mcp.example.com/v2")! + let response = HTTPURLResponse( + url: original.url!, statusCode: 302, httpVersion: "HTTP/1.1", headerFields: [:])! + chain = HTTPRedirectChain() + let kept = await plain.request(redirectedTo: proposed, by: response, original: original, chain: &chain) + #expect(kept?.value(forHTTPHeaderField: "Authorization") == "Bearer t") + #expect(kept?.value(forHTTPHeaderField: "Cookie") == "sid=1") + #expect(kept?.value(forHTTPHeaderField: "Mcp-Session-Id") == "s1") + #expect(kept?.value(forHTTPHeaderField: "DPoP") == nil) + } + + @Test("A discovery redirect the guard follows keeps credentials on the same origin only") + func testGuardRedirectCredentials() { + let original = Self.credentialedRequest("https://mcp.example.com/.well-known/oauth-protected-resource") + let guardDelegate = OAuthRedirectGuard(policy: .validated) + var proposed = original + proposed.url = URL(string: "https://mcp.example.com/metadata")! + var chain = HTTPRedirectChain() + let same = guardDelegate.request(redirectedTo: proposed, original: original, from: original.url, chain: &chain) + #expect(same?.value(forHTTPHeaderField: "Authorization") == "Bearer t") + #expect(same?.value(forHTTPHeaderField: "Cookie") == "sid=1") + #expect(same?.value(forHTTPHeaderField: "Mcp-Session-Id") == "s1") + proposed.url = URL(string: "https://other.example.com/metadata")! + let other = guardDelegate.request(redirectedTo: proposed, original: original, from: original.url, chain: &chain) + #expect(other != nil) + #expect(other?.value(forHTTPHeaderField: "Authorization") == nil) + #expect(other?.value(forHTTPHeaderField: "Cookie") == nil) + #expect(other?.value(forHTTPHeaderField: "Mcp-Session-Id") == nil) + // Back on the origin after the other one: no credentials. + proposed.url = URL(string: "https://mcp.example.com/metadata")! + let back = guardDelegate.request( + redirectedTo: proposed, original: original, from: URL(string: "https://other.example.com/metadata")!, + chain: &chain) + #expect(back != nil) + #expect(back?.value(forHTTPHeaderField: "Authorization") == nil) + #expect(back?.value(forHTTPHeaderField: "Mcp-Session-Id") == nil) + proposed.url = URL(string: "http://other.example.com/metadata")! + chain = HTTPRedirectChain() + #expect(guardDelegate.request(redirectedTo: proposed, original: original, from: original.url, chain: &chain) == nil) + #expect(OAuthRedirectGuard(policy: .none).request( + redirectedTo: proposed, original: original, from: original.url, chain: &chain) == nil) + } + + @Test( + "URLSession.oauthData strips configuration credentials on cross-origin redirects", + .timeLimit(.minutes(1)), arguments: [false, true]) + func testOAuthDataSeparatesConfigurationCredentials(crossOrigin: Bool) async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + let other = try LoopbackHTTPServer() + defer { other.stop() } + let landing = crossOrigin ? other : server + server.routes = ["/meta": (302, ["Location": "\(landing.baseURL)/landed"], Data())] + landing.routes["/landed"] = (200, ["Content-Type": "application/json"], Data("{}".utf8)) + let configuration = URLSessionConfiguration.ephemeral + configuration.httpAdditionalHeaders = [ + "Authorization": "Bearer cfg-token", "Cookie": "sid=cfg", "Mcp-Session-Id": "sess-cfg", + "X-Config": "kept", + ] + let session = URLSession(configuration: configuration) + defer { session.finishTasksAndInvalidate() } + + let (data, response) = try await session.oauthData( + for: URLRequest(url: URL(string: "\(server.baseURL)/meta")!), + redirects: .validated, validator: OAuthURLValidator()) + #expect((response as? HTTPURLResponse)?.statusCode == 200) + #expect(data == Data("{}".utf8)) + let first = try #require(server.requests.first) + #expect(first.headers["authorization"] == "Bearer cfg-token") + #expect(first.headers["cookie"] == "sid=cfg") + #expect(first.headers["mcp-session-id"] == "sess-cfg") + let landed = try #require(landing.requests.first { $0.path == "/landed" }) + #expect(landed.headers["authorization"] == (crossOrigin ? nil : "Bearer cfg-token")) + #expect(landed.headers["cookie"] == (crossOrigin ? nil : "sid=cfg")) + #expect(landed.headers["mcp-session-id"] == (crossOrigin ? nil : "sess-cfg")) + #expect(landed.headers["x-config"] == "kept") + #expect(session.configuration.httpAdditionalHeaders?["Authorization"] as? String == "Bearer cfg-token") + } + @Test("Token and registration requests follow no redirect") func testRedirectGuardNone() { let guardDelegate = OAuthRedirectGuard(policy: .none, validator: OAuthURLValidator()) diff --git a/Tests/MCPTests/ProgressTests.swift b/Tests/MCPTests/ProgressTests.swift index c71fe9af..03fd0001 100644 --- a/Tests/MCPTests/ProgressTests.swift +++ b/Tests/MCPTests/ProgressTests.swift @@ -72,6 +72,39 @@ struct ProgressTests { #expect(set.count == 2) } + @Test("String tokens with different scalars are different tokens, also when canonically equivalent") + func testProgressTokenCanonicallyEquivalentStringsDiffer() { + for (first, second) in IDTests.canonicallyEquivalentPairs { + #expect(first == second, "the pair must be canonically equivalent") + #expect(ProgressToken.string(first) != ProgressToken.string(second)) + #expect(Set([ProgressToken.string(first), ProgressToken.string(second)]).count == 2) + // By assignment: a literal with keys that are equal traps. + var progress: [ProgressToken: String] = [:] + progress[.string(first)] = "first" + progress[.string(second)] = "second" + #expect(progress.count == 2) + #expect(progress[.string(first)] == "first") + #expect(progress[.string(second)] == "second") + } + } + + @Test("Equal tokens hash alike; a string and an integer with the same text differ") + func testProgressTokenEqualTokensHashAlike() { + let spelled = ProgressToken.string("e\u{301}") + let built = ProgressToken.string(String(decoding: Array("e\u{301}".utf16), as: UTF16.self)) + #expect(spelled == built) + #expect(spelled.hashValue == built.hashValue) + #expect(ProgressToken.string("1") != .integer(1)) + #expect(Set([ProgressToken.string("1"), .integer(1)]).count == 2) + #expect(ProgressToken.integer(7).hashValue == ProgressToken.integer(7).hashValue) + #if canImport(ObjectiveC) + let native = "r\u{E9}q-\u{212A}" + let bridged = NSString(string: native) as String + #expect(ProgressToken.string(native) == .string(bridged)) + #expect(ProgressToken.string(native).hashValue == ProgressToken.string(bridged).hashValue) + #endif + } + // MARK: - RequestMeta Tests @Test("RequestMeta empty initialization") diff --git a/Tests/MCPTests/PromptTests.swift b/Tests/MCPTests/PromptTests.swift index 742bfaf4..e63843c6 100644 --- a/Tests/MCPTests/PromptTests.swift +++ b/Tests/MCPTests/PromptTests.swift @@ -66,22 +66,22 @@ struct PromptTests { // Test audio content let audioContent = Prompt.Message.Content.audio( - data: "base64audiodata", mimeType: "audio/wav") + Data("audio bytes".utf8), mimeType: "audio/wav") let audioData = try encoder.encode(audioContent) let decodedAudio = try decoder.decode(Prompt.Message.Content.self, from: audioData) if case .audio(let data, let mimeType) = decodedAudio { - #expect(data == "base64audiodata") + #expect(data == Data("audio bytes".utf8)) #expect(mimeType == "audio/wav") } else { #expect(Bool(false), "Expected audio content") } // Test image content - let imageContent = Prompt.Message.Content.image(data: "base64data", mimeType: "image/png") + let imageContent = Prompt.Message.Content.image(Data("image bytes".utf8), mimeType: "image/png") let imageData = try encoder.encode(imageContent) let decodedImage = try decoder.decode(Prompt.Message.Content.self, from: imageData) if case .image(let data, let mimeType) = decodedImage { - #expect(data == "base64data") + #expect(data == Data("image bytes".utf8)) #expect(mimeType == "image/png") } else { #expect(Bool(false), "Expected image content") @@ -99,7 +99,7 @@ struct PromptTests { if case .resource(let resourceData, let annotations, let _meta) = decodedResource { #expect(resourceData.uri == "file://test.txt") #expect(resourceData.mimeType == "text/plain") - #expect(resourceData.text == "Sample text") + #expect(resourceData.body == .text("Sample text")) #expect(annotations == nil) #expect(_meta == nil) } else { @@ -245,10 +245,10 @@ struct PromptTests { } // Test with image content - let imageMessage: Prompt.Message = .user(.image(data: "base64data", mimeType: "image/png")) + let imageMessage: Prompt.Message = .user(.image(Data("image bytes".utf8), mimeType: "image/png")) #expect(imageMessage.role == .user) if case .image(let data, let mimeType) = imageMessage.content { - #expect(data == "base64data") + #expect(data == Data("image bytes".utf8)) #expect(mimeType == "image/png") } else { #expect(Bool(false), "Expected image content") @@ -256,10 +256,10 @@ struct PromptTests { // Test with audio content let audioMessage: Prompt.Message = .assistant( - .audio(data: "base64audio", mimeType: "audio/wav")) + .audio(Data("audio bytes".utf8), mimeType: "audio/wav")) #expect(audioMessage.role == .assistant) if case .audio(let data, let mimeType) = audioMessage.content { - #expect(data == "base64audio") + #expect(data == Data("audio bytes".utf8)) #expect(mimeType == "audio/wav") } else { #expect(Bool(false), "Expected audio content") @@ -276,7 +276,7 @@ struct PromptTests { if case .resource(let resource, let annotations, let _meta) = resourceMessage.content { #expect(resource.uri == "file://test.txt") #expect(resource.mimeType == "text/plain") - #expect(resource.text == "Sample text") + #expect(resource.body == .text("Sample text")) #expect(annotations == nil) #expect(_meta == nil) } else { @@ -437,7 +437,7 @@ struct PromptTests { // Pattern 3: Mixed content types let mixedContent: [Prompt.Message] = [ .user("Please review this design mockup"), - .assistant(.image(data: "design_mockup_data", mimeType: "image/png")), + .assistant(.image(Data("design_mockup_data".utf8), mimeType: "image/png")), .user("What do you think of the user flow?"), .assistant( "The design looks clean and intuitive. I particularly like the navigation structure." @@ -478,6 +478,58 @@ struct PromptTests { let call = try decoder.decode(CallTool.Parameters.self, from: Data(#"{"name":"t","arguments":null}"#.utf8)) #expect(call.arguments == nil) } + + @Test("Prompt image and audio content encode their bytes as base64 data") + func imageAndAudioGoldens() throws { + let image = Prompt.Message.Content.image(Data([0x89, 0x50, 0x4E, 0x47]), mimeType: "image/png") + #expect(try wireString(image) == #"{"data":"iVBORw==","mimeType":"image/png","type":"image"}"#) + let audio = Prompt.Message.Content.audio(Data("RIFF".utf8), mimeType: "audio/wav") + #expect(try wireString(audio) == #"{"data":"UklGRg==","mimeType":"audio/wav","type":"audio"}"#) + let message = Prompt.Message.user(image) + #expect( + try wireString(message) + == #"{"content":{"data":"iVBORw==","mimeType":"image/png","type":"image"},"role":"user"}"#) + } + + @Test("Prompt image and audio decode a fixed base64 literal") + func imageAndAudioDecodeLiteral() throws { + let png = Data([0x89, 0x50, 0x4E, 0x47]) + for data in [#""iVBORw==""#, #""iVBO\nRw""#] { + let image = #"{"type":"image","data":\#(data),"mimeType":"image/png"}"# + #expect( + try JSONDecoder().decode(Prompt.Message.Content.self, from: Data(image.utf8)) + == .image(png, mimeType: "image/png")) + let audio = #"{"type":"audio","data":\#(data),"mimeType":"audio/wav"}"# + #expect( + try JSONDecoder().decode(Prompt.Message.Content.self, from: Data(audio.utf8)) + == .audio(png, mimeType: "audio/wav")) + } + } + + @Test("Prompt image and audio data that is not base64 fails", arguments: ["image", "audio"]) + func imageAndAudioInvalidData(type: String) throws { + let json = #"{"type":"\#(type)","data":"not base64!","mimeType":"x/y"}"# + let error = try #require(throws: DecodingError.self) { + try JSONDecoder().decode(Prompt.Message.Content.self, from: Data(json.utf8)) + } + guard case .dataCorrupted = error else { + Issue.record("Expected dataCorrupted, got \(error)") + return + } + #expect(codingPath(of: error) == ["data"]) + } + + @Test("A GetPrompt result with one bad image fails") + func getPromptWithBadImage() throws { + let json = #""" + {"messages":[{"role":"user","content":{"type":"text","text":"a"}}, + {"role":"user","content":{"type":"image","data":"%%%","mimeType":"image/png"}}]} + """# + let error = try #require(throws: DecodingError.self) { + try JSONDecoder().decode(GetPrompt.Result.self, from: Data(json.utf8)) + } + #expect(codingPath(of: error) == ["messages", "1", "content", "data"]) + } } @Suite("Prompt Integration Tests") @@ -632,9 +684,9 @@ struct PromptIntegrationTests { let expectedMessages: [Prompt.Message] = [ .user("Please review this design mockup:"), - .user(.image(data: "base64_image_data", mimeType: "image/png")), + .user(.image(Data("image bytes".utf8), mimeType: "image/png")), .assistant("I'll analyze the design mockup for you."), - .assistant(.audio(data: "base64_audio_data", mimeType: "audio/mp3")), + .assistant(.audio(Data("audio bytes".utf8), mimeType: "audio/mp3")), ] // Register get prompt handler diff --git a/Tests/MCPTests/ProtocolFoundationsTests.swift b/Tests/MCPTests/ProtocolFoundationsTests.swift index 7160f7da..6247afbc 100644 --- a/Tests/MCPTests/ProtocolFoundationsTests.swift +++ b/Tests/MCPTests/ProtocolFoundationsTests.swift @@ -282,16 +282,14 @@ struct MCPErrorWireTests { #expect(items.first?["url"] as? String == uri) } - @Test("Server error data from a message decoder still holds data: URLs as data") + @Test("Server error data keeps data: URL strings") func testServerErrorDataURL() throws { - let decoder = JSONDecoder() - decoder.userInfo[.valuePreservesStrings] = true - let error = try decoder.decode( + let error = try JSONDecoder().decode( MCPError.self, from: Data(#"{"code":-32010,"message":"m","data":{"u":"data:,hi"}}"#.utf8)) - #expect( - error == .serverError( - code: -32010, message: "m", data: ["u": .data(mimeType: "text/plain", Data("hi".utf8))])) + #expect(error == .serverError(code: -32010, message: "m", data: ["u": "data:,hi"])) + #expect(error.data == ["u": .string("data:,hi")]) + #expect(try wireString(error) == #"{"code":-32010,"data":{"u":"data:,hi"},"message":"m"}"#) } } @@ -385,13 +383,13 @@ struct EnvelopeMetaTests { #expect(content?.first?["text"] as? String == "data:,hello") } - @Test("A Value result still decodes data: URLs as data for the caller") + @Test("A Value result keeps data: URL strings for the caller") func testPendingValueResult() async throws { let result: Value = try await withCheckedThrowingContinuation { continuation in AnyPendingRequest(PendingRequest(continuation: continuation)) .resume(returning: Value.object(["u": .string("data:,hi")])) } - #expect(result == ["u": .data(mimeType: "text/plain", Data("hi".utf8))]) + #expect(result == ["u": .string("data:,hi")]) } @Test("Typed _meta accessors") @@ -492,4 +490,201 @@ struct ResultTypeAndCacheTests { #expect(try JSONDecoder().decode(ResultType.self, from: JSONEncoder().encode(ResultType.inputRequired)) == .inputRequired) #expect(ResultType.complete.rawValue == "complete") } + + @Test("Millisecond fields decode leniently on every result", arguments: millisecondCases) + func testMillisecondsOnEveryResult(literal: String, expected: Int?) throws { + let skill = Skill( + uri: "skill://a/SKILL.md", frontmatter: ["name": "a", "description": "d"], resources: .dynamic) + let results: [any Codable & CacheableResult] = [ + ListTools.Result(tools: []), + ListPrompts.Result(prompts: []), + ListResources.Result(resources: []), + ListResourceTemplates.Result(templates: []), + ReadResource.Result(contents: []), + ServerDiscover.Result(supportedVersions: [Version.v2026_07_28], capabilities: .init()), + ListSkills.Result(skills: [skill]), + GetSkill.Result(skill: skill), + ] + for result in results { + #expect(try cacheTTL(of: result, member: #""ttlMs":\#(literal)"#) == expected, "\(type(of: result))") + #expect(try cacheTTL(of: result, member: nil) == nil, "\(type(of: result))") + } + } + + @Test("Cache hints encode as integers") + func testCacheHintsEncodeAsIntegers() throws { + #expect( + try wireString(ListTools.Result(tools: [], ttlMs: 0, cacheScope: .private)) + == #"{"cacheScope":"private","tools":[],"ttlMs":0}"#) + #expect( + try wireString(ListTools.Result(tools: [], ttlMs: 60_000, cacheScope: .public)) + == #"{"cacheScope":"public","tools":[],"ttlMs":60000}"#) + #expect(try wireString(ListTools.Result(tools: [])) == #"{"tools":[]}"#) + } + + @Test("A configured cache hint keeps its keys") + func testConfiguredCacheHintKeys() throws { + #expect(try wireString(CacheHint(ttlMs: 60_000, scope: .public)) == #"{"scope":"public","ttlMs":60000}"#) + let saved = #"{"strict":false,"cacheHints":{"tools/list":{"ttlMs":1500,"scope":"public"}}}"# + let configuration = try JSONDecoder().decode(Server.Configuration.self, from: Data(saved.utf8)) + #expect(configuration.cacheHints == [ListTools.name: CacheHint(ttlMs: 1500, scope: .public)]) + #expect(try wireString(configuration).contains(#""cacheHints":{"tools/list":{"scope":"public","ttlMs":1500}}"#)) + #expect(try wireString(configuration).contains(#""defaultCacheHint":{"scope":"private","ttlMs":0}"#)) + } + + @Test( + "Durations convert to whole milliseconds", + arguments: [ + (Duration.zero, 0), (.milliseconds(1500), 1500), (.microseconds(1500), 1), (.microseconds(1), 1), + (.nanoseconds(1), 1), (.seconds(1) + .nanoseconds(999_999), 1000), (.milliseconds(-5), 0), + (.nanoseconds(-1), 0), (.seconds(-1), 0), (.seconds(Int64.max), Int.max), (.milliseconds(Int.max), Int.max), + (Duration(secondsComponent: Int64.max / 1000, attosecondsComponent: 808_000_000_000_000_000), Int.max), + ]) + func testWholeMilliseconds(duration: Duration, expected: Int) { + #expect(duration.wholeMilliseconds == expected) + } + + @Test("Milliseconds from the wire become durations") + func testDurationFromMilliseconds() { + #expect(Duration(wireMilliseconds: 0) == .zero) + #expect(Duration(wireMilliseconds: 1500) == .milliseconds(1500)) + #expect(Duration(wireMilliseconds: Int.max).wholeMilliseconds == Int.max) + } + + @Test("The Duration helpers write integers or null") + func testDurationHelpers() throws { + #expect(try wireString(DurationProbe(.milliseconds(1.5))) == #"{"t":1}"#) + #expect(try wireString(DurationProbe(.milliseconds(1.5), nullWhenAbsent: true)) == #"{"t":1}"#) + #expect(try wireString(DurationProbe(nil)) == "{}") + #expect(try wireString(DurationProbe(nil, nullWhenAbsent: true)) == #"{"t":null}"#) + #expect(try wireString(DurationProbe(.seconds(-1))) == #"{"t":0}"#) + #expect(try wireString(DurationProbe(.seconds(-1), nullWhenAbsent: true)) == #"{"t":0}"#) + #expect(try wireString(DurationProbe(.seconds(Int64.max))) == #"{"t":\#(Int.max)}"#) + + let decoder = JSONDecoder() + #expect(try decoder.decode(DurationProbe.self, from: Data(#"{"t":1500.9}"#.utf8)).t == .milliseconds(1500)) + #expect(try decoder.decode(DurationProbe.self, from: Data(#"{"t":0.4}"#.utf8)).t == .zero) + #expect(try decoder.decode(DurationProbe.self, from: Data(#"{"t":-1}"#.utf8)).t == nil) + #expect(try decoder.decode(DurationProbe.self, from: Data(#"{"t":null}"#.utf8)).t == nil) + #expect(try decoder.decode(DurationProbe.self, from: Data("{}".utf8)).t == nil) + } + + // The watchOS simulator is 64-bit, so a 32-bit `Int` is compiled (arm64_32 + // device build) but never run: `Int32` stands in for it. + @Test( + "Milliseconds past a 32-bit integer saturate it instead of reading as absent", + arguments: [ + ("1500", 1500), ("1500.9", 1500), ("2147483647", .max), ("2147483648", .max), ("3000000000", .max), + ("3e9", .max), ("3000000000.5", .max), (String(Int64.max), .max), ("-1", nil), ("1e300", nil), + (String(UInt64(Int64.max) + 1), nil), + ] as [(String, Int32?)]) + func testMillisecondsSaturate32Bits(json: String, expected: Int32?) throws { + let probe = try JSONDecoder().decode(Int32MillisecondsProbe.self, from: Data(#"{"t":\#(json)}"#.utf8)) + #expect(probe.t == expected) + } +} + +/// Millisecond values a peer may send, as JSON literals, with what the SDK +/// reads: whole milliseconds, a fractional value rounded down, a value past +/// `Int.max` (only on 32-bit platforms) clamped to it, and `nil` for anything +/// that is not a non-negative number in `Int64`'s range. +let millisecondCases: [(String, Int?)] = [ + ("0", 0), ("1500", 1500), ("1500.9", 1500), ("0.4", 0), ("1.0", 1), ("1e3", 1000), ("60000.0", 60000), + (String(Int.max), Int.max), ("3000000000", Int(clamping: 3_000_000_000 as Int64)), + (String(Int64.max), Int(clamping: Int64.max)), ("-1", nil), ("-0.5", nil), ("1e300", nil), + (String(UInt64(Int64.max) + 1), nil), (#""5""#, nil), ("null", nil), ("true", nil), ("{}", nil), +] + +/// The `ttlMs` that `result` decodes to with `member` added to its JSON, or +/// with no `ttlMs` when `member` is `nil`. +private func cacheTTL(of result: Result, member: String?) throws -> Int? { + var json = try wireString(result) + if let member { json = "{\(member)," + json.dropFirst() } + return try JSONDecoder().decode(Result.self, from: Data(json.utf8)).ttlMs +} + +/// Milliseconds under `t` read as an `Int32`, as `Int` reads on 32-bit platforms. +private struct Int32MillisecondsProbe: Decodable { + var t: Int32? + + private enum CodingKeys: String, CodingKey { + case t + } + + init(from decoder: Decoder) throws { + t = try decoder.container(keyedBy: CodingKeys.self).decodeMilliseconds(Int32.self, forKey: .t) + } +} + +/// One duration coded through the millisecond layer under `t`. +private struct DurationProbe: Codable { + var t: Duration? + var nullWhenAbsent = false + + init(_ t: Duration?, nullWhenAbsent: Bool = false) { + self.t = t + self.nullWhenAbsent = nullWhenAbsent + } + + private enum CodingKeys: String, CodingKey { + case t + } + + init(from decoder: Decoder) throws { + t = try decoder.container(keyedBy: CodingKeys.self).decodeDuration(forKey: .t) + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if nullWhenAbsent { + try container.encodeMillisecondsOrNull(t, forKey: .t) + } else { + try container.encodeMilliseconds(t, forKey: .t) + } + } +} + +@Suite("Icon Tests") +struct IconTests { + @Test("An icon with an unknown theme decodes with no theme") + func unknownTheme() throws { + let icon = try decode( + Icon.self, ["src": "https://example.com/i.png", "sizes": ["48x48"], "theme": "high-contrast"]) + #expect(icon == Icon(src: "https://example.com/i.png", sizes: ["48x48"])) + let encoded = try JSONDecoder().decode(Value.self, from: JSONEncoder().encode(icon)) + #expect(encoded == ["src": "https://example.com/i.png", "sizes": ["48x48"]]) + } + + @Test("tools/list with an unknown icon theme decodes every tool") + func listWithUnknownTheme() throws { + let data = Data( + #""" + {"tools":[ + {"name":"a","inputSchema":{"type":"object"}, + "icons":[{"src":"https://example.com/a.png","theme":"high-contrast"}]}, + {"name":"b","inputSchema":{"type":"object"}, + "icons":[{"src":"https://example.com/b.png","theme":"dark"}]} + ]} + """#.utf8) + let result = try JSONDecoder().decode(ListTools.Result.self, from: data) + #expect(result.tools.map(\.name) == ["a", "b"]) + #expect(result.tools.first?.icons == [Icon(src: "https://example.com/a.png")]) + #expect(result.tools.last?.icons == [Icon(src: "https://example.com/b.png", theme: .dark)]) + } + + @Test("An icon theme that isn't a string fails") + func nonStringTheme() { + #expect(throws: DecodingError.self) { + try decode(Icon.self, ["src": "https://example.com/i.png", "theme": 1]) + } + } + + @Test("An icon encodes its theme") + func encodesTheme() throws { + let icon = Icon(src: "https://example.com/i.png", mimeType: "image/png", theme: .dark) + expectWire( + try Value(icon), + matches: ["src": "https://example.com/i.png", "mimeType": "image/png", "theme": "dark"]) + expectWireLacks(try Value(Icon(src: "https://example.com/i.png")), "theme", "mimeType", "sizes") + } } diff --git a/Tests/MCPTests/RequestHeadersTests.swift b/Tests/MCPTests/RequestHeadersTests.swift index 75e7a28f..700e7718 100644 --- a/Tests/MCPTests/RequestHeadersTests.swift +++ b/Tests/MCPTests/RequestHeadersTests.swift @@ -53,6 +53,27 @@ struct RequestHeadersTests { #expect(MCPRequestHeaders.render(["a"]) == nil) } + // A 32-bit Int decodes integers past Int32.max as doubles. + @Test("Whole doubles past a 32-bit Int render in decimal, the same on every platform") + func testRenderLargeWholeDoubles() throws { + #expect(MCPRequestHeaders.render(.double(3_000_000_000)) == "3000000000") + #expect(MCPRequestHeaders.render(.double(-3_000_000_000)) == "-3000000000") + #expect(MCPRequestHeaders.render(.double(9_007_199_254_740_991)) == "9007199254740991") + #expect(MCPRequestHeaders.render(.double(-9_007_199_254_740_991)) == "-9007199254740991") + #expect(MCPRequestHeaders.render(.double(-0.0)) == "0") + #expect(MCPRequestHeaders.render(.double(9_007_199_254_740_992)) == nil) + + // As the server checks a tools/call argument against its header. + let parameters = try MCPRequestHeaders.parameters(in: [ + "type": "object", + "properties": ["n": ["type": "integer", "x-mcp-header": "N"]], + ]) + let arguments: Value = ["n": .double(3_000_000_000)] + #expect(MCPRequestHeaders.parameterHeaders(parameters, arguments: arguments) == ["Mcp-Param-N": "3000000000"]) + #expect(MCPRequestHeaders.validate(parameters, arguments: arguments) { _ in "3000000000" } == nil) + #expect(MCPRequestHeaders.validate(parameters, arguments: arguments) { _ in "3000000001" } != nil) + } + @Test("x-mcp-header annotations are read through properties") func testParameters() throws { let schema: Value = [ @@ -402,4 +423,61 @@ struct HeaderFieldLineTests { #expect(try errorCode(response) == -32020, "\(label)") } } + + @Test("argument(at:in:) and validate match keys and values by exact code points") + func exactCodePointMatching() throws { + // U+212A KELVIN SIGN equals "K", and "e\u{0301}" equals "\u{00E9}" in Swift String. + let schema: Value = [ + "type": "object", + "properties": [ + "Key": ["type": "string", "x-mcp-header": "Key"] + ], + ] + let parameters = try MCPRequestHeaders.parameters(in: schema) + #expect(MCPRequestHeaders.argument(at: ["Key"], in: ["\u{212A}ey": "v"]) == nil) + #expect(MCPRequestHeaders.argument(at: ["Key"], in: ["Key": "v"]) == .string("v")) + + let exact = MCPRequestHeaders.validate( + parameters, arguments: ["Key": "caf\u{E9}"], + header: { _ in MCPRequestHeaders.encode("caf\u{E9}") }) + #expect(exact == nil) + + let nfdHeader = MCPRequestHeaders.validate( + parameters, arguments: ["Key": "caf\u{E9}"], + header: { _ in MCPRequestHeaders.encode("cafe\u{301}") }) + #expect(nfdHeader != nil) + + let kelvinHeader = MCPRequestHeaders.validate( + parameters, arguments: ["Key": "Kelvin"], + header: { _ in MCPRequestHeaders.encode("\u{212A}elvin") }) + #expect(kelvinHeader != nil) + + // Canonically equivalent argument key is rejected whether the header is sent or omitted. + let kelvinKeyWithHeader = MCPRequestHeaders.validate( + parameters, arguments: ["\u{212A}ey": "v"], + header: { _ in "v" }) + #expect(kelvinKeyWithHeader != nil) + + let kelvinKeyWithoutHeader = MCPRequestHeaders.validate( + parameters, arguments: ["\u{212A}ey": "v"], + header: { _ in nil }) + #expect(kelvinKeyWithoutHeader != nil) + + // Nested canonical key mismatch is also rejected. + let nestedSchema: Value = [ + "type": "object", + "properties": [ + "Key": [ + "type": "object", + "properties": [ + "leaf": ["type": "string", "x-mcp-header": "Leaf"] + ], + ] + ], + ] + let nestedParameters = try MCPRequestHeaders.parameters(in: nestedSchema) + #expect( + MCPRequestHeaders.validate( + nestedParameters, arguments: ["\u{212A}ey": ["leaf": "v"]], header: { _ in nil }) != nil) + } } diff --git a/Tests/MCPTests/RequestIDValidationTests.swift b/Tests/MCPTests/RequestIDValidationTests.swift index 6335426e..3998ee1d 100644 --- a/Tests/MCPTests/RequestIDValidationTests.swift +++ b/Tests/MCPTests/RequestIDValidationTests.swift @@ -13,8 +13,18 @@ import Testing /// Ids a request may have, as JSON, with the id the answer echoes. private let validIDs: [(json: String, echo: Value)] = [ - (#""""#, ""), (#""x""#, "x"), ("0", 0), ("-1", -1), ("9007199254740993", .int(9_007_199_254_740_993)), + (#""""#, ""), (#""x""#, "x"), ("0", 0), ("-1", -1), +] + largeIntegerIDs + +/// An id above 2^53, which only a 64-bit `Int` holds (watchOS's arm64_32 +/// has a 32-bit `Int`). +#if _pointerBitWidth(_64) +private let largeIntegerIDs: [(json: String, echo: Value)] = [ + ("9007199254740993", .int(9_007_199_254_740_993)) ] +#else +private let largeIntegerIDs: [(json: String, echo: Value)] = [] +#endif /// Ids a request may not have, as JSON. private let invalidIDs = ["1.5", "5.2", "null", "[]", "{}", "true", "1e20"] @@ -429,7 +439,7 @@ struct StatelessHTTPRequestIDTests { struct StatefulHTTPRequestIDTests { @Test("An invalid id gets 400 and -32600 with a null id", arguments: invalidIDs + ["1e400"]) func invalidID(_ json: String) async throws { - let transport = StatefulHTTPServerTransport(validationPipeline: StandardValidationPipeline(validators: [])) + let transport = StatefulHTTPServerTransport(validators: []) try await transport.connect() let response = await transport.handleRequest( HTTPRequest( @@ -445,7 +455,7 @@ struct StatefulHTTPRequestIDTests { @Test("An invalid jsonrpc gets 400 and -32600 with the request's id", arguments: invalidVersions) func invalidVersion(_ line: String) async throws { - let transport = StatefulHTTPServerTransport(validationPipeline: StandardValidationPipeline(validators: [])) + let transport = StatefulHTTPServerTransport(validators: []) try await transport.connect() let response = await transport.handleRequest( HTTPRequest( @@ -478,7 +488,7 @@ struct StatefulHTTPRequestIDTests { func kind(_ json: String) -> JSONRPCMessageKind? { JSONRPCMessageKind(data: Data(json.utf8)) } if case .notification? = kind(#"{"jsonrpc":"2.0","method":"m"}"#) {} else { Issue.record("notification") } if case .request(let id, _)? = kind(#"{"jsonrpc":"2.0","id":"","method":"m"}"#) { - #expect(id == "") + #expect(id == .string("")) } else { Issue.record("empty string id") } @@ -488,6 +498,39 @@ struct StatefulHTTPRequestIDTests { if case .invalid? = kind(#"{"id":1,"method":"m"}"#) {} else { Issue.record("no jsonrpc") } } + @Test("Classification keeps the type of an id: 1 and \"1\" are different ids") + func classificationKeepsIDType() throws { + func kind(_ json: String) -> JSONRPCMessageKind? { JSONRPCMessageKind(data: Data(json.utf8)) } + for (json, id) in [("1", ID.number(1)), (#""1""#, ID.string("1"))] { + if case .request(let read, _)? = kind(#"{"jsonrpc":"2.0","id":\#(json),"method":"m"}"#) { + #expect(read == id) + } else { + Issue.record("request \(json)") + } + if case .response(let read?)? = kind(#"{"jsonrpc":"2.0","id":\#(json),"result":{}}"#) { + #expect(read == id) + } else { + Issue.record("response \(json)") + } + if case .invalidResponse(let read)? = kind(#"{"id":\#(json),"result":{}}"#) { + #expect(read == id) + } else { + Issue.record("invalid response \(json)") + } + let cancelled = JSONRPCMessageKind.cancelledRequestID( + in: Data(#"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":\#(json)}}"#.utf8)) + #expect(cancelled == id) + } + // A JSON `true` is no id, though it reads as an `NSNumber`. + for json in ["1", #""1""#, "true"] { + let object = try #require( + try JSONSerialization.jsonObject(with: Data(#"{"id":\#(json)}"#.utf8)) as? [String: Any]) + #expect( + JSONRPCMessageKind.extractID(from: object) + == ["1": ID.number(1), #""1""#: ID.string("1")][json], "\(json)") + } + } + @Test( "A request that also has a result or an error that do not read as a response gets 400 and -32600 with its id, and no stream", arguments: [#""error":5"#, #""error":{}"#, #""error":{"message":"x"}"#]) @@ -516,7 +559,7 @@ struct StatefulHTTPRequestIDTests { /// POSTs a `tools/list` with `member` beside its `id`, and returns the /// answer and the request context the transport kept for that `id`. private func postAnswerMember(_ member: String) async throws -> (HTTPResponse, HTTPRequest?) { - let transport = StatefulHTTPServerTransport(validationPipeline: StandardValidationPipeline(validators: [])) + let transport = StatefulHTTPServerTransport(validators: []) try await transport.connect() let response = await transport.handleRequest( HTTPRequest( @@ -524,7 +567,7 @@ struct StatefulHTTPRequestIDTests { headers: ["Content-Type": "application/json", "Accept": "application/json, text/event-stream"], body: Data(#"{"jsonrpc":"2.0","id":"x1","method":"tools/list",\#(member)}"#.utf8))) // Read before disconnecting, which drops every request's context. - let context = await transport.httpRequestContext(for: .string("x1")) + let context = await transport.httpRequest(for: .string("x1")) await transport.disconnect() return (response, context) } @@ -534,7 +577,7 @@ struct StatefulHTTPRequestIDTests { let transport = defaultValidators ? StatefulHTTPServerTransport() - : StatefulHTTPServerTransport(validationPipeline: StandardValidationPipeline(validators: [])) + : StatefulHTTPServerTransport(validators: []) try await transport.connect() func post(_ body: String) async -> HTTPResponse { await transport.handleRequest( @@ -569,7 +612,7 @@ struct StatefulHTTPRequestIDTests { let message = #"{"jsonrpc":"2.0","id":\#(json),"method":"m",\#(member)}"# switch kind(message) { case .response(let read)? where responses.contains(member): - #expect(read == id.description) + #expect(read == id) case .invalid(let method, let read, let reason)? where invalid.contains(member): #expect(method == "m") #expect(read == id) @@ -595,3 +638,51 @@ struct StatefulHTTPRequestIDTests { } } } + +@Suite("Request ids in Client", .timeLimit(.minutes(2))) +struct ClientRequestIDTests { + /// A handshake client connected to `transport`, whose server has tools. + private func connect(_ transport: MockTransport) async throws -> Client { + let client = Client(name: "c", version: "1", configuration: .handshake) + let answer = Task { + try await transport.waitForSentMessages() + let data = try #require(await transport.sentMessages.last?.data(using: .utf8)) + let request = try JSONDecoder().decode(Request.self, from: data) + try await transport.queue( + response: Initialize.response( + id: request.id, + result: .init( + protocolVersion: Version.latestHandshake, capabilities: .init(tools: .init()), + serverInfo: .init(name: "s", version: "1"), instructions: nil))) + } + _ = try await client.connect(transport: transport) + try await answer.value + return client + } + + @Test("Responses to canonically equivalent string ids reach their own requests") + func canonicallyEquivalentIDs() async throws { + let transport = MockTransport() + let client = try await connect(transport) + let precomposed = try await client.send(ListTools.request(id: .string("\u{E9}"), .init())) + let decomposed = try await client.send(ListTools.request(id: .string("e\u{301}"), .init())) + + // Answered in the other order, each naming its request by its scalars. + for (id, name) in [("e\\u0301", "decomposed"), ("\\u00e9", "precomposed")] { + await transport.queue( + data: Data( + #"{"jsonrpc":"2.0","id":"\#(id)","result":{"tools":[{"name":"\#(name)","inputSchema":{"type":"object"}}]}}"# + .utf8)) + } + let first = await outcome(within: .seconds(10)) { try await precomposed.value } + let second = await outcome(within: .seconds(10)) { try await decomposed.value } + guard case .returned(let firstTools) = first, case .returned(let secondTools) = second else { + Issue.record("Not both answered: \(first), \(second)") + await client.disconnect() + return + } + #expect(firstTools.tools.map(\.name) == ["precomposed"]) + #expect(secondTools.tools.map(\.name) == ["decomposed"]) + await client.disconnect() + } +} diff --git a/Tests/MCPTests/RequestLifecycleTests.swift b/Tests/MCPTests/RequestLifecycleTests.swift index a21c2332..69affb1b 100644 --- a/Tests/MCPTests/RequestLifecycleTests.swift +++ b/Tests/MCPTests/RequestLifecycleTests.swift @@ -1,5 +1,6 @@ import Foundation import Logging +import Synchronization import Testing @testable import MCP @@ -8,32 +9,15 @@ import Testing // handlers outside the receive loop, batches, and server error replies. /// Records every message sent through a transport, in order. -private actor RecordingTransport: Transport { - nonisolated let logger = Logger(label: "test.recording") - private let base: any Transport +actor RecordingTransport: TransportWrapper { + nonisolated let wrapped: any Transport private(set) var sent: [Value] = [] - init(_ base: any Transport) { self.base = base } + init(_ wrapped: any Transport) { self.wrapped = wrapped } - func connect() async throws { try await base.connect() } - func disconnect() async { await base.disconnect() } - func send(_ data: Data) async throws { + func send(_ data: Data, options: TransportSendOptions) async throws { if let value = try? JSONDecoder().decode(Value.self, from: data) { sent.append(value) } - try await base.send(data) - } - func receive() -> AsyncThrowingStream { - let base = self.base - return AsyncThrowingStream { continuation in - let task = Task { - do { - for try await data in await base.receive() { continuation.yield(data) } - continuation.finish() - } catch { - continuation.finish(throwing: error) - } - } - continuation.onTermination = { _ in task.cancel() } - } + try await wrapped.send(data, options: options) } /// Methods of the sent messages, `nil` for responses. @@ -222,6 +206,46 @@ struct RequestLifecycleTests { await server.stop() } + @Test("A response waits only for progress of its own token, not of a canonically equivalent one") + func progressTokensMatchExactly() async throws { + let server = Server(name: "s", version: "1", capabilities: .init(tools: .init())) + await server.withMethodHandler(CallTool.self) { [weak server] params in + if params.name == "b", let token = params._meta?.progressToken { + try await server?.notify(ProgressNotification.message(.init(progressToken: token, progress: 1))) + } + return .init(content: [.text(text: params.name)]) + } + let (clientEnd, serverEnd) = await InMemoryTransport.createConnectedPair() + try await server.start(transport: serverEnd) + let client = Client(name: "c", version: "1", configuration: .handshake) + let entered = Flag() + let gate = AsyncStream.makeStream() + await client.onNotification(ProgressNotification.self) { _ in + await entered.set() + for await _ in gate.stream { break } + } + try await client.connect(transport: clientEnd) + + // "K" and U+212A KELVIN SIGN: equal as Swift strings, different tokens. + let b = try await client.startToolCall(name: "b", meta: Metadata(progressToken: .string("K"))) + #expect(await eventually { await entered.isSet }) + let a = try await client.startToolCall(name: "a", meta: Metadata(progressToken: .string("\u{212A}"))) + let first = await outcome(within: .seconds(5)) { try await a.value } + guard case .returned(let result) = first else { + Issue.record("The response to a waited for progress of another token: \(first)") + gate.continuation.finish() + await client.disconnect() + await server.stop() + return + } + #expect(result.content == [.text(text: "a")]) + + gate.continuation.finish() + #expect(try await b.value.content == [.text(text: "b")]) + await client.disconnect() + await server.stop() + } + @Test("A notification handler can await a request started elsewhere") @available(*, deprecated, message: "Uses the deprecated sampling and logging APIs (SEP-2577)") func handlerAwaitsOtherRequest() async throws { @@ -394,6 +418,177 @@ struct ServerToClientLimitTests { return (serverEnd, incoming) } + /// Captures warning log messages emitted through a transport's `Logger`. + private final class WarningLogRecorder: Sendable { + private let messages = Mutex<[String]>([]) + + var warnings: [String] { messages.withLock { $0 } } + + func makeLogger(label: String = "mcp.test.limits") -> Logger { + let recorder = self + return Logger(label: label) { _ in Handler(recorder: recorder) } + } + + private func record(_ message: String) { + messages.withLock { $0.append(message) } + } + + private struct Handler: LogHandler { + let recorder: WarningLogRecorder + var metadata: Logger.Metadata = [:] + var logLevel: Logger.Level = .warning + + subscript(metadataKey key: String) -> Logger.Metadata.Value? { + get { metadata[key] } + set { metadata[key] = newValue } + } + + func log( + level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, + source: String, file: String, function: String, line: UInt + ) { + if level == .warning { + recorder.record(message.description) + } + } + } + } + + /// A transport wrapper whose `send` parks matching messages once `stall` is + /// active, until unstalled, cancelled, or (when `unblockOnDisconnect` is + /// true) disconnected. Tracks current and peak parked sends. + private actor StallingSendTransport: TransportWrapper { + nonisolated let wrapped: any Transport + nonisolated let logger: Logger + private let unblockOnDisconnect: Bool + private var stallPredicate: (@Sendable (Data) -> Bool)? + private(set) var inFlightSends = 0 + private(set) var peakInFlightSends = 0 + private var waiters: [UUID: CheckedContinuation] = [:] + + init(_ wrapped: any Transport, logger: Logger? = nil, unblockOnDisconnect: Bool = true) { + self.wrapped = wrapped + self.logger = logger ?? wrapped.logger + self.unblockOnDisconnect = unblockOnDisconnect + } + + func stall(when predicate: @escaping @Sendable (Data) -> Bool = { _ in true }) { + stallPredicate = predicate + } + + func unstall() { + stallPredicate = nil + let pending = waiters + waiters = [:] + for continuation in pending.values { + continuation.resume(returning: true) + } + } + + func releaseAll() { + stallPredicate = nil + let pending = waiters + waiters = [:] + for continuation in pending.values { + continuation.resume(throwing: CancellationError()) + } + } + + func send(_ data: Data, options: TransportSendOptions) async throws { + guard let predicate = stallPredicate, predicate(data) else { + try await wrapped.send(data, options: options) + return + } + inFlightSends += 1 + peakInFlightSends = max(peakInFlightSends, inFlightSends) + let id = UUID() + let shouldForward: Bool + do { + shouldForward = try await withTaskCancellationHandler { + try await self.parkSend(id) + } onCancel: { + Task { await self.cancelWaiter(id) } + } + } catch { + inFlightSends -= 1 + waiters[id] = nil + throw error + } + inFlightSends -= 1 + waiters[id] = nil + if shouldForward { + try await wrapped.send(data, options: options) + } + } + + private func parkSend(_ id: UUID) async throws -> Bool { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + if Task.isCancelled { + continuation.resume(throwing: CancellationError()) + } else if stallPredicate == nil { + continuation.resume(returning: true) + } else { + waiters[id] = continuation + } + } + } + + func disconnect() async { + if unblockOnDisconnect { + stallPredicate = nil + let pending = waiters + waiters = [:] + for continuation in pending.values { + continuation.resume(throwing: MCPError.connectionClosed) + } + } + await wrapped.disconnect() + } + + private func cancelWaiter(_ id: UUID) { + waiters.removeValue(forKey: id)?.resume(throwing: CancellationError()) + } + } + + /// Connects a handshake client through a `StallingSendTransport`. + private func connectedStalling( + configuration: Client.Configuration = .handshake, capabilities: Client.Capabilities = .init(roots: .init()), + logger: Logger? = nil, unblockOnDisconnect: Bool = true + ) async throws -> (Client, StallingSendTransport, InMemoryTransport, AsyncThrowingStream.Iterator) + { + let client = Client(name: "c", version: "1", capabilities: capabilities, configuration: configuration) + let (clientEnd, serverEnd) = await InMemoryTransport.createConnectedPair() + let stalling = StallingSendTransport(clientEnd, logger: logger, unblockOnDisconnect: unblockOnDisconnect) + try await serverEnd.connect() + var incoming = await serverEnd.receive().makeAsyncIterator() + let connecting = Task { try await client.connect(transport: stalling) } + let initialize = try JSONDecoder().decode(Value.self, from: try #require(await incoming.next())) + let id = try #require(initialize.objectValue?["id"]) + let result = Initialize.Result( + protocolVersion: Version.v2025_11_25, capabilities: .init(), + serverInfo: .init(name: "s", version: "1"), instructions: nil) + try await serverEnd.send(try JSONEncoder().encode(["jsonrpc": "2.0", "id": id, "result": try Value(result)] as Value)) + _ = try await connecting.value + _ = try await incoming.next() // notifications/initialized + return (client, stalling, serverEnd, incoming) + } + + /// Connects a 2026-07-28 stateless client through a `StallingSendTransport`. + private func connectedStatelessStalling() async throws -> (Client, StallingSendTransport, InMemoryTransport) { + let client = Client(name: "c", version: "1") + let (clientEnd, serverEnd) = await InMemoryTransport.createConnectedPair() + let stalling = StallingSendTransport(clientEnd) + try await serverEnd.connect() + var incoming = await serverEnd.receive().makeAsyncIterator() + let connecting = Task { try await client.connect(transport: stalling) } + let discover = try JSONDecoder().decode(Value.self, from: try #require(await incoming.next())) + let id = try #require(discover.objectValue?["id"]) + let result = ServerDiscover.Result(supportedVersions: [Version.v2026_07_28], capabilities: .init()) + try await serverEnd.send(try JSONEncoder().encode(["jsonrpc": "2.0", "id": id, "result": try Value(result)] as Value)) + _ = try await connecting.value + return (client, stalling, serverEnd) + } + @Test("At most the configured number of handlers run at once; the rest wait") @available(*, deprecated, message: "Tests the deprecated roots API (SEP-2577)") func concurrencyLimit() async throws { @@ -534,6 +729,361 @@ struct ServerToClientLimitTests { #expect(answered.objectValue?["result"] != nil) await client.disconnect() } + + @Test("Ping flood against a stalled peer caps in-flight sends and recovers after reconnect") + func pingFloodBoundedAndRecovers() async throws { + let (client, stalling, serverEnd, incoming) = try await connectedStalling() + var replies = incoming + + // Control: a small burst against a reading peer is answered normally. + for index in 0..<5 { + try await serverEnd.send(Data(#"{"jsonrpc":"2.0","id":"ok-\#(index)","method":"ping"}"#.utf8)) + } + var answered: Set = [] + while answered.count < 5 { + let reply = try JSONDecoder().decode(Value.self, from: try #require(await replies.next())) + if let id = reply.objectValue?["id"]?.stringValue { answered.insert(id) } + } + #expect(answered.count == 5) + // Wait for Client to clear all 5 ping slots before stalling. + #expect(await eventually { await client.inFlightPingResponseCount == 0 }) + + // Flood 1000 pings while the peer stops reading. + let drained = Flag() + await client.onNotification(LogMessageNotification.self) { _ in await drained.set() } + await stalling.stall() + for index in 0..<1000 { + try await serverEnd.send(Data(#"{"jsonrpc":"2.0","id":"p-\#(index)","method":"ping"}"#.utf8)) + } + try await serverEnd.send( + Data(#"{"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","data":"done"}}"#.utf8)) + #expect(await eventually { await drained.isSet }) + #expect(await eventually { await stalling.inFlightSends >= Client.incomingPingLimit }) + #expect(await stalling.inFlightSends == Client.incomingPingLimit) + #expect(await stalling.peakInFlightSends == Client.incomingPingLimit) + #expect(await client.inFlightPingResponseCount == Client.incomingPingLimit) + + // Disconnect cancels parked immediate tasks and frees all draining slots for a fresh connection. + await client.disconnect() + #expect(await eventually { await stalling.inFlightSends == 0 }) + #expect(await eventually { await client.inFlightPingResponseCount == 0 }) + + let (freshServer, freshIncoming) = try await connect(client) + var freshReplies = freshIncoming + try await freshServer.send(Data(#"{"jsonrpc":"2.0","id":"after","method":"ping"}"#.utf8)) + let pong = try JSONDecoder().decode(Value.self, from: try #require(await freshReplies.next())) + #expect(pong.objectValue?["id"] == "after") + #expect(pong.objectValue?["result"] == [:]) + await client.disconnect() + } + + @Test("Backlog-full refusal flood against a stalled peer caps in-flight sends") + func backlogRefusalFloodBounded() async throws { + var configuration = Client.Configuration.handshake + configuration.maxConcurrentServerRequests = 1 + let (client, stalling, serverEnd, _) = try await connectedStalling(configuration: configuration) + let drained = Flag() + await client.onNotification(LogMessageNotification.self) { _ in await drained.set() } + + await stalling.stall() + for index in 0..<1000 { + try await serverEnd.send(Data(#"{"jsonrpc":"2.0","id":"u-\#(index)","method":"unknown/method"}"#.utf8)) + } + try await serverEnd.send( + Data(#"{"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","data":"done"}}"#.utf8)) + #expect(await eventually { await drained.isSet }) + let expected = 1 + Client.incomingRefusalLimit + #expect(await eventually { await stalling.inFlightSends >= expected }) + #expect(await stalling.inFlightSends == expected) + #expect(await stalling.peakInFlightSends == expected) + #expect(await client.inFlightRefusalResponseCount == Client.incomingRefusalLimit) + + await client.disconnect() + #expect(await eventually { await stalling.inFlightSends == 0 }) + #expect(await eventually { await client.inFlightRefusalResponseCount == 0 }) + } + + @Test("Stateless incoming request flood against a stalled peer caps in-flight sends") + func statelessRefusalFloodBounded() async throws { + let (client, stalling, serverEnd) = try await connectedStatelessStalling() + #expect(await client.isStateless) + let drained = Flag() + await client.onNotification(LogMessageNotification.self) { _ in await drained.set() } + + await stalling.stall() + for index in 0..<1000 { + try await serverEnd.send(Data(#"{"jsonrpc":"2.0","id":"s-\#(index)","method":"ping"}"#.utf8)) + } + try await serverEnd.send( + Data(#"{"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","data":"done"}}"#.utf8)) + #expect(await eventually { await drained.isSet }) + #expect(await eventually { await stalling.inFlightSends >= Client.incomingRefusalLimit }) + #expect(await stalling.inFlightSends == Client.incomingRefusalLimit) + #expect(await stalling.peakInFlightSends == Client.incomingRefusalLimit) + + await client.disconnect() + #expect(await eventually { await stalling.inFlightSends == 0 }) + #expect(await eventually { await client.inFlightRefusalResponseCount == 0 }) + } + + @Test("Duplicate-ID refusal flood against a stalled peer caps in-flight sends") + @available(*, deprecated, message: "Tests the deprecated roots API (SEP-2577)") + func duplicateIDRefusalFloodBounded() async throws { + let (client, stalling, serverEnd, _) = try await connectedStalling() + let (release, open) = AsyncStream.makeStream() + let running = Flag() + await client.withRootsHandler { + await running.set() + for await _ in release { break } + return [] + } + try await serverEnd.send(Data(#"{"jsonrpc":"2.0","id":"dup","method":"roots/list"}"#.utf8)) + #expect(await eventually { await running.isSet }) + + let drained = Flag() + await client.onNotification(LogMessageNotification.self) { _ in await drained.set() } + await stalling.stall() + for _ in 0..<1000 { + try await serverEnd.send(Data(#"{"jsonrpc":"2.0","id":"dup","method":"roots/list"}"#.utf8)) + } + try await serverEnd.send( + Data(#"{"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","data":"done"}}"#.utf8)) + #expect(await eventually { await drained.isSet }) + #expect(await eventually { await stalling.inFlightSends >= Client.incomingRefusalLimit }) + #expect(await stalling.inFlightSends == Client.incomingRefusalLimit) + #expect(await stalling.peakInFlightSends == Client.incomingRefusalLimit) + + open.yield() + await client.disconnect() + #expect(await eventually { await stalling.inFlightSends == 0 }) + #expect(await eventually { await client.inFlightRefusalResponseCount == 0 }) + } + + @Test("A refusal burst saturating the refusal pool does not starve ping replies") + @available(*, deprecated, message: "Tests the deprecated roots API (SEP-2577)") + func refusalBurstDoesNotStarvePing() async throws { + let (client, stalling, serverEnd, incoming) = try await connectedStalling() + var replies = incoming + let (release, open) = AsyncStream.makeStream() + let running = Flag() + await client.withRootsHandler { + await running.set() + for await _ in release { break } + return [] + } + try await serverEnd.send(Data(#"{"jsonrpc":"2.0","id":"dup","method":"roots/list"}"#.utf8)) + #expect(await eventually { await running.isSet }) + + // Stall only error responses (refusals) so ping replies can still be delivered. + await stalling.stall { data in + (try? JSONDecoder().decode(Value.self, from: data))?.objectValue?["error"] != nil + } + let drained = Flag() + await client.onNotification(LogMessageNotification.self) { _ in await drained.set() } + for _ in 0..<(Client.incomingRefusalLimit + 20) { + try await serverEnd.send(Data(#"{"jsonrpc":"2.0","id":"dup","method":"roots/list"}"#.utf8)) + } + try await serverEnd.send( + Data(#"{"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","data":"done"}}"#.utf8)) + #expect(await eventually { await drained.isSet }) + #expect(await eventually { await stalling.inFlightSends == Client.incomingRefusalLimit }) + #expect(await client.inFlightRefusalResponseCount == Client.incomingRefusalLimit) + + // Ping still uses its own pool and answers promptly while refusals are saturated. + try await serverEnd.send(Data(#"{"jsonrpc":"2.0","id":"alive","method":"ping"}"#.utf8)) + let pong = try JSONDecoder().decode(Value.self, from: try #require(await replies.next())) + #expect(pong.objectValue?["id"] == "alive") + #expect(pong.objectValue?["result"] == [:]) + + open.yield() + await client.disconnect() + #expect(await eventually { await client.inFlightRefusalResponseCount == 0 }) + #expect(await eventually { await client.inFlightPingResponseCount == 0 }) + } + + @Test("disconnect cancels parked immediate tasks even when transport.disconnect does not unblock send") + func disconnectCancelsImmediateTasksWithoutTransportUnblock() async throws { + let (client, stalling, serverEnd, _) = try await connectedStalling(unblockOnDisconnect: false) + defer { Task { await stalling.releaseAll() } } + + await stalling.stall() + for index in 0..<8 { + try await serverEnd.send(Data(#"{"jsonrpc":"2.0","id":"p-\#(index)","method":"ping"}"#.utf8)) + } + #expect(await eventually { await stalling.inFlightSends == 8 }) + + // StallingSendTransport.disconnect() leaves waiters parked; tasks exit only via task.cancel(). + await client.disconnect() + #expect(await eventually { await stalling.inFlightSends == 0 }) + #expect(await eventually { await client.inFlightPingResponseCount == 0 }) + } + + @Test("Draining immediate ping tasks keep their slots across reconnect until they finish") + func drainingImmediateTasksRetainSlotsAcrossReconnect() async throws { + let (client, serverEnd, _) = try await connected() + let started = Counter() + let (release, open) = AsyncStream.makeStream() + await client.withMethodHandler(Ping.self) { _ in + await started.increment() + // Ignore cancellation until released so tasks remain draining after reconnect. + await Task { for await _ in release { break } }.value + return Empty() + } + + for index in 0.. { + var secondIncoming = await secondServer.receive().makeAsyncIterator() + let initialize = try JSONDecoder().decode(Value.self, from: try #require(await secondIncoming.next())) + let id = try #require(initialize.objectValue?["id"]) + let result = Initialize.Result( + protocolVersion: Version.v2025_11_25, capabilities: .init(), + serverInfo: .init(name: "s2", version: "1"), instructions: nil) + try await secondServer.send( + try JSONEncoder().encode(["jsonrpc": "2.0", "id": id, "result": try Value(result)] as Value)) + _ = try await secondIncoming.next() // notifications/initialized + await reconnected.set() + return try JSONDecoder().decode(Value.self, from: try #require(await secondIncoming.next())) + } + + let wasCancelledAfterReconnect = Flag() + let handlerCompleted = Flag() + await client.withMethodHandler(Ping.self) { _ in + try await client.connect(transport: secondClientEnd) + if Task.isCancelled { await wasCancelledAfterReconnect.set() } + await handlerCompleted.set() + return Empty() + } + + try await firstServer.send(Data(#"{"jsonrpc":"2.0","id":"reconn","method":"ping"}"#.utf8)) + #expect(await eventually { await reconnected.isSet }) + #expect(await eventually { await handlerCompleted.isSet }) + #expect(await !wasCancelledAfterReconnect.isSet) + #expect(await eventually { await client.inFlightPingResponseCount == 0 }) + + // Verify the new connection is active and answers pings normally. + await client.withMethodHandler(Ping.self) { _ in Empty() } + try await secondServer.send(Data(#"{"jsonrpc":"2.0","id":"on-second","method":"ping"}"#.utf8)) + let secondReply = try await responder.value + #expect(secondReply.objectValue?["id"] == "on-second") + #expect(secondReply.objectValue?["result"] == [:]) + await client.disconnect() + } + + @Test("Same-connection unstall recovers slots and re-arms the drop warning even with an active ping task") + func sameConnectionUnstallRecoversAndRearmsDropWarning() async throws { + let recorder = WarningLogRecorder() + let (client, stalling, serverEnd, incoming) = try await connectedStalling(logger: recorder.makeLogger()) + var replies = incoming + + // Hold one custom Ping task open for the duration of both bursts so inFlightPingResponseCount + // never hits 0 between bursts (verifying hysteresis re-arming at <= limit / 2). + let (releaseSlow, openSlow) = AsyncStream.makeStream() + let slowStarted = Flag() + let holdNextPing = Flag() + await holdNextPing.set() + await client.withMethodHandler(Ping.self) { _ in + if await holdNextPing.isSet { + await slowStarted.set() + for await _ in releaseSlow { break } + } + return Empty() + } + try await serverEnd.send(Data(#"{"jsonrpc":"2.0","id":"slow","method":"ping"}"#.utf8)) + #expect(await eventually { await slowStarted.isSet }) + // Reset handler to default fast ping for subsequent bursts while "slow" stays active. + await client.withMethodHandler(Ping.self) { _ in Empty() } + + let burst1Drained = Flag() + let burst2Drained = Flag() + let burstCount = Counter() + await client.onNotification(LogMessageNotification.self) { _ in + await burstCount.increment() + if await burstCount.value == 1 { + await burst1Drained.set() + } else { + await burst2Drained.set() + } + } + + // Burst 1: 63 more pings fill the cap (with "slow" holding 1); excess are dropped with 1 warning. + let remaining = Client.incomingPingLimit - 1 + await stalling.stall() + for index in 0..<(remaining + 40) { + try await serverEnd.send(Data(#"{"jsonrpc":"2.0","id":"b1-\#(index)","method":"ping"}"#.utf8)) + } + try await serverEnd.send( + Data(#"{"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","data":"b1"}}"#.utf8)) + #expect(await eventually { await burst1Drained.isSet }) + #expect(await eventually { await stalling.inFlightSends == remaining }) + #expect(await client.inFlightPingResponseCount == Client.incomingPingLimit) + #expect(recorder.warnings.count == 1) + + // Unstall on the same connection: the 63 parked pings complete and inFlightPingResponseCount drops to 1. + await stalling.unstall() + var burst1Replies = 0 + while burst1Replies < remaining { + _ = try #require(await replies.next()) + burst1Replies += 1 + } + #expect(await eventually { await client.inFlightPingResponseCount == 1 }) + + // A fresh ping on the same connection succeeds after recovery. + try await serverEnd.send(Data(#"{"jsonrpc":"2.0","id":"mid","method":"ping"}"#.utf8)) + let midReply = try JSONDecoder().decode(Value.self, from: try #require(await replies.next())) + #expect(midReply.objectValue?["id"] == "mid") + #expect(await eventually { await client.inFlightPingResponseCount == 1 }) + + // Burst 2: drop warning re-armed despite "slow" remaining active, so a 2nd warning logs once. + await stalling.stall() + for index in 0..<(remaining + 40) { + try await serverEnd.send(Data(#"{"jsonrpc":"2.0","id":"b2-\#(index)","method":"ping"}"#.utf8)) + } + try await serverEnd.send( + Data(#"{"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","data":"b2"}}"#.utf8)) + #expect(await eventually { await burst2Drained.isSet }) + #expect(await eventually { await stalling.inFlightSends == remaining }) + #expect(recorder.warnings.count == 2) + + openSlow.yield() + await client.disconnect() + #expect(await eventually { await stalling.inFlightSends == 0 }) + #expect(await eventually { await client.inFlightPingResponseCount == 0 }) + } } @Suite("Batches", .timeLimit(.minutes(2))) @@ -549,8 +1099,8 @@ struct BatchTests { try await client.connect(transport: clientEnd) #expect(await client.isStateless) - nonisolated(unsafe) var era: Task? - nonisolated(unsafe) var confirm: Task? + var era: Task? + var confirm: Task? try await client.withBatch { batch in era = try await batch.addRequest(CallTool.request(.init(name: "era"))) confirm = try await batch.addRequest(CallTool.request(.init(name: "confirm"))) @@ -571,7 +1121,7 @@ struct BatchTests { let client = Client(name: "c", version: "1", configuration: .handshake) try await client.connect(transport: recorder) - nonisolated(unsafe) var tasks: [Task] = [] + var tasks: [Task] = [] try await client.withBatch { batch in for _ in 0..<3 { tasks.append(try await batch.addRequest(CallTool.request(.init(name: "era")))) @@ -595,7 +1145,7 @@ struct BatchTests { let client = Client(name: "c", version: "1", configuration: .handshake) try await client.connect(transport: clientEnd) - nonisolated(unsafe) var added: Task? + var added: Task? await #expect(throws: Stop.self) { try await client.withBatch { batch in added = try await batch.addRequest(CallTool.request(.init(name: "era"))) @@ -629,7 +1179,7 @@ struct BatchTests { await transport.setFailSend(true) - nonisolated(unsafe) var added: [Task] = [] + var added: [Task] = [] await #expect(throws: MCPError.self) { try await client.withBatch { batch in added.append(try await batch.addRequest(Ping.request())) @@ -649,6 +1199,253 @@ struct BatchTests { } await client.disconnect() } + + /// A handshake client connected to a server with a `square` tool and a + /// `greeting` prompt, the ones the `withBatch` doc examples use. + private func connectDocExampleServer() async throws -> (Client, Server) { + let server = Server(name: "s", version: "1", capabilities: .init(prompts: .init(), tools: .init())) + await server.withMethodHandler(CallTool.self) { params in + let n = params.arguments?["n"]?.intValue ?? 0 + return .init(content: [.text(text: "\(n * n)")]) + } + await server.withMethodHandler(GetPrompt.self) { _ in + .init(description: "A greeting", messages: [.user("Hello")]) + } + let (clientEnd, serverEnd) = await InMemoryTransport.createConnectedPair() + try await server.start(transport: serverEnd) + let client = Client(name: "c", version: "1", configuration: .handshake) + try await client.connect(transport: clientEnd) + return (client, server) + } + + /// A handshake client on a `MockTransport` whose `initialize` is answered. + private func connectMockClient() async throws -> (Client, MockTransport) { + let transport = MockTransport() + let client = Client(name: "c", version: "1", configuration: .handshake) + try await connectAnsweringInitialize(client, over: transport) + return (client, transport) + } + + // Both examples are copied from the doc comment of `Client.withBatch` in + // `Client.swift`; keep them in sync. + @Test("The withBatch doc examples compile and run without nonisolated(unsafe)") + func docExamples() async throws { + let (client, server) = try await connectDocExampleServer() + var output: [String] = [] + func print(_ line: String) { output.append(line) } + + // Example 1 + let tasks = try await client.withBatch { batch in + var tasks: [Task] = [] + for i in 0..<10 { + tasks.append(try await batch.addRequest( + CallTool.request(.init(name: "square", arguments: ["n": .int(i)])))) + } + return tasks + } + for (index, task) in tasks.enumerated() { + do { + print("\(index): \(try await task.value.content)") + } catch { + print("\(index) failed: \(error)") + } + } + + // Example 2 + var pingTask: Task? + var promptTask: Task? + try await client.withBatch { batch in + pingTask = try await batch.addRequest(Ping.request()) + promptTask = try await batch.addRequest(GetPrompt.request(.init(name: "greeting"))) + } + _ = try await pingTask?.value + if let prompt = try await promptTask?.value { + print(prompt.description ?? "No description") + } + + #expect(tasks.count == 10) + #expect(output.count == 11) + for (index, task) in tasks.enumerated() { + #expect(text(try await task.value) == "\(index * index)") + #expect(output[index].hasPrefix("\(index): ")) + #expect(output[index].contains("\(index * index)")) + } + #expect(output.last == "A greeting") + #expect(try await #require(promptTask).value.description == "A greeting") + await client.disconnect() + await server.stop() + } + + @Test("withBatch returns the value of its body") + @available(*, deprecated, message: "Uses the deprecated sampling and logging APIs (SEP-2577)") + func returnsBodyValue() async throws { + let server = await makeServer() + let (clientEnd, serverEnd) = await InMemoryTransport.createConnectedPair() + try await server.start(transport: serverEnd) + let client = Client(name: "c", version: "1", configuration: .handshake) + try await client.connect(transport: clientEnd) + + let tasks = try await client.withBatch { batch in + [ + try await batch.addRequest(CallTool.request(.init(name: "era"))), + try await batch.addRequest(CallTool.request(.init(name: "era"))), + ] + } + #expect(tasks.count == 2) + for task in tasks { + #expect(text(try await task.value) == "handshake") + } + await client.disconnect() + await server.stop() + } + + @Test("The value of a single-expression body can be discarded") + func discardedBodyValue() async throws { + let (client, transport) = try await connectMockClient() + + // The body returns the task; without `_ =` this compiles with no + // "result unused" warning. + try await client.withBatch { try await $0.addRequest(Ping.request()) } + + // initialize, notifications/initialized, and the batch + #expect(await transport.sentData.count == 3) + let batch = try JSONDecoder().decode(Value.self, from: try #require(await transport.sentData.last)) + #expect(batch.arrayValue?.map { $0.objectValue?["method"] } == [.string(Ping.name)]) + await client.disconnect() + } + + /// Adds requests to a batch from its own isolation. + private actor BatchCaller { + private(set) var added: [Task] = [] + + func addPings(_ count: Int, to client: Client) async throws { + try await client.withBatch { batch in + for _ in 0...self) { group in + for _ in 0..<4 { + group.addTask { try await batch.addRequest(CallTool.request(.init(name: "era"))) } + } + var tasks: [Task] = [] + for try await task in group { tasks.append(task) } + return tasks + } + } + for task in tasks { + #expect(text(try await task.value) == "handshake") + } + let arrays = await recorder.sent.compactMap(\.arrayValue) + #expect(arrays.map(\.count) == [4]) + await client.disconnect() + await server.stop() + } + + @Test("A batch whose body returns normally after a reconnect fails with connectionClosed and sends nothing") + func normalReturnAfterReconnect() async throws { + let firstServer = Server(name: "s1", version: "1") + let (firstClientEnd, firstServerEnd) = await InMemoryTransport.createConnectedPair() + try await firstServer.start(transport: firstServerEnd) + let firstRecorder = RecordingTransport(firstClientEnd) + + let secondServer = Server(name: "s2", version: "1") + let (secondClientEnd, secondServerEnd) = await InMemoryTransport.createConnectedPair() + try await secondServer.start(transport: secondServerEnd) + let secondRecorder = RecordingTransport(secondClientEnd) + + let client = Client(name: "c", version: "1", configuration: .handshake) + try await client.connect(transport: firstRecorder) + + var added: Task? + await #expect(throws: MCPError.connectionClosed) { + try await client.withBatch { batch in + added = try await batch.addRequest(Ping.request()) + // Reconnect while the batch body is still open, then return normally. + try await client.connect(transport: secondRecorder) + } + } + + let addedTask = try #require(added) + let taskResult = await outcome(within: .seconds(5)) { try await addedTask.value } + #expect(!taskResult.didTimeOut, "Request added before reconnect never completed") + #expect(taskResult.mcpError == .internalError("Client disconnected")) + #expect(await firstRecorder.sent.compactMap(\.arrayValue).isEmpty) + #expect(await secondRecorder.sent.compactMap(\.arrayValue).isEmpty) + + await client.disconnect() + await firstServer.stop() + await secondServer.stop() + } } private let invalidStreamMessages: [(String, Int, Value)] = [ diff --git a/Tests/MCPTests/ResourceTests.swift b/Tests/MCPTests/ResourceTests.swift index 4c08d669..de99941e 100644 --- a/Tests/MCPTests/ResourceTests.swift +++ b/Tests/MCPTests/ResourceTests.swift @@ -61,8 +61,7 @@ struct ResourceTests { #expect(decoded.uri == "file://test.txt") #expect(decoded.mimeType == "text/plain") - #expect(decoded.text == "Hello, world!") - #expect(decoded.blob == nil) + #expect(decoded.body == .text("Hello, world!")) } @Test("Resource.Content binary initialization and encoding") @@ -78,8 +77,7 @@ struct ResourceTests { #expect(decoded.uri == "file://test.bin") #expect(decoded.mimeType == "application/octet-stream") - #expect(decoded.text == nil) - #expect(decoded.blob == binaryData.base64EncodedString()) + #expect(decoded.body == .blob(binaryData)) } @Test("ListResources parameters validation") @@ -158,6 +156,18 @@ struct ResourceTests { #expect(params.uri == "file://test.txt") } + @Test("resources/subscribe and resources/unsubscribe parameters encode as the uri alone") + func testSubscriptionParametersWire() throws { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + let subscribe = try encoder.encode(ResourceSubscribe.Parameters(uri: "test://a")) + let unsubscribe = try encoder.encode(ResourceUnsubscribe.Parameters(uri: "test://a")) + #expect(String(decoding: subscribe, as: UTF8.self) == #"{"uri":"test://a"}"#) + #expect(String(decoding: unsubscribe, as: UTF8.self) == #"{"uri":"test://a"}"#) + let decoded = try JSONDecoder().decode(ResourceUnsubscribe.Parameters.self, from: unsubscribe) + #expect(decoded == ResourceUnsubscribe.Parameters(uri: "test://a")) + } + @Test("ResourceUpdatedNotification parameters validation") func testResourceUpdatedNotification() throws { let params = ResourceUpdatedNotification.Parameters(uri: "file://test.txt") @@ -170,3 +180,176 @@ struct ResourceTests { #expect(ResourceListChangedNotification.name == "notifications/resources/list_changed") } } + +@Suite("Base64 payloads") +struct Base64PayloadTests { + @Test( + "Lenient base64 decodes what other SDKs send", + arguments: [ + ("aGk=", "hi"), ("aGk", "hi"), ("aG\nk=", "hi"), (" aGk= ", "hi"), ("aGVs\r\nbG8=", "hello"), + ("YR==", "a"), ("", ""), ("YQ==\n", "a"), ("YWJj\r\nZGVm", "abcdef"), ("\tYQ\u{0C}==", "a"), + ]) + func lenientDecode(encoded: String, decoded: String) throws { + #expect(Data(lenientBase64Encoded: encoded) == Data(decoded.utf8)) + } + + // Foundation disagrees between Darwin and Linux on "====" (one zero byte or + // empty) and on "YQ==YQ==" with .ignoreUnknownCharacters (one byte or nil); + // the grammar check refuses both on every platform. + @Test( + "Lenient base64 refuses what is not base64", + arguments: ["a", "YQ=", "====", "aG=k", "aGk=!", "-_-_", "YQ==YQ==", "aGk=\u{00A0}", "YQ===", "=", "aGk=="]) + func lenientRefuse(encoded: String) { + #expect(Data(lenientBase64Encoded: encoded) == nil) + } + + @Test("Lenient base64 accepts a Substring") + func substring() { + let header = "data:;base64,aGk" + let payload = header[header.index(after: header.firstIndex(of: ",")!)...] + #expect(Data(lenientBase64Encoded: payload) == Data("hi".utf8)) + } + + @Test("Base64 encodes standard and padded, without line breaks") + func strictEncode() throws { + let long = try wireString(Resource.Content.binary(Data(repeating: 0x01, count: 60), uri: "u")) + let blob = try #require(try JSONDecoder().decode([String: String].self, from: Data(long.utf8))["blob"]) + #expect(blob.count == 80) + #expect(!blob.contains("\n")) + #expect(!long.contains("\\n")) + #expect(try wireString(Resource.Content.binary(Data([0xFF, 0xFE, 0xFD, 0x00]), uri: "u")).contains(#""blob":"//79AA==""#)) + } +} + +@Suite("Resource contents body") +struct ResourceContentsBodyTests { + private func decode(_ json: String) throws -> Resource.Content { + try JSONDecoder().decode(Resource.Content.self, from: Data(json.utf8)) + } + + @Test("A text item encodes text and no blob") + func textGolden() throws { + let content = Resource.Content.text("hi", uri: "file:///a.txt", mimeType: "text/plain") + #expect(try wireString(content) == #"{"mimeType":"text/plain","text":"hi","uri":"file:///a.txt"}"#) + } + + @Test("A binary item encodes standard padded base64 in blob") + func binaryGolden() throws { + let content = Resource.Content.binary(Data([0xFF, 0xFE, 0xFD, 0x00]), uri: "file:///b.bin") + #expect(try wireString(content) == #"{"blob":"//79AA==","uri":"file:///b.bin"}"#) + #expect(try wireString(Resource.Content.binary(Data(), uri: "u")) == #"{"blob":"","uri":"u"}"#) + } + + @Test("The body initializer and the factories make the same item") + func bodyInitializer() throws { + let meta = Metadata(additionalFields: ["vendor.example/k": "v"]) + let text = Resource.Content(uri: "u", mimeType: "text/plain", body: .text("hi"), _meta: meta) + #expect(text == .text("hi", uri: "u", mimeType: "text/plain", _meta: meta)) + let blob = Resource.Content(uri: "u", body: .blob(Data([1]))) + #expect(blob == .binary(Data([1]), uri: "u")) + #expect(blob.mimeType == nil) + #expect(blob._meta == nil) + #expect(try wireString(text) == #"{"_meta":{"vendor.example/k":"v"},"mimeType":"text/plain","text":"hi","uri":"u"}"#) + } + + @Test("Contents decode to their body") + func decodeBody() throws { + #expect(try decode(#"{"uri":"u","blob":"aGk="}"#).body == .blob(Data("hi".utf8))) + #expect(try decode(#"{"uri":"u","text":"","blob":null}"#).body == .text("")) + #expect(try decode(#"{"uri":"u","text":null,"blob":"aGk="}"#).body == .blob(Data("hi".utf8))) + #expect(try decode(#"{"uri":"u","blob":""}"#).body == .blob(Data())) + #expect(try decode(#"{"uri":"u","blob":"aG\nk"}"#).body == .blob(Data("hi".utf8))) + } + + @Test( + "Contents with neither, both, or a non-base64 blob fail", + arguments: [ + (#"{"uri":"u"}"#, "text"), (#"{"uri":"u","blob":null}"#, "text"), + (#"{"uri":"u","text":"a","blob":"aGk="}"#, "blob"), (#"{"uri":"u","blob":"a"}"#, "blob"), + (#"{"uri":"u","blob":"aGk=!"}"#, "blob"), (#"{"uri":"u","blob":"===="}"#, "blob"), + (#"{"uri":"u","blob":"-_-_"}"#, "blob"), + ]) + func malformed(json: String, key: String) throws { + let error = try #require(throws: DecodingError.self) { try decode(json) } + guard case .dataCorrupted = error else { + Issue.record("Expected dataCorrupted, got \(error)") + return + } + #expect(codingPath(of: error) == [key]) + } + + @Test("A blob error names the key, not the payload") + func errorWithoutPayload() throws { + let error = try #require(throws: DecodingError.self) { try decode(#"{"uri":"u","blob":"secret!"}"#) } + guard case .dataCorrupted(let context) = error else { + Issue.record("Expected dataCorrupted, got \(error)") + return + } + #expect(context.debugDescription == "blob is not base64") + } + + @Test("An embedded resource without text or blob fails its tool result") + func embeddedFails() throws { + let json = #"{"content":[{"type":"resource","resource":{"uri":"u"}}]}"# + let error = try #require(throws: DecodingError.self) { + try JSONDecoder().decode(CallTool.Result.self, from: Data(json.utf8)) + } + #expect(codingPath(of: error) == ["content", "0", "resource", "text"]) + } + + @Test("Both bodies round-trip", arguments: [Resource.Content.Body.text("é\n"), .blob(Data([0, 1, 0xFF]))]) + func roundTrip(body: Resource.Content.Body) throws { + let content = Resource.Content(uri: "file:///x", mimeType: "x/y", body: body) + #expect(try JSONDecoder().decode(Resource.Content.self, from: JSONEncoder().encode(content)) == content) + } + + @Test("Deprecated 0.12.1 Resource.Content and content-block shims forward cleanly") + @available(*, deprecated, message: "Tests the deprecated 0.12.1 compatibility shims") + func deprecatedContentShims() { + let textResource = Resource.Content.text("hello", uri: "file:///a.txt") + #expect(textResource.text == "hello") + #expect(textResource.blob == nil) + + let blobResource = Resource.Content.binary(Data("hi".utf8), uri: "file:///a.bin") + #expect(blobResource.text == nil) + #expect(blobResource.blob == "aGk=") + + let bytes = Data("hi".utf8) + let annotations = Resource.Annotations(audience: [.user]) + let meta = Metadata(additionalFields: ["vendor.example/k": "v"]) + + let toolImage: Tool.Content = .image(data: "aGk=", mimeType: "image/png", annotations: annotations, _meta: meta) + #expect(toolImage == .image(bytes, mimeType: "image/png", annotations: annotations, _meta: meta)) + let toolImageDefault: Tool.Content = .image(data: "aGk=", mimeType: "image/png") + #expect(toolImageDefault == .image(bytes, mimeType: "image/png")) + let toolImageInvalid: Tool.Content = .image(data: "!!!", mimeType: "image/png") + #expect(toolImageInvalid == .image(Data(), mimeType: "image/png")) + + let toolAudio: Tool.Content = .audio(data: "aGk=", mimeType: "audio/wav", annotations: annotations, _meta: meta) + #expect(toolAudio == .audio(bytes, mimeType: "audio/wav", annotations: annotations, _meta: meta)) + let toolAudioInvalid: Tool.Content = .audio(data: "!!!", mimeType: "audio/wav") + #expect(toolAudioInvalid == .audio(Data(), mimeType: "audio/wav")) + + let promptImage: Prompt.Message.Content = .image(data: "aGk=", mimeType: "image/png") + #expect(promptImage == .image(bytes, mimeType: "image/png")) + let promptAudio: Prompt.Message.Content = .audio(data: "aGk=", mimeType: "audio/wav") + #expect(promptAudio == .audio(bytes, mimeType: "audio/wav")) + let promptInvalid: Prompt.Message.Content = .image(data: "!!!", mimeType: "image/png") + #expect(promptInvalid == .image(Data(), mimeType: "image/png")) + + let samplingContentImage: Sampling.Message.Content = .image(data: "aGk=", mimeType: "image/png") + #expect(samplingContentImage == .image(bytes, mimeType: "image/png")) + let samplingContentAudio: Sampling.Message.Content = .audio(data: "aGk=", mimeType: "audio/wav") + #expect(samplingContentAudio == .audio(bytes, mimeType: "audio/wav")) + + let samplingBlockImage: Sampling.Message.Content.ContentBlock = .image(data: "aGk=", mimeType: "image/png") + #expect(samplingBlockImage == .image(bytes, mimeType: "image/png")) + let samplingBlockAudio: Sampling.Message.Content.ContentBlock = .audio(data: "aGk=", mimeType: "audio/wav") + #expect(samplingBlockAudio == .audio(bytes, mimeType: "audio/wav")) + + let toolResultBlockImage: Sampling.ToolResultContent.ContentBlock = .image(data: "aGk=", mimeType: "image/png") + #expect(toolResultBlockImage == .image(bytes, mimeType: "image/png")) + let toolResultBlockAudio: Sampling.ToolResultContent.ContentBlock = .audio(data: "aGk=", mimeType: "audio/wav") + #expect(toolResultBlockAudio == .audio(bytes, mimeType: "audio/wav")) + } +} diff --git a/Tests/MCPTests/ResponseTests.swift b/Tests/MCPTests/ResponseTests.swift index 2b6b55fc..fd4c9f42 100644 --- a/Tests/MCPTests/ResponseTests.swift +++ b/Tests/MCPTests/ResponseTests.swift @@ -115,4 +115,57 @@ struct ResponseTests { #expect(Bool(false), "Expected success result") } } + + /// The coding path of the error that decoding `json` as `Response` throws. + private func failurePath(_ type: M.Type, _ json: String) -> [String]? { + do { + _ = try JSONDecoder().decode(Response.self, from: json.data(using: .utf8)!) + return nil + } catch let error as DecodingError { + switch error { + case .typeMismatch(_, let context), .valueNotFound(_, let context), .dataCorrupted(let context): + return context.codingPath.map { $0.intValue.map(String.init) ?? $0.stringValue } + case .keyNotFound(let key, let context): + return (context.codingPath + [key]).map { $0.intValue.map(String.init) ?? $0.stringValue } + @unknown default: + return [] + } + } catch { + return [] + } + } + + @Test("A response whose result doesn't decode reports where") + func resultErrorPath() throws { + let path = try #require( + failurePath(ListTools.self, #"{"jsonrpc":"2.0","id":1,"result":{"tools":[{"name":1}]}}"#)) + #expect(path.first == "result") + #expect(path.contains("tools")) + } + + @Test("A response whose error doesn't decode reports where") + func errorErrorPath() throws { + let path = try #require( + failurePath(ListTools.self, #"{"jsonrpc":"2.0","id":1,"error":{"code":"bad","message":"m"}}"#)) + #expect(path.first == "error") + } + + @Test("A response with neither result nor error throws dataCorrupted at the root path") + func missingResultAndErrorThrowsDataCorrupted() throws { + let data = #"{"jsonrpc":"2.0","id":1}"#.data(using: .utf8)! + do { + _ = try JSONDecoder().decode(Response.self, from: data) + Issue.record("Expected DecodingError.dataCorrupted") + } catch DecodingError.dataCorrupted(let context) { + #expect(context.codingPath.isEmpty) + #expect(context.debugDescription == "Invalid response") + } + } + + @Test("A response with a null result reports result in its coding path") + func nullResultErrorPath() throws { + let path = try #require( + failurePath(ListTools.self, #"{"jsonrpc":"2.0","id":1,"result":null}"#)) + #expect(path == ["result"]) + } } diff --git a/Tests/MCPTests/RootsTests.swift b/Tests/MCPTests/RootsTests.swift index 19dedb9d..6d695579 100644 --- a/Tests/MCPTests/RootsTests.swift +++ b/Tests/MCPTests/RootsTests.swift @@ -483,4 +483,41 @@ struct RootsTests { await server.stop() await client.disconnect() } + + @Test("Cancelling the task awaiting listRoots withdraws the request", .timeLimit(.minutes(1))) + @available(*, deprecated, message: "Tests the deprecated roots API (SEP-2577)") + func testCancellingListRootsWithdrawsRequest() async throws { + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + let server = Server(name: "test-server", version: "1.0.0") + let client = Client( + name: "test-client", version: "1.0.0", + capabilities: Client.Capabilities(roots: Client.Capabilities.Roots(listChanged: true)), + configuration: .handshake) + let started = Flag() + let handlerCancelled = Flag() + await client.withRootsHandler { + await started.set() + do { + try await Task.sleep(for: .seconds(60)) + } catch { + if error is CancellationError { await handlerCancelled.set() } + throw error + } + return [Root(uri: "file:///late")] + } + try await server.start(transport: serverTransport) + try await client.connect(transport: clientTransport) + + let listing = Task { try await server.listRoots() } + try #require(await eventually { await started.isSet }) + listing.cancel() + + let result = await outcome(within: .seconds(30)) { try await listing.value } + #expect(result.error is CancellationError, "got \(result)") + // The client got notifications/cancelled and cancelled its handler. + #expect(await eventually { await handlerCancelled.isSet }) + + await client.disconnect() + await server.stop() + } } diff --git a/Tests/MCPTests/SamplingTests.swift b/Tests/MCPTests/SamplingTests.swift index 2d872731..beeed107 100644 --- a/Tests/MCPTests/SamplingTests.swift +++ b/Tests/MCPTests/SamplingTests.swift @@ -34,14 +34,14 @@ struct SamplingTests { // Test image content let imageMessage: Sampling.Message = .assistant( - .image(data: "base64imagedata", mimeType: "image/png")) + .image(Data("image bytes".utf8), mimeType: "image/png")) let imageData = try encoder.encode(imageMessage) let decodedImageMessage = try decoder.decode(Sampling.Message.self, from: imageData) #expect(decodedImageMessage.role == .assistant) if case .single(.image(let data, let mimeType)) = decodedImageMessage.content { - #expect(data == "base64imagedata") + #expect(data == Data("image bytes".utf8)) #expect(mimeType == "image/png") } else { #expect(Bool(false), "Expected image content") @@ -241,12 +241,12 @@ struct SamplingTests { // Test image content JSON format let imageContent: Sampling.Message.Content = .image( - data: "base64data", mimeType: "image/png") + Data([0x89, 0x50, 0x4E, 0x47]), mimeType: "image/png") let imageData = try encoder.encode(imageContent) let imageJSON = String(data: imageData, encoding: .utf8)! #expect(imageJSON.contains("\"type\":\"image\"")) - #expect(imageJSON.contains("\"data\":\"base64data\"")) + #expect(imageJSON.contains("\"data\":\"iVBORw==\"")) #expect(imageJSON.contains("\"mimeType\":\"image\\/png\"")) } @@ -297,10 +297,10 @@ struct SamplingTests { // Test with image content let imageMessage: Sampling.Message = .user( - .image(data: "base64data", mimeType: "image/png")) + .image(Data("image bytes".utf8), mimeType: "image/png")) #expect(imageMessage.role == .user) if case .single(.image(let data, let mimeType)) = imageMessage.content { - #expect(data == "base64data") + #expect(data == Data("image bytes".utf8)) #expect(mimeType == "image/png") } else { #expect(Bool(false), "Expected image content") @@ -457,7 +457,7 @@ struct SamplingTests { // Pattern 3: Mixed content types let mixedContent: [Sampling.Message] = [ .user("Can you analyze this image?"), - .assistant(.image(data: "analysis_chart_data", mimeType: "image/png")), + .assistant(.image(Data("analysis_chart_data".utf8), mimeType: "image/png")), .user("What does it show?"), .assistant("The chart shows a clear upward trend in sales."), ] @@ -632,8 +632,10 @@ struct SamplingIntegrationTests { let imageMessage: Sampling.Message = .user( .image( - data: - "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==", + Data( + base64Encoded: + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==" + )!, mimeType: "image/png" )) @@ -669,7 +671,7 @@ struct SamplingIntegrationTests { stopReason: .maxTokens, role: .assistant, content: .image( - data: "generated_chart_base64_data_here", + Data("generated chart".utf8), mimeType: "image/png" ) ) @@ -997,6 +999,97 @@ struct SamplingIntegrationTests { #expect(decodedAnalysis == dataAnalysisParams) #expect(decodedCreative == creativeParams) } + + @Test("Cancelling the task awaiting requestSampling withdraws the request", .timeLimit(.minutes(1))) + @available(*, deprecated, message: "Tests the deprecated sampling API (SEP-2577)") + func testCancellingRequestSamplingWithdrawsRequest() async throws { + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + let server = Server(name: "SamplingCancelServer", version: "1.0") + let client = Client( + name: "SamplingCancelClient", version: "1.0", + capabilities: .init(sampling: .init()), configuration: .handshake) + let started = Flag() + let handlerCancelled = Flag() + await client.withSamplingHandler { _ in + await started.set() + do { + try await Task.sleep(for: .seconds(60)) + } catch { + if error is CancellationError { await handlerCancelled.set() } + throw error + } + return CreateSamplingMessage.Result( + model: "test-model", stopReason: .endTurn, role: .assistant, content: .text("late")) + } + try await server.start(transport: serverTransport) + try await client.connect(transport: clientTransport) + + let sampling = Task { try await server.requestSampling(messages: [.user("Hi")], maxTokens: 10) } + try #require(await eventually { await started.isSet }) + sampling.cancel() + + let result = await outcome(within: .seconds(30)) { try await sampling.value } + #expect(result.error is CancellationError, "got \(result)") + // The client got notifications/cancelled and cancelled its handler. + #expect(await eventually { await handlerCancelled.isSet }) + + await client.disconnect() + await server.stop() + } + + @Test("Cancelling requestSampling sends notifications/cancelled for its request", .timeLimit(.minutes(1))) + @available(*, deprecated, message: "Tests the deprecated sampling API (SEP-2577)") + func testCancellingRequestSamplingSendsCancelledNotification() async throws { + let server = Server(name: "SamplingCancelServer", version: "1.0") + let (clientEnd, serverEnd) = await InMemoryTransport.createConnectedPair() + try await server.start(transport: serverEnd) + let peer = RawPeer(clientEnd) + try await peer.start() + try await peer.initialize(capabilities: #"{"sampling":{}}"#) + + let sampling = Task { try await server.requestSampling(messages: [.user("Hi")], maxTokens: 10) } + let request = try #require( + await peer.first { $0.objectValue?["method"]?.stringValue == CreateSamplingMessage.name }) + sampling.cancel() + + let result = await outcome(within: .seconds(30)) { try await sampling.value } + #expect(result.error is CancellationError, "got \(result)") + let cancelled = try #require( + await peer.first { $0.objectValue?["method"]?.stringValue == CancelledNotification.name }) + let params = cancelled.objectValue?["params"]?.objectValue + #expect(params?["requestId"] == request.objectValue?["id"]) + #expect(params?["reason"] == "The server stopped waiting for the response") + + await peer.stop() + await server.stop() + } + + @Test("A request cancelled before it is sent is not sent", .timeLimit(.minutes(1))) + @available(*, deprecated, message: "Tests the deprecated sampling API (SEP-2577)") + func testCancelledRequestSamplingIsNotSent() async throws { + let server = Server(name: "SamplingCancelServer", version: "1.0") + let (clientEnd, serverEnd) = await InMemoryTransport.createConnectedPair() + try await server.start(transport: serverEnd) + let peer = RawPeer(clientEnd) + try await peer.start() + try await peer.initialize(capabilities: #"{"sampling":{}}"#) + + let sampling = Task { + withUnsafeCurrentTask { $0?.cancel() } + return try await server.requestSampling(messages: [.user("Hi")], maxTokens: 10) + } + let result = await outcome(within: .seconds(30)) { try await sampling.value } + #expect(result.error is CancellationError, "got \(result)") + + // Every message the server sent before this ping's answer has arrived. + try await peer.sync("after-cancel") + let methods = await peer.received.compactMap { $0.objectValue?["method"]?.stringValue } + #expect(!methods.contains(CreateSamplingMessage.name)) + #expect(!methods.contains(CancelledNotification.name)) + + await peer.stop() + await server.stop() + } } @Suite("Sampling context inclusion cap", .timeLimit(.minutes(1))) @@ -1143,14 +1236,14 @@ struct Sampling2025_11_25Tests { let decoder = JSONDecoder() let audioMessage: Sampling.Message = .user( - .audio(data: "base64audiodata", mimeType: "audio/mp3")) + .audio(Data("audio bytes".utf8), mimeType: "audio/mp3")) let data = try encoder.encode(audioMessage) let decoded = try decoder.decode(Sampling.Message.self, from: data) #expect(decoded.role == .user) if case .single(.audio(let audioData, let mimeType)) = decoded.content { - #expect(audioData == "base64audiodata") + #expect(audioData == Data("audio bytes".utf8)) #expect(mimeType == "audio/mp3") } else { #expect(Bool(false), "Expected audio content") @@ -1182,9 +1275,9 @@ struct Sampling2025_11_25Tests { let blocks: [Sampling.Message.Content.ContentBlock] = [ .text("Here's an image:"), - .image(data: "imagedata", mimeType: "image/png"), + .image(Data("image bytes".utf8), mimeType: "image/png"), .text("And some audio:"), - .audio(data: "audiodata", mimeType: "audio/mp3") + .audio(Data("audio bytes".utf8), mimeType: "audio/mp3") ] let content = Sampling.Message.Content.multiple(blocks) @@ -1243,3 +1336,77 @@ struct Sampling2025_11_25Tests { #expect(decoded == capabilities) } } + +@Suite("Sampling binary content") +struct SamplingBinaryContentTests { + private let png = Data([0x89, 0x50, 0x4E, 0x47]) + private let pngBlock = #"{"data":"iVBORw==","mimeType":"image/png","type":"image"}"# + + private func message(_ json: String) throws -> Sampling.Message { + try JSONDecoder().decode(Sampling.Message.self, from: Data(json.utf8)) + } + + @Test("Sampling image and audio blocks encode base64 data") + func goldens() throws { + #expect(try wireString(Sampling.Message.user(.image(png, mimeType: "image/png"))) == #"{"content":\#(pngBlock),"role":"user"}"#) + let audio = Sampling.Message.Content.ContentBlock.audio(Data("RIFF".utf8), mimeType: "audio/wav") + #expect(try wireString(audio) == #"{"data":"UklGRg==","mimeType":"audio/wav","type":"audio"}"#) + let multiple = Sampling.Message.assistant(.multiple([.image(png, mimeType: "image/png"), audio])) + #expect( + try wireString(multiple) + == #"{"content":[\#(pngBlock),{"data":"UklGRg==","mimeType":"audio/wav","type":"audio"}],"role":"assistant"}"#) + let wrapped = #"{"role":"user","content":{"type":"image","data":"iVBO\nRw","mimeType":"image/png"}}"# + #expect(try message(wrapped).content == .image(png, mimeType: "image/png")) + } + + @Test("A tool_result block carries image bytes as base64") + func toolResult() throws { + let result = Sampling.ToolResultContent( + toolUseId: "u1", content: [.image(png, mimeType: "image/png"), .audio(Data("RIFF".utf8), mimeType: "audio/wav")]) + let block = Sampling.Message.Content.ContentBlock.toolResult(result) + let audioBlock = #"{"data":"UklGRg==","mimeType":"audio/wav","type":"audio"}"# + #expect( + try wireString(block) + == #"{"content":[\#(pngBlock),\#(audioBlock)],"toolUseId":"u1","type":"tool_result"}"#) + let decoded = try JSONDecoder().decode(Sampling.Message.Content.ContentBlock.self, from: Data(try wireString(block).utf8)) + #expect(decoded == block) + + let bad = #"{"type":"tool_result","toolUseId":"u1","content":[{"type":"audio","data":"%%%","mimeType":"audio/wav"}]}"# + let error = try #require(throws: DecodingError.self) { + try JSONDecoder().decode(Sampling.Message.Content.ContentBlock.self, from: Data(bad.utf8)) + } + #expect(codingPath(of: error) == ["content", "0", "data"]) + } + + @Test("A bad image in a multi-block message reports the base64 error") + func badImageInArray() throws { + let json = #"{"role":"user","content":[{"type":"text","text":"a"},{"type":"image","data":"%%%","mimeType":"image/png"}]}"# + let error = try #require(throws: DecodingError.self) { try message(json) } + guard case .dataCorrupted = error else { + Issue.record("Expected dataCorrupted, got \(error)") + return + } + #expect(codingPath(of: error) == ["content", "1", "data"]) + } + + @Test("A content array with an invalid block reports that block's error") + func invalidBlockInArray() throws { + let json = #"{"role":"user","content":[{"type":"text","text":"a"},{"type":"tool_result"}]}"# + let error = try #require(throws: DecodingError.self) { try message(json) } + if case .typeMismatch = error { Issue.record("The array's error was replaced: \(error)") } + #expect(codingPath(of: error).prefix(2) == ["content", "1"]) + } + + @Test("A content array of one block reads as a single block") + func singleElementArray() throws { + #expect(try message(#"{"role":"user","content":[{"type":"text","text":"a"}]}"#).content == .single(.text("a"))) + #expect(try message(#"{"role":"user","content":{"type":"text","text":"a"}}"#).content == .single(.text("a"))) + #expect(try message(#"{"role":"user","content":[]}"#).content == .multiple([])) + } + + @Test("The image(_:mimeType:) and audio(_:mimeType:) helpers make single blocks") + func helpers() { + #expect(Sampling.Message.Content.image(png, mimeType: "image/png") == .single(.image(png, mimeType: "image/png"))) + #expect(Sampling.Message.Content.audio(png, mimeType: "audio/wav") == .single(.audio(png, mimeType: "audio/wav"))) + } +} diff --git a/Tests/MCPTests/ServerCardTests.swift b/Tests/MCPTests/ServerCardTests.swift index 334a7bae..2a61b97c 100644 --- a/Tests/MCPTests/ServerCardTests.swift +++ b/Tests/MCPTests/ServerCardTests.swift @@ -1,13 +1,11 @@ import Crypto import Foundation +import Synchronization import Testing #if canImport(FoundationNetworking) import FoundationNetworking #endif -#if canImport(Glibc) - import Glibc -#endif @testable import MCP @@ -284,8 +282,7 @@ struct ServerCardValidatorTests { @Test("Both HTTP server transports pass the validator's answers") func transports() async throws { - let pipeline = StandardValidationPipeline(validators: [validator]) - let stateless = StatelessHTTPServerTransport(validationPipeline: pipeline) + let stateless = StatelessHTTPServerTransport(validators: [validator]) let etag = try #require(await stateless.handleRequest(request()).headers[HTTPHeaderName.etag]) #expect(await stateless.handleRequest(request()).statusCode == 200) #expect(await stateless.handleRequest(request(headers: ["If-None-Match": etag])).statusCode == 304) @@ -293,7 +290,7 @@ struct ServerCardValidatorTests { #expect(await stateless.handleRequest(request("HEAD")).statusCode == 200) #expect(await stateless.handleRequest(request("HEAD", headers: ["If-None-Match": etag])).statusCode == 304) - let stateful = StatefulHTTPServerTransport(validationPipeline: pipeline) + let stateful = StatefulHTTPServerTransport(validators: [validator]) #expect(await stateful.handleRequest(request()).statusCode == 200) #expect(await stateful.handleRequest(request(headers: ["If-None-Match": etag])).statusCode == 304) #expect(await stateful.handleRequest(request("OPTIONS")).statusCode == 204) @@ -446,7 +443,7 @@ struct ServerCardValidatorTests { } } #else - @Test("Redirects of a real session are checked before they are followed") + @Test("Redirects of a real session are checked before they are followed", .timeLimit(.minutes(1))) func loopbackRedirects() async throws { let card = try JSONEncoder().encode(validCard) let server = try LoopbackHTTPServer() @@ -466,6 +463,88 @@ struct ServerCardValidatorTests { } #endif + #if !canImport(FoundationNetworking) + /// Records the session and task calls it gets. + final class RecordingSessionDelegate: NSObject, URLSessionTaskDelegate, Sendable { + private let state = Mutex<(invalidated: [ObjectIdentifier], metrics: [URL])>(([], [])) + + var invalidated: [ObjectIdentifier] { state.withLock { $0.invalidated } } + var metricsURLs: [URL] { state.withLock { $0.metrics } } + + func urlSession(_ session: URLSession, didBecomeInvalidWithError error: (any Error)?) { + state.withLock { $0.invalidated.append(ObjectIdentifier(session)) } + } + + func urlSession( + _ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics + ) { + state.withLock { $0.metrics += task.originalRequest?.url.map { [$0] } ?? [] } + } + } + + // The fetch runs in a session of its own when the configuration has + // credentials; the caller's delegate must not learn that it ended. + @Test( + "A fetch with configuration credentials passes its task calls to the session's delegate, but not the end of its own session", + .timeLimit(.minutes(1))) + func delegateOfFetchSession() async throws { + let server = try LoopbackHTTPServer() + defer { server.stop() } + server.routes = ["/card": (200, [:], try JSONEncoder().encode(validCard))] + let configuration = URLSessionConfiguration.ephemeral + configuration.httpAdditionalHeaders = ["Authorization": "Bearer card-token"] + let delegate = RecordingSessionDelegate() + let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) + let url = URL(string: "\(server.baseURL)/card")! + + #expect(try await ServerCard.fetch(from: url, session: session) == validCard) + + #expect(server.requests.first?.headers["authorization"] == "Bearer card-token") + // Its session ended before the fetch returned: the task's calls came, its end didn't. + #expect(delegate.metricsURLs == [url]) + #expect(delegate.invalidated.isEmpty) + // The end of the caller's own session does. + session.finishTasksAndInvalidate() + let deadline = ContinuousClock.now + .seconds(10) + while delegate.invalidated.isEmpty && ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(10)) + } + #expect(delegate.invalidated == [ObjectIdentifier(session)]) + } + #endif + + @Test( + "Credentials of the session's configuration follow a card redirect to the same origin only", + .timeLimit(.minutes(1)), arguments: [false, true]) + func configurationCredentials(crossOrigin: Bool) async throws { + let card = try JSONEncoder().encode(validCard) + let server = try LoopbackHTTPServer() + defer { server.stop() } + let other = try LoopbackHTTPServer() + defer { other.stop() } + let landing = crossOrigin ? other : server + server.routes = ["/card": (302, ["Location": "\(landing.baseURL)/landed"], Data())] + landing.routes["/landed"] = (200, [:], card) + let configuration = URLSessionConfiguration.ephemeral + configuration.httpAdditionalHeaders = [ + "Authorization": "Bearer card-token", "cookie": "sid=card", "X-Config": "kept", + ] + let session = URLSession(configuration: configuration) + defer { session.finishTasksAndInvalidate() } + + #expect(try await ServerCard.fetch(from: URL(string: "\(server.baseURL)/card")!, session: session) == validCard) + + let first = try #require(server.requests.first) + #expect(first.headers["authorization"] == "Bearer card-token") + #expect(first.headers["cookie"] == "sid=card") + let landed = try #require(landing.requests.first { $0.path == "/landed" }) + #expect(landed.headers["authorization"] == (crossOrigin ? nil : "Bearer card-token")) + #expect(landed.headers["cookie"] == (crossOrigin ? nil : "sid=card")) + #expect(landed.headers["x-config"] == "kept") + // The caller's configuration is not changed. + #expect(session.configuration.httpAdditionalHeaders?["Authorization"] as? String == "Bearer card-token") + } + @Test("http is allowed on a loopback host") func loopback() async throws { let session = await serve(body: try JSONEncoder().encode(validCard)) @@ -635,96 +714,4 @@ struct ServerCardValidatorTests { stateLock.withLock { log }?.stop() } } - - #if canImport(FoundationNetworking) - /// An HTTP/1.1 server on every IPv4 address of the host, answering each - /// path with a fixed response, one request per connection. - private final class LoopbackHTTPServer: @unchecked Sendable { - typealias Route = (status: Int, headers: [String: String], body: Data) - - let port: Int - private let socket: Int32 - private let lock = NSLock() - private var paths: [String] = [] - private var table: [String: Route] = [:] - private var stopped = false - - var requested: [String] { lock.withLock { paths } } - var routes: [String: Route] { - get { lock.withLock { table } } - set { lock.withLock { table = newValue } } - } - - init() throws { - let socket = Glibc.socket(AF_INET, Int32(SOCK_STREAM.rawValue), 0) - self.socket = socket - var address = sockaddr_in() - address.sin_family = sa_family_t(AF_INET) - address.sin_addr = in_addr(s_addr: INADDR_ANY) - var length = socklen_t(MemoryLayout.size) - let bound = withUnsafeMutablePointer(to: &address) { pointer in - pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { address in - bind(socket, address, length) == 0 && listen(socket, 16) == 0 - && getsockname(socket, address, &length) == 0 - } - } - guard bound else { - close(socket) - throw URLError(.cannotConnectToHost) - } - port = Int(UInt16(bigEndian: address.sin_port)) - let thread = Thread { [self] in serve() } - thread.start() - } - - /// Stops accepting: a connection wakes the blocked `accept`. - func stop() { - lock.withLock { stopped = true } - let wake = Glibc.socket(AF_INET, Int32(SOCK_STREAM.rawValue), 0) - var address = sockaddr_in() - address.sin_family = sa_family_t(AF_INET) - address.sin_port = UInt16(port).bigEndian - address.sin_addr = in_addr(s_addr: inet_addr("127.0.0.1")) - _ = withUnsafePointer(to: &address) { - $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { - connect(wake, $0, socklen_t(MemoryLayout.size)) - } - } - close(wake) - } - - private func serve() { - defer { close(socket) } - while true { - let connection = accept(socket, nil, nil) - guard connection >= 0, !lock.withLock({ stopped }) else { - if connection >= 0 { close(connection) } - return - } - answer(connection) - close(connection) - } - } - - private func answer(_ connection: Int32) { - var request = Data() - var buffer = [UInt8](repeating: 0, count: 4096) - while request.range(of: Data("\r\n\r\n".utf8)) == nil { - let count = read(connection, &buffer, buffer.count) - guard count > 0 else { return } - request.append(contentsOf: buffer[.. Route? in - paths.append(path) - return table[path] - } ?? (404, [:], Data()) - var head = "HTTP/1.1 \(route.status) Status\r\nContent-Length: \(route.body.count)\r\nConnection: close\r\n" - for (name, value) in route.headers { head += "\(name): \(value)\r\n" } - let response = Data((head + "\r\n").utf8) + route.body - _ = response.withUnsafeBytes { write(connection, $0.baseAddress, response.count) } - } - } - #endif #endif diff --git a/Tests/MCPTests/ServerSentEventParserTests.swift b/Tests/MCPTests/ServerSentEventParserTests.swift index cf4bfe8f..9c8f45ca 100644 --- a/Tests/MCPTests/ServerSentEventParserTests.swift +++ b/Tests/MCPTests/ServerSentEventParserTests.swift @@ -74,6 +74,14 @@ struct ServerSentEventParserTests { } } + @Test("A retry of more digits than Int holds reads as Int.max") + func retryPastIntRange() throws { + // Int64.max is past a 32-bit Int; the others are past a 64-bit one. + for retry in ["9223372036854775807", "9223372036854775808", "99999999999999999999999"] { + #expect(try events("retry: \(retry)\n\n") == [ServerSentEvent(data: "", retry: .max)]) + } + } + @Test("A byte order mark is skipped at the start of the stream only") func byteOrderMark() throws { let bom: [UInt8] = [0xEF, 0xBB, 0xBF] diff --git a/Tests/MCPTests/ServerTests.swift b/Tests/MCPTests/ServerTests.swift index bbe36638..ae0dec22 100644 --- a/Tests/MCPTests/ServerTests.swift +++ b/Tests/MCPTests/ServerTests.swift @@ -4,6 +4,12 @@ import Testing @testable import MCP +#if canImport(System) + import System +#else + @preconcurrency import SystemPackage +#endif + @Suite("Server Tests") struct ServerTests { @Test("Start and stop server") @@ -239,9 +245,8 @@ struct ServerTests { let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() let server = Server(name: "TestServer", version: "1.0") - // Connect transports + // Connect the client's end; server.start connects the server's. try await clientTransport.connect() - try await serverTransport.connect() // Start receiving messages on client side let received = Counter() @@ -383,6 +388,56 @@ struct ServerDefaultHandlerTests { await client.disconnect() await server.stop() } + + // "Kelvin" and "\u{212A}elvin" (KELVIN SIGN): equal as Swift strings, + // different method names on the wire. + private enum KelvinRun: MCP.Method { + static let name = "Kelvin/run" + } + + private enum KelvinSignRun: MCP.Method { + static let name = "\u{212A}elvin/run" + } + + private struct KelvinNote: MCP.Notification { + static let name = "notifications/Kelvin" + struct Parameters: Hashable, Codable, Sendable { let tag: String } + } + + private struct KelvinSignNote: MCP.Notification { + static let name = "notifications/\u{212A}elvin" + typealias Parameters = KelvinNote.Parameters + } + + @Test("A handler answers only its method's exact name, not a canonically equivalent one") + func handlersMatchMethodNamesExactly() async throws { + #expect(KelvinRun.name == KelvinSignRun.name, "the names must be canonically equivalent") + let server = Server(name: "s", version: "1", capabilities: .init(tools: .init())) + await server.withMethodHandler(KelvinRun.self) { _ in Empty() } + let notes = AsyncStream.makeStream() + await server.onNotification(KelvinNote.self) { message in notes.continuation.yield(message.params.tag) } + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + try await server.start(transport: serverTransport) + let client = Client(name: "c", version: "1", configuration: .handshake) + try await client.connect(transport: clientTransport) + + _ = try await client.send(KelvinRun.request(.init())).value + do { + _ = try await client.send(KelvinSignRun.request(.init())).value + Issue.record("A canonically equivalent method name reached the handler") + } catch { + #expect((error as? MCPError)?.code == -32601, "\(error)") + } + + // Notifications are handled in order, so the first one the handler + // sees tells whether the other name reached it. + try await client.notify(KelvinSignNote.message(.init(tag: "equivalent"))) + try await client.notify(KelvinNote.message(.init(tag: "exact"))) + var iterator = notes.stream.makeAsyncIterator() + #expect(await iterator.next() == "exact") + await client.disconnect() + await server.stop() + } } @Suite("Server lifecycle") @@ -574,9 +629,9 @@ struct ServerLifecycleTests { } /// A transport that delivers the messages a test gives it, counts what the -/// server sends, and holds every `httpRequestContext(for:)` call until the +/// server sends, and holds every `httpRequest(for:)` call until the /// test releases it. -private actor ContextGatedTransport: Transport, HTTPContextProviding { +private actor ContextGatedTransport: Transport { nonisolated let logger = Logger(label: "mcp.test.context-gated") { _ in SwiftLogNoOpLogHandler() } private let stream: AsyncThrowingStream private let continuation: AsyncThrowingStream.Continuation @@ -589,14 +644,14 @@ private actor ContextGatedTransport: Transport, HTTPContextProviding { func connect() async throws {} func disconnect() async { continuation.finish() } - func send(_ data: Data) async throws { sentCount += 1 } + func send(_ data: Data, options: TransportSendOptions) async throws { sentCount += 1 } func receive() -> AsyncThrowingStream { stream } func deliver(_ json: String) { continuation.yield(Data(json.utf8)) } - func httpRequestContext(for id: ID) async -> HTTPRequest? { + func httpRequest(for id: ID) async -> HTTPRequest? { await withCheckedContinuation { heldContext = $0 } return nil } @@ -605,7 +660,7 @@ private actor ContextGatedTransport: Transport, HTTPContextProviding { let deadline = ContinuousClock.now.advanced(by: timeout) while heldContext == nil { guard ContinuousClock.now < deadline else { - throw MCPError.internalError("httpRequestContext(for:) was never called") + throw MCPError.internalError("httpRequest(for:) was never called") } try await Task.sleep(for: .milliseconds(5)) } @@ -617,6 +672,764 @@ private actor ContextGatedTransport: Transport, HTTPContextProviding { } } +@Suite("Server completion") +struct ServerCompletionTests { + /// The `Errno` in the ``MCPError/transportError(_:)`` a wait threw. + private static func transportErrno(_ outcome: Outcome) -> Errno? { + guard case .transportError(let error) = outcome.mcpError else { return nil } + return error as? Errno + } + + /// Whether a wait returned, rather than throwing or timing out. + private static func returned(_ outcome: Outcome) -> Bool { + if case .returned = outcome { return true } + return false + } + + @Test("A failed stdio read makes waitUntilCompleted throw transportError with the errno") + func failedStdioReadThrows() async throws { + // A read from a directory fails with EISDIR on Darwin and Linux. + let input = try FileDescriptor.open(FileManager.default.temporaryDirectory.path, .readOnly) + let (reader, output) = try FileDescriptor.pipe() + defer { + try? input.close() + try? reader.close() + try? output.close() + } + let server = Server(name: "s", version: "1") + try await server.start(transport: StdioTransport(input: input, output: output, logger: nil)) + + let outcome = await outcome(within: .seconds(30)) { try await server.waitUntilCompleted() } + // Before the change the wait returned as if standard input had ended. + #expect(Self.transportErrno(outcome) == .isDirectory, "Got \(outcome)") + await server.stop() + } + + @Test("The end of standard input makes waitUntilCompleted return") + func endOfInputReturns() async throws { + let (input, writer) = try FileDescriptor.pipe() + let (reader, output) = try FileDescriptor.pipe() + defer { + try? input.close() + try? reader.close() + try? output.close() + } + let server = Server(name: "s", version: "1") + try await server.start(transport: StdioTransport(input: input, output: output, logger: nil)) + + try writer.close() + let outcome = await outcome(within: .seconds(30)) { try await server.waitUntilCompleted() } + #expect(Self.returned(outcome), "Got \(outcome)") + await server.stop() + } + + @Test("stop() makes a waiter return, though the stream never ends, and so does a later call") + func stopReturns() async throws { + let transport = EndableTransport(mode: .shared, finishesStreamOnDisconnect: false) + let server = Server(name: "s", version: "1") + try await server.start(transport: transport) + let waiting = Task { try await server.waitUntilCompleted() } + #expect(await eventually { await server.completionWaiterCount == 1 }) + + await server.stop() + let result = await outcome(within: .seconds(30)) { try await waiting.value } + #expect(Self.returned(result), "Got \(result)") + let later = await outcome(within: .seconds(30)) { try await server.waitUntilCompleted() } + #expect(Self.returned(later), "Got \(later)") + } + + @Test("stop() over an InMemoryTransport makes a waiter return") + func stopOverInMemoryReturns() async throws { + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + let server = Server(name: "s", version: "1") + try await server.start(transport: serverTransport) + let waiting = Task { try await server.waitUntilCompleted() } + #expect(await eventually { await server.completionWaiterCount == 1 }) + + await server.stop() + let outcome = await outcome(within: .seconds(30)) { try await waiting.value } + #expect(Self.returned(outcome), "Got \(outcome)") + await clientTransport.disconnect() + } + + @Test("An InMemoryTransport's peer disconnecting makes waitUntilCompleted return") + func inMemoryPeerDisconnectReturns() async throws { + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + let server = Server(name: "s", version: "1") + try await server.start(transport: serverTransport) + + // The server's stream finishes with connectionClosed: the peer closed the connection. + await clientTransport.disconnect() + let result = await outcome(within: .seconds(30)) { try await server.waitUntilCompleted() } + #expect(Self.returned(result), "Got \(result)") + await server.stop() + } + + @Test("A stream that throws connectionClosed makes waitUntilCompleted return, for every waiter") + func connectionClosedReturns() async throws { + let transport = EndableTransport(mode: .shared) + let server = Server(name: "s", version: "1") + try await server.start(transport: transport) + let waiting = Task { try await server.waitUntilCompleted() } + #expect(await eventually { await server.completionWaiterCount == 1 }) + + await transport.finishStream(throwing: MCPError.connectionClosed) + let result = await outcome(within: .seconds(30)) { try await waiting.value } + #expect(Self.returned(result), "Got \(result)") + let later = await outcome(within: .seconds(30)) { try await server.waitUntilCompleted() } + #expect(Self.returned(later), "Got \(later)") + await server.stop() + } + + @Test("A stream that throws another transport error makes waitUntilCompleted throw it") + func otherTransportErrorThrows() async throws { + let transport = EndableTransport(mode: .shared) + let server = Server(name: "s", version: "1") + try await server.start(transport: transport) + + await transport.finishStream(throwing: MCPError.transportError(Errno.connectionReset)) + let result = await outcome(within: .seconds(30)) { try await server.waitUntilCompleted() } + #expect(Self.transportErrno(result) == .connectionReset, "Got \(result)") + await server.stop() + } + + @Test("Every waiter gets the stream's error, and later calls throw it at once, also after stop()") + func everyWaiterGetsTheError() async throws { + let transport = EndableTransport(mode: .shared) + let server = Server(name: "s", version: "1") + try await server.start(transport: transport) + let first = Task { try await server.waitUntilCompleted() } + let second = Task { try await server.waitUntilCompleted() } + #expect(await eventually { await server.completionWaiterCount == 2 }) + + await transport.finishStream(throwing: MCPError.internalError("boom")) + for waiter in [first, second] { + let outcome = await outcome(within: .seconds(30)) { try await waiter.value } + #expect(outcome.mcpError == .internalError("boom"), "Got \(outcome)") + } + let later = await outcome(within: .seconds(30)) { try await server.waitUntilCompleted() } + #expect(later.mcpError == .internalError("boom"), "Got \(later)") + + await server.stop() + let afterStop = await outcome(within: .seconds(30)) { try await server.waitUntilCompleted() } + #expect(afterStop.mcpError == .internalError("boom"), "Got \(afterStop)") + } + + @Test("A cancelled waiter keeps waiting until the loop ends, and gets the loop's outcome") + func cancelledWaiterKeepsWaiting() async throws { + let transport = EndableTransport(mode: .shared) + let server = Server(name: "s", version: "1") + try await server.start(transport: transport) + let waiting = Task { try await server.waitUntilCompleted() } + #expect(await eventually { await server.completionWaiterCount == 1 }) + // A caller already cancelled when it calls waits too. + let cancelledFirst = Task { + withUnsafeCurrentTask { $0?.cancel() } + try await server.waitUntilCompleted() + } + #expect(await eventually { await server.completionWaiterCount == 2 }) + + waiting.cancel() + // Before the change the cancelled waiter threw CancellationError at once. + let early = await outcome(within: .milliseconds(250)) { try await waiting.value } + #expect(early.didTimeOut, "Got \(early)") + #expect(await server.completionWaiterCount == 2) + + await transport.finishStream(throwing: MCPError.internalError("later")) + for waiter in [waiting, cancelledFirst] { + let result = await outcome(within: .seconds(30)) { try await waiter.value } + #expect(result.mcpError == .internalError("later"), "Got \(result)") + } + await server.stop() + } + + @Test("The documented run pattern, cancelled, returns only once stop() has ended the listen streams and disconnected") + func cancelledRunPatternWaitsForStop() async throws { + let server = Server( + name: "s", version: "1", capabilities: .init(tools: .init(listChanged: true))) + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + try await server.start(transport: serverTransport) + let client = Client(name: "c", version: "1", configuration: .init(protocolMode: .automatic)) + await client.onNotification(ToolListChangedNotification.self) { _ in } + try await client.connect(transport: clientTransport) + #expect(await eventually { await server.openSubscriptionCount == 1 }) + + let running = Task { + try await withTaskCancellationHandler { + try await server.waitUntilCompleted() + } onCancel: { + Task { await server.stop() } + } + } + #expect(await eventually { await server.completionWaiterCount == 1 }) + running.cancel() + let result = await outcome(within: .seconds(30)) { try await running.value } + #expect(Self.returned(result), "Got \(result)") + + // The server is stopped by then: its listen stream ended and its transport is + // disconnected, so the peer's sends fail. Before the change the wait returned + // before stop() had disconnected. + #expect(await server.openSubscriptionCount == 0) + await #expect(throws: MCPError.connectionClosed) { + try await clientTransport.send(Data("{}".utf8)) + } + await client.disconnect() + } + + @Test("A stop() during another waits for it; the waiter returns only once the transport is disconnected") + func concurrentStopsWaitForDisconnect() async throws { + let transport = EndableTransport(mode: .shared) + let server = Server(name: "s", version: "1") + try await server.start(transport: transport) + let waiting = Task { try await server.waitUntilCompleted() } + #expect(await eventually { await server.completionWaiterCount == 1 }) + + // The first stop() waits in disconnect() until the gate opens. + await transport.holdNextDisconnect() + let firstDone = Flag() + let secondDone = Flag() + let first = Task { + await server.stop() + await firstDone.set() + } + #expect(await eventually { await transport.disconnectCount == 1 }) + let second = Task { + await server.stop() + await secondDone.set() + } + #expect(await eventually { await server.stopWaiterCount == 1 }) + + // Before the change the second stop() found no connection and released the waiter + // while the first one was still disconnecting. + #expect(await server.completionWaiterCount == 1) + #expect(await !firstDone.isSet) + #expect(await !secondDone.isSet) + + await transport.releaseHeldDisconnect() + let result = await outcome(within: .seconds(30)) { try await waiting.value } + #expect(Self.returned(result), "Got \(result)") + await first.value + await second.value + #expect(await server.stopWaiterCount == 0) + + // stop() stays idempotent: a later one has nothing to disconnect. + await server.stop() + #expect(await transport.disconnectCount == 1) + } + + @Test("A wait begun while a restart connects throws start()'s error when connect() fails") + func waitDuringFailedStartThrowsItsError() async throws { + let server = Server(name: "s", version: "1") + let first = EndableTransport(mode: .shared) + try await server.start(transport: first) + await first.finishStream() + let ended = await outcome(within: .seconds(30)) { try await server.waitUntilCompleted() } + #expect(Self.returned(ended), "Got \(ended)") + + let second = EndableTransport(mode: .shared) + await second.holdNextConnect() + let starting = Task { try await server.start(transport: second) } + #expect(await eventually { await second.isConnectHeld }) + // Before the change the wait returned at once with the previous run's outcome. + let waiting = Task { try await server.waitUntilCompleted() } + #expect(await eventually { await server.completionWaiterCount == 1 }) + + await second.releaseHeldConnect(throwing: MCPError.internalError("refused")) + let started = await outcome(within: .seconds(30)) { try await starting.value } + #expect(started.mcpError == .internalError("refused"), "Got \(started)") + let result = await outcome(within: .seconds(30)) { try await waiting.value } + #expect(result.mcpError == .internalError("refused"), "Got \(result)") + await server.stop() + } + + @Test("A wait begun while a restart connects gets the new loop's outcome, not the previous error") + func waitDuringStartGetsTheNewLoopsOutcome() async throws { + let server = Server(name: "s", version: "1") + let first = EndableTransport(mode: .shared) + try await server.start(transport: first) + await first.finishStream(throwing: MCPError.internalError("old")) + let failed = await outcome(within: .seconds(30)) { try await server.waitUntilCompleted() } + #expect(failed.mcpError == .internalError("old"), "Got \(failed)") + await server.stop() + + let second = EndableTransport(mode: .shared) + await second.holdNextConnect() + let starting = Task { try await server.start(transport: second) } + #expect(await eventually { await second.isConnectHeld }) + let waiting = Task { try await server.waitUntilCompleted() } + #expect(await eventually { await server.completionWaiterCount == 1 }) + + await second.releaseHeldConnect() + let started = await outcome(within: .seconds(30)) { try await starting.value } + #expect(Self.returned(started), "Got \(started)") + #expect(await server.completionWaiterCount == 1) + await second.finishStream() + let result = await outcome(within: .seconds(30)) { try await waiting.value } + #expect(Self.returned(result), "Got \(result)") + await server.stop() + } + + @Test("After a failed start(), a wait throws its error, not the previous run's, until the next start()") + func waitAfterFailedStartThrowsItsError() async throws { + let server = Server(name: "s", version: "1") + let first = EndableTransport(mode: .shared) + try await server.start(transport: first) + await first.finishStream(throwing: MCPError.internalError("old")) + let failed = await outcome(within: .seconds(30)) { try await server.waitUntilCompleted() } + #expect(failed.mcpError == .internalError("old"), "Got \(failed)") + await server.stop() + + let second = EndableTransport(mode: .shared) + await second.holdNextConnect() + let starting = Task { try await server.start(transport: second) } + #expect(await eventually { await second.isConnectHeld }) + await second.releaseHeldConnect(throwing: MCPError.internalError("refused")) + let started = await outcome(within: .seconds(30)) { try await starting.value } + #expect(started.mcpError == .internalError("refused"), "Got \(started)") + + for _ in 0..<2 { + let result = await outcome(within: .seconds(30)) { try await server.waitUntilCompleted() } + #expect(result.mcpError == .internalError("refused"), "Got \(result)") + } + + // The next start() begins a new run. + let third = EndableTransport(mode: .shared) + try await server.start(transport: third) + await third.finishStream() + let next = await outcome(within: .seconds(30)) { try await server.waitUntilCompleted() } + #expect(Self.returned(next), "Got \(next)") + await server.stop() + } + + @Test("A stop() while start() connects ends the run normally once disconnected; start() throws") + func stopDuringStartEndsTheRunNormally() async throws { + let server = Server(name: "s", version: "1") + let transport = EndableTransport(mode: .shared) + await transport.holdNextConnect() + let starting = Task { try await server.start(transport: transport) } + #expect(await eventually { await transport.isConnectHeld }) + let waiting = Task { try await server.waitUntilCompleted() } + #expect(await eventually { await server.completionWaiterCount == 1 }) + + // stop() waits in disconnect() while connect() is still pending. + await transport.holdNextDisconnect() + let stopping = Task { await server.stop() } + #expect(await eventually { await transport.disconnectCount == 1 }) + + // connect() succeeds after the stop: start() throws and runs no loop. The waiter + // still waits for the stop() to finish disconnecting. + await transport.releaseHeldConnect() + let started = await outcome(within: .seconds(30)) { try await starting.value } + #expect(started.mcpError == .internalError("Server stopped while starting"), "Got \(started)") + #expect(await server.completionWaiterCount == 1) + #expect(await transport.receiveCallCount == 0) + + await transport.releaseHeldDisconnect() + let result = await outcome(within: .seconds(30)) { try await waiting.value } + #expect(Self.returned(result), "Got \(result)") + await stopping.value + let later = await outcome(within: .seconds(30)) { try await server.waitUntilCompleted() } + #expect(Self.returned(later), "Got \(later)") + } + + @Test("A start() during a stop() waits for it: the stopped run's waiter returns once disconnected") + func startDuringStopWaitsForIt() async throws { + let server = Server(name: "s", version: "1") + let first = EndableTransport(mode: .shared, finishesStreamOnDisconnect: false) + try await server.start(transport: first) + let waiting = Task { try await server.waitUntilCompleted() } + #expect(await eventually { await server.completionWaiterCount == 1 }) + + await first.holdNextDisconnect() + let stopping = Task { await server.stop() } + #expect(await eventually { await first.disconnectCount == 1 }) + let second = EndableTransport(mode: .shared) + let starting = Task { try await server.start(transport: second) } + // Before the change the restart began a new run, and the stopped run's waiter + // waited for that one instead of returning. + #expect(await eventually { await server.stopWaiterCount == 1 }) + #expect(await server.completionWaiterCount == 1) + + await first.releaseHeldDisconnect() + let result = await outcome(within: .seconds(30)) { try await waiting.value } + #expect(Self.returned(result), "Got \(result)") + await stopping.value + let started = await outcome(within: .seconds(30)) { try await starting.value } + #expect(Self.returned(started), "Got \(started)") + + // The new run is waited for: it ends when its stream ends. + let next = Task { try await server.waitUntilCompleted() } + #expect(await eventually { await server.completionWaiterCount == 1 }) + await second.finishStream() + let nextResult = await outcome(within: .seconds(30)) { try await next.value } + #expect(Self.returned(nextResult), "Got \(nextResult)") + await server.stop() + } + + /// A `subscriptions/listen` request at 2026-07-28, with id `listen-1`. + private static let listenRequest = Data( + #"{"jsonrpc":"2.0","id":"listen-1","method":"subscriptions/listen","params":{"notifications":{"toolsListChanged":true},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}"# + .utf8) + + /// A server restarted on `transport` with `connect()` held, and a `stop()` called + /// then and held before it reaches the disconnect. + /// + /// The window is reached by restarting after a run that ended on its own, without + /// `stop()`: that run's listen stream stays open, and `stop()` waits for its result + /// before it disconnects. That leftover state of the run before is a known follow-up, + /// so the tests assert only the outcomes of `start()` and of the wait, not where the + /// result goes. + private struct StopDuringRestart { + let server: Server + let transport: EndableTransport + let starting: Task + let waiting: Task + let stopping: Task + + init() async throws { + let server = Server(name: "s", version: "1", capabilities: .init(tools: .init(listChanged: true))) + let first = EndableTransport(mode: .shared) + try await server.start(transport: first) + await first.deliverFromServer(ServerCompletionTests.listenRequest) + #expect(await eventually { await server.openSubscriptionCount == 1 }) + // Only stop() ends the listen stream: it stays open after the run ends. + await first.finishStream() + let ended = await outcome(within: .seconds(30)) { try await server.waitUntilCompleted() } + #expect(ServerCompletionTests.returned(ended), "Got \(ended)") + + let transport = EndableTransport(mode: .shared) + await transport.holdNextConnect() + let starting = Task { try await server.start(transport: transport) } + #expect(await eventually { await transport.isConnectHeld }) + let waiting = Task { try await server.waitUntilCompleted() } + #expect(await eventually { await server.completionWaiterCount == 1 }) + + // The old stream's result is sent on the current connection: holding it holds + // the stop(). + await transport.holdNextSend() + let stopping = Task { await server.stop() } + #expect(await eventually { await transport.isSendHeld }) + #expect(await transport.disconnectCount == 0) + self.server = server + self.transport = transport + self.starting = starting + self.waiting = waiting + self.stopping = stopping + } + } + + @Test("A stop() still ending the old listen streams while start() connects ends the run; start() throws") + func stopEndingListenStreamsDuringStart() async throws { + let restart = try await StopDuringRestart() + + // connect() succeeds while the stop() still waits for the stream's result. + await restart.transport.releaseHeldConnect() + let started = await outcome(within: .seconds(30)) { try await restart.starting.value } + // Before the change start() saw no stop() yet, ran a loop and returned. + #expect(started.mcpError == .internalError("Server stopped while starting"), "Got \(started)") + #expect(await restart.transport.receiveCallCount == 0) + #expect(await restart.server.completionWaiterCount == 1) + + await restart.transport.releaseHeldSend() + let result = await outcome(within: .seconds(30)) { try await restart.waiting.value } + #expect(Self.returned(result), "Got \(result)") + await restart.stopping.value + #expect(await restart.server.openSubscriptionCount == 0) + let later = await outcome(within: .seconds(30)) { try await restart.server.waitUntilCompleted() } + #expect(Self.returned(later), "Got \(later)") + } + + @Test("A stop() still ending the old listen streams while start() connects ends the run normally when connect() fails") + func stopEndingListenStreamsDuringFailedStart() async throws { + let restart = try await StopDuringRestart() + + await restart.transport.releaseHeldConnect(throwing: MCPError.internalError("refused")) + let started = await outcome(within: .seconds(30)) { try await restart.starting.value } + #expect(started.mcpError == .internalError("refused"), "Got \(started)") + // Before the change the run failed with the error, and the waiter threw it. + #expect(await restart.server.completionWaiterCount == 1) + + await restart.transport.releaseHeldSend() + let result = await outcome(within: .seconds(30)) { try await restart.waiting.value } + #expect(Self.returned(result), "Got \(result)") + await restart.stopping.value + let later = await outcome(within: .seconds(30)) { try await restart.server.waitUntilCompleted() } + #expect(Self.returned(later), "Got \(later)") + } + + @Test("A receive stream ending while stop() tears down listen streams does not settle waitUntilCompleted early") + func streamEndingWhileStopSuspendsDoesNotSettleEarly() async throws { + let server = Server(name: "s", version: "1", capabilities: .init(tools: .init(listChanged: true))) + let transport = EndableTransport(mode: .shared) + try await server.start(transport: transport) + await transport.deliverFromServer(Self.listenRequest) + #expect(await eventually { await server.openSubscriptionCount == 1 }) + // Wait for the acknowledgement send to finish before holding the next send for stop(). + #expect(await eventually { await transport.sentMethods.contains(SubscriptionsAcknowledgedNotification.name) }) + let waiting = Task { try await server.waitUntilCompleted() } + #expect(await eventually { await server.completionWaiterCount == 1 }) + + // Hold stop() while it waits for the listen stream's result, before task?.cancel() + // and disconnect(). + await transport.holdNextSend() + let stopping = Task { await server.stop() } + #expect(await eventually { await transport.isSendHeld }) + #expect(await transport.disconnectCount == 0) + + // End the stream with an error while stop() is suspended before cancelling the loop. + await transport.finishStream(throwing: MCPError.internalError("mid-stop")) + let early = await outcome(within: .milliseconds(150)) { try await waiting.value } + #expect(early.didTimeOut, "Got \(early)") + #expect(await server.completionWaiterCount == 1) + + // Waiter still waits through disconnect(), then returns normally (not throwing). + await transport.holdNextDisconnect() + await transport.releaseHeldSend() + #expect(await eventually { await transport.disconnectCount == 1 }) + #expect(await server.completionWaiterCount == 1) + + await transport.releaseHeldDisconnect() + let result = await outcome(within: .seconds(30)) { try await waiting.value } + #expect(Self.returned(result), "Got \(result)") + await stopping.value + let later = await outcome(within: .seconds(30)) { try await server.waitUntilCompleted() } + #expect(Self.returned(later), "Got \(later)") + } + + @Test("Overlapping start() calls fail without disturbing the active run") + func overlappingStartsThrowWithoutDisturbingActiveRun() async throws { + let server = Server(name: "s", version: "1") + let first = EndableTransport(mode: .shared) + await first.holdNextConnect() + let starting = Task { try await server.start(transport: first) } + #expect(await eventually { await first.isConnectHeld }) + + // A second start() while the first is connecting is rejected. + let second = EndableTransport(mode: .shared) + let duringConnect = await outcome(within: .seconds(30)) { try await server.start(transport: second) } + #expect(duringConnect.mcpError == .internalError("Server is already started"), "Got \(duringConnect)") + #expect(await second.receiveCallCount == 0) + + await first.releaseHeldConnect() + let started = await outcome(within: .seconds(30)) { try await starting.value } + #expect(Self.returned(started), "Got \(started)") + + // A start() while the server is already running is also rejected. + let third = EndableTransport(mode: .shared) + let whileRunning = await outcome(within: .seconds(30)) { try await server.start(transport: third) } + #expect(whileRunning.mcpError == .internalError("Server is already started"), "Got \(whileRunning)") + #expect(await third.receiveCallCount == 0) + + // The active run is undisturbed. + let waiting = Task { try await server.waitUntilCompleted() } + #expect(await eventually { await server.completionWaiterCount == 1 }) + await first.finishStream() + let result = await outcome(within: .seconds(30)) { try await waiting.value } + #expect(Self.returned(result), "Got \(result)") + await server.stop() + } + + @Test("When two start() calls queue behind stop(), only one starts and the other throws") + func twoStartsQueuedBehindStopOnlyOneRuns() async throws { + let server = Server(name: "s", version: "1") + let first = EndableTransport(mode: .shared, finishesStreamOnDisconnect: false) + try await server.start(transport: first) + + await first.holdNextDisconnect() + let stopping = Task { await server.stop() } + #expect(await eventually { await first.disconnectCount == 1 }) + + let second = EndableTransport(mode: .shared) + let third = EndableTransport(mode: .shared) + let startA = Task { try await server.start(transport: second) } + let startB = Task { try await server.start(transport: third) } + #expect(await eventually { await server.stopWaiterCount == 2 }) + + await first.releaseHeldDisconnect() + await stopping.value + + let outcomeA = await outcome(within: .seconds(30)) { try await startA.value } + let outcomeB = await outcome(within: .seconds(30)) { try await startB.value } + let outcomes = [outcomeA, outcomeB] + #expect(outcomes.filter(Self.returned).count == 1, "Got \(outcomes)") + #expect(outcomes.filter { $0.mcpError == .internalError("Server is already started") }.count == 1, "Got \(outcomes)") + #expect(await eventually { await second.receiveCallCount + third.receiveCallCount == 1 }) + await server.stop() + } + + @Test("A stop() queued behind a start() on an active stop() stops the new run before returning") + func stopQueuedBehindStartStopsTheNewRun() async throws { + let server = Server(name: "s", version: "1") + let first = EndableTransport(mode: .shared, finishesStreamOnDisconnect: false) + try await server.start(transport: first) + + await first.holdNextDisconnect() + let stopping1 = Task { await server.stop() } + #expect(await eventually { await first.disconnectCount == 1 }) + + // Queue a start() first, then a stop(), behind the stop() in progress. + let second = EndableTransport(mode: .shared) + await second.holdNextConnect() + let starting = Task { try await server.start(transport: second) } + #expect(await eventually { await server.stopWaiterCount == 1 }) + let stopping2 = Task { await server.stop() } + #expect(await eventually { await server.stopWaiterCount == 2 }) + + // Releasing the first stop() resumes starting first, which begins connecting second; + // stopping2 sees the new loopRun and stops second instead of returning while it starts. + await first.releaseHeldDisconnect() + await stopping1.value + #expect(await eventually { await second.isConnectHeld }) + #expect(await eventually { await second.disconnectCount == 1 }) + + await second.releaseHeldConnect() + let started = await outcome(within: .seconds(30)) { try await starting.value } + #expect(started.mcpError == .internalError("Server stopped while starting"), "Got \(started)") + await stopping2.value + #expect(await second.receiveCallCount == 0) + let later = await outcome(within: .seconds(30)) { try await server.waitUntilCompleted() } + #expect(Self.returned(later), "Got \(later)") + } + + @Test("A stop() queued ahead of a start() on an active stop() returns first and lets the start() run") + func stopQueuedAheadOfStartReturnsThenStartRuns() async throws { + let server = Server(name: "s", version: "1") + let first = EndableTransport(mode: .shared, finishesStreamOnDisconnect: false) + try await server.start(transport: first) + + await first.holdNextDisconnect() + let stopping1 = Task { await server.stop() } + #expect(await eventually { await first.disconnectCount == 1 }) + + // Queue a stop() first, then a start(), behind the stop() in progress. + let stopping2 = Task { await server.stop() } + #expect(await eventually { await server.stopWaiterCount == 1 }) + let second = EndableTransport(mode: .shared) + let starting = Task { try await server.start(transport: second) } + #expect(await eventually { await server.stopWaiterCount == 2 }) + + await first.releaseHeldDisconnect() + await stopping1.value + await stopping2.value + let started = await outcome(within: .seconds(30)) { try await starting.value } + #expect(Self.returned(started), "Got \(started)") + #expect(await eventually { await second.receiveCallCount == 1 }) + await server.stop() + } + + @Test("A fresh stop() queuing while start() waiters drain still stops the newly started run") + func freshStopWhileStartWaitersDrainStopsNewRun() async throws { + let server = Server(name: "s", version: "1") + let first = EndableTransport(mode: .shared, finishesStreamOnDisconnect: false) + try await server.start(transport: first) + + await first.holdNextDisconnect() + let stopping1 = Task { await server.stop() } + #expect(await eventually { await first.disconnectCount == 1 }) + + // Queue start1 followed by duplicate starts behind stopping1. Once stopping1 ends, + // start1 begins run 2 (loopRun = 2) and hands off to the queued duplicates while + // isDrainingStopWaiters stays true. Calling a fresh stop() right as start1 enters + // prepare() enters the queue while loopRun is already 2. + let second = EndableTransport(mode: .shared) + await second.holdNextConnect() + let freshStopDone = Flag() + await second.setOnPrepare { + Task { + await server.stop() + await freshStopDone.set() + } + } + let start1 = Task { try await server.start(transport: second) } + #expect(await eventually { await server.stopWaiterCount == 1 }) + + let duplicateCount = 24 + let duplicates = (0.. ListSkills.Result { try await base.listSkills(cursor: cursor) } + func skill(uri: String) async throws -> Skill? { await base.skill(uri: uri) } + func readResource(uri: String) async throws -> ReadResource.Result? { nil } + } + + @Test( + "A skill file with a malformed content item fails to load", + arguments: [ + (Value.object([:]), "text"), (["text": "a", "blob": "YQ=="], "blob"), (["blob": "YQ==YQ=="], "blob"), + ] as [(Value, String)]) + func malformedContentItem(body: Value, key: String) async throws { + let server = Server(name: "s", version: "1", capabilities: .init(resources: .init())) + await server.withSkills(UnreadableCatalog(base: InMemorySkillCatalog([try pdfPackage()]))) + await server.withMethodHandler(RawResult.self) { params in + var item = body.objectValue ?? [:] + item["uri"] = .string(params.uri) + return ["contents": [.object(item)]] + } + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + try await server.start(transport: serverTransport) + let client = Client(name: "c", version: "1") + try await client.connect(transport: clientTransport) + defer { Task { await client.disconnect(); await server.stop() } } + + let skill = try #require(try await client.listSkills().skills.first) + do { + _ = try await client.loadSkill(skill) + Issue.record("\(body) was loaded") + } catch let error as ResponseDecodingError { + #expect(error.expectedType == String(reflecting: ReadResource.Result.self)) + #expect(codingPath(of: error.underlyingError) == ["contents", "0", key]) + } + } + @Test("A data: URL in the frontmatter is compared as written", arguments: [false, true]) func dataURLFrontmatter(handshake: Bool) async throws { let manifest = data("---\nname: pdf\ndescription: Fill PDF forms\nicon: \"data:text/plain,hello\"\n---\n") diff --git a/Tests/MCPTests/SkillFrontmatterTests.swift b/Tests/MCPTests/SkillFrontmatterTests.swift index c85bfb7b..e76832bd 100644 --- a/Tests/MCPTests/SkillFrontmatterTests.swift +++ b/Tests/MCPTests/SkillFrontmatterTests.swift @@ -195,12 +195,12 @@ struct SkillFrontmatterTests { #expect(throws: SkillFrontmatter.Failure.self) { try SkillFrontmatter.parse("a: .inf", schema: .yaml11) } } - @Test("Comparison: numbers by value, key order ignored, data: URLs as strings") + @Test("Comparison: numbers by value, key order ignored, data: URLs are strings") func comparison() throws { let file = try SkillFrontmatter.parse("n: 1.0\nm: {b: 2, a: 1}\nl: [1, 2]\nd: data:text/plain;base64,aGk=") let entry = try json(#"{"m":{"a":1,"b":2},"l":[1,2],"n":1,"d":"data:text/plain;base64,aGk="}"#) guard case .object(let object) = entry else { Issue.record("not an object"); return } - #expect(object["d"]?.dataValue != nil) + #expect(object["d"] == .string("data:text/plain;base64,aGk=")) #expect(SkillFrontmatter.matches(file, object)) #expect(!SkillFrontmatter.equivalent([1, 2], [2, 1])) @@ -208,6 +208,6 @@ struct SkillFrontmatterTests { #expect(!SkillFrontmatter.equivalent("1", 1)) #expect(!SkillFrontmatter.equivalent(.null, "")) #expect(!SkillFrontmatter.matches(["a": 1], ["a": 1, "b": .null])) - #expect(!SkillFrontmatter.equivalent(.data(mimeType: "text/plain", Data("hi".utf8)), "hi")) + #expect(!SkillFrontmatter.equivalent("data:text/plain;base64,aGk=", "data:,hi")) } } diff --git a/Tests/MCPTests/SkillServerTests.swift b/Tests/MCPTests/SkillServerTests.swift index c6e78084..bf695923 100644 --- a/Tests/MCPTests/SkillServerTests.swift +++ b/Tests/MCPTests/SkillServerTests.swift @@ -185,13 +185,14 @@ struct SkillPackageTests { } @Test("Contents: UTF-8 text as text, other bytes and binary types as blobs") - func contents() { + func contents() throws { let text = SkillPackage.contents(data("é"), uri: "u", mimeType: "text/markdown") - #expect(text.text == "é") + #expect(text.body == .text("é")) let invalid = SkillPackage.contents(Data([0xC3]), uri: "u", mimeType: "text/plain") - #expect(invalid.blob == "ww==") + #expect(invalid.body == .blob(Data([0xC3]))) + #expect(try wireString(invalid).contains(#""blob":"ww==""#)) let image = SkillPackage.contents(data("png"), uri: "u", mimeType: "image/png") - #expect(image.blob != nil) + #expect(image.body == .blob(data("png"))) #expect(SkillPackage.mimeType(of: "scripts/extract.py") == "text/x-python") #expect(SkillPackage.mimeType(of: "templates/a.MD") == "text/markdown") #expect(SkillPackage.mimeType(of: "LICENSE") == "text/plain") @@ -251,7 +252,7 @@ struct InMemorySkillCatalogTests { guard case .manifest(let files) = entry.resources else { Issue.record("no manifest"); return } let x = try #require(files.first { $0.uri == "skill://a/x.md" }) let read = try #require(await catalog.readResource(uri: "skill://a/x.md")) - #expect(read.contents.first?.text == "two") + #expect(read.contents.first?.body == .text("two")) #expect(x.digest == SkillResource.digest(of: data("two"))) let root = try await catalog.readDirectory(uri: "skill://a", cursor: nil) #expect(root?.resources.map(\.name) == ["SKILL.md", "x.md"]) @@ -267,7 +268,7 @@ struct InMemorySkillCatalogTests { #expect(await catalog.skill(uri: "skill://pdf/SKILL.md")?.name == "pdf") #expect(await catalog.skill(uri: "skill://pdf/templates/invoice.md") == nil) let read = try #require(await catalog.readResource(uri: "skill://pdf/templates/invoice.md")) - #expect(read.contents.first?.text == "i") + #expect(read.contents.first?.body == .text("i")) #expect(read.contents.first?.mimeType == "text/markdown") #expect(await catalog.readResource(uri: "skill://pdf/missing.md") == nil) diff --git a/Tests/MCPTests/StatelessGatingTests.swift b/Tests/MCPTests/StatelessGatingTests.swift index bcf49130..a9ba4a90 100644 --- a/Tests/MCPTests/StatelessGatingTests.swift +++ b/Tests/MCPTests/StatelessGatingTests.swift @@ -389,7 +389,7 @@ private struct SupportedVersionsEcho: HTTPRequestValidator { struct StatefulStatelessBoundaryTests { @Test("A stateless version in _meta alone is -32022 on a session") func metaOnlyStatelessVersion() async throws { - let transport = StatefulHTTPServerTransport(validationPipeline: StandardValidationPipeline(validators: [])) + let transport = StatefulHTTPServerTransport(validators: []) try await transport.connect() defer { Task { await transport.disconnect() } } var incoming = await transport.receive().makeAsyncIterator() @@ -414,7 +414,7 @@ struct StatefulStatelessBoundaryTests { func emptyMetaVersion() async throws { let server = Server(name: "empty", version: "1", capabilities: .init(tools: .init())) await server.withMethodHandler(ListTools.self) { _ in .init(tools: []) } - let transport = StatefulHTTPServerTransport(validationPipeline: StandardValidationPipeline(validators: [])) + let transport = StatefulHTTPServerTransport(validators: []) try await server.start(transport: transport) defer { Task { await server.stop() } } @@ -445,7 +445,7 @@ struct StatefulStatelessBoundaryTests { @Test("A stateless request still goes through the origin check") func statelessRequestIsValidated() async throws { let transport = StatefulHTTPServerTransport( - validationPipeline: StandardValidationPipeline(validators: [OriginValidator.localhost()])) + validators: [OriginValidator.localhost()]) try await transport.connect() defer { Task { await transport.disconnect() } } @@ -457,7 +457,7 @@ struct StatefulStatelessBoundaryTests { @Test("A stateless request is validated against the handshake revisions") func statelessRequestContextVersions() async throws { let transport = StatefulHTTPServerTransport( - validationPipeline: StandardValidationPipeline(validators: [SupportedVersionsEcho()])) + validators: [SupportedVersionsEcho()]) try await transport.connect() defer { Task { await transport.disconnect() } } @@ -470,7 +470,7 @@ struct StatefulStatelessBoundaryTests { @Test("A refused initialize leaves no session") func refusedInitializeDropsSession() async throws { let transport = StatefulHTTPServerTransport( - validationPipeline: StandardValidationPipeline(validators: [SessionValidator()])) + validators: [SessionValidator()]) try await transport.connect() defer { Task { await transport.disconnect() } } var incoming = await transport.receive().makeAsyncIterator() @@ -498,7 +498,7 @@ struct StatelessTransportExchangeTests { -> StatelessHTTPServerTransport { let transport = StatelessHTTPServerTransport( - validationPipeline: StandardValidationPipeline(validators: validators)) + validators: validators) try await transport.connect() return transport } @@ -525,6 +525,32 @@ struct StatelessTransportExchangeTests { pending.cancel() } + @Test("notifications/cancelled names a request by its id's scalars, not a canonically equivalent id") + func cancellationMatchesIDScalars() async throws { + let transport = try await makeTransport() + defer { Task { await transport.disconnect() } } + var incoming = await transport.receive().makeAsyncIterator() + + // The id U+00E9; the cancellation names e with U+0301. + let request = call(id: 1).replacingOccurrences(of: #""id":1"#, with: #""id":"\u00e9""#) + let pending = Task { + await transport.handleRequest( + post(request, version: "2026-07-28", accept: "application/json", authorization: "Bearer a")) + } + let forwarded = try await nextIncoming(&incoming) + let internalID = try #require(forwarded.objectValue?["id"]?.stringValue) + + let cancel = #"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"e\u0301"}}"# + #expect(await transport.handleRequest(post(cancel, authorization: "Bearer a")).statusCode == 202) + + // The request is still in flight: the server's answer reaches it. + try await transport.send(Data(#"{"jsonrpc":"2.0","id":"\#(internalID)","result":{"content":[]}}"#.utf8)) + let response = try #require(await resultInTime(of: pending)).get() + #expect(response.statusCode == 200) + let body = try #require(response.bodyData) + #expect(body.range(of: Data(#""id":"\#u{E9}""#.utf8)) != nil) + } + @Test("Cancelling a pending JSON reply cancels the request in the server") func adapterCancellationAbandonsRequest() async throws { let transport = try await makeTransport() @@ -581,7 +607,7 @@ struct StatelessTransportExchangeTests { let internalID = try #require(forwarded.objectValue?["id"]?.stringValue) try await transport.send( Data(#"{"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","data":"x"}}"#.utf8), - relatedRequestID: .string(internalID)) + options: TransportSendOptions(relatedRequestID: .string(internalID))) guard case .stream(let stream, _) = await pending.value else { Issue.record("Expected an SSE stream") return @@ -641,7 +667,7 @@ struct StatelessTransportExchangeTests { return .init(content: []) } let transport = StatelessHTTPServerTransport( - validationPipeline: StandardValidationPipeline(validators: [])) + validators: []) try await server.start(transport: transport) defer { Task { await server.stop() } } @@ -668,13 +694,13 @@ struct StatelessTransportExchangeTests { let forwarded = try await nextIncoming(&incoming) let internalID = try #require(forwarded.objectValue?["id"]?.stringValue) let notification = Data(#"{"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","data":"x"}}"#.utf8) - try await transport.send(notification, relatedRequestID: .string(internalID)) + try await transport.send(notification, options: TransportSendOptions(relatedRequestID: .string(internalID))) guard case .stream(let stream, _) = await pending.value else { Issue.record("Expected an SSE stream") return } for _ in 0..<3000 { - try await transport.send(notification, relatedRequestID: .string(internalID)) + try await transport.send(notification, options: TransportSendOptions(relatedRequestID: .string(internalID))) } try await transport.send( Data(#"{"jsonrpc":"2.0","id":"\#(internalID)","result":{"content":[]}}"#.utf8)) diff --git a/Tests/MCPTests/StatelessServerTests.swift b/Tests/MCPTests/StatelessServerTests.swift index 240b9ae8..0136a391 100644 --- a/Tests/MCPTests/StatelessServerTests.swift +++ b/Tests/MCPTests/StatelessServerTests.swift @@ -104,6 +104,20 @@ struct StatelessServerTests { expectWire(reply[0], matches: try wireJSON(#"{"result":{"ttlMs":60000,"cacheScope":"public"}}"#)) } + @Test("A negative configured cache hint is sent as 0") + func testNegativeCacheHint() async throws { + let configuration = Server.Configuration(cacheHints: [ListTools.name: CacheHint(ttlMs: -5, scope: .public)]) + let wire = WireExchange(server: await makeServer(configuration: configuration)) + try await wire.start() + defer { Task { await wire.stop() } } + + let reply = try await wire.send( + #"{"jsonrpc":"2.0","id":5,"method":"tools/list","params":\#(statelessParams())}"#) + expectWire(reply[0], matches: try wireJSON(#"{"result":{"ttlMs":0,"cacheScope":"public"}}"#)) + let sent = try #require(await wire.transport.sentData.last) + #expect(String(decoding: sent, as: UTF8.self).contains(#""ttlMs":0}"#)) + } + @Test("Missing or invalid _meta members are -32602") func testInvalidMeta() async throws { let wire = WireExchange(server: await makeServer()) @@ -353,9 +367,9 @@ private func bodyJSON(_ response: HTTPResponse) throws -> Value { struct StatelessHTTPTests { private func start(_ server: Server) async throws -> StatelessHTTPServerTransport { let transport = StatelessHTTPServerTransport( - validationPipeline: StandardValidationPipeline(validators: [ + validators: [ AcceptHeaderValidator(mode: .jsonOnly), ContentTypeValidator(), ProtocolVersionValidator(), - ])) + ]) try await server.start(transport: transport) return transport } @@ -368,6 +382,28 @@ struct StatelessHTTPTests { #expect(statelessRequest("{}", version: nil).statelessProtocolVersion == nil) } + @Test("A request validated while the transport stops gets 404") + func testStopDuringValidation() async throws { + let gate = ValidationGate() + let transport = StatelessHTTPServerTransport(validators: [GateValidator(gate, method: "POST")]) + try await transport.connect() + + let request = statelessRequest(#"{"jsonrpc":"2.0","id":1,"method":"tools/list","params":\#(statelessParams())}"#) + let pending = Task { await transport.handleRequest(request) } + #expect(await eventually { await gate.arrivals == 1 }) + await transport.disconnect() + await gate.open() + + // Without the check after validation, the request would wait for a + // server that is gone. + let response = await outcome(within: .seconds(10)) { await pending.value } + guard case .returned(let answer) = response else { + Issue.record("The request did not finish: \(response)") + return + } + #expect(answer.statusCode == 404) + } + @Test("Results keep the client's id; errors map to HTTP status") func testStatusMapping() async throws { let server = await makeServer() @@ -595,7 +631,7 @@ struct StatelessHTTPTests { @Test("Stateful transport rejects stateless requests with -32022") func testStatefulRejectsStateless() async throws { let transport = StatefulHTTPServerTransport( - validationPipeline: StandardValidationPipeline(validators: [])) + validators: []) try await transport.connect() defer { Task { await transport.disconnect() } } @@ -699,7 +735,7 @@ struct StatelessHTTPTests { @Test("Messages are forwarded in the form the headers were checked against") func testForwardedAsChecked() async throws { let transport = StatelessHTTPServerTransport( - validationPipeline: StandardValidationPipeline(validators: [])) + validators: []) try await transport.connect() defer { Task { await transport.disconnect() } } var messages = await transport.receive().makeAsyncIterator() @@ -771,6 +807,93 @@ struct StatelessHTTPTests { } } + @Test("Mcp-Method, Mcp-Name, and Mcp-Param headers match by exact code points") + func testStandardAndParameterHeadersMatchExactly() async throws { + let server = await headerServer() + let transport = try await start(server) + defer { Task { await server.stop() } } + + // Mcp-Method: ASCII "K" in header must not match U+212A KELVIN SIGN in body. + let methodMismatch = await transport.handleRequest( + statelessRequest( + #"{"jsonrpc":"2.0","id":"m","method":"\u212Aelvin/run","params":\#(statelessParams())}"#, + standardHeaders: false, extraHeaders: ["Mcp-Method": "Kelvin/run"])) + #expect(methodMismatch.statusCode == 400) + expectWire(try bodyJSON(methodMismatch), matches: try wireJSON(#"{"id":"m","error":{"code":-32020}}"#)) + + // Mcp-Name: Base64-encoded U+212A / NFD spelling must not match ASCII K / NFC in body. + let nameKelvin = await transport.handleRequest( + statelessRequest( + #"{"jsonrpc":"2.0","id":"nk","method":"tools/call","params":\#(statelessParams(#""name":"Key""#))}"#, + standardHeaders: false, + extraHeaders: ["Mcp-Method": "tools/call", "Mcp-Name": MCPRequestHeaders.encode("\u{212A}ey")])) + #expect(nameKelvin.statusCode == 400) + expectWire(try bodyJSON(nameKelvin), matches: try wireJSON(#"{"id":"nk","error":{"code":-32020}}"#)) + + let nameNFD = await transport.handleRequest( + statelessRequest( + #"{"jsonrpc":"2.0","id":"nn","method":"tools/call","params":\#(statelessParams(#""name":"caf\u00E9""#))}"#, + standardHeaders: false, + extraHeaders: ["Mcp-Method": "tools/call", "Mcp-Name": MCPRequestHeaders.encode("cafe\u{301}")])) + #expect(nameNFD.statusCode == 400) + expectWire(try bodyJSON(nameNFD), matches: try wireJSON(#"{"id":"nn","error":{"code":-32020}}"#)) + + // Mcp-Param-*: Base64-encoded NFD / U+212A spelling must not match NFC / K argument. + let paramNFD = await transport.handleRequest( + statelessRequest( + #"{"jsonrpc":"2.0","id":"pn","method":"tools/call","params":\#(statelessParams(#""name":"route","arguments":{"region":"caf\u00E9"}"#))}"#, + extraHeaders: ["Mcp-Param-Region": MCPRequestHeaders.encode("cafe\u{301}")])) + #expect(paramNFD.statusCode == 400) + expectWire(try bodyJSON(paramNFD), matches: try wireJSON(#"{"id":"pn","error":{"code":-32020}}"#)) + + let paramExact = await transport.handleRequest( + statelessRequest( + #"{"jsonrpc":"2.0","id":"pe","method":"tools/call","params":\#(statelessParams(#""name":"route","arguments":{"region":"caf\u00E9"}"#))}"#, + extraHeaders: ["Mcp-Param-Region": MCPRequestHeaders.encode("caf\u{E9}")])) + #expect(paramExact.statusCode == 200) + + let paramKelvin = await transport.handleRequest( + statelessRequest( + #"{"jsonrpc":"2.0","id":"pk","method":"tools/call","params":\#(statelessParams(#""name":"route","arguments":{"region":"Kelvin"}"#))}"#, + extraHeaders: ["Mcp-Param-Region": MCPRequestHeaders.encode("\u{212A}elvin")])) + #expect(paramKelvin.statusCode == 400) + expectWire(try bodyJSON(paramKelvin), matches: try wireJSON(#"{"id":"pk","error":{"code":-32020}}"#)) + + // Canonically equivalent argument key ("r\u00E9gion" vs "re\u0301gion", or "\u212Aey" vs "Key") + // must be rejected whether the header is omitted or sent. + let keyServer = Server(name: "key-headers", version: "1.0", capabilities: .init(tools: .init())) + await keyServer.withMethodHandler(ListTools.self) { _ in + .init(tools: [ + Tool( + name: "lookup", description: nil, + inputSchema: [ + "type": "object", + "properties": [ + "Key": ["type": "string", "x-mcp-header": "Key"] + ], + ]) + ]) + } + await keyServer.withMethodHandler(CallTool.self) { params in + .init(content: [.text(text: params.arguments?["Key"]?.stringValue ?? "")]) + } + let keyTransport = try await start(keyServer) + defer { Task { await keyServer.stop() } } + + let keyWithoutHeader = await keyTransport.handleRequest( + statelessRequest( + #"{"jsonrpc":"2.0","id":"kw","method":"tools/call","params":\#(statelessParams(#""name":"lookup","arguments":{"\u212Aey":"secret"}"#))}"#)) + #expect(keyWithoutHeader.statusCode == 400) + expectWire(try bodyJSON(keyWithoutHeader), matches: try wireJSON(#"{"id":"kw","error":{"code":-32020}}"#)) + + let keyWithHeader = await keyTransport.handleRequest( + statelessRequest( + #"{"jsonrpc":"2.0","id":"kh","method":"tools/call","params":\#(statelessParams(#""name":"lookup","arguments":{"\u212Aey":"secret"}"#))}"#, + extraHeaders: ["Mcp-Param-Key": "secret"])) + #expect(keyWithHeader.statusCode == 400) + expectWire(try bodyJSON(keyWithHeader), matches: try wireJSON(#"{"id":"kh","error":{"code":-32020}}"#)) + } + @Test("Stateless tools/list omits tools with invalid x-mcp-header annotations") func testInvalidAnnotationsNotListed() async throws { let server = await headerServer() @@ -868,9 +991,9 @@ struct StatelessHTTPTests { let server = Server( name: "listen", version: "1.0", capabilities: .init(tools: .init(listChanged: true))) let transport = StatelessHTTPServerTransport( - validationPipeline: StandardValidationPipeline(validators: [ + validators: [ AcceptHeaderValidator(mode: .jsonOnly), ContentTypeValidator(), ProtocolVersionValidator(), - ]), + ], keepAliveInterval: .milliseconds(20)) try await server.start(transport: transport) defer { Task { await server.stop() } } @@ -931,9 +1054,9 @@ struct ParameterHeaderLookupTests { private func start(_ server: Server) async throws -> StatelessHTTPServerTransport { let transport = StatelessHTTPServerTransport( - validationPipeline: StandardValidationPipeline(validators: [ + validators: [ AcceptHeaderValidator(mode: .jsonOnly), ContentTypeValidator(), ProtocolVersionValidator(), - ])) + ]) try await server.start(transport: transport) return transport } @@ -1060,9 +1183,9 @@ struct ParameterHeaderLookupTests { let counter = CallCounter() let server = await server(counter: counter) let transport = StatelessHTTPServerTransport( - validationPipeline: StandardValidationPipeline(validators: [ + validators: [ AcceptHeaderValidator(mode: .jsonOnly), ContentTypeValidator(), ProtocolVersionValidator(), - ])) + ]) try await server.start( transport: transport, initializeHook: { _, _ in }, statelessRequestHook: { _, _ in throw MCPError.invalidRequest("not allowed") }) diff --git a/Tests/MCPTests/StdioTransportTests.swift b/Tests/MCPTests/StdioTransportTests.swift index 5015ba26..5985716a 100644 --- a/Tests/MCPTests/StdioTransportTests.swift +++ b/Tests/MCPTests/StdioTransportTests.swift @@ -1,3 +1,4 @@ +import Dispatch import Foundation import Testing @@ -28,8 +29,33 @@ struct StdioTransportTests { await transport.disconnect() } - @Test("Disconnect restores file descriptor blocking mode") - func testDisconnectRestoresBlockingMode() async throws { + /// Whether a descriptor a test hands the transport is blocking, as a pipe is when created, + /// or non-blocking, as a parent process may leave it. + enum DescriptorMode: CaseIterable, Sendable, CustomTestStringConvertible { + case blocking + case nonBlocking + + var testDescription: String { self == .blocking ? "blocking" : "non-blocking" } + + func apply(to descriptors: FileDescriptor...) { + for descriptor in descriptors { + let flags = fcntl(descriptor.rawValue, F_GETFL) + let mode = self == .blocking ? flags & ~O_NONBLOCK : flags | O_NONBLOCK + #expect(fcntl(descriptor.rawValue, F_SETFL, mode) == 0) + } + } + } + + /// The status flags of `descriptor` that `F_SETFL` changes. Darwin also reports a flag of + /// its own once a descriptor was written to (`FWASWRITTEN`), which no program sets. + private static func statusFlags(_ descriptor: Int32) -> CInt { + fcntl(descriptor, F_GETFL) & (O_NONBLOCK | O_APPEND) + } + + @Test( + "connect() and disconnect() leave the descriptors' flags unchanged", + arguments: DescriptorMode.allCases) + func testFlagsUnchanged(mode: DescriptorMode) async throws { let (input, writer) = try FileDescriptor.pipe() let (reader, output) = try FileDescriptor.pipe() defer { @@ -38,24 +64,28 @@ struct StdioTransportTests { try? reader.close() try? output.close() } - - let inputFlags = fcntl(input.rawValue, F_GETFL) - let outputFlags = fcntl(output.rawValue, F_GETFL) - #expect(inputFlags & O_NONBLOCK == 0) - #expect(outputFlags & O_NONBLOCK == 0) + mode.apply(to: input, output) + let inputFlags = Self.statusFlags(input.rawValue) + let outputFlags = Self.statusFlags(output.rawValue) let transport = StdioTransport(input: input, output: output, logger: nil) try await transport.connect() - #expect(fcntl(input.rawValue, F_GETFL) & O_NONBLOCK != 0) - #expect(fcntl(output.rawValue, F_GETFL) & O_NONBLOCK != 0) + try await transport.send(Data("{}".utf8)) + #expect(Self.statusFlags(input.rawValue) == inputFlags) + #expect(Self.statusFlags(output.rawValue) == outputFlags) await transport.disconnect() - #expect(fcntl(input.rawValue, F_GETFL) & O_NONBLOCK == 0) - #expect(fcntl(output.rawValue, F_GETFL) & O_NONBLOCK == 0) + #expect(Self.statusFlags(input.rawValue) == inputFlags) + #expect(Self.statusFlags(output.rawValue) == outputFlags) + + // A connect() that fails on its output leaves the input as it was too. + let failing = StdioTransport(input: input, output: FileDescriptor(rawValue: -1), logger: nil) + await #expect(throws: MCPError.self) { try await failing.connect() } + #expect(Self.statusFlags(input.rawValue) == inputFlags) } - @Test("Disconnect cancels a backpressured send before restoring descriptor flags") - func testDisconnectDuringBackpressuredSend() async throws { + @Test("Disconnect releases a send waiting for room in the output", arguments: DescriptorMode.allCases) + func testDisconnectDuringBackpressuredSend(mode: DescriptorMode) async throws { let (input, writer) = try FileDescriptor.pipe() let (reader, output) = try FileDescriptor.pipe() defer { @@ -64,20 +94,47 @@ struct StdioTransportTests { try? reader.close() try? output.close() } + mode.apply(to: output) let transport = StdioTransport(input: input, output: output, logger: nil) try await transport.connect() + // Nothing reads, so the send fills the pipe and waits for room. let send = Task { try await transport.send(Data(repeating: 65, count: 512 * 1024)) } - try await Task.sleep(for: .milliseconds(50)) + #expect(await eventually { await transport.activeSends == 1 }) - await transport.disconnect() - do { - try await send.value - Issue.record("Expected the incomplete send to fail on disconnect") - } catch { - // The caller must be released before the descriptor becomes blocking. + let disconnected = await outcome(within: .seconds(30)) { await transport.disconnect() } + #expect(!disconnected.didTimeOut) + let result = await outcome(within: .seconds(30)) { try await send.value } + guard case .connectionClosed = result.mcpError else { + Issue.record("Expected the incomplete send to fail with connectionClosed, got \(result)") + return } - #expect(fcntl(output.rawValue, F_GETFL) & O_NONBLOCK == 0) + } + + @Test("Disconnect releases a read waiting for input", arguments: DescriptorMode.allCases) + func testDisconnectReleasesWaitingRead(mode: DescriptorMode) async throws { + let (input, writer) = try FileDescriptor.pipe() + let (reader, output) = try FileDescriptor.pipe() + defer { + try? input.close() + try? writer.close() + try? reader.close() + try? output.close() + } + mode.apply(to: input) + + let transport = StdioTransport(input: input, output: output, logger: nil) + try await transport.connect() + let stream: AsyncThrowingStream = await transport.receive() + let receiving = Task { await outcome(within: .seconds(30)) { for try await _ in stream {} } } + + // The writer stays open and silent, so only disconnect() can end the read. + let disconnected = await outcome(within: .seconds(30)) { await transport.disconnect() } + #expect(!disconnected.didTimeOut) + let received = await receiving.value + #expect(!received.didTimeOut) + #expect(received.error == nil) + #expect(await transport.readCount == 0) } /// A frame larger than a pipe's buffer (64 KiB on Linux and macOS), padded with the @@ -184,8 +241,8 @@ struct StdioTransportTests { await transport.disconnect() } - @Test("A send cancelled mid-frame finishes it before the next send writes") - func testSendCancelledMidFrame() async throws { + @Test("A send cancelled mid-frame finishes it before the next send writes", arguments: DescriptorMode.allCases) + func testSendCancelledMidFrame(mode: DescriptorMode) async throws { let (input, writer) = try FileDescriptor.pipe() let (reader, output) = try FileDescriptor.pipe() defer { @@ -193,6 +250,7 @@ struct StdioTransportTests { try? writer.close() try? reader.close() } + mode.apply(to: output) let transport = StdioTransport(input: input, output: output, logger: nil) try await transport.connect() @@ -237,8 +295,10 @@ struct StdioTransportTests { return Data((prefix + padding + suffix).utf8) } - @Test("A send cancelled before it writes anything leaves the output to the next send") - func testSendCancelledBeforeWriting() async throws { + @Test( + "A send cancelled before it writes anything leaves the output to the next send", + arguments: DescriptorMode.allCases) + func testSendCancelledBeforeWriting(mode: DescriptorMode) async throws { let (input, writer) = try FileDescriptor.pipe() let (reader, output) = try FileDescriptor.pipe() defer { @@ -249,8 +309,9 @@ struct StdioTransportTests { let transport = StdioTransport(input: input, output: output, logger: nil) try await transport.connect() - // `connect()` made `output` nonblocking. Fill the pipe with lines of the size the - // cancelled send writes, so that send gets `EAGAIN` before its first byte. + // Fill the pipe with lines of the size the cancelled send writes, so that send finds + // no room before its first byte. Writing until `EAGAIN` needs a non-blocking output. + DescriptorMode.nonBlocking.apply(to: output) let filler = Self.atomicLine("filler") var filled = Data() while true { @@ -258,10 +319,11 @@ struct StdioTransportTests { let written = try filler.withUnsafeBytes { try output.write($0) } #expect(written == filler.count) filled += filler - } catch let error where MCPError.isResourceTemporarilyUnavailable(error) { + } catch let error as Errno where error == .resourceTemporarilyUnavailable { break } } + mode.apply(to: output) let cancelled = Task { try await transport.send(Self.atomicLine("cancelled").dropLast()) } #expect(await eventually { await transport.activeSends == 1 }) @@ -308,11 +370,10 @@ struct StdioTransportTests { let disconnected = await outcome(within: .seconds(30)) { await transport.disconnect() } #expect(!disconnected.didTimeOut) let result = await outcome(within: .seconds(30)) { try await send.value } - guard case .transportError(let underlying) = result.mcpError else { - Issue.record("Expected the send to fail with a transport error, got \(result)") + guard case .connectionClosed = result.mcpError else { + Issue.record("Expected the send to fail with connectionClosed, got \(result)") return } - #expect(underlying as? Errno == Errno(rawValue: ENOTCONN)) #expect(await transport.activeSends == 0) } @@ -342,62 +403,14 @@ struct StdioTransportTests { // others never start writing. for (index, send) in sends.enumerated() { let result = await outcome(within: .seconds(30)) { try await send.value } - guard case .transportError(let underlying) = result.mcpError else { - Issue.record("Expected send \(index) to fail with a transport error, got \(result)") + guard case .connectionClosed = result.mcpError else { + Issue.record("Expected send \(index) to fail with connectionClosed, got \(result)") continue } - #expect(underlying as? Errno == Errno(rawValue: ENOTCONN), "Send \(index)") } #expect(await transport.activeSends == 0) } - @Test("Disconnect preserves an already nonblocking descriptor") - func testDisconnectPreservesNonblockingMode() async throws { - let (input, writer) = try FileDescriptor.pipe() - let (reader, output) = try FileDescriptor.pipe() - defer { - try? input.close() - try? writer.close() - try? reader.close() - try? output.close() - } - let flags = fcntl(output.rawValue, F_GETFL) - #expect(fcntl(output.rawValue, F_SETFL, flags | O_NONBLOCK) == 0) - - let transport = StdioTransport(input: input, output: output, logger: nil) - try await transport.connect() - await transport.disconnect() - #expect(fcntl(input.rawValue, F_GETFL) & O_NONBLOCK == 0) - #expect(fcntl(output.rawValue, F_GETFL) & O_NONBLOCK != 0) - } - - @Test("Disconnect leaves a reused output descriptor unchanged") - func testDisconnectDoesNotChangeReusedOutputDescriptor() async throws { - let (input, writer) = try FileDescriptor.pipe() - let (reader, output) = try FileDescriptor.pipe() - let (replacementReader, replacementWriter) = try FileDescriptor.pipe() - defer { - try? input.close() - try? writer.close() - try? reader.close() - try? replacementReader.close() - try? replacementWriter.close() - } - - let transport = StdioTransport(input: input, output: output, logger: nil) - try await transport.connect() - let replacementFlags = fcntl(replacementWriter.rawValue, F_GETFL) - #expect(fcntl(replacementWriter.rawValue, F_SETFL, replacementFlags | O_NONBLOCK) == 0) - - // dup2 closes `output` and reuses its number in one step, so a test running in - // parallel cannot be given that number in between. - #expect(dup2(replacementWriter.rawValue, output.rawValue) == output.rawValue) - defer { _ = close(output.rawValue) } - - await transport.disconnect() - #expect(fcntl(output.rawValue, F_GETFL) & O_NONBLOCK != 0) - } - @Test("Connect and disconnect over a socket pair") func testSocketPair() async throws { // Node.js gives a child process socket pairs, not pipes, as stdin and stdout; @@ -412,32 +425,22 @@ struct StdioTransportTests { #expect(socketpair(AF_UNIX, stream, 0, &input) == 0) #expect(socketpair(AF_UNIX, stream, 0, &output) == 0) defer { for fd in input + output { _ = close(fd) } } + let inputFlags = Self.statusFlags(input[0]) + let outputFlags = Self.statusFlags(output[0]) let transport = StdioTransport( input: FileDescriptor(rawValue: input[0]), output: FileDescriptor(rawValue: output[0]), logger: nil) try await transport.connect() + let received: AsyncThrowingStream = await transport.receive() + var messages = received.makeAsyncIterator() + try FileDescriptor(rawValue: input[1]).writeAll(Data("{\"a\":1}\n".utf8)) + #expect(try await messages.next() == Data("{\"a\":1}".utf8)) try await transport.send(Data("{}".utf8)) + #expect(try await Self.read(FileDescriptor(rawValue: output[1]), upTo: 3) == Data("{}\n".utf8)) await transport.disconnect() - #expect(fcntl(input[0], F_GETFL) & O_NONBLOCK == 0) - #expect(fcntl(output[0], F_GETFL) & O_NONBLOCK == 0) - } - - @Test("Failed connect restores the input descriptor mode") - func testFailedConnectRestoresInputMode() async throws { - let (input, writer) = try FileDescriptor.pipe() - defer { - try? input.close() - try? writer.close() - } - - let transport = StdioTransport(input: input, output: FileDescriptor(rawValue: -1), logger: nil) - do { - try await transport.connect() - Issue.record("Expected connect to reject the closed output descriptor") - } catch { - #expect(fcntl(input.rawValue, F_GETFL) & O_NONBLOCK == 0) - } + #expect(Self.statusFlags(input[0]) == inputFlags) + #expect(Self.statusFlags(output[0]) == outputFlags) } @Test("Send Message") @@ -530,23 +533,30 @@ struct StdioTransportTests { } /// Writes `bytes` to `writer` off the cooperative pool. The write end is made non-blocking, so - /// a reader that stops early makes this throw after `limit` instead of blocking forever. + /// a reader that stops early makes this throw after `idleLimit` without progress (or `totalLimit` + /// overall) instead of blocking forever. private static func write( - _ bytes: Data, to writer: FileDescriptor, within limit: Duration = .seconds(30) + _ bytes: Data, to writer: FileDescriptor, + idleLimit: Duration = .seconds(30), totalLimit: Duration = .seconds(120) ) async throws { try await offThreadPool { let flags = fcntl(writer.rawValue, F_GETFL) guard flags >= 0, fcntl(writer.rawValue, F_SETFL, flags | O_NONBLOCK) >= 0 else { throw Errno(rawValue: errno) } - let deadline = ContinuousClock.now + limit + let hardDeadline = ContinuousClock.now + totalLimit + var idleDeadline = ContinuousClock.now + idleLimit var remaining = bytes[...] while !remaining.isEmpty { do { let written = try remaining.withUnsafeBytes { try writer.write($0) } remaining = remaining.dropFirst(written) + if written > 0 { + idleDeadline = ContinuousClock.now + idleLimit + } } catch let error as Errno where error == .resourceTemporarilyUnavailable { - guard ContinuousClock.now < deadline else { throw Errno.timedOut } + let now = ContinuousClock.now + guard now < idleDeadline, now < hardDeadline else { throw Errno.timedOut } // Wait until the pipe has room, for at most 100 ms between deadline checks. var descriptor = pollfd(fd: writer.rawValue, events: Int16(POLLOUT), revents: 0) _ = poll(&descriptor, 1, 100) @@ -605,7 +615,7 @@ struct StdioTransportTests { let writing = Task { try await Self.write(bytes, to: writer) } // Before the fix the transport kept reading into its buffer and the stream stayed open. - let result = await outcome(within: .seconds(30)) { + let result = await outcome(within: .seconds(120)) { for try await _ in stream {} } #expect(result.mcpError == .internalError(StdioTransport.messageTooLong)) @@ -628,7 +638,7 @@ struct StdioTransportTests { let stream: AsyncThrowingStream = await transport.receive() let delivered = Counter() let receiving = Task { - await outcome(within: .seconds(30)) { + await outcome(within: .seconds(120)) { for try await _ in stream { await delivered.increment() } } } @@ -637,7 +647,7 @@ struct StdioTransportTests { // one byte past it and carries the next message, which must not be delivered. let limit = StdioTransport.maxMessageLength try await Self.write(Data(repeating: UInt8(ascii: "a"), count: limit - 1), to: writer) - #expect(await eventually { await transport.receiveBufferSpan == limit - 1 }) + #expect(await eventually(within: .seconds(120)) { await transport.receiveBufferSpan == limit - 1 }) try await Self.write( Data(("aa\n" + #"{"jsonrpc":"2.0","method":"ping","id":1}"# + "\n").utf8), to: writer) @@ -729,4 +739,457 @@ struct StdioTransportTests { await transport.disconnect() } + + // MARK: - Readiness + + @Test("A read waits without polling") + func testIdleReadDoesNotPoll() async throws { + let (input, writer) = try FileDescriptor.pipe() + let (reader, output) = try FileDescriptor.pipe() + defer { + try? input.close() + try? writer.close() + try? reader.close() + try? output.close() + } + let transport = StdioTransport(input: input, output: output, logger: nil) + try await transport.connect() + let stream: AsyncThrowingStream = await transport.receive() + var messages = stream.makeAsyncIterator() + + try writer.writeAll(Data("{\"a\":1}\n".utf8)) + #expect(try await messages.next() == Data("{\"a\":1}".utf8)) + // One read for one message: nothing reads again until the input is readable. + #expect(await transport.readCount == 1) + let searched = await transport.searchedByteCount + + // A loop that retried every 10 ms, as before, reads dozens of times in this window. + let woke = await eventually(within: .milliseconds(500)) { + let reads = await transport.readCount + let searchedNow = await transport.searchedByteCount + return reads != 1 || searchedNow != searched + } + #expect(!woke, "An idle transport read again") + await transport.disconnect() + } + + @Test("A cancelled send still writes when the output has room", arguments: DescriptorMode.allCases) + func testCancelledSendWithRoomWrites(mode: DescriptorMode) async throws { + let (input, writer) = try FileDescriptor.pipe() + let (reader, output) = try FileDescriptor.pipe() + defer { + try? input.close() + try? writer.close() + try? reader.close() + try? output.close() + } + mode.apply(to: output) + let transport = StdioTransport(input: input, output: output, logger: nil) + try await transport.connect() + + let send = Task { + withUnsafeCurrentTask { $0?.cancel() } + try await transport.send(Data("{}".utf8)) + } + let result = await outcome(within: .seconds(30)) { try await send.value } + #expect(!result.didTimeOut) + #expect(result.error == nil) + #expect(try await Self.read(reader, upTo: 3) == Data("{}\n".utf8)) + await transport.disconnect() + } + + @Test("A 16 MiB send through a pipe completes", arguments: DescriptorMode.allCases) + func testLargeSendCompletes(mode: DescriptorMode) async throws { + let (input, writer) = try FileDescriptor.pipe() + let (reader, output) = try FileDescriptor.pipe() + defer { + try? input.close() + try? writer.close() + try? reader.close() + try? output.close() + } + mode.apply(to: output) + let transport = StdioTransport(input: input, output: output, logger: nil) + try await transport.connect() + + let message = Data(repeating: UInt8(ascii: "a"), count: StdioTransport.maxMessageLength) + let received = Task { try await Self.read(reader, upTo: message.count + 1) } + // In blocking mode the transport writes at most `PIPE_BUF` bytes per readiness event: + // 32768 writes on Darwin. + let sent = await outcome(within: .seconds(120)) { try await transport.send(message) } + #expect(!sent.didTimeOut) + #expect(sent.error == nil) + let data = try await received.value + #expect(data.count == message.count + 1) + #expect(data == message + Data("\n".utf8)) + await transport.disconnect() + } + + @Test("A send to a blocking output with room writes every chunk without waiting") + func testSendWithRoomDoesNotWait() async throws { + let (input, writer) = try FileDescriptor.pipe() + let (reader, output) = try FileDescriptor.pipe() + defer { + try? input.close() + try? writer.close() + try? reader.close() + try? output.close() + } + let transport = StdioTransport(input: input, output: output, logger: nil) + try await transport.connect() + + // 8 KiB fits an empty pipe on Darwin and Linux, in 16 chunks of `PIPE_BUF` on Darwin. + let message = Data(repeating: UInt8(ascii: "a"), count: 8 * 1024 - 1) + try #require(message.count > StdioTransport.blockingWriteLength) + try await transport.send(message) + // Each wait hops off the actor; a `poll` that finds room needs none. + #expect(await transport.sendWaitCount == 0) + #expect(try await Self.read(reader, upTo: message.count + 1) == message + Data("\n".utf8)) + await transport.disconnect() + } + + @Test("A regular file is read to its end as input, and written as output") + func testRegularFiles() async throws { + let directory = FileManager.default.temporaryDirectory + let inputURL = directory.appendingPathComponent("stdio-input-\(UUID().uuidString)") + let outputURL = directory.appendingPathComponent("stdio-output-\(UUID().uuidString)") + defer { + try? FileManager.default.removeItem(at: inputURL) + try? FileManager.default.removeItem(at: outputURL) + } + try Self.framed(Self.framingMessages).write(to: inputURL) + let input = try FileDescriptor.open(inputURL.path, .readOnly) + let output = try FileDescriptor.open( + outputURL.path, .writeOnly, options: [.create, .truncate], permissions: .ownerReadWrite) + defer { + try? input.close() + try? output.close() + } + + let transport = StdioTransport(input: input, output: output, logger: nil) + try await transport.connect() + let stream: AsyncThrowingStream = await transport.receive() + // kqueue never reports a regular file at its end readable, and epoll refuses regular + // files: the transport reads them without waiting, to the end of the file. + let received = await outcome(within: .seconds(30)) { + var messages: [Data] = [] + for try await message in stream { messages.append(message) } + return messages + } + guard case .returned(let messages) = received else { + Issue.record("Expected the stream to finish at the end of the file, got \(received)") + return + } + #expect(messages == Self.framingMessages) + + let sent = await outcome(within: .seconds(30)) { try await transport.send(Data("{}".utf8)) } + #expect(!sent.didTimeOut) + #expect(sent.error == nil) + await transport.disconnect() + #expect(try Data(contentsOf: outputURL) == Data("{}\n".utf8)) + } + + @Test("/dev/null as input ends the stream, and as output takes every send") + func testDevNull() async throws { + let input = try FileDescriptor.open("/dev/null", .readOnly) + let output = try FileDescriptor.open("/dev/null", .writeOnly) + defer { + try? input.close() + try? output.close() + } + let transport = StdioTransport(input: input, output: output, logger: nil) + try await transport.connect() + let stream: AsyncThrowingStream = await transport.receive() + + // epoll refuses /dev/null, so a dispatch source on it never fires on Linux. + let received = await outcome(within: .seconds(30)) { for try await _ in stream {} } + #expect(!received.didTimeOut) + #expect(received.error == nil) + let sent = await outcome(within: .seconds(30)) { + try await transport.send(Data(repeating: UInt8(ascii: "a"), count: 1 << 20)) + } + #expect(!sent.didTimeOut) + #expect(sent.error == nil) + await transport.disconnect() + } + + // MARK: - End of input and read errors + + /// The messages a stream delivered, kept when the stream then fails. + private actor Delivered { + private(set) var messages: [Data] = [] + func append(_ message: Data) { messages.append(message) } + } + + /// Collects the stream's messages until it finishes, and how it finished. + private static func collect( + _ stream: AsyncThrowingStream + ) async -> (messages: [Data], outcome: Outcome) { + let delivered = Delivered() + let outcome = await outcome(within: .seconds(30)) { + for try await message in stream { await delivered.append(message) } + } + return (await delivered.messages, outcome) + } + + /// The `Errno` a stream that finished by throwing `transportError` carries. + private static func transportErrno(_ outcome: Outcome) -> Errno? { + guard case .transportError(let error) = outcome.mcpError else { return nil } + return error as? Errno + } + + @Test("The end of the input finishes the stream without an error") + func testEndOfInputFinishesNormally() async throws { + let (input, writer) = try FileDescriptor.pipe() + let (reader, output) = try FileDescriptor.pipe() + defer { + try? input.close() + try? reader.close() + try? output.close() + } + let transport = StdioTransport(input: input, output: output, logger: nil) + try await transport.connect() + let stream: AsyncThrowingStream = await transport.receive() + + try writer.writeAll(Data("{\"a\":1}\n".utf8)) + try writer.close() + let (messages, outcome) = await Self.collect(stream) + #expect(!outcome.didTimeOut) + #expect(outcome.error == nil) + #expect(messages == [Data("{\"a\":1}".utf8)]) + await transport.disconnect() + } + + @Test("A failed read finishes the stream with transportError and its errno; sends still work") + func testFailedReadFinishesWithError() async throws { + // A read from a directory fails with EISDIR on Darwin and Linux. + let input = try FileDescriptor.open(FileManager.default.temporaryDirectory.path, .readOnly) + let (reader, output) = try FileDescriptor.pipe() + defer { + try? input.close() + try? reader.close() + try? output.close() + } + let transport = StdioTransport(input: input, output: output, logger: nil) + try await transport.connect() + let stream: AsyncThrowingStream = await transport.receive() + + let (messages, outcome) = await Self.collect(stream) + #expect(!outcome.didTimeOut) + // Before the fix the stream finished as if the input had ended. + #expect(Self.transportErrno(outcome) == .isDirectory, "Got \(outcome)") + #expect(messages.isEmpty) + + // The output is a descriptor of its own: sends go on until disconnect(). + try await transport.send(Data("{}".utf8)) + #expect(try await Self.read(reader, upTo: 3) == Data("{}\n".utf8)) + await transport.disconnect() + await transport.disconnect() + await #expect(throws: MCPError.self) { try await transport.send(Data("{}".utf8)) } + } + + @Test("A reset socket finishes the stream with ECONNRESET after the messages before it") + func testResetSocketFinishesWithError() async throws { + let (input, peer) = try LoopbackTCP.connectedPair() + var peerClosed = false + defer { + _ = close(input) + if !peerClosed { _ = close(peer) } + } + let (reader, output) = try FileDescriptor.pipe() + defer { + try? reader.close() + try? output.close() + } + let transport = StdioTransport(input: FileDescriptor(rawValue: input), output: output, logger: nil) + try await transport.connect() + let stream: AsyncThrowingStream = await transport.receive() + + try FileDescriptor(rawValue: peer).writeAll(Data("{\"a\":1}\n".utf8)) + // Reset only once the message is read: a reset drops what the socket still holds. + #expect(await eventually { await transport.receivedByteCount == 8 }) + peerClosed = true + LoopbackTCP.reset(peer) + + let (messages, outcome) = await Self.collect(stream) + #expect(!outcome.didTimeOut) + #expect(Self.transportErrno(outcome) == .connectionReset, "Got \(outcome)") + #expect(messages == [Data("{\"a\":1}".utf8)]) + await transport.disconnect() + } + + @Test("DescriptorReadiness.wait(afterWouldBlock: true) observes cancellation even when poll reports ready") + func testDescriptorReadinessAfterWouldBlockChecksCancellation() async throws { + let (reader, writer) = try FileDescriptor.pipe() + defer { + try? reader.close() + try? writer.close() + } + let queue = DispatchQueue(label: "mcp.test.readiness") + let writable = try DescriptorReadiness(writer, for: .write, queue: queue) + #expect(writable.isReadyNow()) + + // Without afterWouldBlock, a ready descriptor returns even if the task is cancelled. + let readyTask = Task { + withUnsafeCurrentTask { $0?.cancel() } + try await writable.wait(cancellable: true) + } + try await readyTask.value + + // After EAGAIN (afterWouldBlock: true), cancellation is checked instead of returning + // immediately on poll readiness. + let afterWouldBlockTask = Task { + withUnsafeCurrentTask { $0?.cancel() } + try await writable.wait(cancellable: true, afterWouldBlock: true) + } + await #expect(throws: CancellationError.self) { + try await afterWouldBlockTask.value + } + + await writable.close() + } + + // Glibc's module doesn't export `posix_openpt`, `grantpt`, `unlockpt` and `ptsname` + // (they need `_XOPEN_SOURCE`), and the watchOS and tvOS simulators may refuse /dev/ptmx, + // so the test opens a pseudo-terminal on macOS and iOS (checked on the simulator) only. + #if os(macOS) || os(iOS) + @Test("A terminal as input is read when a line arrives, while sends go on") + func testTerminalInput() async throws { + let primary = posix_openpt(O_RDWR | O_NOCTTY) + try #require(primary >= 0) + defer { _ = close(primary) } + try #require(grantpt(primary) == 0 && unlockpt(primary) == 0) + let path = try #require(ptsname(primary).map { String(cString: $0) }) + let terminalDescriptor = open(path, O_RDONLY | O_NOCTTY) + try #require(terminalDescriptor >= 0) + let terminal = FileDescriptor(rawValue: terminalDescriptor) + let (reader, output) = try FileDescriptor.pipe() + defer { + try? terminal.close() + try? reader.close() + try? output.close() + } + + let transport = StdioTransport(input: terminal, output: output, logger: nil) + try await transport.connect() + let stream: AsyncThrowingStream = await transport.receive() + var messages = stream.makeAsyncIterator() + + // No line is typed yet: a read that blocked the actor would hold this send back. + let sent = await outcome(within: .seconds(30)) { try await transport.send(Data("{}".utf8)) } + #expect(!sent.didTimeOut) + #expect(try await Self.read(reader, upTo: 3) == Data("{}\n".utf8)) + + try FileDescriptor(rawValue: primary).writeAll(Data("{\"a\":1}\n".utf8)) + #expect(try await messages.next() == Data("{\"a\":1}".utf8)) + await transport.disconnect() + } + #endif + + // MARK: - Framing + + /// Messages for the framing tests: an object, a batch, an escaped newline in a string, + /// and the four bytes of U+1F493, which start a 0.12 `NetworkTransport` heartbeat. + static let framingMessages = [ + #"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, + #"[{"jsonrpc":"2.0","id":1,"method":"ping"},{"jsonrpc":"2.0","id":2,"method":"ping"}]"#, + #"{"jsonrpc":"2.0","id":3,"result":{"text":"two\nlines"}}"#, + "{\"jsonrpc\":\"2.0\",\"method\":\"note\",\"params\":{\"text\":\"\u{1F493}\"}}", + ].map { Data($0.utf8) } + + /// `messages`, each followed by a newline. + static func framed(_ messages: [Data]) -> Data { + messages.reduce(into: Data()) { $0 += $1 + Data("\n".utf8) } + } + + @Test("Messages arrive intact when a read ends at any byte") + func testReadEndingAtEveryByte() async throws { + let (input, writer) = try FileDescriptor.pipe() + let (reader, output) = try FileDescriptor.pipe() + defer { + try? input.close() + try? writer.close() + try? reader.close() + try? output.close() + } + let transport = StdioTransport(input: input, output: output, logger: nil) + try await transport.connect() + let stream: AsyncThrowingStream = await transport.receive() + var messages = stream.makeAsyncIterator() + + let bytes = Self.framed(Self.framingMessages) + for split in 1.. = await transport.receive() + + let bytes = Self.framed(Self.framingMessages) + for (index, byte) in bytes.enumerated() { + try writer.writeAll([byte]) + #expect(await eventually { await transport.receivedByteCount == index + 1 }) + } + #expect(await transport.readCount == bytes.count) + try writer.close() + + let received = await outcome(within: .seconds(30)) { + var messages: [Data] = [] + for try await message in stream { messages.append(message) } + return messages + } + guard case .returned(let messages) = received else { + Issue.record("Expected the stream to finish at the end of the input, got \(received)") + return + } + #expect(messages == Self.framingMessages) + await transport.disconnect() + } + + @Test("Several messages in one read arrive intact and in order") + func testSeveralMessagesPerRead() async throws { + let (input, writer) = try FileDescriptor.pipe() + let (reader, output) = try FileDescriptor.pipe() + defer { + try? input.close() + try? writer.close() + try? reader.close() + try? output.close() + } + let transport = StdioTransport(input: input, output: output, logger: nil) + try await transport.connect() + let stream: AsyncThrowingStream = await transport.receive() + var messages = stream.makeAsyncIterator() + + // A pipe write of at most `PIPE_BUF` bytes (512 on Darwin) arrives whole, so one read + // gets every message. + let bytes = Self.framed(Self.framingMessages) + try #require(bytes.count <= Int(PIPE_BUF)) + try writer.writeAll(bytes) + for expected in Self.framingMessages { + #expect(try await messages.next() == expected) + } + #expect(await transport.readCount == 1) + await transport.disconnect() + } } diff --git a/Tests/MCPTests/SubscriptionTests.swift b/Tests/MCPTests/SubscriptionTests.swift index 6842a72d..72bac677 100644 --- a/Tests/MCPTests/SubscriptionTests.swift +++ b/Tests/MCPTests/SubscriptionTests.swift @@ -329,6 +329,129 @@ struct SubscriptionTests { )) } + @Test("A stream receives a resource or task event only for the same code points") + func testEventsMatchExactly() { + // U+00C5, and A with U+030A: equal as Swift strings, different on the wire. + let (precomposed, decomposed) = ("test://\u{C5}", "test://A\u{30A}") + let (kelvin, kelvinSign) = ("task-K", "task-\u{212A}") + let filter = SubscriptionFilter(resourceSubscriptions: [precomposed], taskIds: [kelvin]) + #expect(SubscriptionEvent.resourceUpdated(uri: precomposed).matches(filter)) + #expect(!SubscriptionEvent.resourceUpdated(uri: decomposed).matches(filter)) + #expect(SubscriptionEvent.task(id: kelvin, snapshot: [:]).matches(filter)) + #expect(!SubscriptionEvent.task(id: kelvinSign, snapshot: [:]).matches(filter)) + + let resources: Set = [ExactString(precomposed)] + let tasks: Set = [ExactString(kelvin)] + #expect(SubscriptionEvent.resourceUpdated(uri: precomposed).matches(filter, resources: resources, tasks: tasks)) + #expect(!SubscriptionEvent.resourceUpdated(uri: decomposed).matches(filter, resources: resources, tasks: tasks)) + #expect(SubscriptionEvent.task(id: kelvin, snapshot: [:]).matches(filter, resources: resources, tasks: tasks)) + #expect(!SubscriptionEvent.task(id: kelvinSign, snapshot: [:]).matches(filter, resources: resources, tasks: tasks)) + } + + @Test("subscriptions/listen keeps canonically equivalent resource URIs and task IDs") + func testCheckedDeduplicatesByExactCodePoints() async throws { + let manager = TaskManager() + let (kelvinTask, signTask) = ("task-K", "task-\u{212A}") + for id in [signTask, kelvinTask] { + try await manager.store.insert( + TaskRecord( + id: id, owner: nil, protocolVersion: Version.v2026_07_28, method: CallTool.name, + status: .working, createdAt: Date(), ttlMs: nil, pollIntervalMs: 10)) + } + let server = makeListenServer() + await server.withTasks(manager) + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + try await server.start(transport: serverTransport) + let client = Client( + name: "probe", version: "1.0", + capabilities: .init(extensions: [ExtensionID.tasks: [:]]), + configuration: .init(protocolMode: .automatic)) + defer { Task { await client.disconnect(); await server.stop() } } + + let inbox = Inbox() + await client.onNotification(ResourceUpdatedNotification.self) { message in + await inbox.add(message.params.uri, message._meta?.subscriptionID) + } + try await client.connect(transport: clientTransport) + + let (precomposed, decomposed) = ("file:///caf\u{E9}", "file:///cafe\u{301}") + let subscription = try await client.listen( + .init(resourceSubscriptions: [precomposed, decomposed], taskIds: [signTask, kelvinTask])) + let honoredURIs = try #require(subscription.notifications.resourceSubscriptions) + #expect(honoredURIs.map(ExactString.init) == [ExactString(precomposed), ExactString(decomposed)]) + let honoredTasks = try #require(subscription.notifications.taskIds) + #expect(honoredTasks.map(ExactString.init) == [ExactString(signTask), ExactString(kelvinTask)]) + + try await server.notify(ResourceUpdatedNotification.message(.init(uri: precomposed))) + try await server.notify(ResourceUpdatedNotification.message(.init(uri: decomposed))) + #expect( + await eventually { + let uris = await inbox.received.filter { $0.subscriptionID == subscription.id }.map(\.method) + return uris.map(ExactString.init) == [ExactString(precomposed), ExactString(decomposed)] + }) + await subscription.cancel() + } + + @Test("Client 2026-07-28 resource subscriptions track canonically equivalent URIs separately") + func testClientResourceSubscriptionsMatchExactly() async throws { + let server = makeListenServer() + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + try await server.start(transport: serverTransport) + let client = Client(name: "probe", version: "1.0", configuration: .init(protocolMode: .automatic)) + defer { Task { await client.disconnect(); await server.stop() } } + + let inbox = Inbox() + await client.onNotification(ResourceUpdatedNotification.self) { message in + await inbox.add(message.params.uri, message._meta?.subscriptionID) + } + try await client.connect(transport: clientTransport) + + let (precomposed, decomposed) = ("test://\u{C5}", "test://A\u{30A}") + try await client.subscribeToResource(uri: precomposed) + try await client.subscribeToResource(uri: decomposed) + #expect(await client.subscribedResources.map(ExactString.init) == [ExactString(precomposed), ExactString(decomposed)]) + + try await server.notify(ResourceUpdatedNotification.message(.init(uri: precomposed))) + try await server.notify(ResourceUpdatedNotification.message(.init(uri: decomposed))) + #expect( + await eventually { + let uris = await inbox.methods.map(ExactString.init) + return uris.contains(ExactString(precomposed)) && uris.contains(ExactString(decomposed)) + }) + + // Unsubscribing one spelling keeps the other subscribed. + try await client.unsubscribeFromResource(uri: precomposed) + #expect(await client.subscribedResources.map(ExactString.init) == [ExactString(decomposed)]) + #expect( + await eventually { + await client.notificationStream?.notifications.resourceSubscriptions?.map(ExactString.init) + == [ExactString(decomposed)] + }) + #expect(await eventually { await server.openSubscriptionCount == 1 }) + let countBefore = await inbox.methods.count + try await server.notify(ResourceUpdatedNotification.message(.init(uri: precomposed))) + try await server.notify(ResourceUpdatedNotification.message(.init(uri: decomposed))) + #expect( + await eventually { + let added = await inbox.methods.dropFirst(countBefore).map(ExactString.init) + return added.contains(ExactString(decomposed)) + }) + let addedAfterUnsubscribe = await inbox.methods.dropFirst(countBefore).map(ExactString.init) + #expect(!addedAfterUnsubscribe.contains(ExactString(precomposed))) + + // Replacing one spelling with a canonically equivalent one reopens the stream. + try await client.unsubscribeFromResource(uri: decomposed) + try await client.subscribeToResource(uri: precomposed) + #expect(await client.subscribedResources.map(ExactString.init) == [ExactString(precomposed)]) + let countBeforeSwap = await inbox.methods.count + try await server.notify(ResourceUpdatedNotification.message(.init(uri: precomposed))) + #expect( + await eventually { + let added = await inbox.methods.dropFirst(countBeforeSwap).map(ExactString.init) + return added.contains(ExactString(precomposed)) + }) + } + // MARK: Automatic streams @Test("Handlers for list changes open a background listen stream") @@ -423,6 +546,78 @@ struct SubscriptionTests { #expect(await eventually { await server.openSubscriptionCount == 0 }) } + @Test("subscribedResourceURIs lists handshake subscriptions until unsubscribe or disconnect") + func testHandshakeSubscribedResourceURIs() async throws { + let server = makeListenServer() + await server.withMethodHandler(ResourceSubscribe.self) { _ in Empty() } + await server.withMethodHandler(ResourceUnsubscribe.self) { _ in Empty() } + let client = try await connect(server, mode: .handshake) + defer { Task { await server.stop() } } + + try await client.subscribeToResource(uri: "test://a") + #expect(await client.subscribedResourceURIs == ["test://a"]) + try await client.unsubscribeFromResource(uri: "test://a") + #expect(await client.subscribedResourceURIs.isEmpty) + + try await client.subscribeToResource(uri: "test://a") + #expect(await client.subscribedResourceURIs == ["test://a"]) + await client.disconnect() + #expect(await client.subscribedResourceURIs.isEmpty) + } + + @Test("Handshake subscriptions keep canonically equivalent URIs distinct") + func testHandshakeSubscriptionsMatchExactScalars() async throws { + let server = makeListenServer() + await server.withMethodHandler(ResourceSubscribe.self) { _ in Empty() } + await server.withMethodHandler(ResourceUnsubscribe.self) { _ in Empty() } + let client = try await connect(server, mode: .handshake) + defer { Task { await client.disconnect(); await server.stop() } } + + let precomposed = "test://caf\u{E9}" + let decomposed = "test://cafe\u{301}" + #expect(precomposed == decomposed) + #expect(!precomposed.isExactly(decomposed)) + + try await client.subscribeToResource(uri: precomposed) + try await client.subscribeToResource(uri: decomposed) + // Set merges canonically equivalent spellings into one entry while both stay subscribed. + #expect(await client.subscribedResourceURIs.count == 1) + // Unsubscribing the decomposed spelling must leave the precomposed subscription listed. + try await client.unsubscribeFromResource(uri: decomposed) + let remaining = try #require(await client.subscribedResourceURIs.first) + #expect(await client.subscribedResourceURIs.count == 1) + #expect(remaining.isExactly(precomposed)) + + // Unsubscribing a non-matching canonical spelling again still leaves precomposed listed. + try await client.unsubscribeFromResource(uri: decomposed) + #expect(await client.subscribedResourceURIs.count == 1) + + try await client.unsubscribeFromResource(uri: precomposed) + #expect(await client.subscribedResourceURIs.isEmpty) + } + + @Test("A refused resources/subscribe isn't listed, and a refused resources/unsubscribe keeps its URI") + func testHandshakeRefusedSubscription() async throws { + let server = makeListenServer() + await server.withMethodHandler(ResourceSubscribe.self) { params in + guard params.uri == "test://a" else { throw MCPError.invalidParams("No resource at \(params.uri)") } + return Empty() + } + await server.withMethodHandler(ResourceUnsubscribe.self) { _ in + throw MCPError.internalError("Unsubscribe failed") + } + let client = try await connect(server, mode: .handshake) + defer { Task { await client.disconnect(); await server.stop() } } + + await #expect(throws: MCPError.self) { try await client.subscribeToResource(uri: "test://b") } + #expect(await client.subscribedResourceURIs.isEmpty) + + try await client.subscribeToResource(uri: "test://a") + // The server still sends updates for a URI it failed to unsubscribe. + await #expect(throws: MCPError.self) { try await client.unsubscribeFromResource(uri: "test://a") } + #expect(await client.subscribedResourceURIs == ["test://a"]) + } + @Test("A replacement stream that fails to open leaves the working stream open") func testFailedReplacementKeepsStream() async throws { let server = makeListenServer() @@ -736,6 +931,12 @@ struct SubscriptionTests { } throws: { error in (error as? MCPError)?.code == -32602 } + // The same limit applies to task IDs, separately. + await #expect { + _ = try await client.listen(.init(taskIds: ["t1", "t2", "t3"])) + } throws: { error in + (error as? MCPError)?.code == -32602 + } let long = "test://" + String(repeating: "x", count: Server.maxSubscriptionURILength) await #expect(throws: MCPError.self) { _ = try await client.listen(.init(resourceSubscriptions: [long])) } } @@ -796,7 +997,7 @@ private actor ListenScript: Transport { continuation.finish() } func receive() -> AsyncThrowingStream { stream } - func send(_ data: Data) async throws { + func send(_ data: Data, options: TransportSendOptions) async throws { let message = try JSONDecoder().decode(Value.self, from: data).objectValue ?? [:] sent.append(message) if holdingCancellations, message["method"] == "notifications/cancelled" { diff --git a/Tests/MCPTests/TaskTests.swift b/Tests/MCPTests/TaskTests.swift index 9ac0eb19..36633b75 100644 --- a/Tests/MCPTests/TaskTests.swift +++ b/Tests/MCPTests/TaskTests.swift @@ -159,6 +159,90 @@ struct TaskWireTests { #expect(v2.lastUpdatedAt == "x") } + @Test("A task decoded from the 2025-11-25 form equals the same task built in code") + func equalityIgnoresGeneration() throws { + let decodedV1 = try decoded( + TaskSnapshot.self, + #"{"taskId":"t","status":"working","createdAt":"2026-09-21T14:13:20Z","ttl":1000}"#) + let built = TaskSnapshot( + taskId: "t", status: .working, createdAt: "2026-09-21T14:13:20Z", + lastUpdatedAt: "2026-09-21T14:13:20Z", ttlMs: 1000) + #expect(decodedV1.generation == .v1) + #expect(built.generation == .v2) + #expect(decodedV1 == built) + #expect(decodedV1.hashValue == built.hashValue) + #expect(Set([decodedV1, built, built.shaped(as: .v1)]).count == 1) + // The form still selects the encoding. + #expect(try encoded(decodedV1).objectValue?["ttl"] == 1000) + #expect(try encoded(built).objectValue?["ttlMs"] == 1000) + } + + @Test("Task timing fields decode leniently in both generations", arguments: millisecondCases) + func lenientTimings(literal: String, expected: Int?) throws { + let v2 = try decoded( + TaskSnapshot.self, + #"{"taskId":"a","status":"working","createdAt":"x","ttlMs":\#(literal),"pollIntervalMs":\#(literal)}"#) + #expect(v2.generation == .v2) + #expect(v2.ttlMs == expected) + #expect(v2.pollIntervalMs == expected) + let v1 = try decoded( + TaskSnapshot.self, + #"{"taskId":"a","status":"working","createdAt":"x","ttl":\#(literal),"pollInterval":\#(literal)}"#) + #expect(v1.generation == .v1) + #expect(v1.ttlMs == expected) + #expect(v1.pollIntervalMs == expected) + #expect(try decoded(TaskMetadata.self, #"{"ttl":\#(literal)}"#).ttl == expected) + #expect(try decoded(TaskMetadata.self, "{}").ttl == nil) + } + + @Test("Task payloads from other SDKs decode") + func otherSDKPayloads() throws { + // The result that creates a task at 2025-11-25, as the TypeScript SDK sends it. + let created = try decoded( + CallTool.Result.self, + #"{"task":{"taskId":"t","status":"working","createdAt":"2026-01-01T00:00:00Z","lastUpdatedAt":"2026-01-01T00:00:00Z","ttl":60000,"pollInterval":100}}"# + ) + let task = try #require(created.task) + #expect(task.generation == .v1) + #expect(task.ttlMs == 60_000) + #expect(task.pollIntervalMs == 100) + // Floats from a dynamically typed peer, and null. + let float = try decoded( + TaskSnapshot.self, + #"{"taskId":"t","status":"working","createdAt":"x","ttlMs":300000.0,"pollIntervalMs":null}"#) + #expect(float.ttlMs == 300_000) + #expect(float.pollIntervalMs == nil) + let unlimited = try decoded( + TaskSnapshot.self, #"{"taskId":"t","status":"working","createdAt":"x","ttl":null,"pollInterval":5000.0}"#) + #expect(unlimited.generation == .v1) + #expect(unlimited.ttlMs == nil) + #expect(unlimited.pollIntervalMs == 5000) + } + + @Test("Task timing fields encode as integers") + func timingGoldens() throws { + #expect(try wireString(TaskMetadata(ttl: 60_000)) == #"{"ttl":60000}"#) + #expect(try wireString(TaskMetadata()) == "{}") + #expect( + try wireString(record(ttlMs: 60_000).snapshot(detailed: false)) + == #"{"createdAt":"2026-09-21T14:13:20.250Z","lastUpdatedAt":"2026-09-21T14:13:20.250Z","pollIntervalMs":500,"status":"working","taskId":"t1","ttlMs":60000}"# + ) + #expect( + try wireString(record(Version.v2025_11_25, ttlMs: nil).snapshot(detailed: false)) + == #"{"createdAt":"2026-09-21T14:13:20.250Z","lastUpdatedAt":"2026-09-21T14:13:20.250Z","pollInterval":500,"status":"working","taskId":"t1","ttl":null}"# + ) + } + + @Test("A stored task record keeps its keys") + func storedRecordKeys() throws { + let stored = try wireString(record()) + #expect( + stored + == #"{"createdAt":811692800.25,"id":"t1","inputRequests":{},"lastUpdatedAt":811692800.25,"method":"tools/call","pollIntervalMs":500,"protocolVersion":"2026-07-28","status":"working","ttlMs":60000}"# + ) + #expect(try decoded(TaskRecord.self, stored) == record()) + } + @Test("The result that creates a task: flat at 2026-07-28, nested at 2025-11-25") func createTaskResult() throws { let v2 = CallTool.Result.creating(record().snapshot(detailed: false)) @@ -239,7 +323,7 @@ struct TaskWireTests { #expect(!Version.profile(for: Version.v2026_07_28).usesTaskAugmentation) } - @Test("Timestamps, identifiers and durations") + @Test("Timestamps and identifiers") func helpers() { #expect(TaskTimestamp.string(from: Date(timeIntervalSince1970: 0)) == "1970-01-01T00:00:00.000Z") #expect(TaskTimestamp.date(from: "2026-09-21T14:13:20.250Z") == created) @@ -248,9 +332,43 @@ struct TaskWireTests { let ids = Set((0..<100).map { _ in TaskIdentifier.make() }) #expect(ids.count == 100) #expect(ids.allSatisfy { $0.count == 22 && !$0.contains("+") && !$0.contains("/") && !$0.contains("=") }) - #expect(Duration.milliseconds(1500).wholeMilliseconds == 1500) - #expect(Duration.microseconds(1).wholeMilliseconds == 1) - #expect(Duration.zero.wholeMilliseconds == 0) + } + + // Seconds since 1970, not `Date`s: on Linux `Date.description` traps for some of these + // dates, and Swift Testing prints each argument. + @Test( + "A stored date outside 1970 to 9999 is written as the nearer bound, and reads back", + arguments: [ + (1_790_000_000.25, "2026-09-21T14:13:20.250Z", 1_790_000_000.25), (0, "1970-01-01T00:00:00.000Z", 0), + (253_402_300_799, "9999-12-31T23:59:59.000Z", 253_402_300_799), + (-1, "1970-01-01T00:00:00.000Z", 0), (-1e12, "1970-01-01T00:00:00.000Z", 0), + (-.infinity, "1970-01-01T00:00:00.000Z", 0), (.nan, "1970-01-01T00:00:00.000Z", 0), + (253_402_300_800, "9999-12-31T23:59:59.000Z", 253_402_300_799), + (.infinity, "9999-12-31T23:59:59.000Z", 253_402_300_799), + ] as [(TimeInterval, String, TimeInterval)]) + func outOfRangeTimestamps(seconds: TimeInterval, expected: String, readBack: TimeInterval) throws { + let date = Date(timeIntervalSince1970: seconds) + let string = TaskTimestamp.string(from: date) + #expect(string == expected) + let parsed = try #require(TaskTimestamp.date(from: string)) + #expect(abs(parsed.timeIntervalSince1970 - readBack) < 0.001) + let record = TaskRecord( + id: "t", owner: nil, protocolVersion: Version.v2026_07_28, method: CallTool.name, createdAt: date, + ttlMs: nil, pollIntervalMs: nil) + let snapshot = record.snapshot(detailed: true) + #expect(snapshot.createdAt == expected) + #expect(snapshot.lastUpdatedAt == expected) + } + + @Test( + "A date just before the 2001 reference epoch clamps milliseconds to 999 instead of emitting .1000Z", + arguments: [-1e-17, -Double.leastNormalMagnitude, -Double.leastNonzeroMagnitude]) + func subFemtosecondNegativeReferenceDate(intervalSinceReferenceDate: TimeInterval) throws { + let date = Date(timeIntervalSinceReferenceDate: intervalSinceReferenceDate) + let string = TaskTimestamp.string(from: date) + #expect(string == "2000-12-31T23:59:59.999Z") + let parsed = try #require(TaskTimestamp.date(from: string)) + #expect(abs(parsed.timeIntervalSinceReferenceDate - (-0.001)) < 0.0005) } @Test("Mcp-Name carries the task id of tasks/get, tasks/update and tasks/cancel") @@ -312,6 +430,11 @@ private func makeTaskServer( let names = [first["q"], second["q"]].map { $0?.elicitation?.content?["name"]?.stringValue ?? "?" } return .init(content: [.text(text: names.joined(separator: ","))]) } + case "askKelvin": + return try await Server.runAsTask { task in + let answer = try await task.requestInput(["K": .elicitation(message: "Name?")]) + return .init(content: [.text(text: answer["K"]?.elicitation?.content?["name"]?.stringValue ?? "?")]) + } case "toolError": return try await Server.runAsTask { _ in .init(content: [.text(text: "bad")], isError: true) } case "dataText": @@ -381,6 +504,7 @@ private struct TaskServer { Tool(name: "must", description: nil, inputSchema: [:], execution: .init(taskSupport: .required)), Tool(name: "ask", description: nil, inputSchema: [:], execution: .init(taskSupport: .optional)), Tool(name: "askTwice", description: nil, inputSchema: [:], execution: .init(taskSupport: .optional)), + Tool(name: "askKelvin", description: nil, inputSchema: [:], execution: .init(taskSupport: .optional)), Tool(name: "toolError", description: nil, inputSchema: [:], execution: .init(taskSupport: .optional)), Tool(name: "protocolError", description: nil, inputSchema: [:], execution: .init(taskSupport: .optional)), Tool(name: "plainError", description: nil, inputSchema: [:], execution: .init(taskSupport: .optional)), @@ -649,6 +773,130 @@ struct StatelessTaskServerTests { #expect(done["result"]?.objectValue?["content"] == [["type": "text", "text": "Ada"]]) } + @Test("Input: a response key answers only the request key with the same code points") + func inputKeysMatchExactly() async throws { + let server = try await TaskServer() + defer { Task { await server.stop() } } + let id = try #require(try await server.call("askKelvin")["taskId"]?.stringValue) + let waiting = try await server.wait(id, for: "input_required") + #expect(waiting["inputRequests"]?.objectValue?.keys.sorted() == ["K"]) + + // U+212A KELVIN SIGN: equal to "K" as a Swift string, another key. + let answer: Value = ["action": "accept", "content": ["name": "Ada"]] + let ignored = try await server.result( + UpdateTask.name, ["taskId": .string(id), "inputResponses": ["\u{212A}": answer]]) + #expect(ignored["resultType"] == "complete") + let still = try await server.get(id) + #expect(still["status"] == "input_required") + #expect(still["inputRequests"]?.objectValue?.keys.sorted() == ["K"]) + + _ = try await server.result(UpdateTask.name, ["taskId": .string(id), "inputResponses": ["K": answer]]) + let done = try await server.wait(id) + #expect(done["status"] == "completed") + #expect(done["result"]?.objectValue?["content"] == [["type": "text", "text": "Ada"]]) + } + + @Test("A task id names only the task with the same code points") + func taskIDsMatchExactly() async throws { + let manager = TaskManager() + try await manager.store.insert( + TaskRecord( + id: "task-K", owner: nil, protocolVersion: Version.v2026_07_28, method: CallTool.name, + status: .completed, createdAt: Date(), ttlMs: nil, pollIntervalMs: 10, + result: try Value(CallTool.Result(content: [.text(text: "stored")])))) + let server = try await TaskServer(manager: manager) + defer { Task { await server.stop() } } + + #expect(try await server.get("task-K")["taskId"] == "task-K") + // U+212A KELVIN SIGN: equal to "K" as a Swift string, another id. + let sign = "task-\u{212A}" + #expect(try await server.errorCode(GetTask.name, ["taskId": .string(sign)]) == -32602) + #expect(try await server.errorCode(CancelTask.name, ["taskId": .string(sign)]) == -32602) + #expect( + try await server.errorCode( + UpdateTask.name, ["taskId": .string(sign), "inputResponses": ["k": ["action": "decline"]]]) == -32602) + } + + @Test("InMemoryTaskStore and TaskManager match task IDs and owners by exact code points") + func storeAndManagerMatchIDsAndOwnersExactly() async throws { + // U+212A KELVIN SIGN equals "K" under Swift canonical equality. + let (kelvinID, signID) = ("task-K", "task-\u{212A}") + let (kelvinOwner, signOwner) = ("owner-K", "owner-\u{212A}") + + // InMemoryTaskStore keeps canonically equivalent IDs and owners distinct. + let store = InMemoryTaskStore() + let first = TaskRecord( + id: kelvinID, owner: kelvinOwner, protocolVersion: Version.v2026_07_28, method: CallTool.name, + status: .completed, createdAt: Date(), ttlMs: nil, pollIntervalMs: 10) + let second = TaskRecord( + id: signID, owner: signOwner, protocolVersion: Version.v2026_07_28, method: CallTool.name, + status: .completed, createdAt: Date(), ttlMs: nil, pollIntervalMs: 10) + await store.insert(first) + await store.insert(second) + #expect(await store.record(id: kelvinID)?.id.isExactly(kelvinID) == true) + #expect(await store.record(id: signID)?.id.isExactly(signID) == true) + #expect(await store.records(owner: kelvinOwner).map(\.id).map(ExactString.init) == [ExactString(kelvinID)]) + #expect(await store.records(owner: signOwner).map(\.id).map(ExactString.init) == [ExactString(signID)]) + await store.remove(id: signID) + #expect(await store.record(id: kelvinID) != nil) + #expect(await store.record(id: signID) == nil) + + // A canonical String-keyed custom store must not have an expired task removed + // when looked up under a mismatched spelling, and must remove by the record's own ID. + actor CanonicalStore: TaskStore { + var tasks: [String: TaskRecord] = [:] + private(set) var removedIDs: [String] = [] + func insert(_ record: TaskRecord) { tasks[record.id] = record } + func record(id: String) -> TaskRecord? { tasks[id] } + func update(_ record: TaskRecord) { tasks[record.id] = record } + func remove(id: String) { + removedIDs.append(id) + tasks[id] = nil + } + func records(owner: String?) -> [TaskRecord] { tasks.values.filter { $0.owner == owner } } + func removeExpired(asOf date: Date) -> [String] { [] } + } + let customStore = CanonicalStore() + let expired = TaskRecord( + id: kelvinID, owner: kelvinOwner, protocolVersion: Version.v2026_07_28, method: CallTool.name, + status: .working, createdAt: Date().addingTimeInterval(-60), ttlMs: 1, pollIntervalMs: 10) + await customStore.insert(expired) + let customManager = TaskManager(store: customStore) { $0.clientInfo?.name } + let kelvinContext = Server.HandlerContext( + id: 1, httpContext: nil, clientInfo: .init(name: kelvinOwner, version: "1")) + let signContext = Server.HandlerContext( + id: 2, httpContext: nil, clientInfo: .init(name: signOwner, version: "1")) + + // Mismatched spelling must return nil without expiring or removing the real task. + #expect(try await customManager.lookup(signID, context: kelvinContext, generation: .v2) == nil) + #expect(await customStore.removedIDs.isEmpty) + // Exact spelling expires and removes by the record's exact ID. + #expect(try await customManager.lookup(kelvinID, context: kelvinContext, generation: .v2) == nil) + #expect(await customStore.removedIDs.map(ExactString.init) == [ExactString(kelvinID)]) + + // Owner isolation in lookup, list, and per-principal capacity. + let ownerManager = TaskManager( + configuration: .init(maxActiveTasks: 10, maxActiveTasksPerPrincipal: 1) + ) { $0.clientInfo?.name } + let createdForKelvin = try #require( + try await ownerManager.create( + context: kelvinContext, method: CallTool.name, protocolVersion: Version.v2026_07_28, + requestedTTL: nil, ttl: nil, pollInterval: nil)) + #expect(try await ownerManager.lookup(createdForKelvin.id, context: kelvinContext, generation: .v2) != nil) + #expect(try await ownerManager.lookup(createdForKelvin.id, context: signContext, generation: .v2) == nil) + #expect(try await ownerManager.list(context: signContext, generation: .v2).isEmpty) + // Per-principal limit of 1 for kelvinOwner does not block canonically equivalent signOwner. + let createdForSign = try await ownerManager.create( + context: signContext, method: CallTool.name, protocolVersion: Version.v2026_07_28, + requestedTTL: nil, ttl: nil, pollInterval: nil) + #expect(createdForSign != nil) + // Second task for kelvinOwner is blocked by its own per-principal limit of 1. + let blockedForKelvin = try await ownerManager.create( + context: kelvinContext, method: CallTool.name, protocolVersion: Version.v2026_07_28, + requestedTTL: nil, ttl: nil, pollInterval: nil) + #expect(blockedForKelvin == nil) + } + @Test("Input keys stay unique for the life of the task") func inputKeys() async throws { let server = try await TaskServer() @@ -1124,6 +1372,49 @@ struct ClientTaskTests { #expect(await client.taskPollerCount() == 0) } + @Test("A task notification wakes only the poller of the task with the same code points") + func taskNotificationsMatchExactly() async throws { + let transport = MockTransport() + let client = Client(name: "c", version: "1", configuration: .handshake) + let initialize = Task { + try await transport.waitForSentMessages() + let data = try #require(await transport.sentMessages.last?.data(using: .utf8)) + let request = try JSONDecoder().decode(Request.self, from: data) + try await transport.queue( + response: Initialize.response( + id: request.id, + result: .init( + protocolVersion: Version.latestHandshake, capabilities: .init(tools: .init()), + serverInfo: .init(name: "s", version: "1"), instructions: nil))) + } + try await client.connect(transport: transport) + try await initialize.value + defer { Task { await client.disconnect() } } + func notify(_ escapedID: String) async { + await transport.queue( + data: Data( + #"{"jsonrpc":"2.0","method":"notifications/tasks/status","params":{"taskId":"\#(escapedID)","status":"working","createdAt":"2026-01-01T00:00:00Z","lastUpdatedAt":"2026-01-01T00:00:00Z","ttlMs":null}}"# + .utf8)) + } + + let exact = Task { try await client.waitForTask("task-K", timeout: .seconds(60)) } + #expect(await eventually { await client.taskPollerCount() == 1 }) + + // U+212A KELVIN SIGN: equal to "K" as a Swift string, another task. + // Its poller returns once the notification is handled. + await notify(#"task-\u212A"#) + let sign = await outcome(within: .seconds(10)) { + try await client.waitForTask("task-\u{212A}", timeout: .seconds(60)) + } + #expect(!sign.didTimeOut, "the notification did not reach its own task") + #expect(await client.taskPollerCount() == 1, "the notification woke the poller of another task") + + await notify("task-K") + let woken = await outcome(within: .seconds(10)) { try await exact.value } + #expect(!woken.didTimeOut) + #expect(await client.taskPollerCount() == 0) + } + @Test("Poll intervals are kept within the configured bounds") func pollBounds() throws { let options = Client.Configuration.Tasks( @@ -1133,6 +1424,8 @@ struct ClientTaskTests { #expect(options.pollInterval(suggested: 60_000) == .seconds(2)) #expect(options.pollInterval(suggested: nil) == .milliseconds(700)) #expect(options.pollInterval(suggested: 250) == .milliseconds(250)) + #expect(options.pollInterval(suggested: Int.max) == options.maximumPollInterval) + #expect(options.pollInterval(suggested: 0) == options.minimumPollInterval) let configuration = Client.Configuration(tasks: options) let data = try JSONEncoder().encode(configuration) @@ -1142,6 +1435,50 @@ struct ClientTaskTests { let partial = try JSONDecoder().decode(Client.Configuration.Tasks.self, from: Data("{}".utf8)) #expect(partial == .init()) } + + @Test("Saved task options write durations in milliseconds") + func savedTaskOptions() throws { + #expect( + try wireString(Client.Configuration.Tasks()) + == #"{"augmentation":"whenRequired","defaultPollIntervalMs":1000,"maximumPollIntervalMs":30000,"minimumPollIntervalMs":100}"# + ) + let options = Client.Configuration.Tasks( + minimumPollInterval: .microseconds(2500), maximumPollInterval: .seconds(Int64.max), + defaultPollInterval: .seconds(-1), augmentation: .whenSupported, requestedTTL: .seconds(90)) + let saved = try wireString(options) + #expect( + saved + == #"{"augmentation":"whenSupported","defaultPollIntervalMs":0,"maximumPollIntervalMs":\#(Int.max),"minimumPollIntervalMs":2,"requestedTimeToLiveMs":90000}"# + ) + let loaded = try JSONDecoder().decode(Client.Configuration.Tasks.self, from: Data(saved.utf8)) + #expect(loaded.minimumPollInterval == .milliseconds(2)) + #expect(loaded.maximumPollInterval == .milliseconds(Int.max)) + #expect(loaded.defaultPollInterval == .zero) + #expect(loaded.requestedTTL == .seconds(90)) + let invalid = #"{"minimumPollIntervalMs":-5,"defaultPollIntervalMs":"soon","requestedTimeToLiveMs":null}"# + #expect(try JSONDecoder().decode(Client.Configuration.Tasks.self, from: Data(invalid.utf8)) == .init()) + } + + @Test("Task options saved with the old duration form still decode") + func oldTaskOptions() throws { + func old(_ duration: Duration) throws -> String { + String(decoding: try JSONEncoder().encode(duration), as: UTF8.self) + } + let saved = """ + {"minimumPollInterval":\(try old(.milliseconds(5))),"maximumPollInterval":\(try old(.seconds(3))),\ + "defaultPollInterval":\(try old(.milliseconds(1500))),"requestedTTL":\(try old(.seconds(60)))} + """ + let options = try JSONDecoder().decode(Client.Configuration.Tasks.self, from: Data(saved.utf8)) + #expect( + options + == .init( + minimumPollInterval: .milliseconds(5), maximumPollInterval: .seconds(3), + defaultPollInterval: .milliseconds(1500), requestedTTL: .seconds(60))) + // The millisecond key wins over the old one. + let both = Data(#"{"requestedTimeToLiveMs":1000,"requestedTTL":\#(try old(.seconds(60)))}"#.utf8) + #expect(try JSONDecoder().decode(Client.Configuration.Tasks.self, from: both).requestedTTL == .seconds(1)) + #expect(!(try wireString(options).contains("requestedTTL"))) + } } // MARK: - Server at 2025-11-25 @@ -1424,6 +1761,21 @@ struct HandshakeTaskServerTests { #expect(try await server.errorCode(ListTasks.name, ["cursor": "bogus"]) == -32602) } + @Test("A tasks/list cursor names only the task with the same code points") + func listCursorMatchesExactly() async throws { + let manager = TaskManager { context in context.clientInfo?.name } + try await manager.store.insert( + TaskRecord( + id: "task-K", owner: "c", protocolVersion: Version.v2025_11_25, method: CallTool.name, + createdAt: Date(), ttlMs: nil, pollIntervalMs: 10)) + let server = try await HandshakeTaskServer(manager: manager) + defer { Task { await server.stop() } } + let listed = try await server.result(ListTasks.name, ["cursor": "task-K"]) + #expect(listed["tasks"]?.arrayValue?.compactMap { $0.objectValue?["taskId"] } == ["task-K"]) + // U+212A KELVIN SIGN: equal to "K" as a Swift string, another id. + #expect(try await server.errorCode(ListTasks.name, ["cursor": "task-\u{212A}"]) == -32602) + } + @Test("tasks/update does not exist at 2025-11-25; a v1 task is not visible at 2026-07-28") func generations() async throws { let server = try await HandshakeTaskServer() @@ -1574,6 +1926,31 @@ struct HandshakeClientTaskTests { #expect(ContinuousClock.now - start < .seconds(5)) } + @Test( + "A client asks for a task lifetime in whole milliseconds", + arguments: [ + (Duration.seconds(Int64.max), String(Int.max)), (.microseconds(1500), "1"), (.seconds(-1), "0"), + ]) + func requestedLifetime(requested: Duration, ttl: String) async throws { + let server = await makeTaskServer(manager: TaskManager()) + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + try await server.start(transport: serverTransport) + let transport = FlakyTransport(clientTransport) + let client = Client( + name: "c", version: "1", + configuration: .init(protocolMode: .handshake, tasks: .init(requestedTTL: requested))) + try await client.connect(transport: transport) + defer { Task { await client.disconnect(); await server.stop() } } + _ = try await client.listTools() + + #expect(try await client.startToolCall(name: "must").value.task != nil) + let call = try #require( + await transport.sent.last { + (try? JSONDecoder().decode(Value.self, from: Data($0.utf8)))?.objectValue?["method"] == "tools/call" + }) + #expect(call.contains(#""task":{"ttl":\#(ttl)}"#)) + } + @Test("A tool the client has not listed is called without a task") func unlisted() async throws { let server = await makeTaskServer(manager: TaskManager()) @@ -2189,6 +2566,134 @@ struct TaskLifecycleEdgeTests { #expect(await manager.changeWaiterCount(short.id) == 0) } + @Test("Waiting on a task with the longest lifetime a client can ask for ends at its timeout") + func longestLifetimeWait() async throws { + let manager = TaskManager(configuration: .init(maximumTTL: nil)) + let record = try #require( + try await manager.create( + context: Server.HandlerContext(id: 1, httpContext: nil), method: CallTool.name, + protocolVersion: Version.v2025_11_25, requestedTTL: Int.max, ttl: nil, pollInterval: nil)) + #expect(record.ttlMs == Int.max) + try await manager.waitForChange(record.id, from: record, timeout: .milliseconds(1)) + #expect(await manager.changeWaiterCount(record.id) == 0) + } + + // Creation dates a `TaskStore` may return, from a corrupt row or another epoch unit: + // not finite, or finite but past the range of `Duration`. They are seconds since the + // reference date, not `Date`s: Swift Testing prints each argument, and on Linux + // `Date.description` traps for some of these dates. + @Test( + "Waiting on a stored task with a creation date out of range ends instead of trapping", + .timeLimit(.minutes(2)), + arguments: [ + Double.infinity, -.infinity, .nan, 1e300, -1e300, 1e21, + Date.distantFuture.timeIntervalSinceReferenceDate, + ]) + func outOfRangeCreationDateWait(createdAt: TimeInterval) async throws { + let store = CountingTaskStore() + let record = TaskRecord( + id: "foreign", owner: nil, protocolVersion: Version.v2025_11_25, method: CallTool.name, + createdAt: Date(timeIntervalSinceReferenceDate: createdAt), ttlMs: 60_000, pollIntervalMs: 50) + try await store.insert(record) + let manager = TaskManager(store: store) + let start = ContinuousClock.now + try await manager.waitForChange(record.id, from: record, timeout: .milliseconds(100)) + let elapsed = ContinuousClock.now - start + // Already-expired dates (`-.infinity`, `-1e300`) finish at once without polling; `NaN` + // and future dates keep the timeout and wait for the poll interval instead of busy-spinning. + if createdAt.isNaN || createdAt > 0 { + #expect(await store.reads == 1) + #expect(elapsed >= .milliseconds(40)) + } else { + #expect(await store.reads == 0) + } + } + + @Test( + "Waiting on a foreign task with a non-positive poll interval still sleeps", + .timeLimit(.minutes(2)), + arguments: [0, -5]) + func foreignNonPositivePollIntervalSleeps(pollIntervalMs: Int) async throws { + let store = InMemoryTaskStore() + let record = TaskRecord( + id: "foreign", owner: nil, protocolVersion: Version.v2025_11_25, method: CallTool.name, + createdAt: Date(), ttlMs: 60_000, pollIntervalMs: pollIntervalMs) + await store.insert(record) + let manager = TaskManager(store: store, configuration: .init(pollInterval: .milliseconds(60))) + let start = ContinuousClock.now + try await manager.waitForChange(record.id, from: record, timeout: .milliseconds(200)) + let elapsed = ContinuousClock.now - start + #expect(elapsed >= .milliseconds(45)) + } + + @Test( + "Waiting on a foreign task with no poll interval clamps a non-positive configured interval", + .timeLimit(.minutes(2))) + func foreignZeroConfiguredPollIntervalSleeps() async throws { + let store = InMemoryTaskStore() + let record = TaskRecord( + id: "foreign", owner: nil, protocolVersion: Version.v2025_11_25, method: CallTool.name, + createdAt: Date(), ttlMs: 60_000, pollIntervalMs: nil) + await store.insert(record) + let manager = TaskManager(store: store, configuration: .init(pollInterval: .zero)) + let start = ContinuousClock.now + for _ in 0..<20 { + try await manager.waitForChange(record.id, from: record, timeout: .milliseconds(200)) + } + let elapsed = ContinuousClock.now - start + #expect(elapsed >= .milliseconds(15)) + } + + @Test("TaskRecord change detection treats two NaN dates as unchanged") + func taskRecordIsUnchangedWithNaNDates() { + let nanDate = Date(timeIntervalSinceReferenceDate: .nan) + let base = TaskRecord( + id: "t", owner: nil, protocolVersion: Version.v2025_11_25, method: CallTool.name, + createdAt: nanDate, lastUpdatedAt: nanDate, ttlMs: 60_000, pollIntervalMs: 50) + #expect(base.isUnchanged(from: base)) + var statusChanged = base + statusChanged.status = .completed + #expect(!statusChanged.isUnchanged(from: base)) + var updatedDate = base + updatedDate.lastUpdatedAt = Date(timeIntervalSince1970: 0) + #expect(!updatedDate.isUnchanged(from: base)) + } + + // The clock starts before the task is created, so the task expires at least 200 ms + // after it, and a sleep never ends early: the lower bound holds under any load. + @Test( + "A wait on a task that runs here ends at its expiry, before a longer timeout", + .timeLimit(.minutes(2))) + func waitEndsAtExpiry() async throws { + let manager = TaskManager() + let start = ContinuousClock.now + let record = try #require( + try await manager.create( + context: Server.HandlerContext(id: 1, httpContext: nil), method: CallTool.name, + protocolVersion: Version.v2026_07_28, requestedTTL: nil, ttl: .milliseconds(200), pollInterval: nil)) + try await manager.waitForChange(record.id, from: record, timeout: .seconds(120)) + let elapsed = ContinuousClock.now - start + #expect(elapsed >= .milliseconds(150)) + #expect(elapsed < .seconds(60)) + } + + @Test( + "A wait on a stored task that runs elsewhere ends at its expiry, before its poll interval", + .timeLimit(.minutes(2))) + func foreignWaitEndsAtExpiry() async throws { + let store = InMemoryTaskStore() + let start = ContinuousClock.now + let record = TaskRecord( + id: "foreign", owner: nil, protocolVersion: Version.v2026_07_28, method: CallTool.name, + createdAt: Date(), ttlMs: 200, pollIntervalMs: 120_000) + await store.insert(record) + let manager = TaskManager(store: store) + try await manager.waitForChange(record.id, from: record, timeout: .seconds(120)) + let elapsed = ContinuousClock.now - start + #expect(elapsed >= .milliseconds(150)) + #expect(elapsed < .seconds(60)) + } + @Test("tasks/result polls a task that runs in another process at its poll interval") func foreignTaskIsPolled() async throws { let store = CountingTaskStore() @@ -2295,37 +2800,23 @@ struct TaskLifecycleEdgeTests { } /// Fails the next send of a method once armed, as a dropped connection does. -private actor FlakyTransport: Transport { - nonisolated let logger = Logger(label: "test.flaky") - private let base: any Transport +private actor FlakyTransport: TransportWrapper { + nonisolated let wrapped: any Transport private var failing: String? + /// Every message sent, as JSON text. + private(set) var sent: [String] = [] - init(_ base: any Transport) { self.base = base } + init(_ wrapped: any Transport) { self.wrapped = wrapped } func failNext(_ method: String) { failing = method } - func connect() async throws { try await base.connect() } - func disconnect() async { await base.disconnect() } - func send(_ data: Data) async throws { + func send(_ data: Data, options: TransportSendOptions) async throws { + sent.append(String(decoding: data, as: UTF8.self)) if let failing, (try? JSONDecoder().decode(Value.self, from: data))?.objectValue?["method"] == .string(failing) { self.failing = nil throw MCPError.transportError(POSIXError(.ECONNRESET)) } - try await base.send(data) - } - func receive() -> AsyncThrowingStream { - let base = self.base - return AsyncThrowingStream { continuation in - let task = Task { - do { - for try await data in await base.receive() { continuation.yield(data) } - continuation.finish() - } catch { - continuation.finish(throwing: error) - } - } - continuation.onTermination = { _ in task.cancel() } - } + try await wrapped.send(data, options: options) } } diff --git a/Tests/MCPTests/ToolTests.swift b/Tests/MCPTests/ToolTests.swift index 6c3d4e39..0cab6051 100644 --- a/Tests/MCPTests/ToolTests.swift +++ b/Tests/MCPTests/ToolTests.swift @@ -267,7 +267,7 @@ struct ToolTests { @Test("Image content encoding and decoding") func testToolContentImageEncoding() throws { let content = Tool.Content.image( - data: "base64data", + Data("image bytes".utf8), mimeType: "image/png", annotations: nil, _meta: nil @@ -279,7 +279,7 @@ struct ToolTests { let decoded = try decoder.decode(Tool.Content.self, from: data) if case .image(let data, let mimeType, _, _) = decoded { - #expect(data == "base64data") + #expect(data == Data("image bytes".utf8)) #expect(mimeType == "image/png") } else { #expect(Bool(false), "Expected image content") @@ -303,7 +303,7 @@ struct ToolTests { if case .resource(let resource, let annotations, let _meta) = decoded { #expect(resource.uri == "file://test.txt") #expect(resource.mimeType == "text/plain") - #expect(resource.text == "Sample text") + #expect(resource.body == .text("Sample text")) #expect(annotations == nil) #expect(_meta == nil) } else { @@ -345,7 +345,7 @@ struct ToolTests { @Test("Audio content encoding and decoding") func testToolContentAudioEncoding() throws { let content = Tool.Content.audio( - data: "base64audiodata", + Data("audio bytes".utf8), mimeType: "audio/wav", annotations: nil, _meta: nil @@ -357,7 +357,7 @@ struct ToolTests { let decoded = try decoder.decode(Tool.Content.self, from: data) if case .audio(let data, let mimeType, _, _) = decoded { - #expect(data == "base64audiodata") + #expect(data == Data("audio bytes".utf8)) #expect(mimeType == "audio/wav") } else { #expect(Bool(false), "Expected audio content") @@ -396,7 +396,7 @@ struct ToolTests { "vendor.example/source": .string("tool-image") ]) let expected = Tool.Content.image( - data: "base64-image", + Data([0xFF, 0xD8, 0xFF]), mimeType: "image/jpeg", annotations: annotations, _meta: meta @@ -418,7 +418,7 @@ struct ToolTests { "vendor.example/source": .string("tool-audio") ]) let expected = Tool.Content.audio( - data: "base64-audio", + Data([0x49, 0x44, 0x33]), mimeType: "audio/mp3", annotations: annotations, _meta: meta @@ -429,6 +429,64 @@ struct ToolTests { #expect(decoded == expected) } + @Test("Image content encodes its bytes as base64 data") + func imageGolden() throws { + let content = Tool.Content.image(Data([0x89, 0x50, 0x4E, 0x47]), mimeType: "image/png") + #expect(try wireString(content) == #"{"data":"iVBORw==","mimeType":"image/png","type":"image"}"#) + } + + @Test("Audio content encodes its bytes as base64 data") + func audioGolden() throws { + let content = Tool.Content.audio(Data("RIFF".utf8), mimeType: "audio/wav") + #expect(try wireString(content) == #"{"data":"UklGRg==","mimeType":"audio/wav","type":"audio"}"#) + } + + @Test("Image and audio decode a fixed base64 literal") + func decodeLiteral() throws { + let png = Data([0x89, 0x50, 0x4E, 0x47]) + for data in [#""iVBORw==""#, #""iVBO\nRw""#] { + let image = #"{"type":"image","data":\#(data),"mimeType":"image/png"}"# + #expect(try JSONDecoder().decode(Tool.Content.self, from: Data(image.utf8)) == .image(png, mimeType: "image/png")) + let audio = #"{"type":"audio","data":\#(data),"mimeType":"audio/wav"}"# + #expect(try JSONDecoder().decode(Tool.Content.self, from: Data(audio.utf8)) == .audio(png, mimeType: "audio/wav")) + } + } + + @Test("Image and audio data that is not base64 fails", arguments: ["image", "audio"]) + func invalidData(type: String) throws { + let json = #"{"type":"\#(type)","data":"not base64!","mimeType":"x/y"}"# + let error = try #require(throws: DecodingError.self) { + try JSONDecoder().decode(Tool.Content.self, from: Data(json.utf8)) + } + guard case .dataCorrupted = error else { + Issue.record("Expected dataCorrupted, got \(error)") + return + } + #expect(codingPath(of: error) == ["data"]) + } + + @Test("A tool result with a non-base64 image fails with ResponseDecodingError") + func clientRefusesInvalidImage() async throws { + let server = Server(name: "s", version: "1", capabilities: .init(tools: .init())) + await server.withMethodHandler(RawResult.self) { _ in + ["content": [["type": "image", "data": "%%%", "mimeType": "image/png"]]] + } + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + try await server.start(transport: serverTransport) + let client = Client(name: "c", version: "1") + try await client.connect(transport: clientTransport) + defer { Task { await client.disconnect(); await server.stop() } } + + do { + _ = try await client.callTool(name: "t") + Issue.record("Expected a response decoding error") + } catch let error as ResponseDecodingError { + #expect(error.expectedType == String(reflecting: CallTool.Result.self)) + #expect(codingPath(of: error.underlyingError) == ["content", "0", "data"]) + #expect(!error.description.contains("%%%")) + } + } + @Test("ListTools parameters validation") func testListToolsParameters() throws { let params = ListTools.Parameters(cursor: "next_page") diff --git a/Tests/MCPTests/TransportContractTests.swift b/Tests/MCPTests/TransportContractTests.swift new file mode 100644 index 00000000..9cb9000d --- /dev/null +++ b/Tests/MCPTests/TransportContractTests.swift @@ -0,0 +1,268 @@ +import Foundation +import Logging +import Testing + +@testable import MCP + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +#if canImport(System) + import System +#else + @preconcurrency import SystemPackage +#endif + +#if canImport(Network) + import Network +#endif + +// The contract of `Transport`, checked on every SDK transport. + +/// An SDK transport the contract tests run on. +enum TransportKind: String, CaseIterable, Sendable, CustomTestStringConvertible { + case inMemory + case stdio + #if swift(>=6.1) + case httpClient + #endif + case statefulServer + case statelessServer + #if canImport(Network) + case network + #endif + + var testDescription: String { rawValue } +} + +/// A transport of one kind, not yet connected. +private struct TransportFixture: Sendable { + let transport: any Transport + /// Makes the transport's peer send `message` to it, once it is connected. + let deliver: @Sendable (_ message: String) async throws -> Void + /// Releases what the fixture holds besides the transport. + let tearDown: @Sendable () async -> Void + + static func make(_ kind: TransportKind) async throws -> TransportFixture { + switch kind { + case .inMemory: + let (transport, peer) = await InMemoryTransport.createConnectedPair() + return TransportFixture( + transport: transport, + deliver: { message in + try await peer.connect() + try await peer.send(Data(message.utf8)) + }, + tearDown: { await peer.disconnect() }) + + case .stdio: + let (input, writer) = try FileDescriptor.pipe() + let (reader, output) = try FileDescriptor.pipe() + return TransportFixture( + transport: StdioTransport(input: input, output: output, logger: nil), + deliver: { message in + let line = Data((message + "\n").utf8) + _ = try line.withUnsafeBytes { try writer.writeAll($0) } + }, + tearDown: { + for descriptor in [input, writer, reader, output] { try? descriptor.close() } + }) + + #if swift(>=6.1) + case .httpClient: + let key = UUID().uuidString + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [IsolatedMockURLProtocol.self] + configuration.httpAdditionalHeaders = [IsolatedMockURLProtocol.sessionKeyHeader: key] + let endpoint = URL(string: "http://127.0.0.1:9/mcp")! + let transport = HTTPClientTransport(endpoint: endpoint, configuration: configuration, streaming: false) + return TransportFixture( + transport: transport, + deliver: { message in + // The server's answer to a request is what the transport yields. + await IsolatedMockURLProtocol.setHandler(key: key) { _ in + ( + HTTPURLResponse( + url: endpoint, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/json"])!, + Data(message.utf8) + ) + } + try await transport.send(Data(#"{"jsonrpc":"2.0","id":"c1","method":"ping"}"#.utf8)) + }, + tearDown: {}) + #endif + + case .statefulServer: + let transport = StatefulHTTPServerTransport() + return TransportFixture( + transport: transport, + deliver: { message in + // The POST waits for the response; the message reaches receive() first. + Task { + _ = await transport.handleRequest( + HTTPRequest( + method: "POST", + headers: [ + "Content-Type": "application/json", + "Accept": "application/json, text/event-stream", + ], + body: Data(message.utf8))) + } + }, + tearDown: {}) + + case .statelessServer: + let transport = StatelessHTTPServerTransport() + return TransportFixture( + transport: transport, + deliver: { message in + Task { + _ = await transport.handleRequest( + HTTPRequest( + method: "POST", + headers: ["Content-Type": "application/json", "Accept": "application/json"], + body: Data(message.utf8))) + } + }, + tearDown: {}) + + #if canImport(Network) + case .network: + let connection = MockNetworkConnection() + return TransportFixture( + transport: NetworkTransport(connection), + deliver: { message in connection.queueDataForReceiving(Data((message + "\n").utf8)) }, + tearDown: {}) + #endif + } + } +} + +/// A message every transport kind yields as one element: an `initialize` +/// request for the server transports, the response to the HTTP client's +/// request, and a plain message for the others. Each contains `"c1"`, except +/// in the stateless transport, which replaces request IDs with its own. +private func probe(for kind: TransportKind) -> String { + switch kind { + case .statefulServer, .statelessServer: + #"{"jsonrpc":"2.0","id":"c1","method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"c","version":"1"}}}"# + default: + #"{"jsonrpc":"2.0","id":"c1","result":{}}"# + } +} + +/// Whether `stream` finishes, normally or with an error, within `limit`. +private func finishes( + _ stream: AsyncThrowingStream, within limit: Duration = .seconds(10) +) async -> Bool { + let result = await outcome(within: limit) { + for try await _ in stream {} + } + return !result.didTimeOut +} + +/// The first element of `stream`, waiting at most `limit`. +private func firstElement( + of stream: AsyncThrowingStream, within limit: Duration = .seconds(10) +) async -> Data? { + let result = await outcome(within: limit) { () -> Data? in + var iterator = stream.makeAsyncIterator() + return try await iterator.next() + } + guard case .returned(let data) = result else { return nil } + return data +} + +private let notification = Data(#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#.utf8) + +/// What every SDK transport throws from `connect()` when it is connected. +private let alreadyConnected = MCPError.internalError("Transport already connected") +/// What every SDK transport throws from `connect()` after `disconnect()`. +private let disconnected = MCPError.internalError("Transport disconnected; create a new transport to reconnect") + +@Suite("Transport contract", .timeLimit(.minutes(2))) +struct TransportContractTests { + @Test("connect() on a connected transport throws", arguments: TransportKind.allCases) + func connectTwiceThrows(kind: TransportKind) async throws { + let fixture = try await TransportFixture.make(kind) + try await fixture.transport.connect() + await #expect(throws: alreadyConnected) { try await fixture.transport.connect() } + await fixture.transport.disconnect() + await fixture.tearDown() + } + + @Test("connect() after disconnect() throws", arguments: TransportKind.allCases) + func connectAfterDisconnectThrows(kind: TransportKind) async throws { + let connected = try await TransportFixture.make(kind) + try await connected.transport.connect() + await connected.transport.disconnect() + await #expect(throws: disconnected) { try await connected.transport.connect() } + await connected.tearDown() + + // Also when it never connected. + let unused = try await TransportFixture.make(kind) + await unused.transport.disconnect() + await #expect(throws: disconnected) { try await unused.transport.connect() } + await unused.tearDown() + } + + @Test("disconnect() twice, or before connect(), returns and finishes the stream", arguments: TransportKind.allCases) + func disconnectIsIdempotent(kind: TransportKind) async throws { + let unused = try await TransportFixture.make(kind) + await unused.transport.disconnect() + await unused.transport.disconnect() + #expect(await finishes(await unused.transport.receive())) + await unused.tearDown() + + let connected = try await TransportFixture.make(kind) + try await connected.transport.connect() + await connected.transport.disconnect() + await connected.transport.disconnect() + #expect(await finishes(await connected.transport.receive())) + await connected.tearDown() + } + + @Test("send after disconnect() throws connectionClosed", arguments: TransportKind.allCases) + func sendAfterDisconnectThrows(kind: TransportKind) async throws { + let fixture = try await TransportFixture.make(kind) + try await fixture.transport.connect() + await fixture.transport.disconnect() + await #expect(throws: MCPError.connectionClosed) { + try await fixture.transport.send(notification, options: TransportSendOptions()) + } + await #expect(throws: MCPError.connectionClosed) { try await fixture.transport.send(notification) } + await fixture.tearDown() + } + + @Test("receive() returns the same stream on every call", arguments: TransportKind.allCases) + func receiveReturnsOneStream(kind: TransportKind) async throws { + let fixture = try await TransportFixture.make(kind) + let first = await fixture.transport.receive() + _ = await fixture.transport.receive() + try await fixture.transport.connect() + _ = await fixture.transport.receive() + + // A message reaches the stream of the first call: there is only one. + try await fixture.deliver(probe(for: kind)) + let data = try #require(await firstElement(of: first)) + let received = String(decoding: data, as: UTF8.self) + #expect(received.contains(kind == .statelessServer ? #""initialize""# : #""c1""#)) + + await fixture.transport.disconnect() + await fixture.tearDown() + } + + @Test("disconnect() finishes the stream for every caller of receive()", arguments: TransportKind.allCases) + func disconnectFinishesEveryStream(kind: TransportKind) async throws { + let fixture = try await TransportFixture.make(kind) + try await fixture.transport.connect() + let first = await fixture.transport.receive() + let second = await fixture.transport.receive() + await fixture.transport.disconnect() + #expect(await finishes(first)) + #expect(await finishes(second)) + await fixture.tearDown() + } +} diff --git a/Tests/MCPTests/TransportWrapperTests.swift b/Tests/MCPTests/TransportWrapperTests.swift new file mode 100644 index 00000000..025a125d --- /dev/null +++ b/Tests/MCPTests/TransportWrapperTests.swift @@ -0,0 +1,733 @@ +import Foundation +import Logging +import Synchronization +import Testing + +@testable import MCP + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +// `TransportWrapper` forwarding, the no-op hook defaults, and the behavior the +// SDK transports keep behind a wrapper. + +/// Records every requirement and hook called on it, in order. +private actor RecordingInner: Transport { + nonisolated let logger = Logger(label: "test.recording-inner") { _ in SwiftLogNoOpLogHandler() } + nonisolated let isSessionless = true + + /// What `authorizationEnd(of:)` returns. + static let authorizationEnded = ContinuousClock.now + /// What `httpRequest(for:)` returns. + static let request = HTTPRequest(method: "POST", headers: ["X-Inner": "1"], path: "/inner") + + private(set) var calls: [String] = [] + private(set) var sentOptions: [TransportSendOptions] = [] + private let stream: AsyncThrowingStream + private let continuation: AsyncThrowingStream.Continuation + + init() { + (stream, continuation) = AsyncThrowingStream.makeStream() + } + + func connect() async throws { calls.append("connect") } + + func disconnect() async { + calls.append("disconnect") + continuation.finish() + } + + func send(_ data: Data, options: TransportSendOptions) async throws { + calls.append("send") + sentOptions.append(options) + } + + func receive() async -> AsyncThrowingStream { + calls.append("receive") + return stream + } + + func didNegotiate(protocolVersion version: String) async { + calls.append("didNegotiate(\(version))") + } + + func abandonRequest(_ id: ID) async -> Bool { + calls.append("abandonRequest(\(id))") + return true + } + + func authorizationEnd(of id: ID) async -> ContinuousClock.Instant? { + calls.append("authorizationEnd(\(id))") + return Self.authorizationEnded + } + + func prepare(servingProtocolVersions versions: [String]) async { + calls.append("prepare(\(versions.joined(separator: ",")))") + } + + func httpRequest(for id: ID) async -> HTTPRequest? { + calls.append("httpRequest(\(id))") + return Self.request + } +} + +/// A wrapper that implements nothing itself. +private actor PassThrough: TransportWrapper { + nonisolated let wrapped: any Transport + init(_ wrapped: any Transport) { self.wrapped = wrapped } +} + +/// A wrapper that implements only `send(_:options:)`. +private actor SendCounting: TransportWrapper { + nonisolated let wrapped: any Transport + private(set) var sent = 0 + + init(_ wrapped: any Transport) { self.wrapped = wrapped } + + func send(_ data: Data, options: TransportSendOptions) async throws { + sent += 1 + try await wrapped.send(data, options: options) + } +} + +/// A wrapper whose `didNegotiate(version:)` only nearly matches the hook +/// `didNegotiate(protocolVersion:)`. +private actor NearMissWrapper: TransportWrapper { + nonisolated let wrapped: any Transport + private(set) var nearMissCalls = 0 + + init(_ wrapped: any Transport) { self.wrapped = wrapped } + + func didNegotiate(version: String) async { + nearMissCalls += 1 + } +} + +/// A wrapper that records the session ID of the HTTP client transport it +/// wraps each time `didNegotiate(protocolVersion:)` reaches it. +private actor SessionIDAtNegotiation: TransportWrapper { + nonisolated let wrapped: any Transport + private let transport: HTTPClientTransport + private(set) var sessionIDs: [String?] = [] + + init(_ transport: HTTPClientTransport) { + self.wrapped = transport + self.transport = transport + } + + func didNegotiate(protocolVersion version: String) async { + sessionIDs.append(await transport.sessionID) + await wrapped.didNegotiate(protocolVersion: version) + } +} + +/// Implements the requirements that have no default, and nothing else. +private actor MinimalTransport: Transport { + nonisolated let logger = Logger(label: "test.minimal") { _ in SwiftLogNoOpLogHandler() } + private(set) var sentOptions: [TransportSendOptions] = [] + + func connect() async throws {} + func disconnect() async {} + func send(_ data: Data, options: TransportSendOptions) async throws { sentOptions.append(options) } + func receive() -> AsyncThrowingStream { AsyncThrowingStream { $0.finish() } } +} + +/// What a caller of the hooks got back. +private struct HookResults { + let abandoned: Bool + let authorizationEnd: ContinuousClock.Instant? + let request: HTTPRequest? +} + +private let message = Data(#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#.utf8) +private let options = TransportSendOptions(relatedRequestID: .string("r1"), headers: ["Mcp-Param-A": "1"]) + +/// The calls ``exercise(existential:)`` and ``exercise(generic:)`` make, as +/// ``RecordingInner`` records them. +private let expectedCalls = [ + "connect", "receive", "send", "didNegotiate(2025-11-25)", "abandonRequest(7)", "authorizationEnd(7)", + "prepare(2026-07-28,2025-11-25)", "httpRequest(7)", "disconnect", +] + +/// Calls every requirement and hook through `any Transport`, as `Client` and `Server` do. +private func exercise(existential transport: any Transport) async throws -> HookResults { + try await transport.connect() + _ = await transport.receive() + try await transport.send(message, options: options) + await transport.didNegotiate(protocolVersion: "2025-11-25") + let abandoned = await transport.abandonRequest(.number(7)) + let ended = await transport.authorizationEnd(of: .number(7)) + await transport.prepare(servingProtocolVersions: ["2026-07-28", "2025-11-25"]) + let request = await transport.httpRequest(for: .number(7)) + await transport.disconnect() + return HookResults(abandoned: abandoned, authorizationEnd: ended, request: request) +} + +/// Calls every requirement and hook through a generic `T: Transport`. +private func exercise(generic transport: T) async throws -> HookResults { + try await transport.connect() + _ = await transport.receive() + try await transport.send(message, options: options) + await transport.didNegotiate(protocolVersion: "2025-11-25") + let abandoned = await transport.abandonRequest(.number(7)) + let ended = await transport.authorizationEnd(of: .number(7)) + await transport.prepare(servingProtocolVersions: ["2026-07-28", "2025-11-25"]) + let request = await transport.httpRequest(for: .number(7)) + await transport.disconnect() + return HookResults(abandoned: abandoned, authorizationEnd: ended, request: request) +} + +/// Checks that the results are what ``RecordingInner`` returns. +private func expectInnerResults(_ results: HookResults, sourceLocation: SourceLocation = #_sourceLocation) { + #expect(results.abandoned, sourceLocation: sourceLocation) + #expect(results.authorizationEnd == RecordingInner.authorizationEnded, sourceLocation: sourceLocation) + #expect(results.request?.path == RecordingInner.request.path, sourceLocation: sourceLocation) + #expect(results.request?.header("X-Inner") == "1", sourceLocation: sourceLocation) +} + +@Suite("Transport wrapper forwarding") +struct TransportWrapperForwardingTests { + @Test("A wrapper that overrides nothing forwards every requirement and hook through any Transport") + func passThroughForwardsThroughExistential() async throws { + let inner = RecordingInner() + let results = try await exercise(existential: PassThrough(inner)) + #expect(await inner.calls == expectedCalls) + #expect(await inner.sentOptions == [options]) + expectInnerResults(results) + } + + @Test("A wrapper that overrides only send forwards every hook through a generic Transport") + func sendOnlyWrapperForwardsThroughGeneric() async throws { + let inner = RecordingInner() + let wrapper = SendCounting(inner) + let results = try await exercise(generic: wrapper) + #expect(await inner.calls == expectedCalls) + #expect(await inner.sentOptions == [options]) + #expect(await wrapper.sent == 1) + expectInnerResults(results) + + // And through `any Transport`, with the `send(_:)` convenience. + let again = RecordingInner() + let existential: any Transport = SendCounting(again) + expectInnerResults(try await exercise(existential: existential)) + try await existential.send(message) + #expect(await again.calls == expectedCalls + ["send"]) + #expect(await again.sentOptions == [options, TransportSendOptions()]) + } + + @Test("A wrapper of a wrapper forwards to the innermost transport") + func nestedWrappersForward() async throws { + let inner = RecordingInner() + let results = try await exercise(existential: PassThrough(SendCounting(inner))) + #expect(await inner.calls == expectedCalls) + expectInnerResults(results) + } + + @Test("isSessionless and logger forward without await") + func nonisolatedMembersForward() { + let inner = RecordingInner() + let wrapper = PassThrough(inner) + let existential: any Transport = wrapper + // Both read synchronously: these lines would not compile with `await`. + #expect(wrapper.isSessionless) + #expect(existential.isSessionless) + #expect(wrapper.logger.label == "test.recording-inner") + #expect(existential.logger.label == "test.recording-inner") + #expect(!PassThrough(MinimalTransport()).isSessionless) + } + + @Test("A transport that implements only the requirements without defaults gets the no-op hooks") + func defaultsDoNothing() async throws { + let minimal = MinimalTransport() + let transport: any Transport = minimal + await transport.didNegotiate(protocolVersion: "2025-11-25") + #expect(await transport.abandonRequest(.number(1)) == false) + #expect(await transport.authorizationEnd(of: .number(1)) == nil) + await transport.prepare(servingProtocolVersions: Version.stateless + Version.handshake) + #expect(await transport.httpRequest(for: .number(1)) == nil) + #expect(transport.isSessionless == false) + + // `send(_:)` is a convenience for `send(_:options:)` with no options. + try await transport.send(message) + #expect(await minimal.sentOptions == [TransportSendOptions()]) + } + + // Pins compiler behavior: a method whose signature only nearly matches a + // requirement is not a witness, and Swift gives no warning for it. The + // `TransportWrapper` doc comment warns about this. + @Test("A near-miss hook is not called") + func nearMissIsNotCalled() async throws { + let inner = RecordingInner() + let wrapper = NearMissWrapper(inner) + let transport: any Transport = wrapper + await transport.didNegotiate(protocolVersion: "2026-07-28") + #expect(await wrapper.nearMissCalls == 0) + #expect(await inner.calls == ["didNegotiate(2026-07-28)"]) + } + + @Test("A hook called on a concrete SDK transport runs its implementation, not the default") + func concreteCallsReachWitnesses() async throws { + // An `async` call on the concrete type picks the `async` default when the + // implementation is synchronous, so the SDK's implementations are `async`. + let client = HTTPClientTransport(endpoint: URL(string: "http://127.0.0.1:9/mcp")!, streaming: false) + await client.didNegotiate(protocolVersion: "2026-07-28") + #expect(await client.protocolVersion == "2026-07-28") + #expect(await client.abandonRequest(.number(1))) + await client.disconnect() + + let stateless = StatelessHTTPServerTransport() + #expect(stateless.isSessionless) + await stateless.prepare(servingProtocolVersions: ["2026-07-28"]) + let response = await stateless.handleRequest( + HTTPRequest( + method: "POST", + headers: [ + "Content-Type": "application/json", "Accept": "application/json", + HTTPHeaderName.protocolVersion: "2099-01-01", + ], + body: Data(#"{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}"#.utf8))) + let body = try JSONDecoder().decode(Value.self, from: try #require(response.bodyData)) + #expect(body.objectValue?["error"]?.objectValue?["data"]?.objectValue?["supported"] == ["2026-07-28"]) + #expect(await stateless.httpRequest(for: .string("unknown")) == nil) + #expect(!StatefulHTTPServerTransport().isSessionless) + } +} + +// MARK: - Behavior behind a wrapper + +#if swift(>=6.1) + @Suite("Wrapped transports keep their behavior", .timeLimit(.minutes(2))) + struct WrappedTransportBehaviorTests { + @Test("A wrapped HTTP client sends the negotiated MCP-Protocol-Version after initialize") + func negotiatedVersionHeader() async throws { + let host = WrappedServerProtocol.host(.handshake) + // Starts with an older version, so only didNegotiate can set 2025-11-25. + let transport = WrappedServerProtocol.transport(host: host, protocolVersion: Version.v2025_06_18) + let client = Client(name: "c", version: "1", configuration: .handshake) + let result = try await client.connect(transport: PassThrough(transport)) + #expect(result.protocolVersion == Version.v2025_11_25) + try await client.ping() + + let requests = WrappedServerProtocol.state.requests(to: host) + #expect(requests.map(\.method) == [Initialize.name, InitializedNotification.name, Ping.name]) + #expect(requests.first?.protocolVersion == Version.v2025_06_18) + #expect(requests.dropFirst().allSatisfy { $0.protocolVersion == Version.v2025_11_25 }) + await client.disconnect() + } + + @Test("A wrapped HTTP client drops its session after server/discover") + func statelessSwitch() async throws { + let host = WrappedServerProtocol.host(.stateless) + // With a timeout this long, only a session ID can open the GET stream before + // didNegotiate stops it. + let transport = WrappedServerProtocol.transport(host: host, streaming: true, sseInitializationTimeout: 3600) + let wrapper = SessionIDAtNegotiation(transport) + let client = Client(name: "c", version: "1") + let result = try await client.connect(transport: wrapper) + #expect(result.protocolVersion == Version.v2026_07_28) + // The server set Mcp-Session-Id on its reply to server/discover, a 2026-07-28 + // request: the transport never took it, not even before didNegotiate. + #expect(await wrapper.sessionIDs == [nil]) + #expect(await transport.sessionID == nil) + #expect(await transport.protocolVersion == Version.v2026_07_28) + + try await client.ping() // server/discover again + #expect(await transport.sessionID == nil) + let requests = WrappedServerProtocol.state.requests(to: host) + #expect(requests.map(\.method) == [ServerDiscover.name, ServerDiscover.name]) + #expect(requests.allSatisfy { $0.sessionID == nil }) + #expect(requests.allSatisfy { $0.httpMethod == "POST" }) + await client.disconnect() + } + + @Test("A wrapped HTTP client opens no GET stream after server/discover") + func noGETStreamAfterDiscover() async throws { + // With streaming, the GET stream opens once its wait for a session ID times out, + // unless the switch to 2026-07-28 that didNegotiate makes has stopped it. An attempt + // whose connect outlasted the timeout tests nothing, so it runs again with the next. + for timeout in Self.discoveryTimeouts { + let host = WrappedServerProtocol.host(.sessionless) + let start = ContinuousClock.now + let transport = WrappedServerProtocol.transport( + host: host, streaming: true, sseInitializationTimeout: Self.seconds(timeout)) + let client = Client(name: "c", version: "1") + let result = try await client.connect(transport: PassThrough(transport)) + guard ContinuousClock.now < start + timeout else { + await client.disconnect() + continue + } + #expect(result.protocolVersion == Version.v2026_07_28) + #expect(await transport.protocolVersion == Version.v2026_07_28) + + // An absence: wait past the timeout for a GET that must not come. + let deadline = start + timeout + .milliseconds(500) + var opened = false + while !opened, ContinuousClock.now < deadline { + opened = WrappedServerProtocol.state.requests(to: host).contains { $0.httpMethod == "GET" } + try await Task.sleep(for: .milliseconds(20)) + } + #expect(!opened) + #expect(WrappedServerProtocol.state.requests(to: host).map(\.method) == [ServerDiscover.name]) + await client.disconnect() + return + } + Issue.record("connect outlasted every session ID timeout") + } + + /// `duration` in seconds. + static func seconds(_ duration: Duration) -> TimeInterval { + TimeInterval(duration.components.seconds) + TimeInterval(duration.components.attoseconds) / 1e18 + } + + @Test("Cancelling a stateless request closes the wrapped transport's POST") + func cancellationClosesPOST() async throws { + let host = WrappedServerProtocol.host(.stateless) + let transport = WrappedServerProtocol.transport(host: host) + let client = Client(name: "c", version: "1") + _ = try await client.connect(transport: PassThrough(transport)) + + let call = try await client.startToolCall(name: "slow", arguments: [:]) + #expect(await eventually { WrappedServerProtocol.state.requests(to: host).contains { $0.method == CallTool.name } }) + try await client.cancelRequest(call.requestID, reason: "test") + + await #expect(throws: CancellationError.self) { _ = try await call.value } + #expect(await eventually { WrappedServerProtocol.state.stoppedMethods(of: host) == [CallTool.name] }) + // Closing the POST told the server: no notifications/cancelled. + #expect(!WrappedServerProtocol.state.requests(to: host).contains { $0.method == CancelledNotification.name }) + await client.disconnect() + } + + /// The discovery timeouts to try, shortest first: a loaded machine can + /// start the sign-in after a short timeout ran out, and then the attempt + /// tests nothing. + static let discoveryTimeouts: [Duration] = [.seconds(1), .seconds(4), .seconds(12)] + + @Test("Signing in through a wrapped transport does not count against the discovery timeout") + func signInThroughWrapper() async throws { + for timeout in Self.discoveryTimeouts { + let start = ContinuousClock.now + let host = WrappedServerProtocol.host(.signIn) + let authorizer = HeldSignInAuthorizer() + let transport = WrappedServerProtocol.transport(host: host, authorizer: authorizer) + let client = Client( + name: "c", version: "1", + configuration: .init(protocolMode: .automatic, discoveryTimeout: timeout)) + let connecting = Task { try await client.connect(transport: PassThrough(transport)) } + + let deadline = start + timeout + while authorizer.firstSignInStart == nil, ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(10)) + } + guard let started = authorizer.firstSignInStart, started < deadline else { + authorizer.release() + _ = await outcome(within: .seconds(30)) { try await connecting.value } + await client.disconnect() + continue + } + // The client's discovery timer reached the transport's authorizationEnd(of:) + // through the wrapper, and waits for the sign-in. + #expect(await eventually(within: timeout + .seconds(10)) { await transport.authorizationWaiterCount == 1 }) + authorizer.release() + + let result = await outcome(within: .seconds(30)) { try await connecting.value } + guard case .returned(let info) = result else { + Issue.record("connect did not return: \(result)") + connecting.cancel() + await client.disconnect() + return + } + #expect(info.protocolVersion == Version.v2026_07_28) + #expect(authorizer.challenges == 1) + await client.disconnect() + return + } + Issue.record("The sign-in of server/discover started after every discovery timeout") + } + + @Test("A handler behind a wrapped stateful transport reads httpContext") + func statefulHTTPContext() async throws { + let transport = StatefulHTTPServerTransport() + let server = Server(name: "s", version: "1", capabilities: .init(tools: .init())) + let captured = CapturedAuthorization() + await server.withMethodHandler(CallTool.self) { _ in + await captured.set(Server.currentHandlerContext?.httpContext?.header("Authorization")) + return CallTool.Result(content: [.text(text: "ok")]) + } + try await server.start(transport: PassThrough(transport)) + defer { Task { await server.stop() } } + + let initialize = await transport.handleRequest( + statefulPOST( + #"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"c","version":"1"}}}"# + )) + let sessionID = try #require(initialize.headers[HTTPHeaderName.sessionID]) + _ = try await responseText(of: initialize) + _ = await transport.handleRequest( + statefulPOST(#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, sessionID: sessionID)) + + let call = await transport.handleRequest( + statefulPOST( + #"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"whoami"}}"#, + sessionID: sessionID, authorization: "Bearer wrapped")) + #expect(try await responseText(of: call).contains(#""result""#)) + #expect(await captured.value == "Bearer wrapped") + } + + @Test("A server behind a wrapped stateless transport serves handshake requests without initialize") + func statelessServesHandshakeRequests() async throws { + let transport = StatelessHTTPServerTransport() + // A strict server refuses requests before `initialize`, unless the + // transport is sessionless. + let server = Server( + name: "s", version: "1", capabilities: .init(tools: .init()), configuration: .init(strict: true)) + await server.withMethodHandler(ListTools.self) { _ in + .init(tools: [Tool(name: "t", description: nil, inputSchema: ["type": "object"])]) + } + try await server.start(transport: PassThrough(transport)) + defer { Task { await server.stop() } } + + let response = await transport.handleRequest( + statelessPOST(#"{"jsonrpc":"2.0","id":3,"method":"tools/list","params":{}}"#, version: "2025-11-25")) + #expect(response.statusCode == 200) + let body = try JSONDecoder().decode(Value.self, from: try #require(response.bodyData)) + #expect(body.objectValue?["result"]?.objectValue?["tools"]?.arrayValue?.count == 1) + } + + @Test("prepare reaches a wrapped stateless transport: -32022 lists the server's versions") + func prepareReachesStatelessTransport() async throws { + let transport = StatelessHTTPServerTransport() + let server = Server(name: "s", version: "1", configuration: .init(protocolVersions: ["2026-07-28"])) + try await server.start(transport: PassThrough(transport)) + defer { Task { await server.stop() } } + + let response = await transport.handleRequest( + statelessPOST(#"{"jsonrpc":"2.0","id":4,"method":"tools/list","params":{}}"#, version: "2099-01-01")) + #expect(response.statusCode == 400) + let body = try JSONDecoder().decode(Value.self, from: try #require(response.bodyData)) + let error = body.objectValue?["error"]?.objectValue + #expect(error?["code"] == -32022) + #expect(error?["data"]?.objectValue?["supported"] == ["2026-07-28"]) + } + } + + private actor CapturedAuthorization { + private(set) var value: String? + func set(_ value: String?) { self.value = value } + } + + private func statefulPOST(_ body: String, sessionID: String? = nil, authorization: String? = nil) -> HTTPRequest { + var headers = ["Content-Type": "application/json", "Accept": "application/json, text/event-stream"] + if let sessionID { + headers[HTTPHeaderName.sessionID] = sessionID + headers[HTTPHeaderName.protocolVersion] = Version.v2025_11_25 + } + headers[HTTPHeaderName.authorization] = authorization + return HTTPRequest(method: "POST", headers: headers, body: Data(body.utf8), path: "/mcp") + } + + private func statelessPOST(_ body: String, version: String) -> HTTPRequest { + HTTPRequest( + method: "POST", + headers: [ + "Content-Type": "application/json", "Accept": "application/json", + HTTPHeaderName.protocolVersion: version, + ], + body: Data(body.utf8)) + } + + /// The body of `response`, read until it holds a JSON-RPC response. + private func responseText(of response: HTTPResponse) async throws -> String { + guard case .stream(let stream, _) = response else { + return String(decoding: response.bodyData ?? Data(), as: UTF8.self) + } + var text = "" + for try await chunk in stream { + text += String(decoding: chunk, as: UTF8.self) + if text.contains(#""result""#) || text.contains(#""error""#) { break } + } + return text + } + + /// A Streamable HTTP server for the wrapped client tests, by host: + /// + /// - `handshake`: answers `initialize` with a session, other requests with + /// an empty result, notifications with 202. + /// - `stateless`: answers `server/discover` for 2026-07-28 with + /// `Mcp-Session-Id` set, never answers `tools/call`, and records when its + /// POST stops. + /// - `sessionless`: as `stateless`, without `Mcp-Session-Id`. + /// - `signIn`: answers 401 to a request without credentials, else as + /// `stateless`. + /// + /// Every host is unique to one test, so tests can run in parallel. + private final class WrappedServerProtocol: URLProtocol { + enum Kind: String { case handshake, stateless, sessionless, signIn = "sign-in" } + + struct Recorded: Sendable { + let httpMethod: String + let method: String? + let protocolVersion: String? + let sessionID: String? + } + + // @unchecked Sendable: every mutable field is read and written under `lock`. + final class State: @unchecked Sendable { + private let lock = NSLock() + private var recorded: [String: [Recorded]] = [:] + private var stopped: [String: [String]] = [:] + + func record(_ request: Recorded, host: String) { + lock.withLock { recorded[host, default: []].append(request) } + } + func stop(_ method: String, host: String) { + lock.withLock { stopped[host, default: []].append(method) } + } + /// The requests `host` received, in order. + func requests(to host: String) -> [Recorded] { lock.withLock { recorded[host] ?? [] } } + /// The methods of the requests to `host` whose loading stopped before an answer. + func stoppedMethods(of host: String) -> [String] { lock.withLock { stopped[host] ?? [] } } + } + + static let state = State() + + static func host(_ kind: Kind) -> String { "\(UUID().uuidString).\(kind.rawValue).test" } + + static func transport( + host: String, streaming: Bool = false, sseInitializationTimeout: TimeInterval = 10, + protocolVersion: String = Version.latestHandshake, authorizer: (any HTTPClientAuthorizer)? = nil + ) -> HTTPClientTransport { + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [WrappedServerProtocol.self] + return HTTPClientTransport( + endpoint: URL(string: "https://\(host)/mcp")!, configuration: configuration, streaming: streaming, + sseInitializationTimeout: sseInitializationTimeout, protocolVersion: protocolVersion, + authorizer: authorizer) + } + + /// The method of the request this instance is loading, while it waits for an answer. + private var unanswered: String? + + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + + override func startLoading() { + let host = request.url?.host ?? "" + let message = (try? JSONSerialization.jsonObject(with: body())) as? [String: Any] ?? [:] + let method = message["method"] as? String + Self.state.record( + Recorded( + httpMethod: request.httpMethod ?? "", + method: method, + protocolVersion: request.value(forHTTPHeaderField: HTTPHeaderName.protocolVersion), + sessionID: request.value(forHTTPHeaderField: HTTPHeaderName.sessionID)), + host: host) + guard request.httpMethod == "POST" else { return reply(405) } + if host.hasSuffix(".sign-in.test"), request.value(forHTTPHeaderField: "Authorization") == nil { + return reply(401, headers: ["WWW-Authenticate": "Bearer"]) + } + guard let method, let id = message["id"] else { return reply(202) } + let idJSON = String(decoding: (try? JSONSerialization.data(withJSONObject: [id])) ?? Data("[0]".utf8), as: UTF8.self) + .dropFirst().dropLast() + switch method { + case Initialize.name: + reply( + 200, + #"{"jsonrpc":"2.0","id":\#(idJSON),"result":{"protocolVersion":"2025-11-25","capabilities":{},"serverInfo":{"name":"wrapped","version":"0"}}}"#, + headers: [HTTPHeaderName.sessionID: "session-1"]) + case ServerDiscover.name where !host.hasSuffix(".handshake.test"): + reply( + 200, + #"{"jsonrpc":"2.0","id":\#(idJSON),"result":{"supportedVersions":["2026-07-28"],"capabilities":{"tools":{}},"resultType":"complete"}}"#, + headers: host.hasSuffix(".sessionless.test") ? [:] : [HTTPHeaderName.sessionID: "session-1"]) + case CallTool.name where !host.hasSuffix(".handshake.test"): + unanswered = method + default: + reply(200, #"{"jsonrpc":"2.0","id":\#(idJSON),"result":{}}"#) + } + } + + override func stopLoading() { + guard let unanswered else { return } + Self.state.stop(unanswered, host: request.url?.host ?? "") + } + + private func reply(_ status: Int, _ body: String = "", headers: [String: String] = [:]) { + let response = HTTPURLResponse( + url: request.url!, statusCode: status, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/json"].merging(headers) { $1 })! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: Data(body.utf8)) + client?.urlProtocolDidFinishLoading(self) + } + + private func body() -> Data { + if let body = request.httpBody { return body } + guard let stream = request.httpBodyStream else { return Data() } + stream.open() + defer { stream.close() } + var data = Data() + var buffer = [UInt8](repeating: 0, count: 4096) + while stream.hasBytesAvailable { + let count = stream.read(&buffer, maxLength: buffer.count) + guard count > 0 else { break } + data.append(buffer, count: count) + } + return data + } + } + + /// Signs in on a 401, like a user at a browser, until ``release()``; then + /// authorizes every request. + private final class HeldSignInAuthorizer: HTTPClientAuthorizer { + private struct State { + var signedIn = false + var released = false + var challengeCount = 0 + var firstChallenge: ContinuousClock.Instant? + var waiting: [CheckedContinuation] = [] + } + + private let state = Mutex(State()) + + var maxAuthorizationAttempts: Int { 2 } + var challenges: Int { state.withLock { $0.challengeCount } } + /// When the first sign-in started, if one has. + var firstSignInStart: ContinuousClock.Instant? { state.withLock { $0.firstChallenge } } + + /// Ends every sign-in, and lets later ones end at once. + func release() { + let pending = state.withLock { state in + state.released = true + defer { state.waiting = [] } + return state.waiting + } + for continuation in pending { continuation.resume() } + } + + func prepare(for endpoint: URL, session: URLSession) async throws {} + + func authorizationHeaders(for url: URL, method: String) throws -> [String: String] { + state.withLock { $0.signedIn ? ["Authorization": "Bearer signed-in"] : [:] } + } + + func handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) async throws + -> HTTPChallengeResult + { + state.withLock { state in + state.challengeCount += 1 + if state.firstChallenge == nil { state.firstChallenge = .now } + } + // The continuation is resumed after the lock is released. + await withCheckedContinuation { continuation in + let now = state.withLock { state in + if !state.released { state.waiting.append(continuation) } + return state.released + } + if now { continuation.resume() } + } + state.withLock { $0.signedIn = true } + return .retry + } + } +#endif diff --git a/Tests/MCPTests/UnknownKindTests.swift b/Tests/MCPTests/UnknownKindTests.swift index 45eeffb8..c6d26dd2 100644 --- a/Tests/MCPTests/UnknownKindTests.swift +++ b/Tests/MCPTests/UnknownKindTests.swift @@ -123,17 +123,28 @@ struct UnknownKindTests { #expect(roots.roots?.first?.uri == "file:///x") } + @Test("A sampling input response with a non-base64 image is kept as unknown") + func inputResponseInvalidImage() throws { + let json = #"{"role":"assistant","content":{"type":"image","data":"%%%","mimeType":"image/png"},"model":"m"}"# + let (response, encoded) = try roundTrip(InputResponse.self, json) + #expect(response == .unknown(try value(json))) + #expect(encoded == (try value(json))) + let valid = json.replacingOccurrences(of: "%%%", with: "iVBORw==") + let (sampling, _) = try roundTrip(InputResponse.self, valid) + #expect(sampling.sampling?.content == .image(Data([0x89, 0x50, 0x4E, 0x47]), mimeType: "image/png")) + } + @Test("Unknown blocks keep data: URL strings as written") func unknownBlockDataURL() throws { let json = #"{"type":"hologram","src":"data:,hi","frames":["data:text/plain,a%20b"],"_meta":{"k":"data:,x"}}"# - let preserved = try JSONDecoder().decode(Value.Preserved.self, from: Data(json.utf8)).value + let preserved = try JSONDecoder().decode(Value.self, from: Data(json.utf8)) #expect(preserved.objectValue?["src"] == .string("data:,hi")) func check(_ type: T.Type, _ json: String) throws -> T { let decoded = try JSONDecoder().decode(T.self, from: Data(json.utf8)) let encoded = try JSONEncoder().encode(decoded) - let expected = try JSONDecoder().decode(Value.Preserved.self, from: Data(json.utf8)).value - #expect(try JSONDecoder().decode(Value.Preserved.self, from: encoded).value == expected, "\(T.self)") + let expected = try JSONDecoder().decode(Value.self, from: Data(json.utf8)) + #expect(try JSONDecoder().decode(Value.self, from: encoded) == expected, "\(T.self)") return decoded } #expect(try check(Tool.Content.self, json) == .unknown(type: "hologram", preserved)) @@ -171,8 +182,8 @@ struct UnknownKindTests { let decoded = try JSONDecoder().decode(T.self, from: json) #expect(decoded == value, "\(value)") let reencoded = try JSONEncoder().encode(decoded) - let expected = try JSONDecoder().decode(Value.Preserved.self, from: json).value - #expect(try JSONDecoder().decode(Value.Preserved.self, from: reencoded).value == expected, "\(value)") + let expected = try JSONDecoder().decode(Value.self, from: json) + #expect(try JSONDecoder().decode(Value.self, from: reencoded) == expected, "\(value)") } try check(InputResponse.unknown(.object(["src": "data:,hi"]))) try check(InputRequest.unknown(method: "example/approve", params: ["src": "data:,hi", "list": ["data:,x"]])) @@ -187,17 +198,15 @@ struct UnknownKindTests { try sampling.params().objectValue?["messages"]?.arrayValue?.first?.objectValue?["content"] == ["type": "text", "text": "data:,hello"]) - // A known result reads a `Value` field as its decoder does, once. + // A known result keeps a string in a `Value` field. let accept = Data(#"{"action":"accept","content":{"x":"data:,hi"}}"#.utf8) - let preserving = JSONDecoder() - preserving.userInfo[.valuePreservesStrings] = true - let elicitation = try preserving.decode(InputResponse.self, from: accept).elicitation + let elicitation = try JSONDecoder().decode(InputResponse.self, from: accept).elicitation #expect(elicitation?.content?["x"] == .string("data:,hi")) // A client handler's result is sent on as the handler returned it. let returned = try InputResponse( method: CreateElicitation.name, result: ["action": "accept", "content": ["x": "data:,hi"]]) #expect(returned.elicitation?.content?["x"] == .string("data:,hi")) - #expect(try Value.preservingStrings(returned) == ["action": "accept", "content": ["x": "data:,hi"]]) + #expect(try Value(returned) == ["action": "accept", "content": ["x": "data:,hi"]]) } @Test("Elicitation parameters of an unknown mode are kept") diff --git a/Tests/MCPTests/ValueTests.swift b/Tests/MCPTests/ValueTests.swift index f384e80e..a76c6b6d 100644 --- a/Tests/MCPTests/ValueTests.swift +++ b/Tests/MCPTests/ValueTests.swift @@ -1,5 +1,6 @@ import Testing +import struct Foundation.Data import class Foundation.JSONDecoder import class Foundation.JSONEncoder @@ -70,4 +71,33 @@ struct ValueTests { #expect(decoded.doubleValue == 0.5) #expect(decoded.numberValue == 0.5) } + + // MARK: - Strings + + @Test( + "A string stays a string and encodes back to the same JSON string", + arguments: [ + "data:,hi", + "data:text/plain;base64,aGk=", + "data:image/png;base64,iVBORw0KGgo=", + "data: 3 rows, 2 columns", + "data:text/plain,a%20b", + "DATA:,hi", + ]) + func stringStaysString(_ string: String) throws { + let json = "\"\(string)\"" + let value = try JSONDecoder().decode(Value.self, from: Data(json.utf8)) + #expect(value == .string(string)) + #expect(value.stringValue == string) + #expect(try wireString(value) == json) + #expect(try Value(string) == .string(string)) + } + + @Test("An object of data: strings decodes and re-encodes unchanged") + func objectOfDataURLStrings() throws { + let json = #"{"a":"data:,x","b":["data:,y"],"c":{"d":"data:,z"}}"# + let value = try JSONDecoder().decode(Value.self, from: Data(json.utf8)) + #expect(value == ["a": "data:,x", "b": ["data:,y"], "c": ["d": "data:,z"]]) + #expect(try wireString(value) == json) + } } diff --git a/Tests/MCPTests/WireGoldenTests.swift b/Tests/MCPTests/WireGoldenTests.swift index 061106b7..a999542c 100644 --- a/Tests/MCPTests/WireGoldenTests.swift +++ b/Tests/MCPTests/WireGoldenTests.swift @@ -95,11 +95,56 @@ struct WireGoldenTests { #expect(error?.expected == 1) #expect(error?.received == 0) } + + @Test("resources/read sends a binary item as base64 in blob") + func testBinaryResource() async throws { + let server = Server(name: "golden", version: "1.0.0", capabilities: .init(resources: .init())) + await server.withMethodHandler(ReadResource.self) { _ in + .init(contents: [.binary(Data([0xFF, 0xFE, 0xFD, 0x00]), uri: "file:///b.bin")]) + } + let wire = WireExchange(server: server) + try await wire.start() + defer { Task { await wire.stop() } } + + let reply = try await wire.send( + #"{"jsonrpc":"2.0","id":1,"method":"resources/read","params":{"uri":"file:///b.bin"}}"#) + expectWire( + reply[0], + matches: try wireJSON( + #"{"jsonrpc":"2.0","id":1,"result":{"contents":[{"uri":"file:///b.bin","blob":"//79AA=="}]}}"#)) + let item = try #require(reply[0].objectValue?["result"]?.objectValue?["contents"]?.arrayValue?.first) + expectWireLacks(item, "text", "mimeType") + let raw = String(decoding: try #require(await wire.transport.sentData.last), as: UTF8.self) + #expect(raw.contains(#""blob":"//79AA==""#)) + } + + @Test("tools/call sends image bytes as base64 data") + func testImageContent() async throws { + let server = Server(name: "golden", version: "1.0.0", capabilities: .init(tools: .init())) + await server.withMethodHandler(CallTool.self) { _ in + .init(content: [.image(Data([0x89, 0x50, 0x4E, 0x47]), mimeType: "image/png")]) + } + let wire = WireExchange(server: server) + try await wire.start() + defer { Task { await wire.stop() } } + + let reply = try await wire.send( + #"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"t"}}"#) + expectWire( + reply[0], + matches: try wireJSON( + #"{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"image","data":"iVBORw==","mimeType":"image/png"}]}}"# + )) + let block = try #require(reply[0].objectValue?["result"]?.objectValue?["content"]?.arrayValue?.first) + expectWireLacks(block, "annotations", "_meta") + let raw = String(decoding: try #require(await wire.transport.sentData.last), as: UTF8.self) + #expect(raw.contains(#""content":[{"data":"iVBORw==","mimeType":"image/png","type":"image"}]"#), "\(raw)") + } } @Suite("Data URL String Tests") struct DataURLStringTests { - /// The last message the server sent, parsed without turning `data:` URLs into data. + /// The last message the server sent, parsed with `JSONSerialization`. private func lastSent(_ wire: WireExchange) async throws -> Any { let data = try #require(await wire.transport.sentData.last) return try JSONSerialization.jsonObject(with: data) @@ -135,22 +180,44 @@ struct DataURLStringTests { #expect(await seen.values == ["data:,abc", "data:,batch"]) } - @Test("Value parameters still decode data: URLs as data for the handler") - func testHandlerValueSemantics() async throws { + /// Calls tool `t` with `string` as its `blob` argument, from a handler that + /// returns the argument in a text block and in `structuredContent`, and + /// checks the argument and the reply. + private func expectEcho(_ string: String, sourceLocation: SourceLocation = #_sourceLocation) async throws { let server = Server(name: "s", version: "1", capabilities: .init(tools: .init())) let seen = ValueRecorder() await server.withMethodHandler(CallTool.self) { params in await seen.record(params.arguments?["blob"]) - return .init(content: []) + let text = params.arguments?["blob"]?.stringValue ?? "" + return .init(content: [.text(text: text)], structuredContent: ["blob": .string(text)]) } let wire = WireExchange(server: server) try await wire.start() defer { Task { await wire.stop() } } - try await wire.send( - #"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"t","arguments":{"blob":"data:,x"}}}"# + let argument = try wireString(string) + let reply = try await wire.send( + #"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"t","arguments":{"blob":\#(argument)}}}"# ) - #expect(await seen.value == .data(mimeType: "text/plain", Data("x".utf8))) + #expect(await seen.value == .string(string), sourceLocation: sourceLocation) + expectWire( + reply[0], + matches: try wireJSON( + #"{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":\#(argument)}],"structuredContent":{"blob":\#(argument)}}}"# + ), sourceLocation: sourceLocation) + let sent = String(decoding: try #require(await wire.transport.sentData.last), as: UTF8.self) + #expect(sent.contains(#""blob":\#(argument)"#), "\(sent)", sourceLocation: sourceLocation) + } + + @Test("A data: URL tool argument reaches the handler as a string and goes back as written") + func testHandlerValueSemantics() async throws { + try await expectEcho("data:,x") + try await expectEcho("data:image/png;base64,iVBORw==") + } + + @Test("Prose that starts with data: is a string") + func testProseStaysString() async throws { + try await expectEcho("data: 3 rows, 2 columns") } @Test("The client reads a data: URL text block as sent") @@ -171,7 +238,7 @@ struct DataURLStringTests { return } #expect(text == "data:,hello") - #expect(result.structuredContent == .data(mimeType: "text/plain", Data("hi".utf8))) + #expect(result.structuredContent == .string("data:,hi")) } } diff --git a/VERSIONING.md b/VERSIONING.md index cebb3bb8..313e1f66 100644 --- a/VERSIONING.md +++ b/VERSIONING.md @@ -99,7 +99,7 @@ Every public enum is one of three kinds, and its documentation says which: | Kind | Types | |---|---| -| Frozen | `ID`, `ProgressToken`, `Value`, `LogLevel`, `Prompt.Message.Role`, `Sampling.Message.Role`, `Resource.Annotations.Audience`, `CreateElicitation.Result.Action`, `Sampling.ContextInclusion`, `Elicitation.RequestSchema.SchemaType`, `Icon.Theme`, `CompletionReference`, `Sampling.Message.Content`, `OAuthConfiguration.ApplicationType`, `OAuthConfiguration.PrivateKeyJWTAssertionError`, `OAuthConfiguration.EnterpriseIdentityProvider.Endpoint`, `Client.ProtocolMode`, `HTTPResponse`, `AcceptHeaderValidator.Mode`, `ServerCard.FetchResult` | +| Frozen | `ID`, `ProgressToken`, `Value`, `LogLevel`, `Prompt.Message.Role`, `Sampling.Message.Role`, `Resource.Annotations.Audience`, `Resource.Content.Body`, `CreateElicitation.Result.Action`, `Sampling.ContextInclusion`, `Elicitation.RequestSchema.SchemaType`, `Icon.Theme`, `CompletionReference`, `Sampling.Message.Content`, `OAuthConfiguration.ApplicationType`, `OAuthConfiguration.PrivateKeyJWTAssertionError`, `OAuthConfiguration.EnterpriseIdentityProvider.Endpoint`, `Client.ProtocolMode`, `HTTPResponse`, `AcceptHeaderValidator.Mode`, `ServerCard.FetchResult` | | `unknown` case | `Tool.Content`, `Prompt.Message.Content`, `Sampling.Message.Content.ContentBlock`, `Sampling.ToolResultContent.ContentBlock`, `InputRequest`, `InputResponse`, `CreateElicitation.Parameters`; `MCPError`, where `serverError(code:message:data:)` plays that role; `Skill.Resources`, where `unrecognized(_:)` plays that role | | Open | `OAuthAuthorizationError` and its `Code`, `MCPError.Code`, `OAuthConfiguration.GrantType`, `OAuthConfiguration.TokenEndpointAuthentication`, `OAuthConfiguration.PrivateKeyJWTSigningAlgorithm`, `BearerTokenValidationResult`, `Elicitation.Mode`, `CreateSamplingMessage.ToolChoice.Mode`, `ResultType`, `CacheScope`, `TaskStatus`, `TaskSupport`, `ServerCard.Remote.TransportType`, `ServerCard.Input.Format` | diff --git a/conformance/everything-server/HTTPApp.swift b/conformance/everything-server/HTTPApp.swift index f708f6a0..f5b8d5e9 100644 --- a/conformance/everything-server/HTTPApp.swift +++ b/conformance/everything-server/HTTPApp.swift @@ -48,8 +48,8 @@ actor HTTPApp { private let configuration: Configuration private let serverFactory: ServerFactory - private let validationPipeline: (any HTTPRequestValidationPipeline)? - private let statelessValidationPipeline: (any HTTPRequestValidationPipeline)? + private let validators: [any HTTPRequestValidator] + private let statelessValidators: [any HTTPRequestValidator] private var channel: Channel? private var sessions: [String: SessionContext] = [:] private var stateless: (server: Server, transport: StatelessHTTPServerTransport)? @@ -70,21 +70,21 @@ actor HTTPApp { /// /// - Parameters: /// - configuration: Application configuration. - /// - validationPipeline: Custom validation pipeline passed to each transport. - /// If `nil`, transports use their sensible defaults. + /// - validators: The validators of each session's stateful transport. + /// - statelessValidators: The validators of the stateless transport. /// - serverFactory: Factory function to create Server instances for each session. /// - logger: Optional logger instance. init( configuration: Configuration = Configuration(), - validationPipeline: (any HTTPRequestValidationPipeline)? = nil, - statelessValidationPipeline: (any HTTPRequestValidationPipeline)? = nil, + validators: [any HTTPRequestValidator] = StatefulHTTPServerTransport.defaultValidators, + statelessValidators: [any HTTPRequestValidator] = StatelessHTTPServerTransport.defaultValidators, serverFactory: @escaping ServerFactory, logger: Logger? = nil ) { self.configuration = configuration self.serverFactory = serverFactory - self.validationPipeline = validationPipeline - self.statelessValidationPipeline = statelessValidationPipeline + self.validators = validators + self.statelessValidators = statelessValidators self.logger = logger ?? Logger( label: "mcp.http.app", factory: { _ in SwiftLogNoOpLogHandler() } @@ -216,9 +216,9 @@ actor HTTPApp { private func statelessTransport() async throws -> StatelessHTTPServerTransport { if let stateless { return stateless.transport } if let statelessStart { return try await statelessStart.value.transport } - let start = Task { [serverFactory, statelessValidationPipeline, logger] in + let start = Task { [serverFactory, statelessValidators, logger] in let transport = StatelessHTTPServerTransport( - validationPipeline: statelessValidationPipeline, logger: logger) + validators: statelessValidators, logger: logger) let server = try await serverFactory(nil, transport) try await server.start(transport: transport) return (server: server, transport: transport) @@ -246,7 +246,7 @@ actor HTTPApp { let transport = StatefulHTTPServerTransport( sessionIDGenerator: FixedSessionIDGenerator(sessionID: sessionID), - validationPipeline: validationPipeline, + validators: validators, retryInterval: configuration.retryInterval, logger: logger ) diff --git a/conformance/everything-server/main.swift b/conformance/everything-server/main.swift index a8635b40..70dc3b2d 100644 --- a/conformance/everything-server/main.swift +++ b/conformance/everything-server/main.swift @@ -20,8 +20,8 @@ import MCP // MARK: - Test Data -private let testImageBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==" -private let testAudioBase64 = "UklGRiYAAABXQVZFZm10IBAAAAABAAEAQB8AAAB9AAACABAAZGF0YQIAAAA=" +private let testImageData = Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==")! +private let testAudioData = Data(base64Encoded: "UklGRiYAAABXQVZFZm10IBAAAAABAAEAQB8AAAB9AAACABAAZGF0YQIAAAA=")! // MARK: - Server State @@ -153,15 +153,15 @@ func createConformanceServer(state: ServerState, transport: any Transport) async let region = params.arguments?["region"]?.stringValue ?? "" return .init(content: [.text(text: "Region: \(region)")], isError: false) case "test_image_content": - return .init(content: [.image(data: testImageBase64, mimeType: "image/png")], isError: false) + return .init(content: [.image(testImageData, mimeType: "image/png")], isError: false) case "test_audio_content": - return .init(content: [.audio(data: testAudioBase64, mimeType: "audio/wav")], isError: false) + return .init(content: [.audio(testAudioData, mimeType: "audio/wav")], isError: false) case "test_embedded_resource": return .init(content: [.resource(resource: .text("This is an embedded resource content.", uri: "test://embedded-resource", mimeType: "text/plain"))], isError: false) case "test_multiple_content_types": return .init(content: [ .text(text: "Multiple content types test:"), - .image(data: testImageBase64, mimeType: "image/png"), + .image(testImageData, mimeType: "image/png"), .resource(resource: .text("{\"test\":\"data\",\"value\":123}", uri: "test://mixed-content-resource", mimeType: "application/json"))], isError: false) case "test_error_handling": return .init(content: [.text(text: "An error occurred during tool execution")], isError: true) @@ -228,7 +228,7 @@ func createConformanceServer(state: ServerState, transport: any Transport) async if let requestID = Server.currentHandlerContext?.id, let stateful = transport as? StatefulHTTPServerTransport { - await stateful.closeSSEStream(forRequestID: requestID.description) + await stateful.closeSSEStream(forRequestID: requestID) } // Wait briefly for the client to reconnect before sending the response. try await Task.sleep(for: .milliseconds(100)) @@ -437,10 +437,7 @@ func createConformanceServer(state: ServerState, transport: any Transport) async case "test://static-text": return .init(contents: [.text("This is static text content for testing.", uri: params.uri, mimeType: "text/plain")]) case "test://static-binary": - guard let imageData = Data(base64Encoded: testImageBase64) else { - return .init(contents: [.text("Failed to decode binary data", uri: params.uri)]) - } - return .init(contents: [.binary(imageData, uri: params.uri, mimeType: "application/octet-stream")]) + return .init(contents: [.binary(testImageData, uri: params.uri, mimeType: "application/octet-stream")]) case "test://watched-resource": let content = await state.watchedResourceContent return .init(contents: [.text(content, uri: params.uri)]) @@ -494,7 +491,7 @@ func createConformanceServer(state: ServerState, transport: any Transport) async ]) case "test_prompt_with_image": return .init(description: "Prompt with image", messages: [ - .user(.image(data: testImageBase64, mimeType: "image/png")), + .user(.image(testImageData, mimeType: "image/png")), .user(.text(text: "Please analyze the image above.")) ]) default: @@ -528,7 +525,7 @@ struct MCPHTTPServer { let transport = StdioTransport() let server = await createConformanceServer(state: ServerState(), transport: transport) try await server.start(transport: transport) - await server.waitUntilCompleted() + try await server.waitUntilCompleted() return } var port = 3001 @@ -557,19 +554,19 @@ struct MCPHTTPServer { endpoint: "/mcp", retryInterval: 1000 ), - validationPipeline: StandardValidationPipeline(validators: [ + validators: [ OriginValidator.localhost(port: port), AcceptHeaderValidator(mode: .sseRequired), ContentTypeValidator(), ProtocolVersionValidator(), SessionValidator(), - ]), - statelessValidationPipeline: StandardValidationPipeline(validators: [ + ], + statelessValidators: [ OriginValidator.localhost(port: port), AcceptHeaderValidator(mode: .jsonOnly), ContentTypeValidator(), ProtocolVersionValidator(), - ]), + ], serverFactory: { sessionID, transport in logger.debug("Creating server", metadata: ["sessionID": "\(sessionID ?? "stateless")"]) return await createConformanceServer(state: state, transport: transport) diff --git a/design/apps.md b/design/apps.md index 4b16b111..cec009d9 100644 --- a/design/apps.md +++ b/design/apps.md @@ -78,7 +78,8 @@ recommend listing the same tools for every client, with text `content` for hosts 2. `resources/read`; the content item with the requested URI. 3. The MIME type must be `text/html` with `profile=mcp-app`. Case, whitespace around `;` and `=`, quotes and other parameters are accepted. -4. `text`, or a `blob` of base64-encoded UTF-8. +4. `text`, or a `blob` whose bytes are UTF-8 (else `invalidContent`). A malformed item + (neither, both, or a `blob` that is not base64) fails earlier, in `readResource`. 5. The effective metadata is the content item's `_meta.ui`, or, when it has none, the listing entry's: the whole value, not a merge of fields (`resource._meta?.ui ?? listingResource._meta?.ui` in the specification). A content `_meta.ui` that is present but diff --git a/design/auth.md b/design/auth.md index fd7e8d59..8aec3abe 100644 --- a/design/auth.md +++ b/design/auth.md @@ -10,7 +10,8 @@ client registration, RFC 7591, or a Client ID Metadata Document, CIMD), obtains The SDK implements the client side in `Sources/MCP/Base/Authorization/`. On the server side it provides HTTP validators: `ProtectedResourceMetadataValidator` serves PRM and -`BearerTokenValidator` checks tokens with an application closure. +`BearerTokenValidator` checks tokens with an `async` application closure, which may call an +introspection endpoint (RFC 7662). 1.0.0 adds issuer checks (RFC 8414 §3.3, RFC 9207, SEP-2468), `application_type` (SEP-837), authorization server migration (SEP-2352) and the 2025-03-26 @@ -29,28 +30,46 @@ fallback endpoints. ### Layers ```swift -public protocol HTTPClientAuthorizer: AnyObject, Sendable { +public protocol HTTPClientAuthorizer: Sendable { var maxAuthorizationAttempts: Int { get } - func validateEndpointSecurity(for endpoint: URL) throws - func authorizationHeaders(for url: URL, method: String) throws -> [String: String] - func handleChallenge(statusCode: Int, headers: [String: String], endpoint: URL, - operationKey: String?, session: URLSession) async throws -> Bool - func prepareAuthorization(for endpoint: URL, session: URLSession) async throws // default no-op + func prepare(for endpoint: URL, session: URLSession) async throws // default: nothing + func authorizationHeaders(for url: URL, method: String) async throws -> [String: String] + func handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) async throws + -> HTTPChallengeResult + func didReceiveResponse(headers: [String: String], for url: URL) async // default: nothing } ``` -`HTTPClientTransport(endpoint:authorizer:)` calls, for each POST and before opening the GET -stream: `validateEndpointSecurity`, `prepareAuthorization` (errors ignored), then, after the -`requestModifier`, sets the headers from `authorizationHeaders` for the final URL and method -(DPoP proofs sign both). It passes the headers of every response, with the request URL, to -`didReceiveResponse` (default: nothing). On 401 or 403 it calls `handleChallenge` and retries -while the result's `retry` is `true` and fewer than `maxAuthorizationAttempts` attempts were -made; a retry the result marks `isDPoPNonceRetry` (a `use_dpop_nonce` challenge) does not count, -and a second one fails the request. The authorizer classifies the challenge, not the transport: -the default of the `sentAuthorization` variant reads it with `DefaultOAuthWWWAuthenticateParser`. -An error from `validateEndpointSecurity`, `authorizationHeaders` or `handleChallenge` fails the -request as `MCPError.transportError(error)`, except a `CancellationError`, which is thrown as is, -and a 401 or 403 that is not retried fails it as `transportError(HTTPStatusError)`. +A class, a struct or an actor can conform; an actor declares `maxAuthorizationAttempts` +`nonisolated`. For each POST and each GET of an SSE stream (the standalone stream and the +resumption of a POST's stream), `HTTPClientTransport(endpoint:authorizer:)` first requires its +endpoint to be `https`, or `http` on a loopback host, without a fragment, and fails the request +with `MCPError.transportError(insecureOAuthEndpoint)` (`invalidResourceURI` for a fragment) +before it calls the authorizer: the transport runs the check itself, so an authorizer that +implements `prepare` can't skip it. Then it calls `prepare` (the default does nothing), builds +the request, runs the `requestModifier` (`@Sendable (inout URLRequest) async throws -> Void`), +checks the request's final URL in the same way (the token goes where the request goes, so a +modifier that points it at cleartext `http` gets no token and nothing is sent), and sets the +headers from `authorizationHeaders` for the final URL and +method (DPoP proofs sign both). The modifier and the authorizer may suspend, and the transport is +an actor, so other requests run meanwhile: after the awaits it checks that it is still +connected and sets `Mcp-Session-Id` again from the current state, so a session another response +replaced or a 404 dropped is not sent (the DPoP proof signs only `htm` and `htu`, RFC 9449 §4.2). +On the GET path the awaits run outside the actor, which is held only to build and finish the +request. The transport passes the headers of every response, with the request URL, to +`didReceiveResponse`. On 401 or 403 it calls `handleChallenge` with an +`HTTPAuthorizationChallenge` (status, headers, endpoint, JSON-RPC method, the `Authorization` +header the request carried; its description names no header value) and retries while the +result's `shouldRetry` is `true` and fewer than `maxAuthorizationAttempts` attempts were made; a +retry the result marks `isDPoPNonceRetry` (`.retryWithDPoPNonce`, a `use_dpop_nonce` challenge) +does not count, and a second one fails the request. The authorizer classifies the challenge, not +the transport. An error from `prepare`, the `requestModifier`, `authorizationHeaders` or +`handleChallenge` fails the request as `MCPError.transportError(error)`, except a +`CancellationError`, which is thrown as is, and a 401 or 403 that is not retried fails it as +`transportError(HTTPStatusError)`. `prepare`, the `requestModifier` and `authorizationHeaders` +of a POST count as authorization time, which `Client` does not count against the discovery +timeout: a modifier that reads a Keychain item behind Face ID waits for the user as an authorizer +does. `OAuthAuthorizer` is the built-in implementation, configured with `OAuthConfiguration`: @@ -72,7 +91,7 @@ and a 401 or 403 that is not retried fails it as `transportError(HTTPStatusError | Component | Visibility | Default | |---|---|---| -| `TokenStorage` | public | `InMemoryTokenStorage` | +| `OAuthTokenStorage` | public | `InMemoryOAuthTokenStorage` | | `OAuthScopeSelecting` | public | `DefaultOAuthScopeSelector` | | `OAuthWWWAuthenticateParsing` | public | `DefaultOAuthWWWAuthenticateParser` | | `OAuthMetadataDiscovering` | public | `DefaultOAuthMetadataDiscovery` (well-known URLs, canonical resource URI, resource matching) | @@ -83,23 +102,89 @@ and a 401 or 403 that is not retried fails it as `transportError(HTTPStatusError | `OAuthAuthorizationCodeFlowing` | internal | `OAuthAuthorizationCodeFlow` | The public convenience initializer takes the public components. The internal initializer takes -all of them; tests use it. - -`OAuthAuthorizer` is a class marked `@unchecked Sendable`. The transport runs each POST in its own -task, so calls overlap: every mutable property is behind a lock, and `handleChallenge` and -`prepareAuthorization` run one at a time through `AsyncGate`. One authorizer serves one resource. +all of them; tests use it. Every component protocol refines `Sendable`. + +`OAuthAuthorizer` is a `final class`, checked `Sendable`: its mutable state is one `Mutex`, +and each access takes the lock once (a read-modify-write, such as counting a step-up attempt, +takes it once for both). No lock is held across an `await`, and no `withLock` body calls the +storage or the network. The transport runs each POST in its own task, so calls overlap. Two +`AsyncGate`s order the async work: `gate` runs challenges and proactive renewals one at a time, +and `TokenStore.writes` runs storage writes one at a time. A body holding `gate` may wait for +`writes`, never the reverse, and a `writes` body calls only the storage, so they can't deadlock. +`authorizationHeaders` doesn't wait for `gate`, which can hold an interactive sign-in for +minutes. One authorizer serves one MCP server. + +### Token storage + +`OAuthTokenStorage` is `Sendable` and `async throws`, and keyed by resource: +`load(for:)`, `save(_:for:)`, `clear(for:)`. The key is the canonical URI the authorizer sends as +the RFC 8707 `resource`: `endpointOverrides.resource`, else the PRM `resource` when it matches the +endpoint, else the canonical endpoint (`canonicalResource(for:)`). The canonical form follows the +MCP "Canonical Server URI" (the form without a trailing slash) and RFC 3986 §6.2.2-6.2.3: +lowercase scheme, and the ASCII letters of the host in its encoded (punycode) form; no user +information, default port (`:443`, `:80`), query, fragment (refused, RFC 8707 §2) or trailing +`/` (all of them, so the form is idempotent); percent-encodings with uppercase hex digits, +unreserved characters decoded; no `.` or `..` segments (RFC 3986 §5.2.4), since matching is a +path prefix and `/mcp/../admin` must not lie under `/mcp`. Matching compares the percent-encoded +paths, so `%2F` is not a separator. User information is dropped, not refused: it is a +credential, not part of the server's identity (RFC 3986 §3.2.1, §7.5), and must not reach the +authorization server, a storage key or an error message; the URL validator's errors drop it and +the query too, and discovery URLs carry neither. The trailing slash is always dropped, also from +`endpointOverrides.resource`; a server whose slash is significant gets it back from an +`OAuthMetadataDiscovering` that wraps the default (`OAuthAuthorizer.init(metadataDiscovery:)`), +since the default's matching ignores trailing slashes. Saves use the `resource` of +the token request that obtained the token; loads and clears use `canonicalResource(for:)` of the +request URL. So one store serves authorizers for several servers, and a token is attached only to +a URL its resource covers: after discovery, `authorizationHeaders` for a URL outside the PRM +`resource` throws `protectedResourceMismatch`. When neither the configuration nor the PRM names a +resource (a 2025-03-26 server without metadata, or a PRM without `resource`), the resource is the +endpoint the authorizer serves (recorded by `prepare` and each challenge), whose canonical URI the +token requests sent: every URL on the endpoint's origin, such as one a `requestModifier` gives +another path, loads under the endpoint's key, so save and load agree, and after discovery a URL +on another origin throws `protectedResourceMismatch`. + +The key can change at discovery: before the PRM is cached it is the endpoint (or the override), +after it the PRM `resource`. A persisted token saved after discovery isn't found by the first +request after a relaunch. The 401 path reads the PRM, recomputes the key, and when it differs +loads the token under the new key. It retries with that token, before any refresh or grant, when +the token is valid, isn't the one the request sent, is bound to the configured DPoP key (or to +none), and was issued by an AS the current PRM lists in `authorization_servers` (or by the +configured `endpointOverrides.authorizationServerURL`), and not by another AS than the selected +one. A token that records no AS is not used. Without a usable token under the new key, the +refresh of step 3 uses that key's token, or, when it has no refresh token, the token found +under the old key, refreshed for the new key and saved under it. In each of these outcomes, and +before a new grant, the token under the old key, which no request reads any more, is cleared +with a compare-then-clear; an error that fails the challenge leaves it. That clear is best +effort: a storage error there doesn't fail a request that has a usable token, and the token +stays until a challenge after the next launch, which starts from the old key again. A token +saved under the old key meanwhile is not the one compared, so it stays. Applications that +persist tokens set `endpointOverrides.resource` to send the token on the first request. The +clears on an AS change use the key in use before the metadata is replaced. + +Writes go through `TokenStore.writes`. A save waits there with `ignoringCancellation: true`: the +token endpoint has issued the token, and may have rotated the refresh token it replaces (OAuth 2.1 +§4.3.1). `authorizationHeaders` clears a token from another AS, or bound to another DPoP key, with +a compare-then-clear in one `writes` body: it loads the token again, and clears it only while it +is still that token and still unusable. A save from a concurrent challenge waits and lands after +the clear. Before, the compare and the clear were two storage calls outside the gate, and a token +saved between them was removed: the next request started the flow again. The gates don't +serialize two authorizers sharing a key in one store, or another process sharing a Keychain item. + +A storage error fails the request (`MCPError.transportError`). A challenge whose save fails +records the error like any other: challenges that waited for it fail with it, and a later +challenge runs the flow again. `prepare` rethrows a load error and `CancellationError`, and +ignores a failed renewal. ### Challenge handling 401: -`handleChallenge` and `prepareAuthorization` run through `AsyncGate`, one at a time. The token -a request was sent with is the one in its `Authorization` header: `HTTPClientTransport` passes it -through `handleChallenge(statusCode:headers:endpoint:operationKey:sentAuthorization:session:)` -(an `HTTPClientAuthorizer` requirement whose default calls the method without it; there the -stored token is read before waiting). When another challenge replaced it meanwhile, the request -retries with the new token. A waiter whose task is cancelled leaves the gate's queue and throws -`CancellationError`. Every mutable property is read and written under a lock. +`handleChallenge` and `prepare` run through `gate`, one at a time. The token a request was sent +with is the one in its `Authorization` header, which `HTTPClientTransport` passes as +`HTTPAuthorizationChallenge.sentAuthorization`. (Two internal overloads keep the older calling +shapes for tests; the one without `sentAuthorization` reads the stored token before waiting.) +When another challenge replaced it meanwhile, the request retries with the new token. A waiter +whose task is cancelled leaves the gate's queue and throws `CancellationError`. The authorizer counts the challenges that ran to the end and keeps the error of the last one. A challenge that waited while another ended with an error, and finds no unexpired token, throws @@ -109,7 +194,7 @@ cancelled. A cancelled challenge is not counted. 0. With DPoP, a `DPoP-Nonce` header is stored for the MCP server's origin (`didReceiveResponse` stores it for the origin each request went to). A `DPoP` challenge with `error="use_dpop_nonce"` while a valid DPoP token is stored retries with the nonce and - keeps the token; the result's `isDPoPNonceRetry` says so, read with `challengeParser`. The + keeps the token; the result is `.retryWithDPoPNonce`, read with `challengeParser`. The transport retries a request once for such a challenge without counting it; a second one fails the request. 1. If the stored token has a refresh token, the challenge names no other PRM URL, the token is @@ -117,8 +202,13 @@ cancelled. A cancelled challenge is not counted. Success → retry. 2. Re-read the PRM (`refresh: true` when a token is stored). A failed re-read keeps the cached PRM; a PRM that no longer lists the selected AS resets the selection and clears the token. -3. If no refresh was tried yet and a token is still stored (the PRM still lists its AS), refresh - at the selected AS, also when it is the token the last refresh returned. Success → retry. AS + When the PRM changes the storage key, load the token under the new key; a usable one that + the request didn't send, from an AS the PRM lists → retry, and clear the token under the old + key (see [Token storage](#token-storage)). +3. If a token is still stored (the PRM still lists its AS) and its refresh was not tried in step + 1, refresh at the selected AS, also when it is the token the last refresh returned; after a + key change, the new key's token, or the old key's when the new key's has no refresh token. + Success → retry. AS metadata that is unavailable (`OAuthMetadataUnavailable`: a network error, an unexpected status) or a cancelled read fails the challenge and keeps the stored tokens. 4. Clear the token. Select scopes (challenge `scope`, else `scopes_supported`). @@ -132,10 +222,16 @@ an AS only when an AS or token endpoint override is configured. token with the required scopes while this one waited, the request retries with it. Otherwise the requested scopes are the union of the token's scopes and the challenge's. Attempts are counted per resource, operation (the JSON-RPC method) and scope set, up to `maxScopeUpgradeAttempts`. +A 403 can run the first discovery and change the storage key too: as on the 401 path, a token +under the new key counts only when an AS the PRM lists issued it, the old key's token gives its +scopes to the union, and it is cleared (best effort) once the step-up obtains a token (so a failed +or cancelled elevation keeps the narrower token, and a retry recovers it via `pendingSuperseded`). -`prepareAuthorization` refreshes a token that expires within `proactiveRefreshWindowSeconds`, -when a refresh token and AS metadata are known. It checks the expiry again once it holds the -gate, so concurrent requests refresh once. +`OAuthAuthorizer.prepare` checks the endpoint again with its URL validator (its error fails the +request), then refreshes a token that +expires within `proactiveRefreshWindowSeconds`, when a refresh token and AS metadata are known. +It checks the expiry again once it holds the gate, so concurrent requests refresh once. A failed +renewal is ignored, except a cancelled one, which is tried again by the next request. ### Discovery order @@ -152,8 +248,13 @@ status, invalid body) makes the fetch unavailable: `OAuthMetadataUnavailable` is candidate succeeds, and cancellation is rethrown. Only when every candidate is absent, and only on first discovery, a synthetic PRM names the endpoint's origin as the AS and is marked `isFallback` (2025-03-26 servers). A PRM `resource` must match the endpoint's canonical resource -URI, else `protectedResourceMismatch`. A new challenge URL drops the cached PRM, AS selection and -AS metadata. +URI, else `protectedResourceMismatch`. Both sides are canonicalized before the comparison (scheme, +host and port equal, the endpoint path equal to or under the resource path), so a PRM that names +`https://mcp.example.com/mcp/` or `https://mcp.example.com:443/mcp` matches the endpoint +`https://mcp.example.com/mcp`, and the `resource` sent is the canonical +`https://mcp.example.com/mcp`. RFC 9728 §3.3 asks for an identical value; the prefix match is the +MCP practice that lets a server publish one PRM at its origin. A new challenge URL drops the +cached PRM, AS selection and AS metadata. AS candidates: `endpointOverrides.authorizationServerURL`, else the selected AS, else the PRM's `authorization_servers` in order. Candidates that fail validation or are private IPs are skipped @@ -258,10 +359,12 @@ no PRM) and leaves leg 1 to the application; the Go SDK has both legs (`Enterpri ### DPoP (RFC 9449, SEP-1932) -`DPoPProofSigner` (internal) holds the key (`any DPoPSigningKey`: `publicKey` and -`signature(for:)`; `P256.Signing.PrivateKey` and, with CryptoKit, -`SecureEnclave.P256.Signing.PrivateKey` conform), its JWK and RFC 7638 thumbprint, and the -nonces, keyed by kind (authorization server or resource server) and origin, behind a lock. +`DPoPProofSigner` (internal, checked `Sendable`) holds the key (`any DPoPSigningKey`: +`publicKey` and an `async throws` `signature(for:)`; `P256.Signing.PrivateKey` and, with +CryptoKit, `SecureEnclave.P256.Signing.PrivateKey` conform, their synchronous methods witnessing +the requirement), its JWK and RFC 7638 thumbprint, and the nonces, keyed by kind (authorization +server or resource server) and origin, in a `Mutex`. Each request awaits its proof; a signing +error fails it. - Proof: compact JWS, header `typ` `dpop+jwt`, `alg` `ES256`, `jwk` (EC P-256 `x`, `y`); claims `jti` (16 random bytes), `htm`, `htu` (scheme and host lowercased, no user information, query @@ -313,7 +416,8 @@ Comparison: the Python and Go SDKs declare the DPoP metadata fields only. - If the selected AS is no longer listed, the selection and AS metadata are reset and the stored token is cleared, unless `endpointOverrides.authorizationServerURL` configures the AS: the override decides the AS whatever the PRM lists. -- `authorizationHeaders` clears a stored token whose AS differs from the selected one. +- `authorizationHeaders` clears a stored token whose AS differs from the selected one, with the + compare-then-clear of [Token storage](#token-storage). - A refresh token is used only at the AS that issued it. - Registered credentials are bound to `registrationIssuer`. When the AS changes, authentication returns to the configured value and registration runs again at the new AS. @@ -357,9 +461,17 @@ URI is validated before the flow starts. - **Always `native`.** Rejected: OpenID Connect Dynamic Client Registration limits `native` clients to custom-scheme or loopback redirect URIs, so an `https` redirect on a public host belongs to a `web` client. -- **An actor for `OAuthAuthorizer`.** Not done: the protocol's synchronous `authorizationHeaders` - would become `async`. A lock per property plus a gate for the async flows gives the same - guarantees without changing the protocol. +- **An actor for `OAuthAuthorizer`.** Rejected, although the protocol is now `async` and would + allow one. A `Mutex` class keeps the in-memory path synchronous (an `InMemoryOAuthTokenStorage` + load and the header building need no actor hop per request), and it avoids actor reentrancy + across the long flows: a sign-in suspends for minutes, and an actor would let every other call + interleave with its state at each `await`. The gates already order the flows, and the `Mutex` + makes each state access atomic. Conformers may still be actors. +- **Storage keyed by the canonical endpoint always.** Rejected: the token is requested for the + `resource` sent, which the PRM may set to another URI; keying by it keeps the token where + RFC 8707 bound it. The cost is the key change at discovery, handled by the recheck. +- **A shadow copy of the token in memory when a save fails.** Rejected: it would diverge from + the store. A failed save fails the challenge. - **Keep `authorizationHeader(for:) -> String?` and add the proof elsewhere.** Rejected: a DPoP proof signs the method and URL, and a second header needs a second return value. The new requirement returns all headers; the major version allows the break. @@ -368,8 +480,8 @@ URI is validated before the flow starts. ## Open questions -- A missing `authorization_endpoint` throws `tokenEndpointMissing`. -- `TokenStorage` holds one token, so one authorizer serves one resource. +- Storage is keyed by resource, so one store serves several servers; one authorizer still serves + one MCP server, and two authorizers for the same server don't coordinate their sign-ins. - DPoP: only ES256; tokens from `accessTokenProvider` are Bearer only. - No OpenID Connect sign-in helper produces the ID token for `enterpriseManaged` (the Go SDK has `PerformOIDCLogin`). diff --git a/design/design.md b/design/design.md index d60722e4..9ce38401 100644 --- a/design/design.md +++ b/design/design.md @@ -188,21 +188,42 @@ Why a task-local: ```swift public protocol Transport: Actor { - var logger: Logger { get } + nonisolated var logger: Logger { get } func connect() async throws func disconnect() async - func send(_ data: Data) async throws - func send(_ data: Data, relatedRequestID: ID?) async throws // default calls send(_:) - func receive() -> AsyncThrowingStream + func send(_ data: Data, options: TransportSendOptions) async throws + func receive() async -> AsyncThrowingStream + + // Hooks, each with a default that does nothing: + func didNegotiate(protocolVersion: String) async + @discardableResult func abandonRequest(_ id: ID) async -> Bool + func authorizationEnd(of id: ID) async -> ContinuousClock.Instant? + func prepare(servingProtocolVersions versions: [String]) async + nonisolated var isSessionless: Bool { get } + func httpRequest(for id: ID) async -> HTTPRequest? } ``` - A transport moves whole JSON-RPC messages as `Data`. Framing (newline-delimited stdio, HTTP bodies, SSE events) is the transport's job; parsing is the client's or server's job. -- `send(_:relatedRequestID:)` was added in 1.0.0 with a default implementation, so - existing custom transports compile unchanged. Transports with per-request streams use the id - to deliver progress, log and server-to-client messages on the stream of the request that - produced them (SEP-1699 behavior at 2025-11-25). +- The contract: `connect()` throws when already connected and after `disconnect()`; + `disconnect()` can be called any number of times, also before `connect()`, and finishes the + stream; a send after `disconnect()`, or once the transport knows the peer can no longer read, + throws `connectionClosed`; `receive()` returns the same stream on every call, to be iterated + from one task; its end means the peer sends nothing more, though a transport may still send + (stdio after the end of its input). +- `TransportSendOptions` carries what a message needs besides its bytes: `relatedRequestID`, + which transports with per-request streams use to deliver progress, log and server-to-client + messages on the stream of the request that produced them (SEP-1699 behavior at 2025-11-25), + and `headers`, the `Mcp-Param-*` headers of a 2026-07-28 `tools/call`. `send(_:)` is a + convenience in an extension. +- `Client` and `Server` call each hook on every transport, never a concrete transport type. + Every hook is a protocol requirement: a method declared only in an extension is dispatched + statically, so a call through `any Transport` would never reach a wrapper's version. +- `TransportWrapper` (`nonisolated var wrapped: any Transport`) forwards every requirement and + hook, so a logging or metrics wrapper keeps the wrapped transport's behavior. A hook added in + 1.x is added to the protocol, its default and the wrapper's forwarding in the same change. A + method that only nearly matches a hook's signature compiles silently and is never called. ### HTTP server transports @@ -212,16 +233,11 @@ converts its request to `HTTPRequest` (method, headers, body, path), calls an SSE body as `AsyncThrowingStream`. `conformance/everything-server/HTTPApp.swift` and `Examples/http-server` are SwiftNIO adapters. -Both server transports conform to `HTTPContextProviding`: - -```swift -public protocol HTTPContextProviding: Sendable { - func httpRequestContext(for id: ID) async -> HTTPRequest? -} -``` - -`Server` asks for the `HTTPRequest` of each request id and puts it in -`HandlerContext.httpContext`. Handlers read headers and authentication data there. +Both server transports implement the `httpRequest(for:)` hook. `Server` asks for the +`HTTPRequest` of each request id and puts it in `HandlerContext.httpContext`. Handlers read +headers and authentication data there. The stateless transport also implements +`prepare(servingProtocolVersions:)`, for the versions its validators accept, and +`isSessionless`, which makes `Server` serve each handshake request without `initialize`. | | `StatefulHTTPServerTransport` | `StatelessHTTPServerTransport` | |---|---|---| @@ -237,8 +253,16 @@ Route requests with `HTTPRequest.statelessProtocolVersion`: a non-`nil` value is `MCP-Protocol-Version` header that names a revision outside `Version.handshake`. The -32022 answer of the stateful transport lets a `.automatic` client fall back to `initialize`. -Request validation is a pipeline of `HTTPRequestValidator` values (`StandardValidationPipeline`). -Defaults: localhost `OriginValidator`, `AcceptHeaderValidator`, `ContentTypeValidator`, +Request validation runs the transport's `validators:`, an array of `HTTPRequestValidator` values, +in order; the first response ends the request. `validate` is `async`, so a validator can call an +introspection endpoint. The built-in validators other than `BearerTokenValidator` conform to the +internal `SynchronousRequestValidator`, which the transports run on their actor without +suspending, so the defaults handle each request atomically, as before validation was `async`. +Other requests run while a validator suspends: the stateful transport counts changes of the +session ID (created, or dropped by a refused `initialize`) and validates a request again when +one happened meanwhile, up to three runs and then 503; both transports check for termination +before acting on a request. `StandardValidationPipeline` groups validators into one. +Defaults (`defaultValidators`): localhost `OriginValidator`, `AcceptHeaderValidator`, `ContentTypeValidator`, `ProtocolVersionValidator`, and on the stateful transport `SessionValidator`. Applications add `BearerTokenValidator` and `ProtectedResourceMetadataValidator` for authorization. @@ -249,20 +273,22 @@ Defaults: localhost `OriginValidator`, `AcceptHeaderValidator`, `ContentTypeVali - `MCP-Protocol-Version` comes from the outgoing message's `_meta["io.modelcontextprotocol/protocolVersion"]` when present, otherwise from the negotiated version. -- `useStatelessProtocol(_:)` drops the session id and the GET stream. `Client` calls it after a +- `didNegotiate(protocolVersion:)` sets the version header. At a revision without sessions it + also drops the session id and the GET stream. `Client` calls it after `initialize` and after a successful `server/discover`. - When the version's profile has `usesStandardHeaders`, every POST carries `Mcp-Method` and, for `tools/call`, `prompts/get` and `resources/read`, `Mcp-Name`. -- `send(_:additionalHeaders:)` carries `Mcp-Param-*` headers. -- Each POST of a message with a JSON-RPC id runs in a task keyed by that id. `cancelRequest(_:)` - cancels it, which closes the response stream. At 2026-07-28 this is how a request is cancelled. +- `options.headers` of `send(_:options:)` carry `Mcp-Param-*` headers. +- Each POST of a message with a JSON-RPC id runs in a task keyed by that id. + `abandonRequest(_:)` cancels it, which closes the response stream. At 2026-07-28 this is how a + request is cancelled, so it returns `true` there and `Client` sends no `notifications/cancelled`. +- `authorizationEnd(of:)` reports when the authorizer last finished with a request, so `Client` + doesn't count a sign-in against `discoveryTimeout`. - A non-2xx reply with a JSON-RPC response body is delivered as a response, so the client sees the -32020/-32022 error instead of an HTTP error. -`Client` hands the `Mcp-Param-*` headers to any transport through the `Transport` requirement -`send(_:additionalHeaders:)`, whose default ignores them. It reaches the other features by -downcasting its transport to `HTTPClientTransport`, so a custom HTTP client transport does not -get abort-based cancellation. +`Client` reaches each of these through a `Transport` hook, so a custom HTTP client transport, or +a wrapper around `HTTPClientTransport`, gets the same behavior. ## JSON-RPC types @@ -299,22 +325,23 @@ Type erasure: `AnyMethod` has `Value` parameters and result. `AnyRequest`, `AnyR decodes it as `Request`. A decode failure becomes -32602 `Invalid params for `. The round trip through JSON costs time; it keeps the handler table a plain `[String: RequestHandlerBox]`. -Batches: the server accepts JSON-RPC batch arrays and answers with one array. The client sends -batches with `withBatch(body:)`. +Batches: the server accepts JSON-RPC batch arrays on stream transports and answers with one +array; the HTTP server transports answer an array with 400. The client sends batches with +`withBatch(isolation:body:)`. ### `Value` -`Value` is the dynamic JSON type: `null`, `bool`, `int`, `double`, `string`, `data`, `array`, -`object`. It is used for tool arguments, schemas, error data, capability extensions and `_meta` -fields. It has literal conformances, so `["type": "object"]` is a `Value`. +`Value` is the dynamic JSON type: `null`, `bool`, `int`, `double`, `string`, `array`, `object`. +It is used for tool arguments, schemas, error data, capability extensions and `_meta` fields. It +has literal conformances, so `["type": "object"]` is a `Value`. -Decoding tries `Bool`, then `Int`, then `Double`, then `String`. A string that is a `data:` URL -decodes as `.data(mimeType:_:)`, which encodes as a base64 `data:` URL: `data:,hi` comes back as -`data:text/plain;base64,aGk=`. The SDK's own hops through `Value` (the client and server message -decoders, batch items, type-erased requests and responses, handler results, `_meta` accessors, -error data) decode with `userInfo[.valuePreservesStrings]` or `Value.preservingStrings`, so a -`data:` string is forwarded as written. The typed decode before a handler runs is a plain -decode: a handler still sees `.data` in a `Value` field, such as a tool argument. +Decoding tries `Bool`, then `Int`, then `Double`, then `String`. A string is always `.string`, +as written, so every hop through `Value` (the message decoders, type-erased requests and +responses, handler results, `_meta` accessors, error data) forwards it unchanged. MCP carries +binary content in typed fields (image and audio `data`, a resource's `blob`); `DataURL` parses a +`data:` URL string on request, and a `Codable` type can declare a `DataURL` property to decode +and validate one. A number is an `Int` when it is whole and in range, else a `Double`, so a very +large or very precise number can change value through `Value`. ### `_meta` @@ -504,7 +531,9 @@ Each change and the reason for it. [docs/migration.md](../docs/migration.md) has | `Server.init` gains `requestStateProtection:`, default `.ephemeral()` | `requestState` is client-held input; sealing is on by default ([mrtr.md](mrtr.md)). | | `CallTool`, `GetPrompt`, `ReadResource` parameters and results gain MRTR fields; results have custom `Codable` | SEP-2322. An input-required result encodes without content. | | List and read results conform to `CacheableResult` (`ttlMs`, `cacheScope`) | SEP-2549. | -| `Transport.send(_:relatedRequestID:)` | Per-request streams. Defaulted, so custom transports compile. | +| `Transport.send(_:options:)` replaces `send(_:)` as the requirement; `send(_:)` is a convenience | Per-request streams and HTTP headers in one call. A 0.12 conformer fails to compile until it implements it. | +| `Transport` hooks with no-op defaults; `TransportWrapper` | `Client` and `Server` stop downcasting to the SDK's transports; wrappers keep the wrapped behavior. | +| `Transport.logger` is `nonisolated`; `receive()` is `async` | No `await` to log; a wrapper can await the wrapped stream. | | `Request._meta`, `Message._meta`; `Message.init(method:params:_meta:)` | The stateless envelope on any request. | | `Client.Configuration` gains `protocolMode`, `logLevel`, `multiRoundTrip` | 2026-07-28 client. All defaulted. | | List-changed and resource-updated notifications are not sent on a connection without `initialize` | At 2026-07-28 they go only to listen streams. | @@ -559,10 +588,5 @@ Implied by the design, not recorded as separate decisions: - A slow notification handler delays later notifications and the responses queued behind them. Running notification handlers concurrently, as the Python SDK does, would lose the ordering of progress before results. -- `Client` hands the `Mcp-Param-*` headers to any transport through - `Transport.send(_:additionalHeaders:)`, but still downcasts to `HTTPClientTransport` to cancel - a request at 2026-07-28, to pass on the negotiated or discovered protocol version, and to - extend a request's timeout while a sign-in runs. A transport capability protocol would let - custom transports opt in. - The type-erasure round trip through JSON on every request could be replaced by direct decoding from the received bytes. diff --git a/design/foundation_models.md b/design/foundation_models.md index f5a35487..efc9110f 100644 --- a/design/foundation_models.md +++ b/design/foundation_models.md @@ -84,7 +84,6 @@ on one side and the `Value` cases on the other: | `.bool` | `.bool` | | `.int`, `.double` | `.number(Double)` | | `.string` | `.string` | -| `.data(mimeType:_:)` | `.string`, as the `data:` URL it is encoded as on the wire | | `.array` | `.array` | | `.object` | `.structure(properties:orderedKeys:)` | diff --git a/design/request_headers.md b/design/request_headers.md index 60575d17..7843dd99 100644 --- a/design/request_headers.md +++ b/design/request_headers.md @@ -64,7 +64,7 @@ numbers, arrays and objects have no header form. | Standard headers | `HTTPClientTransport.post` | When `Version.profile(for: version).usesStandardHeaders`, set `Mcp-Method` and, where defined, `Mcp-Name` (encoded). The version comes from the message's `_meta`. | | Schema cache | `Client.dispatch` → `recordTools` | Every `tools/list` result on a stateless connection fills `toolHeaderParameters[tool.name]`. Tools with invalid annotations are removed from the result returned to the caller, and their cache entry is cleared. A warning is logged. | | Parameter headers | `Client.dispatch` | For `tools/call` on a stateless connection, `MCPRequestHeaders.parameterHeaders` builds `Mcp-Param-*` from the cached parameters and the call's arguments. Absent, `null` and non-primitive arguments send no header. | -| Sending | `Transport.send(_:additionalHeaders:)` | Used only when there are headers. `HTTPClientTransport` sends them on the request's POST. The default implementation ignores them and calls `send(_:)`, so a custom or wrapping transport implements the method to receive or forward them. | +| Sending | `TransportSendOptions.headers` of `Transport.send(_:options:)` | Empty when there are no headers. `HTTPClientTransport` sends them on the request's POST; other transports ignore them. A `TransportWrapper` forwards them unless it overrides `send(_:options:)` and drops `options`. | The cache is filled only by `tools/list` results the client has received. A `tools/call` for a tool that was never listed sends no `Mcp-Param-*` headers. @@ -135,11 +135,10 @@ header that disagrees with `_meta` ([stateless.md](stateless.md)). `tools/call` that has arguments or headers (and per call on a server with tasks). - **Checking parameter headers in the transport.** The transport has no access to handlers. The check runs in `Server`, where `HandlerContext.httpContext` provides the headers. -- **Downcasting to `HTTPClientTransport`.** Replaced by `Transport.send(_:additionalHeaders:)`. +- **Downcasting to `HTTPClientTransport`.** Replaced by `TransportSendOptions.headers`. With the downcast, a wrapping transport (a logger, a decorator) or a custom Streamable HTTP transport received a `tools/call` without its headers, and a conforming server answered -32020. - The requirement has a default that ignores the headers, so existing conformers compile - unchanged. + `send(_:options:)` is the one send requirement, so every conformer receives the headers. - **Lenient Base64 decoding.** Rejected. Canonical-only decoding means one header text per value, so comparisons are exact. @@ -149,6 +148,5 @@ header that disagrees with `_meta` ([stateless.md](stateless.md)). them answers -32020. The client could list tools on demand. - The server calls the `tools/list` handler on every stateless `tools/call` with arguments. Cost is linear in the number of pages before the tool. -- A custom transport whose `send(_:additionalHeaders:)` keeps the default sends no parameter - headers. +- A custom HTTP transport that ignores `options.headers` sends no parameter headers. - Annotations under `$ref`, `allOf`, `anyOf` or `oneOf` are not found. diff --git a/design/skills.md b/design/skills.md index 81b00dff..cdd9f856 100644 --- a/design/skills.md +++ b/design/skills.md @@ -68,10 +68,9 @@ continuation, so neither the client actor nor a cooperative thread is held. The bounded and happens on registration and on load only. `FuzzFrontmatter` parses arbitrary documents with both schemas. -Comparison is JSON equality: numbers by value (`1` equals `1.0`), key order ignored, and a -`data:` URL string equal to the `Value.data` it decodes to. Entries decode their frontmatter -with strings as written (`Value.Preserved`), and handler results now become `Value`s the same -way, so a server sends the frontmatter it parsed byte for byte. +Comparison is JSON equality: numbers by value (`1` equals `1.0`), key order ignored, and +strings as strings. `Value` keeps every string as written, `data:` URLs included, so a server +sends the frontmatter it parsed byte for byte. ### Wire types (`Base/SkillTypes.swift`) diff --git a/design/stateless.md b/design/stateless.md index 6cc1415e..2e13cc3a 100644 --- a/design/stateless.md +++ b/design/stateless.md @@ -57,12 +57,13 @@ Client side (`Client.discoverOrInitialize`): `initialize` when `data.supported` is empty or lists a handshake revision. `.stateless(v)` throws the error. 4. With `.automatic`, any other JSON-RPC error from the server, an HTTP 400/404/405 refusal - without a JSON-RPC error for the request (`HTTPClientTransport.isSessionlessRefusal`), or no + without a JSON-RPC error for the request (`HTTPStatusError.isSessionlessRefusal`), or no answer within `Configuration.discoveryTimeout`: fall back to `initialize`. The client tells transport errors from the server's answer by wrapping send failures (`SendFailure`); other transport errors propagate. 5. `adopt` records capabilities, version, `serverInfo` (from `_meta`, `nil` when absent) and - instructions, and calls `HTTPClientTransport.useStatelessProtocol(_:)`; `connect(transport:)` + instructions, and calls the transport's `didNegotiate(protocolVersion:)`, which makes + `HTTPClientTransport` drop its session and GET stream; `connect(transport:)` returns that state as a `Client.ConnectionInfo`. On a stateless connection `ping()` sends `server/discover`, `setLoggingLevel(_:)` changes the @@ -139,7 +140,7 @@ Responses: Why rewrite ids: without sessions, two clients may send the same id at the same time. The `Server` keys pending tasks and cancellation by id, so the transport makes them unique. The -`HandlerContext.id` is therefore the internal id, and `HTTPContextProviding` is keyed by it. +`HandlerContext.id` is therefore the internal id, and `httpRequest(for:)` is keyed by it. ### Result annotation diff --git a/design/subscriptions.md b/design/subscriptions.md index f8253455..da9779a7 100644 --- a/design/subscriptions.md +++ b/design/subscriptions.md @@ -117,7 +117,8 @@ await subscription.cancel() - Notifications on the stream go to the handlers registered with `onNotification`, like any other notification. - `Subscription.cancel()` calls `Client.cancelRequest(id)`. On a stateless HTTP connection that - aborts the POST (`HTTPClientTransport.cancelRequest`) and sends no `notifications/cancelled`. + aborts the POST (`Transport.abandonRequest(_:)`, which returns `true` there) and sends no + `notifications/cancelled`. On other transports it sends `notifications/cancelled`. - `Subscription.finished()` waits for the request: it returns on a graceful end and throws on failure or cancellation. @@ -166,7 +167,7 @@ nothing on handshake connections. |---|---|---| | `subscribeToResource(uri:)` | `resources/subscribe` | adds the URI to the background stream; returns after an acknowledgement that names it; no-op if already served; -32600 if the URI is not honored | | `unsubscribeFromResource(uri:)` | `resources/unsubscribe` | replaces the stream with one without the URI; no-op if not subscribed | -| `subscribedResourceURIs` | empty | subscribed URIs the open stream serves | +| `subscribedResourceURIs` | URIs whose `resources/subscribe` succeeded and were not unsubscribed on this connection | subscribed URIs the open stream serves | `disconnect()` cancels the background stream and fails waiting subscribe calls before closing the transport, and again afterwards for a call made while it was closing. After `disconnect()`, diff --git a/design/threat_model.md b/design/threat_model.md index 8de7834e..50321f9f 100644 --- a/design/threat_model.md +++ b/design/threat_model.md @@ -14,8 +14,8 @@ vulnerabilities as described in [SECURITY.md](../SECURITY.md). | stdio, in-memory, `NetworkTransport` | none: the peer owns the connection | | Even so, one message is bounded: stdio and `NetworkTransport` end the receive stream once a message -passes 16 MiB, or a larger `BufferConfiguration.maxReceiveBufferSize`, plus at most one read (unless -`NetworkTransport` uses `BufferConfiguration.unlimited`), so a peer whose line never ends cannot grow +passes 16 MiB (on `NetworkTransport`, its `maximumMessageLength`), plus at most one read (unless +`NetworkTransport` has `maximumMessageLength: Int.max`), so a peer whose line never ends cannot grow memory without bound. Complete messages are still queued for the reader without a limit. The SDK assumes that the host's HTTP framework terminates TLS, and that a server's adapter @@ -35,7 +35,9 @@ and side channels other than the `requestState` principal tag (compared in const ## Server side -**Request validation.** `StandardValidationPipeline` runs on every HTTP request before decoding. +**Request validation.** The transport's validators run on every HTTP request before decoding. +A request whose session is created, or dropped by a refused `initialize`, while its validators +suspend is validated again, and none reaches a terminated session. `OriginValidator.localhost()`, the default, refuses a `Host` that is not a loopback host (421) and an `Origin` that is not a loopback origin (403): the defense against DNS rebinding and cross-origin POSTs. A deployed server replaces it with its own hosts and origins. `AcceptHeaderValidator`, `ContentTypeValidator` and `ProtocolVersionValidator` reject what @@ -99,20 +101,45 @@ Other requests have no default timeout; cancel the awaiting task. See [auth.md](auth.md). In short: - The MCP endpoint, discovery URLs and authorization server endpoints must be HTTPS or loopback - HTTP. URLs a server names are refused when their host is a private, link-local or reserved IP - literal, in any spelling (`isPrivateIPHost` parses with `inet_pton`), and when their host is - loopback (`OAuthURLValidator.isLoopbackHost`) unless the server that named them is on loopback - too. URLs set in `endpointOverrides` may be on loopback. + HTTP. `HTTPClientTransport` checks the MCP endpoint itself, before it calls its authorizer, and + the final URL of each request after its `requestModifier`, so neither a custom + `HTTPClientAuthorizer` nor a modifier can send a token in the clear. URLs a server names are refused when their + host is a private, link-local or reserved IP literal, in any spelling (`isPrivateIPHost` parses + with `inet_pton`), and when their host is loopback (`OAuthURLValidator.isLoopbackHost`) unless + the server that named them is on loopback too. URLs set in `endpointOverrides` may be on + loopback. - Discovery follows redirects only to URLs that pass the same checks; token, registration and exchange requests follow none (`OAuthRedirectGuard`, on every platform). +- MCP requests follow redirects to `http` and `https` URLs only (`HTTPRedirect.refusal(of:from:)`), + never to a loopback or unspecified host (`localhost`, `*.localhost`, `127.0.0.0/8`, `0.0.0.0/8`, + `::1`, `::`, including non-canonical IPv4 spellings and IPv4-embedded IPv6 forms) from a remote + host, and never from `https` to `http` (loopback included), so a request sent over TLS and any + 307 or 308 body are not resent without it. A redirect from a loopback or unspecified host to + `http` on a host that is not a canonical loopback host (`localhost`, `127.0.0.1`, `::1`) is + refused too, so a request that stayed on this machine isn't sent off it in clear text. A request + whose endpoint is `http` on a remote host already goes out in clear text, and its redirects to + remote `http` may too. OAuth discovery and server card redirects are stricter + (`OAuthRedirectGuard`): `https`, or loopback `http` from loopback `http`, and no private + addresses. `Authorization`, `Proxy-Authorization`, `Cookie` and `Mcp-Session-Id` go to the first + request's origin only, and not after a hop through another origin; with an authorizer, a + same-origin hop's `Authorization` is the authorizer's for its URL or none, never the first + request's, nor the one a `requestModifier` or the configuration set; `DPoP` goes on no redirect; + credentials in the configuration's `httpAdditionalHeaders` are moved onto each request so the + same rule covers them (`HTTPRedirect`, `HTTPClientRedirects`, `URLSession.oauthData`, + `ServerCard.fetch`). A 401 or 403 reached without credentials fails with + `protectedResourceMismatch` and never reaches the authorizer. Redirects of MCP requests to RFC + 1918 and other private non-loopback addresses remain allowed by design so clients can talk to + MCP servers on private networks. - Authorization server metadata whose `issuer` differs from the candidate is refused. A refresh token is sent only to the server that issued it; a token whose server is unknown is not refreshed at one chosen by discovery. - PKCE with S256 and a checked `state` on the authorization code grant. - A JWT bearer assertion goes to a token endpoint the application configured. A discovered one needs `allowsDiscoveredAuthorizationServer`, and the assertion's `aud` must then name it. -- `handleChallenge` and `prepareAuthorization` run one at a time, and the authorizer's state is - behind a lock. +- Challenges and proactive renewals run one at a time, storage writes run one at a time with + compare-then-clear, and the authorizer's state is behind a `Mutex`. Tokens are kept per + resource (the RFC 8707 `resource` they were requested for), and a token is attached only to a + URL its resource covers. A challenge's description names no header value and no token. Host names are not resolved, so a name that resolves to an internal address is not caught. diff --git a/docs/client.md b/docs/client.md index ddf6cf12..791be9b4 100644 --- a/docs/client.md +++ b/docs/client.md @@ -147,7 +147,7 @@ let http = HTTPClientTransport(endpoint: URL(string: "http://localhost:8080/mcp" ### Strict mode -With `strict: true`, `listTools`, `callTool`, `listPrompts`, `getPrompt`, `listResources`, `listResourceTemplates`, `readResource`, `subscribeToResource`, `unsubscribeFromResource` (2025-11-25 only), `setLoggingLevel` and both `complete` methods check `serverCapabilities` first. When the capability is missing they throw `MCPError.methodNotFound` without sending anything; before `connect` the detail is "Server capabilities not initialized". The default configuration sends the request and lets the server answer. +With `strict: true`, `listTools`, `callTool`, `listPrompts`, `getPrompt`, `listResources`, `listResourceTemplates`, `readResource`, `subscribeToResource`, `unsubscribeFromResource` (2025-11-25 only), `setLoggingLevel` and both `complete` methods check `serverCapabilities` first. They throw `MCPError.methodNotFound` without sending anything when the capability is missing, and for resource subscriptions when `resources.subscribe` isn't `true`; before `connect` the detail is "Server capabilities not initialized". The default configuration sends the request and lets the server answer. ```swift let client = Client( @@ -240,14 +240,14 @@ if let structured = result.structuredContent { } ``` -A string in `structuredContent`, in another `Value` field of a result, or in the `data` of an `MCPError` from the server, that is a whole `data:` URL arrives as `.data(mimeType:_:)`. The rules are the same as for [tool arguments](server.md#calling-tools). Read it with `dataValue`. When you encode the `Value` again, as above, it becomes a base64 `data:` URL: `data:,hi` becomes `data:text/plain;base64,aGk=`. +Strings in `structuredContent`, in other `Value` fields of a result and in the `data` of an `MCPError` from the server arrive as sent, `data:` URLs included. Parse a `data:` URL with `DataURL(_:)`; the rules are in [tool arguments](server.md#calling-tools). ### Header parameters At 2026-07-28 over Streamable HTTP, a tool can ask for some arguments to be mirrored into HTTP headers (SEP-2243), so that gateways can route without parsing the body. The input schema marks the argument with `"x-mcp-header": ""`. The client handles this itself: - On every `tools/list` result at 2026-07-28, it records the annotated arguments of each tool. A first page (no cursor) replaces what earlier listings recorded; `connect` and `disconnect` clear them. -- On `tools/call` through `HTTPClientTransport`, or a custom transport that implements `send(_:additionalHeaders:)`, it sends `Mcp-Param-` for each annotated argument that is present and not null. Strings are sent as-is, booleans as `true`/`false`, integers in decimal. A value that is empty, is not printable ASCII, has a leading or trailing space, or looks like an encoded value is sent as `=?base64??=`. +- On `tools/call` through `HTTPClientTransport`, or a custom transport that sends `options.headers` of `send(_:options:)`, it sends `Mcp-Param-` for each annotated argument that is present and not null. Strings are sent as-is, booleans as `true`/`false`, integers in decimal. A value that is empty, is not printable ASCII, has a leading or trailing space, or looks like an encoded value is sent as `=?base64??=`. - It drops a tool with an invalid annotation from the `tools/list` result and logs a warning. An annotation is invalid when its value is empty or not a string, is not an HTTP token, or repeats another name of the tool case-insensitively, when the property type is not `string`, `integer` or `boolean`, or when the tool has more than 64 annotations or nests `properties` more than 32 deep. The warning names the property path, not the annotation. `Tool.headerParameters()` returns the parsed annotations: @@ -364,7 +364,7 @@ for message in prompt.messages { } ``` -Resources: `listResources(cursor:)`, `listResourceTemplates(cursor:)` and `readResource(uri:)`. A `Resource.Content` holds `text` or a Base64 `blob`. +Resources: `listResources(cursor:)`, `listResourceTemplates(cursor:)` and `readResource(uri:)`. A `Resource.Content` holds a `body`: `.text(String)` or `.blob(Data)`, decoded from base64. An item with neither `text` nor `blob`, with both, or with a `blob` that is not base64 fails the read with `ResponseDecodingError`; whitespace and missing `=` padding in base64 are accepted, as in image and audio `data`. ```swift let resources = try await client.listResources().resources @@ -373,9 +373,10 @@ print(resources.map(\.uri), templates.map(\.uriTemplate)) let contents = try await client.readResource(uri: "file:///notes.txt").contents for content in contents { - if let text = content.text { + switch content.body { + case .text(let text): print("\(content.uri): \(text)") - } else if let blob = content.blob, let data = Data(base64Encoded: blob) { + case .blob(let data): print("\(content.uri): \(data.count) bytes") } } @@ -887,16 +888,16 @@ await client.onNotification(ResourceUpdatedNotification.self) { message in } // resources/subscribe at 2025-11-25; a listen stream per URI at 2026-07-28. try await client.subscribeToResource(uri: "file:///notes.txt") -let subscribed = await client.subscribedResourceURIs // 2026-07-28 streams only +let subscribed = await client.subscribedResourceURIs // ["file:///notes.txt"] // ... try await client.unsubscribeFromResource(uri: "file:///notes.txt") ``` | | 2025-11-25 | 2026-07-28 | |---|---|---| -| `subscribeToResource(uri:)` | Sends `resources/subscribe` | Adds the URI to the background listen stream and waits for the acknowledgement of a stream that names it; does nothing if the URI is already subscribed | -| `unsubscribeFromResource(uri:)` | Sends `resources/unsubscribe` | Replaces the stream with one without the URI; updates may arrive until the replacement is acknowledged; does nothing if the URI is not subscribed | -| `subscribedResourceURIs` | Always empty | The subscribed URIs the open stream serves | +| `subscribeToResource(uri:)` | Sends `resources/subscribe` on every call, also for a subscribed URI | Adds the URI to the background listen stream and waits for the acknowledgement of a stream that names it; does nothing if the URI is already subscribed | +| `unsubscribeFromResource(uri:)` | Sends `resources/unsubscribe` on every call, also for a URI that is not subscribed | Replaces the stream with one without the URI; updates may arrive until the replacement is acknowledged; does nothing if the URI is not subscribed | +| `subscribedResourceURIs` | The URIs whose `resources/subscribe` succeeded and that were not unsubscribed; a failed `resources/unsubscribe` keeps its URI | The subscribed URIs the open stream serves | At 2026-07-28, `subscribeToResource` throws `invalidRequest("The server does not send updates for ")` when the server's acknowledgement omits the URI, and the error that kept the stream from opening otherwise. When the server ends the stream, `subscribedResourceURIs` is empty until the client reopens it after the backoff delay; subscribing again reopens it at once. When the stream fails, the subscriptions are kept and the client reopens the stream for them; only a `subscribeToResource` call still waiting for its acknowledgement fails when that reopening fails. Cancelling the task that waits in `subscribeToResource` ends the call with `CancellationError` and drops the URI again when that call added it. After `disconnect()`, `subscribeToResource` throws. @@ -974,28 +975,27 @@ let content = try await client.callTool( ## Batching -`withBatch(body:)` sends several requests as one JSON-RPC array. `Batch.addRequest(_:)` returns a `Task` for each result; the batch is sent when the closure returns. +`withBatch(isolation:body:)` sends several requests as one JSON-RPC array and returns the value of its closure. `Batch.addRequest(_:)` returns a `Task` for each result; the batch is sent when the closure returns. The closure runs on the caller's actor, so it can also assign to local variables. Await the tasks after `withBatch` returns: nothing is sent while the closure runs. ```swift -// withBatch's closure is @Sendable, so collect the tasks in an actor. -let collected = TaskCollector() -try await client.withBatch { batch in +let tasks = try await client.withBatch { batch in + var tasks: [Task] = [] for word in ["one", "two", "three"] { - let task = try await batch.addRequest( - CallTool.request(.init(name: "echo", arguments: ["text": .string(word)]))) - await collected.append(task) + tasks.append(try await batch.addRequest( + CallTool.request(.init(name: "echo", arguments: ["text": .string(word)])))) } + return tasks } // The batch is sent when the closure returns; await each result. var results: [CallTool.Result] = [] -for task in await collected.tasks { +for task in tasks { results.append(try await task.value) } ``` -JSON-RPC batching was removed from the specification in 2025-06-18. Use it only with peers that accept batches; an SDK server does. Each request gets what `send(_:)` adds: the 2026-07-28 `_meta` envelope, the header parameters and the multi round-trip loop. On a stateless connection the requests are sent one by one, because each 2026-07-28 request carries its own HTTP headers. A request cancelled with `cancelRequest(_:reason:)` before the batch is sent is left out. When the closure throws, the requests it added fail with the same error and nothing is sent. +JSON-RPC batching is part of MCP 2025-03-26 only; 2025-06-18 removed it. Use it only with peers that accept batches: an SDK `Server` on a stream transport (stdio, network, in-memory) does, but the SDK's HTTP server transports answer a JSON array with HTTP 400. Each request gets what `send(_:)` adds: the 2026-07-28 `_meta` envelope, the header parameters and the multi round-trip loop. On a stateless connection the requests are sent one by one, because each 2026-07-28 request carries its own HTTP headers. A request cancelled with `cancelRequest(_:reason:)` before the batch is sent is left out. When the closure throws, the requests it added fail with the same error and nothing is sent. -`withBatch` throws `internalError("Client connection not initialized")` when not connected. An empty batch sends nothing. +`withBatch` throws `internalError("Client connection not initialized")` when not connected. An empty batch sends nothing. A `Batch` is valid only while the closure runs: `addRequest(_:)` throws `internalError` after `withBatch` returns. ## Capabilities and extensions diff --git a/docs/migration.md b/docs/migration.md index 17f8844e..3fe70cb3 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -22,22 +22,34 @@ each change that breaks source code. | -32042 error decoding | If the data cannot be represented entirely by `urlElicitationRequired`, decodes as `serverError` and keeps `data` | Match `errorCode == .urlElicitationRequired` to handle both cases | | `HTTPResponse` | `.data` and `.error` have new associated values | Update patterns | | `Client.Capabilities.experimental` | `[String: String]?` became `[String: Value]?` | Pass `Value`s | -| `OAuthAuthorizationError` | A struct with a `code`, not an enum; eight new codes | Read details from properties instead of binding associated values | +| `OAuthAuthorizationError` | A struct with a `code`, not an enum; twelve new codes; `tokenRequestFailed(statusCode:oauthError:)` takes `Int?`; URLs in descriptions are redacted | Read details from properties instead of binding associated values | | `GrantType`, `TokenEndpointAuthentication`, `PrivateKeyJWTSigningAlgorithm` | Structs, not enums; new grant type `.jwtBearer` | Add a `default` to `switch` statements; write `.ES256` instead of `init(rawValue:)` | | `BearerTokenValidationResult`, `Elicitation.Mode`, `ToolChoice.Mode` | Structs, not enums; `Mode(rawValue:)` is not optional | Add a `default` to `switch` statements; drop the optional binding | | Roots, sampling and logging | Deprecated by the specification (SEP-2577): the entry points are `@available(*, deprecated)`, and a notice is logged once when the peer declares them | Nothing now; plan the migration in [rough_edges.md](rough_edges.md#deprecated-by-the-specification) | | `includeContext` | `.thisServer` and `.allServers` are deprecated (SEP-2596) | Omit `includeContext`, or use `.none` | | `ToolChoice(mode:)` | Takes a `Mode`; the initializer with an optional mode is deprecated | Pass a mode. `.init(mode: .none)` is now the `none` mode, not `nil` (`auto`) | | Content blocks, `InputRequest`, `InputResponse`, `CreateElicitation.Parameters` | New case `.unknown` for kinds from a later revision | Add it, or a `default`, to `switch` statements | -| `HTTPClientAuthorizer` | `authorizationHeader(for:)` became `authorizationHeaders(for:method:)`; new requirement `handleChallenge(statusCode:headers:endpoint:operationKey:sentAuthorization:session:)`, returning `HTTPChallengeResult`, with a default that calls the Bool method | Update custom authorizers | +| `HTTPClientAuthorizer` | Not class-bound (`Sendable`); `authorizationHeaders(for:method:) async throws` replaces `authorizationHeader(for:)`; `prepare(for:session:)` replaces `prepareAuthorization(for:session:)` and its thrown errors fail the request; `handleChallenge(_:session:)` takes `HTTPAuthorizationChallenge` and returns `HTTPChallengeResult`; `didReceiveResponse(headers:for:)` is `async`; `validateEndpointSecurity(for:)` is removed from `HTTPClientAuthorizer` and `OAuthAuthorizer` | Update custom authorizers; rename `prepareAuthorization(for:session:)` to `prepare(for:session:)` (it still compiles without being called) and remove `validateEndpointSecurity(for:)` | +| `OAuthTokenStorage` | Replaces `TokenStorage` and `InMemoryTokenStorage` (`InMemoryOAuthTokenStorage`); not class-bound; resource-keyed `async throws` `load(for:)`, `save(_:for:)`, `clear(for:)` | Update custom token stores; set `endpointOverrides.resource` for persistence across launches | +| `HTTPClientTransport` `requestModifier` | `(URLRequest) -> URLRequest` became `@Sendable (inout URLRequest) async throws -> Void` | Mutate the request in place and drop `return` | | `Client` convenience methods | Return the result type, not a tuple; `startToolCall` replaces the `RequestContext` overload of `callTool`; `initialize()` is removed | Read the result's properties | | Peer result decoding | An undecodable result, including a server-to-client or task result, throws `ResponseDecodingError` with the expected type, raw result and decoding error. It is separate from `MCPError` | Catch this error to inspect a malformed result; use a `Method` with `Result == Value` for raw access | | `Client.connect(transport:)` | Returns `Client.ConnectionInfo`, whose `serverInfo` is optional | Unwrap `serverInfo` | | `Version.latest` | Renamed `Version.latestHandshake`; the old name is deprecated | Rename | -| `Tool.Content` | `annotations` and `_meta` default to `nil`; the deprecated short forms are removed | Use `.text(text:)`, `.image(data:mimeType:)`, `.audio(data:mimeType:)` | +| `Tool.Content`, `Prompt.Message.Content`, `Sampling` content blocks | `image` and `audio` take unlabeled `Data` instead of base64 `String`; `Tool.Content` `annotations` and `_meta` default to `nil` and the deprecated 0.12 short forms are removed; deprecated `data: String` construction shims remain | Pass `Data` with `.image(_:mimeType:)` / `.audio(_:mimeType:)`; update `case .image(let d, ...)` patterns to expect `Data` | +| `Resource.Content` | `body: Resource.Content.Body` (`.text(String)` or `.blob(Data)`) replaces stored `text` and `blob`; deprecated `text` and `blob` accessors remain; items with both or neither fail decoding | Switch on `body` instead of reading `text` and `blob` | | `HTTPClientTransport` errors | HTTP statuses and OAuth failures are `transportError` with `HTTPStatusError` or `OAuthAuthorizationError`, not `internalError` with a message | Match the typed errors | +| `Transport` protocol | `logger` is `nonisolated`; `send(_:options:)` with `TransportSendOptions` replaces `send(_:)`; `receive()` is `async`; `HTTPContextProviding` removed (`httpRequestContext(for:)` → `httpRequest(for:)`); `HTTPClientTransport.updateNegotiatedProtocolVersion(_:)` → `didNegotiate(protocolVersion:)` | Update custom transports; wrap transports with `TransportWrapper` | +| HTTP request validation | `HTTPRequestValidationPipeline` and `validationPipeline:` removed; `validate` methods and `TokenValidator` are `async` | Pass `validators:` (defaulting to `defaultValidators`) and mark custom validators `async` | +| `NetworkTransport` | `HeartbeatConfiguration`, `BufferConfiguration`, and old 5-arg `init` removed; reconnection off by default; heartbeats no longer sent | Use `init(connection:maximumMessageLength:connectionTimeout:reconnection:logger:)`; opt in to reconnection if needed | +| `MCPError.isResourceTemporarilyUnavailable(_:)` | Removed; transports handle `EAGAIN` internally | Remove calls | +| `Server.waitUntilCompleted()` | Now `async throws`; `Server.start` throws on overlapping starts or a `stop()` while connecting | Add `try` and handle or propagate transport and start errors | +| `Client.withBatch` and `Client.Batch` | `withBatch(body:)` becomes generic `@discardableResult withBatch(isolation:body:)`; `Client.Batch` is a `Sendable` struct whose `addRequest(_:)` throws after return | Trailing-closure calls compile unchanged; drop `nonisolated(unsafe)` workarounds and avoid escaping `Batch` | +| `Server.cancelRequest(_:reason:)` | Deprecated; `requestSampling`, `requestElicitation`, and `listRoots` withdraw on task cancellation | Cancel the task awaiting the server-to-client request instead | +| Resource subscriptions | Strict `Client` requires `resources.subscribe: true` (`false` throws -32601); `subscribedResourceURIs` lists handshake subscriptions; public `init(uri:)` on subscribe/unsubscribe `Parameters` | Declare `resources: .init(subscribe: true)` for strict clients | +| `Icon.Theme`, `Response` decoding, `TaskSnapshot` | Unknown icon `theme` strings decode as `nil`; `Response` decoding reports the failing coding path; `TaskSnapshot` equality ignores wire generation | Treat `Icon.theme == nil` as usable with any theme (unknown themes are omitted on re-encode) | | `Server.start(transport:)` | Keeps handlers registered before it; answers `logging/setLevel` and filters `log` when the server declares `logging` | Remove workarounds | -| `OAuthWWWAuthenticateParsing` | New requirement `parseChallenge(scheme:from:)`, with a default | Nothing | +| `OAuthScopeSelecting`, `OAuthWWWAuthenticateParsing` | Both refine `Sendable`; `OAuthWWWAuthenticateParsing` adds `parseChallenge(scheme:from:)` with a default | Conform custom implementations to `Sendable` | | `Server` | Serves 2026-07-28 requests by default | Nothing, or opt out | | `Client` | Connects at 2026-07-28 by default, with a fallback to `initialize` | Nothing, or opt out | | `Version.supported` | Lists 2026-07-28 | Read `Version.handshake` for the `initialize` revisions | @@ -49,12 +61,15 @@ each change that breaks source code. | Sampling with tools | The client refuses tools without `sampling.tools`, and tool messages that break the rules, with -32602; `requestSampling` refuses them before it sends | Declare `sampling.tools` when the sampling handler takes tools | | `.none(clientID:)` | A plain client ID is pre-registered: no dynamic registration | Pass `""` to register | | OAuth loopback URLs | A URL a server names may be on a loopback host only when that server is; otherwise `privateIPAddressBlocked`, also from `OAuthTokenExchange.tokenEndpoint(issuer:)` | Set `endpointOverrides` for a local authorization server used with a remote MCP endpoint | +| OAuth canonical resource URI | Normalized per RFC 3986 §6 (lowercase scheme/host, dot segments collapsed, trailing slash stripped, hostless URLs rejected), including `endpointOverrides.resource` | Pass a custom `OAuthMetadataDiscovering` wrapper if your server requires a trailing slash | +| HTTP redirects | `Authorization`, `Proxy-Authorization`, `Cookie`, and `Mcp-Session-Id` stay same-origin (also separated from `httpAdditionalHeaders`); non-HTTP(S), `https`→`http`, and remote↔loopback/unspecified hops are refused; credential-less `401`/`403` fails with `protectedResourceMismatch` | Configure the final origin as `endpoint`, or handle `protectedResourceMismatch` | | `StatelessHTTPServerTransport` with an `initializeHook` | Handshake requests other than `initialize` are refused with -32600 unless a `statelessRequestHook` is set | Set a `statelessRequestHook` | | Terminated stateful HTTP session | After a session ends and validation passes, requests without a session ID receive 400 instead of 404; requests with any session ID receive 404 | Route a new sessionless `initialize` to a new transport and `Server` | -| `data:` URL strings | Arrive as sent instead of rewritten as base64 `data:` URLs; prose such as `data: 3 rows, 2 columns` is no longer a `data:` URL | Nothing | +| `Value.data` and `data:` URLs | `Value.data` is removed (all JSON strings decode as `.string`); `DataURL` replaces the `Data` data-URL helpers (deprecated shims remain for `Value.dataValue`, `Data.isDataURL(string:)`, `Data.parseDataURL(_:)`, `Data.dataURLEncoded(mimeType:)`) | Remove `case .data` branches and parse strings explicitly with `DataURL(_:)` | | HTTP transports | New error bodies, status codes and streaming | See below | | `HTTPClientTransport` | Default per-host connection limit 64; POST streams resume per stream; SSE on Linux | Raise `httpMaximumConnectionsPerHost` in custom configurations | -| `StdioTransport`, `NetworkTransport` | A received message longer than 16 MiB ends the receive stream with `internalError` | Make sure the peer sends no message longer than 16 MiB; `StdioTransport` has no setting that raises the limit. For `NetworkTransport`, raise `maxReceiveBufferSize` or use `BufferConfiguration.unlimited` | +| `StdioTransport`, `NetworkTransport` | A received message longer than 16 MiB ends the receive stream with `internalError`; stdio read errors finish with `transportError` | Make sure the peer sends no message longer than 16 MiB; `StdioTransport` has no setting that raises the limit. For `NetworkTransport`, pass `maximumMessageLength:` (`Int.max` for no limit) | +| Exact code-point matching | `ID`, `ProgressToken`, task IDs/owners, method names, SEP-2243 headers/keys, subscription URIs, and `RequestState` audiences compare by exact Unicode scalars | Send matching Unicode scalar spellings (canonically equivalent forms no longer match) | | Package | Requires Swift 6.1 tools; depends on swift-crypto and Yams, no longer on eventsource; swift-docc-plugin `from: "1.4.0"` instead of its `main` branch | Use Xcode 16.3 or later; resolve packages again | | Platforms | Minimums raised to macOS 15, Mac Catalyst 18, iOS 18, tvOS 18, watchOS 11, visionOS 2 | Raise your deployment targets, or stay on 0.12 to keep older ones | @@ -251,11 +266,18 @@ func describeAuthorizationError(_ error: any Error) -> String { } ``` -Eight codes are new: `authorizationResponseIssuerMismatch`, +Twelve codes are new: `authorizationResponseIssuerMismatch`, `authorizationResponseMissingIssuer`, `assertionProviderMissing`, `issuedTokenTypeMismatch`, `authorizationServerNotConfigured`, -`assertionAudienceMismatch`, `dpopRequired` and `dpopAlgorithmUnsupported`. -More can appear in a minor release, so a `switch` needs a `default`. See +`assertionAudienceMismatch`, `dpopRequired`, `dpopAlgorithmUnsupported`, +`authorizationEndpointMissing`, `authorizationEndpointInvalid`, +`registrationRequestFailed`, and `registrationResponseInvalid`. +`tokenRequestFailed(statusCode:oauthError:)` (like +`registrationRequestFailed(statusCode:oauthError:)`) now takes +`statusCode: Int?` (`nil` when the response is not an HTTP response). Error +descriptions and messages redact URL user information, queries, and fragments +(including redirect URI mismatches and challenge endpoints). More codes can +appear in a minor release, so a `switch` needs a `default`. See [Authorization](#authorization). ### Open structs @@ -375,24 +397,85 @@ func describeServer(_ client: Client, transport: any Transport) async throws -> which every request carries in `_meta`, instead of changing `configuration.logLevel`. -### `Tool.Content` +### `Tool.Content`, `Prompt.Message.Content` and `Sampling` content blocks -The `text`, `image` and `audio` cases have default values for `annotations` -and `_meta`, so `.text(text: "Hello")` is the case itself. The deprecated -helpers that took `metadata:` or unlabeled values (`.text(_:)`, -`.text(text:metadata:)`, `.image(_:_:metadata:)`, +The `Tool.Content` `text`, `image` and `audio` cases have default values for +`annotations` and `_meta`, so `.text(text: "Hello")` is the case itself. The +deprecated 0.12 helpers that took `metadata:` or unlabeled values +(`.text(_:)`, `.text(text:metadata:)`, `.image(_:_:metadata:)`, `.image(data:mimeType:metadata:)`, `.audio(_:_:metadata:)`, `.audio(data:mimeType:metadata:)`) are removed: write `.text(text: "Hello")`, and `_meta:` where you passed `metadata:`. +The `image` and `audio` cases of `Tool.Content`, `Prompt.Message.Content`, +`Sampling.Message.Content.ContentBlock` and +`Sampling.ToolResultContent.ContentBlock`, along with the convenience +factories `Sampling.Message.Content.image(_:mimeType:)` and +`.audio(_:mimeType:)`, now take unlabeled `Data` instead of a base64-encoded +`String` (`data:`). Deprecated `data: String` static forwarding factories +remain for 0.12.1 construction call sites (decoding leniently and falling back +to empty `Data()` on invalid base64). + +> Warning: Positional patterns such as `case .image(let d, let mimeType, _, _)` +> or `case .image(let d, let mimeType)` still compile, but `d` now binds `Data` +> instead of a base64 `String`. Labeled patterns such as +> `case .image(data: let s, ...)` fail to compile and should be updated to bind +> `Data`. + +On the wire, `data` still encodes as standard padded base64 (RFC 4648 §4) and +decodes leniently with respect to ASCII whitespace and omitted trailing `=` +padding. Per the MCP specification, non-standard URL-safe base64 (`-`, `_`) or +invalid base64 throws `DecodingError.dataCorrupted` and fails decoding of the +containing message or result. + ```swift /// `annotations` and `_meta` default to `nil`. let greeting: [Tool.Content] = [ .text(text: "Hello"), - .image(data: "iVBORw0KGgo=", mimeType: "image/png"), + .image(Data([0x89, 0x50, 0x4E, 0x47]), mimeType: "image/png"), ] ``` +### `Resource.Content` + +`Resource.Content` replaces its stored `text: String?` and `blob: String?` +properties with `body: Resource.Content.Body` (`.text(String)` or +`.blob(Data)`), and exposes `Resource.Content(uri:mimeType:body:_meta:)` +alongside the `.text(...)` and `.binary(...)` factories. Deprecated `text` and +`blob` computed properties remain as forwarding shims (`blob` encodes +`.blob(Data)` as standard base64). + +Per the MCP specification, a resource contents item with both `text` and +`blob`, with neither, or with a `blob` that is not standard RFC 4648 §4 base64 +(including URL-safe `-` and `_`) throws `DecodingError.dataCorrupted` and +fails decoding of the containing result, including embedded resources. + +### `Value.data` and `DataURL` + +`Value.data(mimeType:_:)` is removed so `Value` represents only the JSON data +model. Every JSON string, including `data:` URLs, now decodes as +`Value.string` and arrives as sent rather than being rewritten as base64. +Parse and format `data:` URLs explicitly with the new `DataURL` type +(`Codable`, `Hashable`, `Sendable`). + +Deprecated 0.12.1 forwarding shims remain for `Value.dataValue`, +`Data.isDataURL(string:)`, `Data.parseDataURL(_:)` and +`Data.dataURLEncoded(mimeType:)`. Remove `case .data` branches from `switch` +statements over `Value`, and switch callers to `DataURL`: + +```swift +/// Reads the bytes of a `data:` URL argument, which is now a `.string`. +func imageBytes(_ arguments: [String: Value]?) -> (mimeType: String, data: Data)? { + guard let string = arguments?["image"]?.stringValue, let url = DataURL(string) else { return nil } + return (url.mimeType, url.data) +} + +/// Builds a `data:` URL from bytes. +func dataURLString(_ data: Data, mimeType: String) -> String { + DataURL(data: data, mimeType: mimeType).description +} +``` + ### HTTP client errors `HTTPClientTransport` throws `MCPError.transportError(_:)` with a typed error @@ -441,31 +524,315 @@ func describeFailure(_ error: any Error) -> String { ### `HTTPClientAuthorizer` -`authorizationHeader(for endpoint: URL) -> String?` is replaced by -`authorizationHeaders(for url: URL, method: String) throws -> [String: String]`, -so that an authorizer can sign the request (a DPoP proof covers the method and -the URL). Return `["Authorization": value]` where the old method returned -`value`, and `[:]` for `nil`. The transport now sets these headers after the -`requestModifier`, for the final URL and method; they replace an -`Authorization` header the modifier set. A thrown error fails the request with -`transportError(_:)` carrying that error. - -The transport now calls the new requirement -`handleChallenge(statusCode:headers:endpoint:operationKey:sentAuthorization:session:)` -with the `Authorization` header the challenged request carried. It returns an -`HTTPChallengeResult`: `retry`, as the Bool method returns, and -`isDPoPNonceRetry`, whether the retry only answers a DPoP `use_dpop_nonce` -challenge, which the transport allows once per request without counting it -against `maxAuthorizationAttempts`. Its default calls -`handleChallenge(statusCode:headers:endpoint:operationKey:session:)` and reads -the nonce challenge with `DefaultOAuthWWWAuthenticateParser`, so custom -authorizers compile and behave as before. An authorizer that implements it can -tell a challenge for a token another request has already replaced from one for -the current token, and decide which challenge is a nonce retry. - -`OAuthAccessToken` has a new stored property, `keyThumbprint`, with a -defaulted initializer parameter; tokens saved by the previous release decode -with `nil`. +`HTTPClientAuthorizer` is no longer class-bound (`Sendable`, not +`AnyObject`): classes, structs, and actors can conform (an actor declares +`maxAuthorizationAttempts` `nonisolated`). + +- `authorizationHeader(for endpoint: URL) -> String?` is replaced by + `authorizationHeaders(for url: URL, method: String) async throws -> [String: String]`, + so an authorizer can load tokens asynchronously and sign each request (a DPoP + proof covers the method and the URL). Return `["Authorization": value]` where + the old method returned `value`, and `[:]` for `nil`. The transport sets + these headers after `requestModifier`, for the final URL and method, and + calls the method again on every same-origin redirect; returned headers + replace any of the same name. A thrown error fails the request with + `transportError(_:)` carrying that error. +- `prepareAuthorization(for:session:)` is renamed to + `prepare(for endpoint: URL, session: URLSession) async throws`, with an empty + default implementation. **Rename it in custom authorizers**: a type that + still implements `prepareAuthorization(for:session:)` continues to compile + because of the default, but the transport will never call it. Errors thrown + by `prepare(for:session:)` now fail the request with + `MCPError.transportError(_:)` (`CancellationError` is thrown as is), where + the previous release ignored them; `OAuthAuthorizer.prepare` still ignores + failed proactive renewals itself. +- `handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) async throws -> HTTPChallengeResult` + replaces `handleChallenge(statusCode:headers:endpoint:operationKey:session:)` + and `handleChallenge(statusCode:headers:endpoint:operationKey:sentAuthorization:session:)`. + `HTTPAuthorizationChallenge` carries `statusCode`, `headers`, `endpoint`, + `operationKey`, `sentAuthorization`, and `value(forHeader:)`, and redacts + header values, `sentAuthorization`, and URL userinfo, query, and fragment in + its descriptions and mirror. `HTTPChallengeResult` provides `.retry`, + `.retryWithDPoPNonce`, and `.unhandled`; `HTTPChallengeResult.init(shouldRetry:isDPoPNonceRetry:)` + sets `isDPoPNonceRetry` to `false` when `shouldRetry` is `false`. The + transport allows one `isDPoPNonceRetry` per request without counting it + against `maxAuthorizationAttempts`. `maxAuthorizationAttempts` (on + `HTTPClientAuthorizer` and `OAuthConfiguration.RetryPolicy`) counts total + attempts for one request, including the initial attempt (`1` allows no + non-nonce retry; the default `3` allows up to `2` retries). +- `didReceiveResponse(headers:for:)` is now `async` and receives the URL that + answered, after any redirects. +- `validateEndpointSecurity(for:)` is removed from both `HTTPClientAuthorizer` + and `OAuthAuthorizer`: `HTTPClientTransport` always checks that the endpoint + (and the URL after `requestModifier`) is `https`, or `http` on a loopback + host, without a fragment, before calling the authorizer. +- `OAuthScopeSelecting` and `OAuthWWWAuthenticateParsing` now refine + `Sendable`, because `OAuthAuthorizer` calls them from several tasks at once. +- `OAuthAccessToken` has a new stored property, `keyThumbprint`, with a + defaulted initializer parameter; tokens saved by the previous release decode + with `nil`. + +### `OAuthTokenStorage` + +`TokenStorage` and `InMemoryTokenStorage` are replaced by `OAuthTokenStorage` +(not class-bound, `: Sendable`) and `InMemoryOAuthTokenStorage`. Tokens are now +keyed by canonical resource `URL` (RFC 8707 §2) so one store can serve +authorizers for multiple servers, and every method is `async throws`: storage +errors fail the request with `MCPError.transportError(_:)`. + +Before: + +```swift +final class KeychainTokenStorage: TokenStorage { + func save(_ token: OAuthAccessToken) { ... } + func load() -> OAuthAccessToken? { ... } + func clear() { ... } +} +``` + +After: + +```swift +struct KeychainTokenStorage: OAuthTokenStorage { + func save(_ token: OAuthAccessToken, for resource: URL) async throws { ... } + func load(for resource: URL) async throws -> OAuthAccessToken? { ... } + func clear(for resource: URL) async throws { ... } +} +``` + +The resource key can change once the authorizer reads the server's protected +resource metadata (for example, from `https://mcp.example.com/mcp` to +`https://mcp.example.com`). For a store that persists tokens across launches, +set `OAuthConfiguration.EndpointOverrides(resource:)` to the server's resource +so the first request after launch finds its token immediately. + +### `HTTPClientTransport` `requestModifier` + +`HTTPClientTransport.init`'s `requestModifier` changed from +`(URLRequest) -> URLRequest` to +`@Sendable (inout URLRequest) async throws -> Void` (default `{ _ in }`). It +runs after the transport's headers and before the authorizer's headers and +`Mcp-Session-Id`. An error it throws fails the request with +`MCPError.transportError(_:)`, and its time does not count against +`Client.Configuration.discoveryTimeout`. + +Before: + +```swift +let transport = HTTPClientTransport( + endpoint: endpoint, + requestModifier: { request in + var modified = request + modified.setValue("value", forHTTPHeaderField: "X-Custom") + return modified + } +) +``` + +After: + +```swift +let transport = HTTPClientTransport( + endpoint: endpoint, + requestModifier: { request in + request.setValue("value", forHTTPHeaderField: "X-Custom") + } +) +``` + +### `Transport` protocol + +`Transport` is frozen for 1.0 with `TransportSendOptions`, `TransportWrapper`, +and six defaulted protocol hooks replacing concrete transport downcasts in +`Client` and `Server`: + +- `Transport.logger` is now `nonisolated`. +- `send(_ data: Data, options: TransportSendOptions) async throws` replaces + `send(_ data: Data) async throws` as the protocol requirement. A default + extension provides `send(_ data: Data)` forwarding with empty options, so + call sites passing only `Data` still compile. +- `receive()` is now `async` (existing `await transport.receive()` calls still + compile). +- Six hooks with default implementations handle optional transport features: + `didNegotiate(protocolVersion:)`, `abandonRequest(_:)`, + `authorizationEnd(of:)`, `prepare(servingProtocolVersions:)`, + `isSessionless`, and `httpRequest(for:)`. Wrap another transport with + `TransportWrapper` to forward every hook automatically. +- `HTTPContextProviding` is removed: implement `Transport.httpRequest(for:)` + directly. `httpRequestContext(for:)` is renamed to `httpRequest(for:)` on + `StatefulHTTPServerTransport` and `StatelessHTTPServerTransport`. +- `HTTPClientTransport.updateNegotiatedProtocolVersion(_:)` is renamed to + `didNegotiate(protocolVersion:)`. + +Before: + +```swift +actor CustomTransport: Transport, HTTPContextProviding { + let logger: Logger + func send(_ data: Data) async throws { ... } + func receive() -> AsyncThrowingStream { ... } + func httpRequestContext(for id: ID) async -> HTTPRequest? { ... } +} +``` + +After: + +```swift +actor CustomTransport: Transport { + nonisolated let logger: Logger + func send(_ data: Data, options: TransportSendOptions) async throws { ... } + func receive() async -> AsyncThrowingStream { ... } + func httpRequest(for id: ID) async -> HTTPRequest? { ... } +} +``` + +### Async HTTP request validation + +`HTTPRequestValidationPipeline` is removed, and HTTP request validation is now +asynchronous so token and request validators can perform async work (such as +JWKS fetches or remote introspection) without blocking threads: + +- `StatefulHTTPServerTransport.init` and `StatelessHTTPServerTransport.init` + take `validators: [any HTTPRequestValidator] = defaultValidators` instead of + `validationPipeline:`. +- `HTTPRequestValidator.validate(_:context:)`, + `BearerTokenValidator.TokenValidator`, and + `StandardValidationPipeline.validate(_:context:)` are now `async`. +- Built-in SDK validators other than `BearerTokenValidator` (which awaits its + token validator) continue to run inline without suspending on the transport + actor; custom async validators suspend. + +Before: + +```swift +let transport = StatefulHTTPServerTransport( + validationPipeline: StandardValidationPipeline(validators: [ + OriginValidator.localhost(), + BearerTokenValidator( + resourceMetadataURL: metadataURL, + resourceIdentifier: resourceURL, + tokenValidator: { token, _, _ in .valid(BearerTokenInfo()) } + ), + ]) +) +// Or, for defaults: +let defaults = StatefulHTTPServerTransport(validationPipeline: nil) +``` + +After: + +```swift +let transport = StatefulHTTPServerTransport( + validators: [ + OriginValidator.localhost(), + BearerTokenValidator( + resourceMetadataURL: metadataURL, + resourceIdentifier: resourceURL, + tokenValidator: { token, _, _ in .valid(BearerTokenInfo()) } + ), + ] +) +// Or, for defaults (omit `validators:` or pass `StatefulHTTPServerTransport.defaultValidators`): +let defaults = StatefulHTTPServerTransport() +``` + +### `NetworkTransport` and `MCPError.isResourceTemporarilyUnavailable` + +- `NetworkTransport.HeartbeatConfiguration`, `NetworkTransport.BufferConfiguration`, + and `NetworkTransport.init(connection:logger:heartbeatConfig:reconnectionConfig:bufferConfig:)` + are removed. +- Use `NetworkTransport.init(connection:maximumMessageLength:connectionTimeout:reconnection:logger:)`: + - `maximumMessageLength` defaults to 16 MiB (`Int.max` removes the limit). + - `connectionTimeout` defaults to `.seconds(30)` (must be positive) and caps + both `connect()` and reconnections. + - `reconnection` defaults to `.disabled` (reconnection was on by default in + 0.12.1). Pass `.default` (or `NetworkTransport.ReconnectionConfiguration(...)`) + to opt back in. + - `NetworkTransport` no longer sends heartbeats (it still skips heartbeats + received from 0.12 peers). +- `MCPError.isResourceTemporarilyUnavailable(_:)` is removed: transports handle + `EAGAIN` internally, and `Client` and `Server` no longer retry `receive()` + after it. + +Before: + +```swift +let transport = NetworkTransport( + connection: connection, + heartbeatConfig: .disabled, + reconnectionConfig: .default, + bufferConfig: .unlimited +) +``` + +After: + +```swift +let transport = NetworkTransport( + connection: connection, + maximumMessageLength: .max, + connectionTimeout: .seconds(30), + reconnection: .default +) +``` + +### `Server.waitUntilCompleted()` + +`Server.waitUntilCompleted()` is now `async throws`. Every call without `try` +no longer compiles: add `try`, then handle or propagate the error. + +Before: + +```swift +try await server.start(transport: transport) +await server.waitUntilCompleted() +``` + +After: + +```swift +try await server.start(transport: transport) +try await server.waitUntilCompleted() +``` + +- It returns normally when the receive stream finishes (for example at the end + of standard input), when the stream throws `MCPError.connectionClosed` (the + peer closed the connection), or after `stop()` once the transport is + disconnected. +- It throws any other error the receive stream throws (for example + `MCPError.transportError` when a stdio read fails or a `NetworkTransport` + loses its connection), and it throws `start()`'s error when called during or + after a failed `start()`. +- As before, cancelling the calling task does not end the wait: call `stop()` + from a cancellation handler, and the wait returns once `stop()` has + disconnected the transport. +- `Server.start` throws `MCPError.internalError` if called while the server is + already starting or running (leaving the active run unaffected), or if + `stop()` is called while `connect()` is pending and `connect()` succeeds + (ending the run normally once `stop()` disconnects). + +### `Client.withBatch(isolation:body:)` and `Client.Batch` + +`Client.withBatch(body:)` took an `@escaping @Sendable` closure returning +`Void`, which prevented mutating local variables or actor state in Swift 6, and +`Client.Batch` was an `actor` that kept registering unsent requests if it +escaped `withBatch`. It is now: + +```swift +@discardableResult +public func withBatch( + isolation: isolated (any Actor)? = #isolation, + body: (Batch) async throws -> R +) async throws -> R +``` + +- Trailing-closure call sites compile unchanged, and a single-expression body + ending in `batch.addRequest(...)` needs no `_ =`. +- `body` inherits the caller's actor isolation and can return a value directly, + so `nonisolated(unsafe)` workarounds and collector actors can be removed. +- `Client.Batch` is now a `Sendable` struct instead of an `actor`. Calling + `addRequest(_:)` after `withBatch` returns now throws + `MCPError.internalError("Batch.addRequest(_:) was called after withBatch returned")`. ### Platforms @@ -507,9 +874,22 @@ these releases. `Server.Configuration` gained `protocolVersions`, `cacheHints` and `defaultCacheHint`; `Client.Configuration` gained `protocolMode`, `logLevel`, -`discoveryTimeout`, `multiRoundTrip` and `maxContextInclusion`. A missing key decodes to the default -of its initializer parameter, so JSON encoded by the previous release, -`{"strict":true}`, still decodes. +`discoveryTimeout`, `multiRoundTrip`, `tasks` and `maxContextInclusion`. A +missing key decodes to the default of its initializer parameter, so JSON +encoded by the previous release, `{"strict":true}`, still decodes. + +`Client.Configuration` and `Client.Configuration.Tasks` encode their durations +as whole-millisecond JSON keys (`discoveryTimeoutMs`, `minimumPollIntervalMs`, +`maximumPollIntervalMs`, `defaultPollIntervalMs` and `requestedTimeToLiveMs`) +instead of Swift `Duration`'s `[high, low]` attosecond representation. +`discoveryTimeoutMs: null` disables the timeout while an absent key keeps the +10-second default. Configurations saved by a prerelease under the old keys +(`discoveryTimeout`, `minimumPollInterval`, `maximumPollInterval`, +`defaultPollInterval`, `requestedTTL`) still decode. `TaskRecord` and +`CacheHint` pin their `CodingKeys`, and task RFC 3339 timestamps (`createdAt`, +`lastUpdatedAt`) clamp store dates outside +`1970-01-01T00:00:00Z...9999-12-31T23:59:59Z` (and `NaN` to the epoch) so +encoded timestamps are always valid four-digit-year dates. ### Sampling handlers see `includeContext` capped at `none` @@ -593,21 +973,16 @@ or a shorter `discoveryTimeout`. ### `data:` URL strings -The SDK no longer rewrites a `data:` URL string when it passes a message -through `Value`: the client and server message decoders, batches, -type-erased requests and responses, handler results and `_meta` accessors -keep the string as written. Error data that a server sends also keeps it, -but a decoded `MCPError` holds `.data(mimeType:_:)` in its `data`. A text -block, a URI or an icon `src` such as `data:,hi` arrives as sent; the -previous release delivered `data:text/plain;base64,aGk=`. A `Value` field the -application decodes, such as a tool argument or `structuredContent`, still -holds `.data(mimeType:_:)` for such a string, which encodes as a base64 -`data:` URL. - -A string is a `data:` URL only when its media type is empty or -`type/subtype` with RFC 2045 tokens, as RFC 2397 requires. Text such as -`data: 3 rows, 2 columns` now stays `.string`, and `Data.isDataURL(string:)` -and `Data.parseDataURL(_:)` refuse it. +Because `Value.data` is removed (see [`Value.data` and `DataURL`](#valuedata-and-dataurl)), +the SDK no longer parses or rewrites `data:` URL strings automatically anywhere +— not in messages, tool arguments, `structuredContent`, `_meta`, or +`MCPError.data`. A `data:` URL string such as `data:,hi` arrives verbatim as +`Value.string` instead of being rewritten as `data:text/plain;base64,aGk=`. + +`DataURL` (and the deprecated `Data.isDataURL(string:)` and +`Data.parseDataURL(_:)` shims) accepts a string as a `data:` URL only when its +media type is empty or `type/subtype` made of RFC 2045 tokens (RFC 2397 §3), +so prose such as `data: 3 rows, 2 columns` is rejected. ### Handlers @@ -662,11 +1037,27 @@ and `Data.parseDataURL(_:)` refuse it. - A request is registered before `send(_:)` returns. `cancelRequest(_:reason:)` right after `send` always ends the request; a request cancelled before it was sent is not sent. -- `withBatch(body:)` requests get the 2026-07-28 `_meta` envelope, header - parameters and the multi round-trip loop. On a stateless connection they - are sent one by one. When the closure throws, its requests fail. When the - connection closes or is replaced while the closure runs, the batch is not - sent and `withBatch` throws `connectionClosed`. +- `withBatch(isolation:body:)` requests get the 2026-07-28 `_meta` envelope, + header parameters and the multi round-trip loop. On a stateless connection + they are sent one by one. When the closure throws, its requests fail. When + the connection closes or is replaced while the closure runs, the batch is not + sent and `withBatch` throws `connectionClosed` (even if the closure returns + normally). +- In strict mode (`Client.Configuration.strict`), `subscribeToResource(uri:)` + (both revisions) and `unsubscribeFromResource(uri:)` (handshake revisions) + now require the server to declare `resources.subscribe: true` and throw + `MCPError.methodNotFound` (-32601) when `subscribe` is `false` or omitted. + 0.12.1 only checked that `resources.subscribe` was non-`nil`, so `false` was + accepted. +- `Client.subscribedResourceURIs` now lists active handshake subscriptions + (added when `resources/subscribe` succeeds, removed when + `resources/unsubscribe` succeeds, and cleared on disconnect or reconnect) as + well as 2026-07-28 listen-stream subscriptions. Internally subscriptions are + tracked by exact Unicode scalars so canonically equivalent spellings stay + independent; the returned `Set` merges canonically equivalent + spellings into one entry while both remain subscribed. +- `ResourceSubscribe.Parameters` and `ResourceUnsubscribe.Parameters` now have + public `init(uri:)` initializers. - `.stateless(version)` no longer retries with another version on -32022: it connects at `version` or throws. @@ -741,7 +1132,8 @@ The specification's rules for sampling with tools (SEP-1577) are checked: `StatefulHTTPServerTransport` keeps at most `eventStoreCapacity` events (default 1000) and `eventStoreByteCapacity` bytes (default 16 MiB) per session for `Last-Event-ID` replay. The previous release kept every event until the -session ended. +session ended. Emitted event counters start at `1`, so a `Last-Event-ID` with +counter `0` is rejected with HTTP 400. ### Server default handlers @@ -759,6 +1151,39 @@ session ended. kept every started `Server` alive, so a server per session leaked one per session. +### Server-to-client request cancellation + +- `Server.requestSampling`, both `requestElicitation` overloads, and + `listRoots` now withdraw the outgoing request with `notifications/cancelled` + and throw `CancellationError` when the task awaiting them is cancelled. The + withdrawal waits for an in-flight request send to finish (skipping + `notifications/cancelled` if the request send fails) and finishes sending + before the awaiting handler resumes. If the client has already answered, the + answer is returned and no `notifications/cancelled` is sent. +- Over HTTP, after the client cancels the parent request whose handler awaits + one of these methods, the parent request's stream is already closed: + `StatefulHTTPServerTransport` sends `notifications/cancelled` on the + session's standalone GET stream (or stores it for replay when no GET stream + is open), and `StatelessHTTPServerTransport` drops it cleanly. On stdio, + `InMemoryTransport`, and `NetworkTransport`, the withdrawal arrives on the + connection as usual. +- `Server.cancelRequest(_:reason:)` is deprecated; cancel the task awaiting + `requestSampling`, `requestElicitation`, or `listRoots` instead. + +### Icon themes, response errors, and task equality + +- `Icon` decodes an unrecognized `theme` string as `nil` instead of failing the + enclosing tool, resource, or prompt listing. `Icon.Theme` remains frozen in + 1.x; treat `theme == nil` as usable with any theme. Because unrecognized + themes decode as `nil`, such an icon compares equal to one with no theme and + omits `theme` if re-encoded. +- `Response.init(from:)` re-decodes a present `result` or `error` member on + failure so `DecodingError` reports the failing coding path (such as + `result.tools[0].name`) instead of a generic root `"Invalid response"` error. +- `TaskSnapshot` equality and hashing ignore its internal wire-generation + field, so a task decoded from 2025-11-25 compares equal to the same task + constructed with `init`. + ### HTTP client transport - A non-2xx response with a JSON-RPC error body for the request (same ID) is @@ -795,20 +1220,87 @@ session ended. transport to reconnect. The previous release raised an exception at the next send on Apple platforms. `disconnect()` also ends a notification's POST still waiting for its response. - -### Stdio and network transports +- `Mcp-Session-Id` on a reply to a 2026-07-28 request, or on a transport + configured for 2026-07-28, is ignored and does not open a standalone GET + stream. When a transport configured for 2026-07-28 falls back to `initialize` + against a handshake-only server, it still records `Mcp-Session-Id` from the + `initialize` reply and opens the GET stream once `didNegotiate` switches to + the handshake revision. +- Redirect handling: + - `Authorization`, `Proxy-Authorization`, `Cookie`, and `Mcp-Session-Id` are + sent only on same-origin redirects and stripped once a redirect goes to + another origin (and stay stripped on any later hop, including a chain back + to the initial origin). Credentials in + `URLSessionConfiguration.httpAdditionalHeaders` are separated by + `HTTPClientTransport.init` so they apply only to same-origin MCP requests + and never reach cross-origin redirects or the authorizer's own token, + discovery, or registration requests; `ServerCard.fetch` and OAuth + discovery/token requests apply the same separation. + - With an authorizer, each same-origin redirect calls + `authorizationHeaders(for:method:)` again for the target URL and method (so + DPoP proofs are freshly signed for the new hop and no stale `Authorization` + header is carried when the authorizer returns empty); `DPoP` headers are + stripped when not re-signed. + - Redirects to non-HTTP(S) schemes, `https` to `http` downgrades, and hops + crossing between remote and loopback or unspecified hosts (such as + `localhost`, `*.localhost`, `127.0.0.0/8`, `::1`, `0.0.0.0`, `::`, and + IPv4-mapped/translated forms) are refused. Non-loopback private network + addresses (RFC 1918) remain allowed for MCP requests. + - A `401` or `403` after a cross-origin redirect (which carried no + credentials, including chains that return to the original origin) fails + immediately with `OAuthAuthorizationError.protectedResourceMismatch` + without calling `handleChallenge(_:session:)`. + - A `404` from a redirected hop that did not carry `Mcp-Session-Id` does not + mark a live session expired (`HTTPStatusError.isSessionExpired` is `true` + only when `Mcp-Session-Id` was sent on that hop). + - On Linux, `HTTPClientTransport` follows up to 20 redirects itself, + preserving request bodies on 307 and 308 redirects and stripping + representation headers (`Content-Type`, `Content-Length`, + `Content-Encoding`, `Content-Language`, `Content-Location`) and `Host` when + 301, 302, or 303 rewrite a request to `GET`. + +### Stdio, network, and in-memory transports - A received message longer than 16 MiB, the limit of an SSE line on the HTTP client transport, ends the receive stream of `StdioTransport` and `NetworkTransport` with `internalError`. That closes the connection: a `Client` fails its pending requests with the error, and `NetworkTransport` cancels its `NWConnection`. The previous release buffered the message however - long it grew. A `NetworkTransport` whose - `BufferConfiguration.maxReceiveBufferSize` is larger than 16 MiB accepts - messages up to that size, and one with `BufferConfiguration.unlimited` keeps - no limit. `StdioTransport` has no setting that raises or removes the limit, - so a peer that sends a longer message over stdio, such as a large resource or - image as base64, ends the connection. + long it grew. On `NetworkTransport`, pass `maximumMessageLength:` to raise + the limit (`Int.max` removes it). `StdioTransport` has no setting that raises + or removes the limit, so a peer that sends a longer message over stdio, such + as a large resource or image as base64, ends the connection. +- `StdioTransport` no longer changes `O_NONBLOCK` on its descriptors and uses + dispatch-source readiness instead of polling. Read errors (such as `EIO` or + `ECONNRESET`) finish its receive stream with `MCPError.transportError` + instead of ending the stream like end of input. +- `NetworkTransport` reconnection is off by default; `connectionTimeout` + (30 seconds by default) bounds `connect()` and reconnects, and `.waiting` + states do not consume retry attempts. A graceful peer close (final content + context) finishes the stream with `MCPError.connectionClosed`, while a + non-final completed context (such as a UDP datagram or WebSocket message) + keeps the stream open. With reconnection off, a lost connection finishes the + stream with `MCPError.transportError` carrying the `NWError`; a failed send + does not trigger reconnection. +- Every SDK transport (`HTTPClientTransport`, `StdioTransport`, + `NetworkTransport`, and `InMemoryTransport`) serves a single connection: + `connect()` after `disconnect()` throws `internalError` (create a new + transport to reconnect), and sends after `disconnect()` or peer close throw + `MCPError.connectionClosed`. Disconnected `InMemoryTransport` pairs clear + their peer reference so both actors deallocate. + +### Exact code-point matching and 32-bit safety + +- JSON-RPC `ID`, `ProgressToken`, task IDs and owners, method names, SEP-2243 + `Mcp-Method`/`Mcp-Name`/`Mcp-Param-*` headers and schema argument keys, + resource subscription URIs, and `RequestState` audiences now compare by exact + Unicode scalars rather than Swift canonical `String` equivalence. Canonically + equivalent spellings (such as `"K"` vs `"\u{212A}"`, or NFC vs NFD forms) no + longer match each other, and a `tools/call` argument key that matches a + header-annotated schema property only by canonical equivalence is rejected + with -32020. +- Wire-controlled integers that exceed `Int` bounds on 32-bit platforms + saturate instead of trapping. ### Authorization @@ -843,12 +1335,12 @@ session ended. for less than the window is renewed halfway between its issue and 30 seconds before its expiry. The previous release refreshed before every request while the token was within the window, also after a failure; -- handle concurrent challenges one at a time. `InMemoryTokenStorage` is now - thread-safe; custom `TokenStorage` implementations are called from several - tasks. A challenge that waited for one that failed and left no usable - token fails with the same error instead of running the flow again (one - prompt for a cancelled authorization), and a waiting request can be - cancelled; +- handle concurrent challenges one at a time. `InMemoryOAuthTokenStorage` + (replacing `InMemoryTokenStorage`) is thread-safe and keyed per resource; + custom `OAuthTokenStorage` implementations are called from several tasks. A + challenge that waited for one that failed and left no usable token fails with + the same error instead of running the flow again (one prompt for a cancelled + authorization), and a waiting request can be cancelled; - register again on the next flow when dynamic client registration throws. The previous release did not try again until the authorizer was recreated; - treat a `.none(clientID:)` client ID that is not empty and not a URL as @@ -891,7 +1383,23 @@ session ended. swift-crypto, so they work on Linux. `pkceS256Unavailable` and `cryptographyUnavailable` are no longer thrown; - read a `DPoP` challenge (RFC 9449) for `resource_metadata`, `scope` and - `error` when the response has no `Bearer` challenge. + `error` when the response has no `Bearer` challenge; +- canonicalize resource URIs per RFC 3986 §6 (lowercase scheme and host, no + userinfo, default port, query, fragment, dot segments, or trailing slash, + uppercase percent-encoding, and rejecting hostless URLs such as `https:///`), + including `endpointOverrides.resource`. For a server where a trailing slash is + significant, pass a custom `OAuthMetadataDiscovering` wrapper around + `DefaultOAuthMetadataDiscovery` to `OAuthAuthorizer`. When discovery changes + the resource key, a token reloaded under the new key is used only if issued + by an authorization server listed in the protected resource metadata, bound + to the configured DPoP signing key (when DPoP-bound), and DPoP-bound when + the resource metadata sets `dpop_bound_access_tokens_required` (including + raising `dpopRequired` when DPoP is not configured); +- normalize DPoP nonce storage keys by origin (ASCII-lowercased `encodedHost` + with default ports `443` and `80` omitted); +- compute `private_key_jwt` `iat` and `exp` claims as `Int64` `NumericDate`s + (safe past 2038 on 32-bit platforms) and reject non-finite or out-of-range + dates and lifetimes. ### Package @@ -913,11 +1421,12 @@ released `MCP` version now resolves. These commits on `main` (`a0ae212..234e412`) are part of 1.0.0: -- `Data.parseDataURL(_:)` takes `;base64` from the header only: - `data:text/plain,hello;base64,world` is a text URL, where the previous - release returned `nil` (#309). A payload without `;base64` decodes every - percent-escaped byte, so `%FF` no longer makes it fail (#310). `Value` - decodes such strings as `.data(mimeType:_:)`. +- `DataURL` (and the deprecated `Data.parseDataURL(_:)` shim) takes `;base64` + from the header only: `data:text/plain,hello;base64,world` is a text URL, + where the previous release returned `nil` (#309). A payload without + `;base64` decodes every percent-escaped byte, so `%FF` no longer makes it + fail (#310). Because `Value.data` is removed, `Value` keeps these strings as + `.string` until parsed with `DataURL(_:)`. - `client_secret_basic` percent-encodes the client ID and secret (`application/x-www-form-urlencoded`, RFC 6749 §2.3.1) before the Base64 step; the previous release sent them verbatim, so a credential with `:`, @@ -937,35 +1446,29 @@ These commits on `main` (`a0ae212..234e412`) are part of 1.0.0: process exited. After five consecutive empty reads on a connection that is no longer ready, the receive stream finishes with `connectionClosed` and the connection is cancelled, where the receive loop - ended and `receive()` kept waiting (#283). The transport then also counts - as disconnected and stops its heartbeats, which the previous release kept - sending to the closed connection (#326). + ended and `receive()` kept waiting (#283). Heartbeats are no longer sent in + 1.0.0 (#326). - `NetworkTransport` clears the connection's state update handler on the actor's executor when a connection attempt ends. The previous release also cleared it from the state stream's termination callback, on any thread, a data race (#301). -- `NetworkTransport.connect()` retries by dialing a fresh connection to the - same endpoint instead of restarting the cancelled `NWConnection`, which the - platform does not allow, so a retry now completes. `connect()` no longer - blocks indefinitely on an unreachable peer: a `.waiting` connection counts as - a failed attempt, so the configured `maxAttempts` and backoff apply and - `connect()` throws once they are exhausted. Code that connected while offline - and relied on `NWConnection` waiting for connectivity fails instead. - `disconnect()` stops a `connect()` in progress. A second `connect()` while - one is in progress throws instead of replacing the first one's connection, - and that includes a `connect()` stopped by `disconnect()` until it has - returned, which can take the rest of its backoff. A `connect()` after that - dials a fresh connection. A retry dials `connection.endpoint`, so it is for - outbound (client) connections; a connection accepted from an `NWListener` - cannot be rebuilt this way. +- `NetworkTransport.connect()` retries (when reconnection is enabled) by + dialing a fresh connection to the same endpoint instead of restarting the + cancelled `NWConnection`, which the platform does not allow, so a retry now + completes. `connect()` no longer blocks indefinitely on an unreachable peer: + `connectionTimeout` (30 seconds by default) bounds the dial while `.waiting` + states wait without consuming retry attempts. `disconnect()` stops a + `connect()` in progress, and `connect()` after `disconnect()` throws + `internalError` (create a new transport to reconnect). A second `connect()` + while one is in progress throws instead of replacing the first one's + connection. A retry dials `connection.endpoint`, so it is for outbound + (client) connections; a connection accepted from an `NWListener` cannot be + rebuilt this way. - `StdioTransport.disconnect()` waits for the read loop and the sends in - progress, then turns `O_NONBLOCK` off again on each descriptor that was - blocking at `connect()` and still refers to the same file, and then - finishes the receive stream. The previous release left both descriptors - non-blocking, which also affects other users of the process's stdin and - stdout. A send in progress throws `transportError` (ENOTCONN) before its - next write once `disconnect()` is called, and `connect()` waits for a - `disconnect()` in progress (#297). + progress, then finishes the receive stream; in 1.0.0, `StdioTransport` never + changes `O_NONBLOCK` on its descriptors (#297). A send in progress throws + `connectionClosed` once `disconnect()` is called, and `connect()` after + `disconnect()` throws `internalError`. Three commits add API, listed in [New opt-in features](#new-opt-in-features): `Server.init` takes `description`, `websiteUrl` and `icons` (#258), @@ -1003,11 +1506,12 @@ CODEOWNERS changed (#155, #294, #306, #308, #318, #320, #331, #333). | Sealed request state | `Server.init(requestStateProtection:)`, `RequestStateProtection`, `AESGCMRequestStateCodec`, `RequestStateCodec` | [server.md](server.md#protecting-requeststate) | | Cache hints | `CacheableResult`, `ttlMs`, `cacheScope`, `CacheHint`, `Server.Configuration.cacheHints` | [server.md](server.md#cacheable-results) | | Result type | `ResultType`, `resultType` on the three input-capable results | [server.md](server.md#multi-round-trip-requests) | -| Request headers (SEP-2243) | `MCPRequestHeaders`, `Tool.headerParameters()`, `Transport.send(_:additionalHeaders:)`, with a default, and `HTTPClientTransport.send(_:additionalHeaders:)` | [protocol.md](protocol.md#request-headers-sep-2243), [custom transports](protocol.md#custom-transports) | +| Request headers (SEP-2243) | `MCPRequestHeaders`, `Tool.headerParameters()`, `TransportSendOptions.headers`, `Transport.send(_:options:)` | [protocol.md](protocol.md#request-headers-sep-2243), [custom transports](protocol.md#custom-transports) | | HTTP routing | `HTTPRequest.statelessProtocolVersion` | [protocol.md](protocol.md#routing-both-eras-on-one-endpoint) | -| Per-request transport streams | `Transport.send(_:relatedRequestID:)`, with a default | [protocol.md](protocol.md#custom-transports) | +| Per-request transport streams | `TransportSendOptions.relatedRequestID`, `Transport.send(_:options:)` | [protocol.md](protocol.md#custom-transports) | +| Wrapping transports | `TransportWrapper` | [custom transports](protocol.md#custom-transports) | +| Async HTTP validators | `StatefulHTTPServerTransport(validators:)`, `StatelessHTTPServerTransport(validators:)`, `defaultValidators` | [protocol.md](protocol.md#transports) | | Gate requests without `initialize` | `statelessRequestHook` of `Server.start(transport:initializeHook:statelessRequestHook:)`, `Server.StatelessRequestHook` | [server.md](server.md#the-initialize-hook) | -| Abort a request's POST | `HTTPClientTransport.cancelRequest(_:)` | [protocol.md](protocol.md#http-client) | | Capability extensions | `extensions` on both capability structs | [server.md](server.md#capabilities-and-extensions) | | Log level order | `LogLevel: Comparable` | [server.md](server.md#logging) | | OAuth | `OAuthConfiguration.ApplicationType`, `OAuthAuthorizationCodeFlow.ExpectedIssuer` | [protocol.md](protocol.md#authorization) | @@ -1016,4 +1520,5 @@ CODEOWNERS changed (#155, #294, #306, #308, #318, #320, #331, #333). | Replay store size | `StatefulHTTPServerTransport(eventStoreCapacity:)` | [protocol.md](protocol.md#transports) | | Server metadata | `Server.init(name:version:title:description:websiteUrl:icons:instructions:capabilities:configuration:requestStateProtection:)`: sent in the `initialize` result and, at 2026-07-28, in `_meta["io.modelcontextprotocol/serverInfo"]` of every result, with `data:` icon URLs as written | [server.md](server.md#creating-a-server) | | `Value` | `Value.numberValue` (`.int` or `.double` as `Double`); `Value.init(_:)` takes any `Encodable`, not only `Codable` | [server.md](server.md#calling-tools) | +| `data:` URLs | `DataURL` (`init(_:)`, `init(data:mimeType:)`, `Codable`) | [server.md](server.md#calling-tools) | diff --git a/docs/protocol.md b/docs/protocol.md index 270ae2cc..d531c6a8 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -217,7 +217,7 @@ A transport moves JSON-RPC messages between a client and a server. In the SDK a | `StatefulHTTPServerTransport` | server | handshake | One instance per `Mcp-Session-Id`. | | `StatelessHTTPServerTransport` | server | 2026-07-28 (and sessionless handshake use) | One instance for all requests. | | `InMemoryTransport` | both | both | Same process; tests and embedding. | -| `NetworkTransport` | both | both | Network.framework `NWConnection`; Apple platforms only. | +| `NetworkTransport` | both | both | Network.framework `NWConnection`; Apple platforms only. A peer on the local network needs Local Network access (`NSLocalNetworkUsageDescription`); on watchOS, use `HTTPClientTransport`. | The HTTP server transports do not open sockets. They take a framework-neutral `HTTPRequest` and return an `HTTPResponse`; an adapter for your HTTP framework converts between the two. [`Examples/http-server/main.swift`](../Examples/http-server/main.swift) is a complete adapter for SwiftNIO that serves both eras. @@ -230,10 +230,10 @@ A server started by its client reads requests from stdin and writes responses to ```swift let server = Server(name: "example", version: "1.0.0", capabilities: .init(tools: .init())) try await server.start(transport: StdioTransport()) -await server.waitUntilCompleted() +try await server.waitUntilCompleted() ``` -`waitUntilCompleted()` returns when the message loop ends, which happens when stdin closes. +`waitUntilCompleted()` returns when the message loop ends, which happens when stdin closes, and throws `MCPError.transportError` with the error when a read from stdin fails. The SDK has no process-launching transport. A client starts the server itself and passes the pipe file descriptors to `StdioTransport(input:output:logger:)`: @@ -253,7 +253,7 @@ let client = Client(name: "example-client", version: "1.0.0") try await client.connect(transport: transport) ``` -`send` fails with `MCPError.transportError` (ENOTCONN) before `connect()` or after `disconnect()`. `connect()` makes the descriptors non-blocking; `disconnect()` waits for the read loop and the sends in progress, then makes blocking again each descriptor that was blocking and still refers to the same file. The protocol era is independent of stdio: with `.automatic` the client sends `server/discover` over the pipe like any other request. +`send` fails with `MCPError.connectionClosed` after `disconnect()`, and with `MCPError.transportError` (ENOTCONN) before `connect()`. The transport never changes the descriptors' flags, and works with blocking and non-blocking descriptors alike. On a pipe, a socket or a terminal it waits until the descriptor is ready before each read and write; the wait blocks no thread, and an idle transport never wakes up. A regular file or a device such as `/dev/null` is read and written directly. The read or write itself runs on the transport's actor, so on a blocking descriptor that another process reads or writes too, or on a terminal that reports room for less than `PIPE_BUF` bytes, one call can block and hold up the transport until it returns. `disconnect()` ends a read or a send that is waiting, waits for the read loop and the sends in progress, and leaves the descriptors open. The end of the input finishes the receive stream normally; a read that fails, for example with `EIO`, finishes it by throwing `MCPError.transportError` with the error, and the client fails its pending requests with that error instead of `MCPError.connectionClosed`. Sends still work after either, until `disconnect()`. The protocol era is independent of stdio: with `.automatic` the client sends `server/discover` over the pipe like any other request. ### HTTP client @@ -264,9 +264,7 @@ let transport = HTTPClientTransport( endpoint: endpoint, // for example http://localhost:3000/mcp streaming: true, // open the GET stream on handshake connections requestModifier: { request in - var request = request request.setValue("example/1.0", forHTTPHeaderField: "User-Agent") - return request }) let client = Client(name: "example-client", version: "1.0.0") try await client.connect(transport: transport) @@ -277,12 +275,12 @@ What the transport sends depends on the era of each message: | | Handshake connection | 2026-07-28 connection | |---|---|---| | `MCP-Protocol-Version` | negotiated version, after `initialize` | from the message's `_meta` | -| `Mcp-Session-Id` | the ID the server returned on `initialize` | never; `useStatelessProtocol(_:)` drops it | +| `Mcp-Session-Id` | the ID the server returned on `initialize` | never; `didNegotiate(protocolVersion:)` drops it | | `Mcp-Method`, `Mcp-Name`, `Mcp-Param-*` | not sent | sent (see [request headers](#request-headers-sep-2243)) | | GET stream | opened when `streaming` is `true` | closed and never opened | | `Last-Event-ID` resumption | on the GET stream and on POST response streams | not used: a response stream that ends early fails its request | -The client switches the transport when the connection opens: `Client` calls `updateNegotiatedProtocolVersion(_:)` after `initialize` and `useStatelessProtocol(_:)` after `server/discover`. +The client switches the transport when the connection opens: `Client` calls the transport's `didNegotiate(protocolVersion:)` after `initialize` and after `server/discover`. At 2026-07-28 the transport then drops the session ID and the GET stream. On handshake connections with `streaming: true`, the transport waits up to `sseInitializationTimeout` (10 s) for a session ID, then opens the GET stream for server-initiated messages. When the stream ends it reconnects after the server's SSE `retry:` interval (3000 ms by default) and sends `Last-Event-ID` with the last event ID it saw. A 405 on GET stops the stream, and so does a 404 on a GET that carried the session ID: the stream is not reopened, and the session ID is kept. The next request carries it, receives the server's 404, drops the session and reports `isSessionExpired`. A line, or the data of one event, over 16 MiB ends the stream, and the next GET opens a fresh stream without `Last-Event-ID`, since a replay would repeat the event; that event is lost. @@ -302,7 +300,7 @@ Without a JSON-RPC error for the request, the transport throws `MCPError.transpo | 404 | To a POST that carried the session ID: `isSessionExpired` is `true` (for each such POST in flight), the session ID is dropped and the GET stream stops. To the GET stream: the stream stops, and the session ID is kept for the next request | | 405 | On the GET stream, the stream stops; a 405 to a POST does not stop it | -To add headers to every request (an API key, a user agent), pass `requestModifier`. For OAuth, pass an `authorizer` (see [Authorization](#authorization)). +To add headers to every request (an API key, a user agent), pass `requestModifier`. It changes each request in place, and it may suspend and throw: an error fails the request with `MCPError.transportError(_:)`. It runs after the transport's headers and before the authorizer's, which it can't replace. It sees the current `Mcp-Session-Id`, but the transport sets that header again after the modifier and the authorizer, since another request may have replaced or dropped the session meanwhile. Like the authorizer's, its time doesn't count against `discoveryTimeout`, so it can wait for the user, for example to unlock a Keychain item. For OAuth, pass an `authorizer` (see [Authorization](#authorization)). ### Stateful HTTP server @@ -318,7 +316,7 @@ To add headers to every request (an API key, a user agent), pass `requestModifie Requests whose `MCP-Protocol-Version` is a stateless revision get 400 with -32022 and `data.supported` set to the handshake revisions, so a client in `.automatic` mode falls back to `initialize`. -The default validation pipeline is `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .sseRequired)`, `ContentTypeValidator()`, `ProtocolVersionValidator()`, `SessionValidator()`. Pass `validationPipeline:` to replace it, for example to add authentication or allow other hosts. `sessionIDGenerator:` replaces the UUID generator; IDs must be visible ASCII (0x21-0x7E) or the transport answers 500. `retryInterval:` sets the SSE `retry:` field of the priming event; priming events are sent at 2025-03-26 through 2025-11-25. +The default validators, `StatefulHTTPServerTransport.defaultValidators`, are `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .sseRequired)`, `ContentTypeValidator()`, `ProtocolVersionValidator()`, `SessionValidator()`. Pass `validators:` to replace them, for example to add authentication or allow other hosts. The transport runs them in order, and the first that returns a response ends the request. A validator may suspend (`validate` is `async`), but the built-in ones other than `BearerTokenValidator` run without suspending, so with them each request is handled without other requests in between. While a validator suspends, the transport handles other requests: it validates a request again when its session is created, or dropped by a refused `initialize`, meanwhile, and answers a request whose session ended meanwhile as one on a terminated session. A `notifications/cancelled` whose validators finish before those of the request it cancels is ignored. `sessionIDGenerator:` replaces the UUID generator; IDs must be visible ASCII (0x21-0x7E) or the transport answers 500. `retryInterval:` sets the SSE `retry:` field of the priming event; priming events are sent at 2025-03-26 through 2025-11-25. Your HTTP layer keeps one transport and one `Server` per session and routes by `Mcp-Session-Id`. The snippet leaves out what a deployed router needs: create a session only for a POST `initialize`, cap the number of sessions, and close idle ones, as [`Examples/http-server/main.swift`](../Examples/http-server/main.swift) does: @@ -371,10 +369,11 @@ Validation errors: | Status | Cause | |---|---| | 400 | Empty or invalid JSON-RPC body; missing `Mcp-Session-Id`, including after termination; request before `initialize`; second `initialize`; unsupported `MCP-Protocol-Version` (-32022); a stateless request (-32022). | -| 404 | Unknown or expired session ID, including any ID sent after the session ended. A transport stopped before a session existed answers 400, as before `initialize`. | +| 404 | Unknown or expired session ID, including any ID sent after the session ended, and a request whose session ended while its validators ran. A transport stopped before a session existed answers 400, as before `initialize`. | | 403, 421 | `Origin` or `Host` not allowed by `OriginValidator`. | | 406 | POST `Accept` lacks `application/json` or `text/event-stream`; GET `Accept` lacks `text/event-stream`. | | 415 | `Content-Type` is not `application/json`. | +| 503 | A POST, GET or DELETE whose session was created, or dropped by a refused `initialize`, during each of three runs of its validators. | ### Stateless HTTP server @@ -389,9 +388,9 @@ Validation errors: - A POSTed `notifications/cancelled` is honored only when it carries the same `Authorization` header as exactly one request in flight with that id (compared by value: `1` and `"1"` differ). The cancelled request's HTTP response then ends without a JSON-RPC response: 202 Accepted when no reply was sent yet, or the end of its SSE stream. - An open SSE reply carries a `: keep-alive` comment every `keepAliveInterval` (15 seconds; `nil` turns it off), so that idle listen streams survive client and proxy timeouts. - At 2026-07-28 JSON-RPC errors get an HTTP status: 404 for -32601; 400 for -32600, -32602, -32020, -32021 and -32022; 200 otherwise. -- After `disconnect()` every request gets 404; a request in flight at that moment gets 503. +- After `disconnect()` every request gets 404, also one whose validators were still running; a request in flight at that moment gets 503. -The default pipeline is `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .jsonOnly)`, `ContentTypeValidator()`, `ProtocolVersionValidator()`. The transport accepts the versions in `Version.stateless + Version.handshake`; the `Server` then applies its own `protocolVersions`. +The default validators, `StatelessHTTPServerTransport.defaultValidators`, are `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .jsonOnly)`, `ContentTypeValidator()`, `ProtocolVersionValidator()`; pass `validators:` to replace them. The transport accepts the versions in `Version.stateless + Version.handshake`; the `Server` then applies its own `protocolVersions`. A 2026-07-28 request over HTTP needs these headers and `_meta` keys: @@ -471,7 +470,7 @@ At 2026-07-28 the HTTP transports mirror parts of the body in headers so that pr | `Mcp-Name` | `params.name` (`tools/call`, `prompts/get`) or `params.uri` (`resources/read`) | those methods | | `Mcp-Param-` | a `tools/call` argument whose input schema property has `"x-mcp-header": ""` | `tools/call` | -The client adds `Mcp-Method` and `Mcp-Name` in `HTTPClientTransport` when `Version.profile(for:).usesStandardHeaders` is `true`. It adds `Mcp-Param-*` from the schemas it saw in `tools/list` results, and passes them to the transport's `send(_:additionalHeaders:)` (see [custom transports](#custom-transports)); call `listTools()` before `callTool` to get them. Values that are empty, contain characters outside printable ASCII, have a leading or trailing space, or look like an encoded value are sent as `=?base64??=`. Annotated properties must be `string`, `integer` or `boolean`, reached only through `properties`, with header names made of token characters and unique without regard to case. At 2026-07-28 a tool with an invalid annotation is dropped from `tools/list` results, by the server before it sends them and by the client when it receives them, with a logged warning. +The client adds `Mcp-Method` and `Mcp-Name` in `HTTPClientTransport` when `Version.profile(for:).usesStandardHeaders` is `true`. It adds `Mcp-Param-*` from the schemas it saw in `tools/list` results, and passes them to the transport in `send(_:options:)`'s `options.headers` (see [custom transports](#custom-transports)); call `listTools()` before `callTool` to get them. Values that are empty, contain characters outside printable ASCII, have a leading or trailing space, or look like an encoded value are sent as `=?base64??=`. Annotated properties must be `string`, `integer` or `boolean`, reached only through `properties`, with header names made of token characters and unique without regard to case. At 2026-07-28 a tool with an invalid annotation is dropped from `tools/list` results, by the server before it sends them and by the client when it receives them, with a logged warning. `MCPRequestHeaders` exposes the codec for custom transports and gateways: @@ -509,34 +508,83 @@ try await client.connect(transport: clientTransport) ### Custom transports -A transport is an actor with a `logger`, `connect()`, `disconnect()`, `send(_:)` and `receive()`. Each `Data` value is one complete JSON-RPC message or batch. `receive()` returns the same stream every time; finish it when the connection ends so the client or server loop exits. +A transport is an actor with a `nonisolated` `logger`, `connect()`, `disconnect()`, `send(_:options:)` and `receive()`. Each `Data` value is one complete JSON-RPC message or batch, without framing. `Client` and `Server` rely on this contract: + +- `connect()` throws when the transport is already connected, and after `disconnect()`: a transport serves one connection. +- `disconnect()` can be called any number of times, also before `connect()`, and finishes the stream `receive()` returns. +- `send(_:options:)` throws `MCPError.connectionClosed` after `disconnect()`, and once the transport knows the peer can no longer read. +- `receive()` returns the same stream on every call. Iterate it from one task only: two concurrent iterators of an `AsyncThrowingStream` trap. The client and server iterate it themselves; a wrapper that taps it iterates the wrapped transport's stream and returns its own. +- The end of the stream, normally or with an error, means the peer sends nothing more: the client stops reading and disconnects, and the server stops reading. A transport may still send, as `StdioTransport` does after the end of its input. ```swift -/// A transport over a pair of `AsyncStream`s, for example a WebSocket bridge. +/// A transport over a message channel, for example a WebSocket bridge. The bridge +/// passes each message from the peer to `deliver(_:)`, reads `outgoing`, and calls +/// `disconnect()` when the channel closes. actor StreamTransport: Transport { nonisolated let logger = Logger(label: "example.stream-transport") private let outgoing: AsyncStream.Continuation private let incoming: AsyncThrowingStream + private let incomingContinuation: AsyncThrowingStream.Continuation + private var state = State.idle + + private enum State { case idle, connected, closed } - init(incoming: AsyncThrowingStream, outgoing: AsyncStream.Continuation) { - self.incoming = incoming + init(outgoing: AsyncStream.Continuation) { self.outgoing = outgoing + (incoming, incomingContinuation) = AsyncThrowingStream.makeStream() } - func connect() async throws {} + /// Hands a message from the peer to the client or server. + func deliver(_ data: Data) { incomingContinuation.yield(data) } - func disconnect() async { outgoing.finish() } + /// A transport serves one connection: it can't connect twice, or after `disconnect()`. + func connect() async throws { + guard state == .idle else { throw MCPError.internalError("Transport already used") } + state = .connected + } + + /// Finishes the stream `receive()` returns; calling it again does nothing more. + func disconnect() async { + state = .closed + outgoing.finish() + incomingContinuation.finish() + } /// `data` is one JSON-RPC message or batch, without a trailing newline. - func send(_ data: Data) async throws { outgoing.yield(data) } + /// `options` carry a related request ID and HTTP headers, which only HTTP + /// transports use. + func send(_ data: Data, options: TransportSendOptions) async throws { + switch state { + case .idle: throw MCPError.internalError("Transport not connected") + case .connected: outgoing.yield(data) + case .closed: throw MCPError.connectionClosed + } + } + /// Returns the same stream on every call. func receive() -> AsyncThrowingStream { incoming } } ``` -`send(_:relatedRequestID:)` has a default implementation that calls `send(_:)`. The server passes the id of the request whose handler produced a notification or a server-to-client request. Override it when your transport has a stream per request, as the HTTP server transports do. To expose HTTP details to handlers, also conform to `HTTPContextProviding` and return the `HTTPRequest` for a request id. +`send(_:options:)` gets what the transport needs besides the bytes, in `TransportSendOptions`: -`send(_:additionalHeaders:)` also has a default implementation, which ignores the headers and calls `send(_:)`. At 2026-07-28 the client passes the `Mcp-Param-*` headers of a `tools/call` to it (see [request headers](#request-headers-sep-2243)), and only when there are headers to send. A Streamable HTTP transport sends them on the request's POST, as `HTTPClientTransport` does; a transport that wraps another one forwards them. A server that serves 2026-07-28 answers a call without its headers with -32020. +- `relatedRequestID`: the server passes the id of the request whose handler produced a notification or a server-to-client request. A transport with a stream per request, as the HTTP server transports have, delivers the message on that request's stream. +- `headers`: at 2026-07-28 the client passes the `Mcp-Param-*` headers of a `tools/call` (see [request headers](#request-headers-sep-2243)). A Streamable HTTP transport sends them on the request's POST, as `HTTPClientTransport` does. A server that serves 2026-07-28 answers a call without its headers with -32020. + +A transport that is not HTTP ignores both. `send(_:)`, without options, is a convenience that calls `send(_:options:)`. + +The client and server also call hooks on every transport. Each has a default implementation that does nothing; implement the ones that apply: + +| Hook | Called by | For | +|---|---|---| +| `didNegotiate(protocolVersion:)` | client, after `initialize` and `server/discover` | the version header; dropping the session at 2026-07-28 | +| `abandonRequest(_:)` | client, when a 2026-07-28 request is cancelled or `server/discover` times out | closing the request's exchange; return `true` when that tells the server, so the client sends no `notifications/cancelled` | +| `authorizationEnd(of:)` | client, while `server/discover` waits | not counting a sign-in against `discoveryTimeout` | +| `prepare(servingProtocolVersions:)` | server, in `start(transport:)` before `connect()` | the versions -32022 lists | +| `isSessionless` | server | serving each handshake request on its own, without `initialize` | +| `httpRequest(for:)` | server, before each handler | `HandlerContext.httpContext` | + +A transport that wraps another one, to log or count messages, adopts `TransportWrapper`: it forwards every requirement and hook to `wrapped`, so the wrapped transport keeps its behavior. Implement only what the wrapper changes, with the exact signature from `Transport`: a method whose signature only nearly matches a requirement compiles and is never called. [Troubleshooting](troubleshooting.md#recording-the-messages) has an example. ### Concurrency @@ -640,7 +688,7 @@ await subscription.cancel() Most clients do not call `listen` directly: - At 2026-07-28 the client keeps one background stream for the list kinds that have a registered handler and that the server declares, and for the subscribed resources. When the filter changes, the client opens the new stream and cancels the old one after the new one is acknowledged; if the new one fails, the old one stays. Until the old stream ends, its notifications that the client still wants are delivered, so one sent during the replacement may arrive twice. A stream that ends is reopened with a backoff from 1 to 60 seconds that keeps growing while streams end within a minute, even after being acknowledged; a failed reopen keeps the subscribed resources. That includes a stream the server ends with its result, for example when it stops for a restart. -- `subscribeToResource(uri:)` adds the URI to that stream at 2026-07-28 and waits for an acknowledgement that names it; on handshake connections it sends `resources/subscribe`. `unsubscribeFromResource(uri:)` replaces the stream with one without the URI, or sends `resources/unsubscribe`. `subscribedResourceURIs` lists the URIs the open stream serves. +- `subscribeToResource(uri:)` adds the URI to that stream at 2026-07-28 and waits for an acknowledgement that names it; on handshake connections it sends `resources/subscribe`. `unsubscribeFromResource(uri:)` replaces the stream with one without the URI, or sends `resources/unsubscribe`. `subscribedResourceURIs` lists the URIs the open stream serves, or on handshake connections the URIs whose `resources/subscribe` succeeded and that were not unsubscribed. - `disconnect()` cancels the stream. ### Closing a stream @@ -677,9 +725,9 @@ let transport = HTTPClientTransport(endpoint: endpoint, authorizer: authorizer) What happens on a request: -1. Before the first request, `validateEndpointSecurity` requires the MCP endpoint to be `https`, or `http` on a loopback host. -2. Before every request, the authorizer refreshes a token that expires within `proactiveRefreshWindowSeconds` (60 s). A token issued for less than the window is refreshed halfway through the time it is sent (until 30 s before it expires), so it is not refreshed on every request. Each token is tried once; when that fails, the next 401 recovers. The transport then sets the authorizer's headers, after `requestModifier`: `Authorization: Bearer `, or for a [DPoP](#dpop) token `Authorization: DPoP ` and a proof. -3. On 401 or 403 the transport calls `handleChallenge`. The authorizer parses `WWW-Authenticate`, discovers metadata and gets a token, and the transport retries. It sends one request at most `RetryPolicy.maxAuthorizationAttempts` (3) times. A 403 with `error="insufficient_scope"` requests the union of the current and the challenged scopes, up to `maxScopeUpgradeAttempts` (2) times per resource, method and scope set. +1. Before every request, and before each GET of an SSE stream, the transport requires the MCP endpoint to be `https`, or `http` on a loopback host, and fails the request with `insecureOAuthEndpoint` otherwise; it runs this check itself, whatever the authorizer is. Then it calls the authorizer's `prepare(for:session:)`, whose error fails the request too. `OAuthAuthorizer` refreshes a token that expires within `proactiveRefreshWindowSeconds` (60 s). A token issued for less than the window is refreshed halfway through the time it is sent (until 30 s before it expires), so it is not refreshed on every request. Each token is tried once; a failed refresh is ignored, and the next 401 recovers. +2. The transport builds the request, runs `requestModifier`, checks the final URL as in step 1 (a modifier that points a request at cleartext `http` gets no token, and the request fails unsent), then sets the headers of `authorizationHeaders(for:method:)` for the final URL and method: `Authorization: Bearer `, or for a [DPoP](#dpop) token `Authorization: DPoP ` and a proof. `OAuthAuthorizer` attaches a token only to a URL its resource covers; once it has read the protected resource metadata, a URL outside the resource fails with `protectedResourceMismatch`. When neither `endpointOverrides.resource` nor the metadata names a resource, the resource is the MCP endpoint: a URL on its origin (for example one `requestModifier` gives another path) uses the endpoint's token, and a URL on another origin fails with `protectedResourceMismatch`. +3. On 401 or 403 the transport calls `handleChallenge(_:session:)` with an `HTTPAuthorizationChallenge`: the status, the response headers, the endpoint, the JSON-RPC method and the `Authorization` header the request carried. The authorizer parses `WWW-Authenticate`, discovers metadata and gets a token, and the transport retries while the `HTTPChallengeResult` says so (`.retry`, `.retryWithDPoPNonce`; `.unhandled` fails the request). It sends one request at most `RetryPolicy.maxAuthorizationAttempts` (3) times. A 403 with `error="insufficient_scope"` requests the union of the current and the challenged scopes, up to `maxScopeUpgradeAttempts` (2) times per resource, method and scope set. Discovery follows the MCP authorization spec: protected resource metadata (RFC 9728) from the challenge's `resource_metadata` or the well-known URLs, then authorization server metadata (RFC 8414, then OpenID Connect discovery). Tokens are bound to the resource with the RFC 8707 `resource` parameter. `EndpointOverrides` skips parts of discovery. @@ -731,24 +779,24 @@ How the client identifies itself, with `.none(clientID:)`: - **Dynamic client registration (RFC 7591).** Otherwise, with an empty client ID or a CIMD URL the server does not accept, when the server has a `registration_endpoint`, the authorizer registers with `client_name` (`clientName`, default `"mcp-swift-sdk"`), the redirect URI, the grant and response types, and `application_type` (SEP-837). `applicationType: nil` sends `web` for the authorization code grant with an `https` redirect URI on a non-loopback host, else `native`. The registered credentials replace `authentication` for this authorizer. A registration that fails with an error is tried again in the next flow. Without a `registration_endpoint`, an empty client ID fails with `registrationInformationRequired` before any token request, and the next flow checks the metadata again. - **Pre-registration.** Pass `.clientSecretBasic`, `.clientSecretPost` or `.privateKeyJWT`; no registration happens. -Tokens are kept in a `TokenStorage`. The default `InMemoryTokenStorage` loses them when the process exits. Implement the protocol to persist them, for example in the Keychain. Its methods may be called from several tasks at once: +Tokens are kept in an `OAuthTokenStorage`, one per protected resource: the authorizer stores each token under the canonical URI it sent as the RFC 8707 `resource` (`endpointOverrides.resource`, else the `resource` of the protected resource metadata, else the MCP endpoint), so one storage can serve authorizers for several servers. The canonical URI has a lowercase scheme and host, and no user information, default port, query, dot segments or trailing slash: `https://MCP.example.com:443/mcp/` becomes `https://mcp.example.com/mcp`. This also holds for `endpointOverrides.resource`. For a server whose trailing slash is significant, pass `OAuthAuthorizer(configuration:metadataDiscovery:)` an `OAuthMetadataDiscovering` that wraps `DefaultOAuthMetadataDiscovery` and returns its `canonicalResourceURI(from:)` with the slash; matching ignores trailing slashes, so only the `resource` sent and the storage key change. The default `InMemoryOAuthTokenStorage` loses them when the process exits. Implement the protocol to persist them, in the Keychain rather than `UserDefaults` or a file, since a token carries its refresh token. Its methods are `async throws`: an error fails the request that needed the token, and `MCPError.transportError(_:)` carries it. The authorizer calls them from several tasks at once, and writes one token at a time: ```swift -/// Keeps the access token across launches. Replace the dictionary with the Keychain. -final class PersistentTokenStorage: TokenStorage, @unchecked Sendable { - private let lock = NSLock() - private var stored: Data? +/// Keeps access tokens across launches, one per server. Replace the dictionary +/// with the Keychain, under the resource's `absoluteString`. +actor PersistentTokenStorage: OAuthTokenStorage { + private var stored: [URL: Data] = [:] - func save(_ token: OAuthAccessToken) { - lock.withLock { stored = try? JSONEncoder().encode(token) } + func save(_ token: OAuthAccessToken, for resource: URL) throws { + stored[resource] = try JSONEncoder().encode(token) } - func load() -> OAuthAccessToken? { - lock.withLock { stored.flatMap { try? JSONDecoder().decode(OAuthAccessToken.self, from: $0) } } + func load(for resource: URL) throws -> OAuthAccessToken? { + try stored[resource].map { try JSONDecoder().decode(OAuthAccessToken.self, from: $0) } } - func clear() { - lock.withLock { stored = nil } + func clear(for resource: URL) { + stored[resource] = nil } } ``` @@ -759,7 +807,9 @@ let authorizer = OAuthAuthorizer( tokenStorage: PersistentTokenStorage()) ``` -Use one `OAuthAuthorizer` per transport. Requests of a transport run concurrently: the authorizer handles one challenge or proactive refresh at a time, and a request whose 401, or 403 for the same scopes, arrives while another is handled retries with the token that one obtained, so concurrent challenges cause one refresh or sign-in. The authorizer compares a challenge with the token the challenged request carried, so a late 401 for a token another request already replaced retries with the new one instead of starting over. When the challenge being handled fails and leaves no usable token other than the one the waiting requests carried (the user cancelled the authorization, the grant was refused), the requests that waited for it fail with its error instead of each starting the flow again; a later request starts a new flow. A request cancelled while it waits stops waiting. +Until the authorizer has read the protected resource metadata, the key is the MCP endpoint (or `endpointOverrides.resource`); after it, the metadata's `resource`, for example `https://mcp.example.com` for the endpoint `https://mcp.example.com/mcp`. So after a relaunch the first request goes out without a stored token; its 401 reads the metadata and finds the token under the resource, without a new sign-in. To send the token on the first request, set `endpointOverrides.resource` to the server's resource. Finish a `save` even when the calling task is cancelled: the authorization server may have rotated the refresh token, and a token that is not saved can cost the user another sign-in. + +Use one `OAuthAuthorizer` per MCP server, and the same one for every transport to that server: two authorizers for one server don't coordinate their sign-ins, even with one storage. Requests run concurrently: the authorizer handles one challenge or proactive refresh at a time, and a request whose 401, or 403 for the same scopes, arrives while another is handled retries with the token that one obtained, so concurrent challenges cause one refresh or sign-in. The authorizer compares a challenge with the token the challenged request carried, so a late 401 for a token another request already replaced retries with the new one instead of starting over. When the challenge being handled fails and leaves no usable token other than the one the waiting requests carried (the user cancelled the authorization, the grant was refused), the requests that waited for it fail with its error instead of each starting the flow again; a later request starts a new flow. A request cancelled while it waits stops waiting. `accessTokenProvider` lets the app supply a token it got elsewhere. The SDK calls it after discovery with an `AccessTokenProviderContext` (resource, endpoints, scopes); return `nil` to run the configured grant. The provider and the `authorizationDelegate` run while the authorizer handles a challenge, and the transport's other challenges wait for them: they must not send requests through the transport they authorize. @@ -771,7 +821,7 @@ Issuer checks and authorization server changes: - A refresh token is sent only to the server that issued it. A token without a recorded server is refreshed only at a configured `authorizationServerURL` or `tokenEndpoint`. - For 2025-03-26 servers that publish no metadata at all, the authorizer falls back to `/authorize`, `/token` and `/register` at the server origin, with S256. It does so only on first discovery, and only when every metadata URL answers 404 or 410; a network error, a cancelled request or another status fails the request instead. -Errors reach the caller as `MCPError.transportError(_:)` with the `OAuthAuthorizationError` (or the error a custom authorizer threw; a `CancellationError` is thrown as is), or with an `HTTPStatusError` of 401 or 403 when retries run out. +Errors reach the caller as `MCPError.transportError(_:)` with the `OAuthAuthorizationError` (or the error of the token storage, of the `requestModifier`, or of a custom authorizer; a `CancellationError` is thrown as is), or with an `HTTPStatusError` of 401 or 403 when retries run out. #### Enterprise-managed authorization @@ -843,8 +893,8 @@ let configuration = OAuthConfiguration( - Every token request (authorization code, refresh, client credentials, jwt-bearer) carries a `DPoP` proof: an ES256 JWS with `typ` `dpop+jwt`, the public key as `jwk`, and the claims `jti`, `htm`, `htu` (the URL without user information, query and fragment) and `iat`. - A `token_type` of `DPoP` is presented as `Authorization: DPoP ` with a new proof per request, which also carries `ath`, the hash of the token. A `Bearer` answer means the server does not bind tokens: the token is used as a Bearer token, unless the protected resource sets `dpop_bound_access_tokens_required`, which fails with `dpopRequired`. -- A `use_dpop_nonce` error, from the token endpoint (400) or from the MCP server (401 with a `DPoP` challenge), is retried once with the `DPoP-Nonce` the server sent; this retry does not count against `maxAuthorizationAttempts`. A 401 `use_dpop_nonce` without a `DPoP-Nonce` header is an ordinary challenge and counts, and so does one that arrives without a valid DPoP token, which `OAuthAuthorizer` answers with a new token. The authorizer, not the transport, decides that a challenge is a nonce retry: `OAuthAuthorizer` reads it with its `challengeParser` and reports it as `HTTPChallengeResult.isDPoPNonceRetry`; a custom `HTTPClientAuthorizer` that implements only the Bool `handleChallenge` gets the reading of `DefaultOAuthWWWAuthenticateParser`. A `DPoP-Nonce` in any MCP server response is kept for the origin the request went to; the MCP server's token is kept. -- The stored token records the key's thumbprint (`OAuthAccessToken.keyThumbprint`). A token bound to another key is discarded. Persist the key with the tokens (`P256.Signing.PrivateKey.rawRepresentation`) to use them after a relaunch, or keep it in the Secure Enclave: `DPoP(key:)` takes any `DPoPSigningKey`, which `SecureEnclave.P256.Signing.PrivateKey` is on Apple platforms. The key signs synchronously for every request, and the transport waits for it, so a key behind a network call (a remote HSM, a key service) slows every request. +- A `use_dpop_nonce` error, from the token endpoint (400) or from the MCP server (401 with a `DPoP` challenge), is retried once with the `DPoP-Nonce` the server sent; this retry does not count against `maxAuthorizationAttempts`. A 401 `use_dpop_nonce` without a `DPoP-Nonce` header is an ordinary challenge and counts, and so does one that arrives without a valid DPoP token, which `OAuthAuthorizer` answers with a new token. The authorizer, not the transport, decides that a challenge is a nonce retry: `OAuthAuthorizer` reads it with its `challengeParser` and reports it as `HTTPChallengeResult.isDPoPNonceRetry`; a custom `HTTPClientAuthorizer` returns `.retryWithDPoPNonce` for such a challenge. A `DPoP-Nonce` in any MCP server response is kept for the origin the request went to; the MCP server's token is kept. +- The stored token records the key's thumbprint (`OAuthAccessToken.keyThumbprint`). A token bound to another key is discarded. Persist the key with the tokens (`P256.Signing.PrivateKey.rawRepresentation`) to use them after a relaunch, or keep it in the Secure Enclave: `DPoP(key:)` takes any `DPoPSigningKey`, which `SecureEnclave.P256.Signing.PrivateKey` is on Apple platforms. The key signs once for every request, and the request waits for the signature, which may be `async`; a signing error fails the request. A key behind a network call (a remote HSM, a key service) slows every request. - With `dpop`, an authorization server whose `dpop_signing_alg_values_supported` lacks ES256 fails with `dpopAlgorithmUnsupported`, and a `Bearer` token for a resource with `dpop_bound_access_tokens_required` fails with `dpopRequired`. Without `dpop`, such a resource fails with `dpopRequired` before the grant. - Tokens from `accessTokenProvider` are always Bearer tokens. - When the MCP server sends both a `Bearer` and a `DPoP` challenge, `OAuthAuthorizer` reads the `error` and `scope` of the one for the scheme the request used (RFC 9449 §7.2), so a 403 `insufficient_scope` in the `DPoP` challenge steps up a DPoP token. @@ -852,10 +902,10 @@ let configuration = OAuthConfiguration( ### Server -A protected server puts two validators in front of its transport's pipeline: +A protected server puts two validators in front of its transport's other validators: - `ProtectedResourceMetadataValidator` answers GET `/.well-known/oauth-protected-resource` (and paths below it) with an `OAuthProtectedResourceServerMetadata` document. Put it first, so discovery needs no token. -- `BearerTokenValidator` requires `Authorization: Bearer`. Your `tokenValidator` closure verifies the token (signature, introspection) and returns a `BearerTokenValidationResult`. With `.valid(BearerTokenInfo)` the validator also rejects an `expiresAt` in the past and an `audience` that does not match `resourceIdentifier`; set both fields. Pass `requiresAuthentication:` to exempt requests. +- `BearerTokenValidator` requires `Authorization: Bearer`. Your `tokenValidator` closure verifies the token (signature, introspection) and returns a `BearerTokenValidationResult`. The closure is `async`: it can call an introspection endpoint (RFC 7662) or fetch signing keys without blocking a thread, and the transport handles other requests while it waits. It does not throw: map a failed call to a result, usually `.invalidToken`. With `.valid(BearerTokenInfo)` the validator also rejects an `expiresAt` in the past and an `audience` that does not match `resourceIdentifier`; set both fields. Pass `requiresAuthentication:` to exempt requests. ```swift let resource = URL(string: "https://mcp.example.com/mcp")! @@ -871,7 +921,8 @@ let bearer = BearerTokenValidator( resourceMetadataURL: metadataURL, resourceIdentifier: resource, tokenValidator: { token, request, context in - guard let claims = verifyToken(token) else { + // The closure may suspend; the transport serves other requests meanwhile. + guard let claims = await introspectToken(token) else { return .invalidToken(errorDescription: "Unknown token") } guard claims.scopes.contains("tools:read") else { @@ -882,7 +933,7 @@ let bearer = BearerTokenValidator( audience: claims.audience, scopes: claims.scopes, expiresAt: claims.expiresAt)) }) -let pipeline = StandardValidationPipeline(validators: [ +let validators: [any HTTPRequestValidator] = [ metadata, // before the bearer check: discovery is unauthenticated bearer, OriginValidator(allowedHosts: ["mcp.example.com"], allowedOrigins: ["https://app.example.com"]), @@ -890,13 +941,13 @@ let pipeline = StandardValidationPipeline(validators: [ ContentTypeValidator(), ProtocolVersionValidator(), SessionValidator(), -]) +] ``` -Pass the pipeline to the transport. The stateless transport takes the same validators; use `AcceptHeaderValidator(mode: .jsonOnly)` and leave out `SessionValidator`. +Pass the validators to the transport. The stateless transport takes the same validators; use `AcceptHeaderValidator(mode: .jsonOnly)` and leave out `SessionValidator`. To reuse a group of validators as one, wrap them in `StandardValidationPipeline(validators:)`, itself a validator. ```swift -let transport = StatefulHTTPServerTransport(validationPipeline: protectedPipeline()) +let transport = StatefulHTTPServerTransport(validators: protectedValidators()) ``` Responses: @@ -948,7 +999,7 @@ A malicious server can point OAuth discovery at internal addresses. `OAuthAuthor - **HTTPS.** The MCP endpoint, resource metadata URLs and authorization server endpoints must be `https`; `http` is accepted only for loopback hosts (`localhost`, `127.0.0.1`, `::1`), and for authorization server endpoints not at all by default. URLs with fragments are rejected. - **Private addresses.** `OAuthURLValidator.isPrivateIPHost` parses literal IP hosts with `inet_pton` and rejects `0.0.0.0/8`, `10.0.0.0/8`, `100.64.0.0/10`, `169.254.0.0/16` (cloud metadata), `172.16.0.0/12`, `192.0.0.0/24`, `192.168.0.0/16`, `198.18.0.0/15`, `224.0.0.0/4`, `240.0.0.0/4`, `::`, `fc00::/7`, `fe80::/10`, `fec0::/10` and `ff00::/8`, in any spelling: bracketed, zoned (`%en0`), and IPv4 addresses embedded as IPv4-mapped, IPv4-compatible or NAT64 IPv6. Numeric hosts that are not a canonical dotted quad (`167772161`, `10.1`, `0x0a.0.0.1`, `012.0.0.1`) are rejected too. It never rejects host names or loopback addresses. It is applied to the challenge's `resource_metadata` URL, authorization server candidates (skipped; when every candidate is refused, discovery throws the first refusal, `privateIPAddressBlocked` or `insecureAuthorizationServerEndpoint`), the authorization, token and registration endpoints, and the token endpoint an identity provider's metadata names (`privateIPAddressBlocked`). - **Loopback hosts.** A URL a server names may be on a loopback host (`localhost`, a name under `.localhost`, `127.0.0.0/8`, `::1`) only when that server is on one too: the challenge's `resource_metadata` URL and the resource's authorization servers when the MCP endpoint is, and the authorization, token and registration endpoints when the selected authorization server is. Otherwise they are refused like private addresses, before any request. URLs set in `endpointOverrides` may be on loopback; the servers a configured `protectedResourceMetadataURL` lists still follow the MCP endpoint, so set `authorizationServerURL` for a local authorization server. The token endpoint that an identity provider's metadata names (`OAuthTokenExchange.tokenEndpoint(issuer:)`, which `enterpriseManaged` uses with `.issuer`) follows that provider's issuer. Redirects follow the same rule. -- **Redirects.** Metadata discovery follows a redirect only to an `https` URL, or from loopback `http` to loopback `http`, whose host is not a private address, and to a loopback host (`localhost`, a name under `.localhost`, `127.0.0.0/8`, `::1`) only from a loopback host. Each hop is checked against the one before it. Token and registration requests, which carry credentials, follow no redirects. +- **Redirects.** Metadata discovery follows a redirect only to an `https` URL, or from loopback `http` to loopback `http`, whose host is not a private address, and to a loopback host (`localhost`, a name under `.localhost`, `127.0.0.0/8`, `::1`) only from a loopback host. Each hop is checked against the one before it. Token and registration requests, which carry credentials, follow no redirects. `HTTPClientTransport` follows the redirects of MCP requests to `http` and `https` URLs, except to a loopback host from a remote host, from `https` to `http`, or from a loopback host to `http` on a host that is not a loopback host; `Authorization`, `Proxy-Authorization`, `Cookie` and `Mcp-Session-Id` (of the request, the `requestModifier` or the configuration's `httpAdditionalHeaders`) go to the same origin (scheme, host and port) only (with an authorizer, a same-origin hop has the authorizer's `Authorization` for the new URL or none, not one the `requestModifier` or the configuration set), `DPoP` goes on no redirect, and a hop through another origin removes them for the rest of the chain. A 401 or 403 that such a hop leads to fails the request with `protectedResourceMismatch` instead of reaching the authorizer. OAuth discovery and server card fetches apply the same rule to their session's headers. What the SDK does not do: it checks literal IP addresses only, so a host name that resolves to a private address passes, and DNS rebinding is not prevented. On Linux (swift-corelibs-foundation), which has no per-task delegates, each OAuth request runs in a session with the caller session's configuration and the redirect check as its delegate. Run clients that connect to untrusted servers behind an egress proxy or firewall that blocks internal ranges. @@ -959,7 +1010,7 @@ On the server side, `OriginValidator` protects local servers against DNS rebindi An attacker who learns a session ID could send requests in another user's session. - `StatefulHTTPServerTransport` generates session IDs with `UUID()` (`UUIDSessionIDGenerator`) and rejects IDs outside visible ASCII. A custom `SessionIDGenerator` must produce unguessable IDs. -- The SDK does not bind a session to a user. Put `BearerTokenValidator` in every session's pipeline so each request is authenticated, and in your session router record the token subject when the session is created and reject later requests whose subject differs. +- The SDK does not bind a session to a user. Put `BearerTokenValidator` in every session's validators so each request is authenticated, and in your session router record the token subject when the session is created and reject later requests whose subject differs. - At 2026-07-28 there are no sessions: every request is authenticated on its own. ### Issuer mix-up @@ -1039,7 +1090,7 @@ Details: - In a multi round-trip exchange, `cancelRequest` with the first request id cancels the current round. - Over stateless HTTP the transport cancels a handler only after its reply has become an SSE stream, which happens when the handler sends a notification for the request and the client accepts SSE. A reply still pending as a JSON body is not cancelled when the client goes away; the handler runs to completion and the response is discarded. -- The server can cancel its own requests to the client (sampling, elicitation, roots) with `Server.cancelRequest(_:reason:)`, which sends `notifications/cancelled`. These requests exist only on handshake connections. +- The server withdraws its own requests to the client (sampling, elicitation, roots) when the task that awaits them is cancelled: it sends `notifications/cancelled` on the route of the request. After the client cancelled the request whose handler awaits them, the HTTP server transports have closed that route: `StatefulHTTPServerTransport` sends the notification on the session's GET stream, or stores it for replay when none is open, and `StatelessHTTPServerTransport` doesn't send it. These requests exist only on handshake connections. - `RequestContext.value` throws `CancellationError` after a cancellation; `MCPError` is not used. ### Ping @@ -1052,7 +1103,7 @@ Details: try await client.ping() // `ping`, or `server/discover` at 2026-07-28 ``` -The server answers `ping` with an empty result. `Server` has no method to ping the client, and the SDK has no keep-alive timer. `NetworkTransport` has its own heartbeat (`HeartbeatConfiguration`), which is not an MCP message. +The server answers `ping` with an empty result. `Server` has no method to ping the client, and the SDK has no keep-alive timer. `NetworkTransport` sends no heartbeat either; it skips the heartbeat frames a 0.12 `NetworkTransport` sends, so call `Client.ping()` periodically to check a connection. ### Progress diff --git a/docs/protocol_versions.md b/docs/protocol_versions.md index 77717963..d6e7ef79 100644 --- a/docs/protocol_versions.md +++ b/docs/protocol_versions.md @@ -274,7 +274,7 @@ On a stateless connection the client: `_meta` win. `logLevel` comes from `Client.logLevel`, which starts as `Configuration.logLevel`; - sends no `Mcp-Session-Id` and opens no GET stream over HTTP - (`HTTPClientTransport.useStatelessProtocol(_:)`), and adds the `Mcp-Method`, + (`HTTPClientTransport.didNegotiate(protocolVersion:)`), and adds the `Mcp-Method`, `Mcp-Name` and `Mcp-Param-*` headers; - sends `server/discover` for `ping()`; - stores the level of `setLoggingLevel(_:)` in `Client.logLevel` instead of diff --git a/docs/quick_start.md b/docs/quick_start.md index fc32a091..885f629c 100644 --- a/docs/quick_start.md +++ b/docs/quick_start.md @@ -41,6 +41,7 @@ until standard input closes ([`Examples/hello-server/main.swift`](../Examples/hello-server/main.swift)): ```swift +import Foundation import MCP let server = Server( @@ -70,7 +71,13 @@ await server.withMethodHandler(CallTool.self) { params in } try await server.start(transport: StdioTransport()) -await server.waitUntilCompleted() +do { + // Returns when standard input closes; throws when reading it fails. + try await server.waitUntilCompleted() +} catch { + FileHandle.standardError.write(Data("hello-server: \(error)\n".utf8)) + exit(1) +} ``` - `withMethodHandler(_:handler:)` registers one handler per method type. The @@ -79,7 +86,8 @@ await server.waitUntilCompleted() should see is a result with `isError: true` instead; see [server.md](server.md#errors-and-iserror). - `start(transport:)` connects the transport and returns. The server handles messages in a background task; `waitUntilCompleted()` waits until that task - ends. + ends, and throws when reading standard input failed, so the server exits + with status 1. - The server serves both protocol eras: `initialize` clients and stateless 2026-07-28 clients. See [protocol_versions.md](protocol_versions.md). diff --git a/docs/server.md b/docs/server.md index 7002b52f..382a2d9e 100644 --- a/docs/server.md +++ b/docs/server.md @@ -125,15 +125,15 @@ func registerToolList(on server: Server) async { There is one handler per method. A server with several tools switches on `params.name`. `params.arguments` is a `[String: Value]?`; read it with `stringValue`, `intValue`, `doubleValue`, `numberValue` (an integer or a double, as `Double`), `boolValue`, `arrayValue` and `objectValue`. -A string argument that is a whole `data:` URL, such as `data:image/png;base64,iVBORw0K...`, arrives as `.data(mimeType:_:)`, not as `.string`. Its `stringValue` is `nil`. Read the MIME type and the bytes with `dataValue`. Both are what the client sent, and the SDK does not check that the bytes match the MIME type. Check the content and the size before you store, serve or decode them. +A string argument is a `.string`, also a `data:` URL such as `data:image/png;base64,iVBORw0K...`. To read its bytes, parse it with `DataURL(_:)`, which returns `nil` for anything that isn't a `data:` URL. The MIME type and the bytes are what the client sent, and the SDK does not check that they match: check the content and the size before you store, serve or decode them. A `Codable` arguments type can declare a `DataURL` property, which decodes and validates the string. -The rules for a `data:` URL (RFC 2397): +`DataURL(_:)` follows RFC 2397, narrowly: - It starts with `data:` in lowercase. -- Before the first `,`, it has an optional media type `type/subtype`, then an optional `;charset=`, then an optional `;base64`. The type, the subtype and the charset have no spaces, so prose such as `data: 3 rows, 2 columns` stays `.string`. -- The payload after that `,` decodes: valid base64, or text where every `%` starts a `%XX` escape. +- Before the first `,`, it has an optional media type `type/subtype`, then an optional `;charset=`, then an optional `;base64` (`charset` and `base64` in any ASCII case). The type, the subtype and the charset have no spaces, so prose such as `data: 3 rows, 2 columns` is not a `data:` URL. +- The payload after that `,` decodes: base64 (whitespace and missing `=` padding are accepted), or text where every `%` starts a `%XX` escape. -Other strings stay `.string`. The MIME type is `text/plain` for an empty media type. `;charset=` stays in the MIME type only for a `text/` or empty media type. To get a `data:` URL again, call `Data.dataURLEncoded(mimeType:)`. It returns the base64 form, not always the spelling the client sent: `data:,hi` becomes `data:text/plain;base64,aGk=`. +The MIME type is `text/plain` for an empty media type, and keeps `;charset=` only for a `text/` or empty media type. Its type, subtype and parameter names are lowercase (ASCII only). `DataURL(data:mimeType:)` and the `mimeType` setter also remove ASCII whitespace at either end of the media type, around each `;` and around the first `=` of each parameter, so `text/html; charset=utf-8` becomes `text/html;charset=utf-8`; `DataURL(_:)` rejects whitespace in the URL header and normalizes case and the default `text/plain`. `DataURL(data:mimeType:).description` makes a `data:` URL in base64 form, so it is not always the spelling the client sent: `data:,hi` becomes `data:text/plain;base64,aGk=`. ```swift func registerToolCall(on server: Server) async { @@ -167,16 +167,16 @@ func registerToolCall(on server: Server) async { | Case | Wire `type` | Use | | --- | --- | --- | | `.text(text:annotations:_meta:)` | `text` | Text for the model | -| `.image(data:mimeType:annotations:_meta:)` | `image` | Base64-encoded image | -| `.audio(data:mimeType:annotations:_meta:)` | `audio` | Base64-encoded audio | -| `.resource(resource:annotations:_meta:)` | `resource` | An embedded resource, with its text or blob | +| `.image(_:mimeType:annotations:_meta:)` | `image` | Image bytes, sent base64 | +| `.audio(_:mimeType:annotations:_meta:)` | `audio` | Audio bytes, sent base64 | +| `.resource(resource:annotations:_meta:)` | `resource` | An embedded resource, with its text or bytes | | `.resourceLink(uri:name:title:description:mimeType:annotations:)` | `resource_link` | A link the client may read with `resources/read` | ```swift func chartResult(png: Data) -> CallTool.Result { CallTool.Result(content: [ .text(text: "Temperature over 24 hours"), - .image(data: png.base64EncodedString(), mimeType: "image/png"), + .image(png, mimeType: "image/png"), .resource( resource: .text("time,celsius\n00:00,12\n", uri: "weather://paris/today.csv", mimeType: "text/csv")), .resourceLink( @@ -190,7 +190,7 @@ The factories with a `metadata:` label, such as `.text(_:metadata:)`, are deprec ### Structured content -A tool with an `outputSchema` returns its data in `structuredContent`. `CallTool.Result(content:structuredContent:isError:_meta:)` takes any `Codable` value and throws if it cannot be encoded. It converts the value with `Value(_:)`, so a string field that is a whole `data:` URL is sent in base64 form: `data:,hi` becomes `data:text/plain;base64,aGk=`. A `Value` that you pass is kept as is. Send the same data as text too, for clients that read only `content`. +A tool with an `outputSchema` returns its data in `structuredContent`. `CallTool.Result(content:structuredContent:isError:_meta:)` takes any `Codable` value and throws if it cannot be encoded. It converts the value with `Value(_:)`, which sends strings as written. A `Value` that you pass is kept as is. Send the same data as text too, for clients that read only `content`. ```swift struct Forecast: Codable, Sendable { @@ -437,8 +437,8 @@ A message is `.user(_:)` or `.assistant(_:)` with one `Prompt.Message.Content`. | Case | Wire `type` | | --- | --- | | `.text(text:)` | `text` | -| `.image(data:mimeType:)` | `image` (base64) | -| `.audio(data:mimeType:)` | `audio` (base64) | +| `.image(_:mimeType:)` | `image` (bytes, sent base64) | +| `.audio(_:mimeType:)` | `audio` (bytes, sent base64) | | `.resource(resource:annotations:_meta:)` | `resource` | | `.resourceLink(uri:name:title:description:mimeType:annotations:)` | `resource_link` | @@ -447,7 +447,7 @@ func reviewMessages(diff: String, screenshot: Data) -> [Prompt.Message] { [ .user(.text(text: "Review the change below.")), .user(.resource(resource: .text(diff, uri: "repo://changes/42.diff", mimeType: "text/x-diff"))), - .user(.image(data: screenshot.base64EncodedString(), mimeType: "image/png")), + .user(.image(screenshot, mimeType: "image/png")), .user(.resourceLink(uri: "repo://files/README.md", name: "README.md", mimeType: "text/markdown")), ] } @@ -499,7 +499,7 @@ func registerResources(on server: Server) async { ### Binary resources -`Resource.Content.text(_:uri:mimeType:_meta:)` sends `text`. `Resource.Content.binary(_:uri:mimeType:_meta:)` takes `Data` and sends it base64-encoded in `blob`. Clients decode `blob` themselves. +`Resource.Content.text(_:uri:mimeType:_meta:)` sends `text`. `Resource.Content.binary(_:uri:mimeType:_meta:)` takes `Data` and sends it base64-encoded in `blob`. Clients get the bytes from `body`. ### Resource templates @@ -550,7 +550,7 @@ func resourceDidChange(_ uri: String, on server: Server) async throws { ## List-changed notifications -A server whose tools, prompts or resources change at run time tells clients with `notifications/tools/list_changed`, `notifications/prompts/list_changed` or `notifications/resources/list_changed`. The SDK does not send them for you: call `notify` after each change. Declare `listChanged: true` on the matching capability. +A server whose tools, prompts or resources change at run time tells clients with `notifications/tools/list_changed`, `notifications/prompts/list_changed` or `notifications/resources/list_changed`. The SDK does not send them for you: call `notify` after each change. Declare `listChanged: true` on the matching capability: the flag says the server sends the notification, not that the list changed. ```swift /// Tools that change at run time. Each change notifies the clients. @@ -660,7 +660,7 @@ The pieces: | `requestState` | A string the handler writes and reads as plaintext. The SDK seals it on the way out. | | `resultType` | `.inputRequired` on such results, `.complete` otherwise | -A `data:` URL string in an answer arrives as `.data`, as in [tool arguments](#calling-tools): in the `content` of an elicitation, for example text that a user typed into a form, and in the `input` of a sampling tool use. The same applies to the results of `requestElicitation` and `requestSampling`. +A `data:` URL string in an answer arrives as a `.string`, as in [tool arguments](#calling-tools): in the `content` of an elicitation, for example text that a user typed into a form, and in the `input` of a sampling tool use. The same applies to the results of `requestElicitation` and `requestSampling`. A result may carry `requestState` without input requests. The client then retries with the state and no responses, which lets a long operation continue in steps. @@ -1407,7 +1407,7 @@ func describeCaller() -> String { ### HTTP context -`httpContext` is the originating `HTTPRequest` (method, headers, body, path) when the transport conforms to `HTTPContextProviding`. `StatefulHTTPServerTransport` and `StatelessHTTPServerTransport` do; `StdioTransport` and `InMemoryTransport` do not, so it is `nil` there. `HTTPRequest.header(_:)` looks headers up case-insensitively and joins repeated ones; `headerValues(_:)` returns the value of each field line. +`httpContext` is the originating `HTTPRequest` (method, headers, body, path), from the transport's `httpRequest(for:)`. `StatefulHTTPServerTransport` and `StatelessHTTPServerTransport` return it; `StdioTransport` and `InMemoryTransport` return `nil`. `HTTPRequest.header(_:)` looks headers up case-insensitively and joins repeated ones; `headerValues(_:)` returns the value of each field line. ```swift /// The bearer token of the HTTP request being handled, if any. @@ -1492,10 +1492,11 @@ func registerPagedTools(on server: Server, tools: [Tool], pageSize: Int = 50) as ## Lifecycle -`start(transport:initializeHook:statelessRequestHook:)` registers the built-in handlers, connects the transport and starts the receive loop. It returns once the loop is running. `waitUntilCompleted()` returns when the loop ends, for example when the transport closes. `stop()` ends the listen streams, cancels the loop, fails pending server-to-client requests with -32603 "Server disconnected" and disconnects the transport. +`start(transport:initializeHook:statelessRequestHook:)` registers the built-in handlers, connects the transport and starts the receive loop. It returns once the loop is running. `waitUntilCompleted()` returns when the loop ends normally: when the transport finishes its receive stream, for example when stdin closes, when the stream throws `MCPError.connectionClosed` because the peer closed the connection, and after `stop()`. It throws any other error the stream throws, for example `MCPError.transportError` when a read from stdin fails, so a stdio server can exit with a failure status. Every caller gets the same outcome, and a call after the end gets it at once. Each `start` begins a new run, after any `stop()` in progress has disconnected its transport: from then on a call waits for that run, and a call before then gets the stopped run's outcome. When `start` throws after beginning a run, for example because the transport fails to connect, the wait throws the same error until the next `start`; a `start` while a run is already active throws without affecting it. A `stop()` while `start` is still connecting ends the run normally instead, and `start` throws. Cancelling the caller doesn't end the wait: to stop the server on cancellation, call `stop()` from a cancellation handler, as below, and the wait returns once `stop()` has disconnected the transport. `stop()` ends the listen streams, cancels the loop, fails pending server-to-client requests with -32603 "Server disconnected" and disconnects the transport. A `stop()` or `start` called while a `stop()` is in progress waits until that one has disconnected the transport. ```swift -/// Serves until the transport closes or the calling task is cancelled. +/// Serves until the transport closes or, when the calling task is cancelled, until the +/// server is stopped. Throws the transport's error when its receive stream fails. func serve(_ server: Server, on transport: any Transport) async throws { try await server.start(transport: transport) { clientInfo, capabilities in // Runs for `initialize` only. 2026-07-28 clients never send it. @@ -1503,8 +1504,8 @@ func serve(_ server: Server, on transport: any Transport) async throws { throw MCPError.invalidRequest("This client is not allowed") } } - await withTaskCancellationHandler { - await server.waitUntilCompleted() + try await withTaskCancellationHandler { + try await server.waitUntilCompleted() } onCancel: { Task { await server.stop() } } @@ -1552,9 +1553,10 @@ struct MCPService: Service { func run() async throws { try await server.start(transport: StdioTransport()) - // Returns when the transport closes, or after `stop()`. - await withTaskCancellationOrGracefulShutdownHandler { - await server.waitUntilCompleted() + // Returns when the transport closes, or once `stop()` has disconnected it; throws + // when the transport fails. + try await withTaskCancellationOrGracefulShutdownHandler { + try await server.waitUntilCompleted() } onCancelOrGracefulShutdown: { Task { await server.stop() } } diff --git a/docs/src/client.src.md b/docs/src/client.src.md index c60623b8..d7ce1210 100644 --- a/docs/src/client.src.md +++ b/docs/src/client.src.md @@ -99,7 +99,7 @@ When `isStateless` is `true`: ### Strict mode -With `strict: true`, `listTools`, `callTool`, `listPrompts`, `getPrompt`, `listResources`, `listResourceTemplates`, `readResource`, `subscribeToResource`, `unsubscribeFromResource` (2025-11-25 only), `setLoggingLevel` and both `complete` methods check `serverCapabilities` first. When the capability is missing they throw `MCPError.methodNotFound` without sending anything; before `connect` the detail is "Server capabilities not initialized". The default configuration sends the request and lets the server answer. +With `strict: true`, `listTools`, `callTool`, `listPrompts`, `getPrompt`, `listResources`, `listResourceTemplates`, `readResource`, `subscribeToResource`, `unsubscribeFromResource` (2025-11-25 only), `setLoggingLevel` and both `complete` methods check `serverCapabilities` first. They throw `MCPError.methodNotFound` without sending anything when the capability is missing, and for resource subscriptions when `resources.subscribe` isn't `true`; before `connect` the detail is "Server capabilities not initialized". The default configuration sends the request and lets the server answer. %include Examples/Snippets/Client/Client.swift strict @@ -138,14 +138,14 @@ A tool with an `outputSchema` returns `structuredContent` as well: %include Examples/Snippets/Client/Tools.swift call-structured -A string in `structuredContent`, in another `Value` field of a result, or in the `data` of an `MCPError` from the server, that is a whole `data:` URL arrives as `.data(mimeType:_:)`. The rules are the same as for [tool arguments](server.md#calling-tools). Read it with `dataValue`. When you encode the `Value` again, as above, it becomes a base64 `data:` URL: `data:,hi` becomes `data:text/plain;base64,aGk=`. +Strings in `structuredContent`, in other `Value` fields of a result and in the `data` of an `MCPError` from the server arrive as sent, `data:` URLs included. Parse a `data:` URL with `DataURL(_:)`; the rules are in [tool arguments](server.md#calling-tools). ### Header parameters At 2026-07-28 over Streamable HTTP, a tool can ask for some arguments to be mirrored into HTTP headers (SEP-2243), so that gateways can route without parsing the body. The input schema marks the argument with `"x-mcp-header": ""`. The client handles this itself: - On every `tools/list` result at 2026-07-28, it records the annotated arguments of each tool. A first page (no cursor) replaces what earlier listings recorded; `connect` and `disconnect` clear them. -- On `tools/call` through `HTTPClientTransport`, or a custom transport that implements `send(_:additionalHeaders:)`, it sends `Mcp-Param-` for each annotated argument that is present and not null. Strings are sent as-is, booleans as `true`/`false`, integers in decimal. A value that is empty, is not printable ASCII, has a leading or trailing space, or looks like an encoded value is sent as `=?base64??=`. +- On `tools/call` through `HTTPClientTransport`, or a custom transport that sends `options.headers` of `send(_:options:)`, it sends `Mcp-Param-` for each annotated argument that is present and not null. Strings are sent as-is, booleans as `true`/`false`, integers in decimal. A value that is empty, is not printable ASCII, has a leading or trailing space, or looks like an encoded value is sent as `=?base64??=`. - It drops a tool with an invalid annotation from the `tools/list` result and logs a warning. An annotation is invalid when its value is empty or not a string, is not an HTTP token, or repeats another name of the tool case-insensitively, when the property type is not `string`, `integer` or `boolean`, or when the tool has more than 64 annotations or nests `properties` more than 32 deep. The warning names the property path, not the annotation. `Tool.headerParameters()` returns the parsed annotations: @@ -193,7 +193,7 @@ Prompts: `listPrompts(cursor:)` and `getPrompt(name:arguments:)`. Prompt argumen %include Examples/Snippets/Client/Tools.swift prompts -Resources: `listResources(cursor:)`, `listResourceTemplates(cursor:)` and `readResource(uri:)`. A `Resource.Content` holds `text` or a Base64 `blob`. +Resources: `listResources(cursor:)`, `listResourceTemplates(cursor:)` and `readResource(uri:)`. A `Resource.Content` holds a `body`: `.text(String)` or `.blob(Data)`, decoded from base64. An item with neither `text` nor `blob`, with both, or with a `blob` that is not base64 fails the read with `ResponseDecodingError`; whitespace and missing `=` padding in base64 are accepted, as in image and audio `data`. %include Examples/Snippets/Client/Tools.swift resources @@ -461,9 +461,9 @@ At 2026-07-28 the client keeps one background listen stream for the list kinds t | | 2025-11-25 | 2026-07-28 | |---|---|---| -| `subscribeToResource(uri:)` | Sends `resources/subscribe` | Adds the URI to the background listen stream and waits for the acknowledgement of a stream that names it; does nothing if the URI is already subscribed | -| `unsubscribeFromResource(uri:)` | Sends `resources/unsubscribe` | Replaces the stream with one without the URI; updates may arrive until the replacement is acknowledged; does nothing if the URI is not subscribed | -| `subscribedResourceURIs` | Always empty | The subscribed URIs the open stream serves | +| `subscribeToResource(uri:)` | Sends `resources/subscribe` on every call, also for a subscribed URI | Adds the URI to the background listen stream and waits for the acknowledgement of a stream that names it; does nothing if the URI is already subscribed | +| `unsubscribeFromResource(uri:)` | Sends `resources/unsubscribe` on every call, also for a URI that is not subscribed | Replaces the stream with one without the URI; updates may arrive until the replacement is acknowledged; does nothing if the URI is not subscribed | +| `subscribedResourceURIs` | The URIs whose `resources/subscribe` succeeded and that were not unsubscribed; a failed `resources/unsubscribe` keeps its URI | The subscribed URIs the open stream serves | At 2026-07-28, `subscribeToResource` throws `invalidRequest("The server does not send updates for ")` when the server's acknowledgement omits the URI, and the error that kept the stream from opening otherwise. When the server ends the stream, `subscribedResourceURIs` is empty until the client reopens it after the backoff delay; subscribing again reopens it at once. When the stream fails, the subscriptions are kept and the client reopens the stream for them; only a `subscribeToResource` call still waiting for its acknowledgement fails when that reopening fails. Cancelling the task that waits in `subscribeToResource` ends the call with `CancellationError` and drops the URI again when that call added it. After `disconnect()`, `subscribeToResource` throws. @@ -506,13 +506,13 @@ To receive progress for a request, put a progress token in its `_meta` and handl ## Batching -`withBatch(body:)` sends several requests as one JSON-RPC array. `Batch.addRequest(_:)` returns a `Task` for each result; the batch is sent when the closure returns. +`withBatch(isolation:body:)` sends several requests as one JSON-RPC array and returns the value of its closure. `Batch.addRequest(_:)` returns a `Task` for each result; the batch is sent when the closure returns. The closure runs on the caller's actor, so it can also assign to local variables. Await the tasks after `withBatch` returns: nothing is sent while the closure runs. %include Examples/Snippets/Client/Notifications.swift batch -JSON-RPC batching was removed from the specification in 2025-06-18. Use it only with peers that accept batches; an SDK server does. Each request gets what `send(_:)` adds: the 2026-07-28 `_meta` envelope, the header parameters and the multi round-trip loop. On a stateless connection the requests are sent one by one, because each 2026-07-28 request carries its own HTTP headers. A request cancelled with `cancelRequest(_:reason:)` before the batch is sent is left out. When the closure throws, the requests it added fail with the same error and nothing is sent. +JSON-RPC batching is part of MCP 2025-03-26 only; 2025-06-18 removed it. Use it only with peers that accept batches: an SDK `Server` on a stream transport (stdio, network, in-memory) does, but the SDK's HTTP server transports answer a JSON array with HTTP 400. Each request gets what `send(_:)` adds: the 2026-07-28 `_meta` envelope, the header parameters and the multi round-trip loop. On a stateless connection the requests are sent one by one, because each 2026-07-28 request carries its own HTTP headers. A request cancelled with `cancelRequest(_:reason:)` before the batch is sent is left out. When the closure throws, the requests it added fail with the same error and nothing is sent. -`withBatch` throws `internalError("Client connection not initialized")` when not connected. An empty batch sends nothing. +`withBatch` throws `internalError("Client connection not initialized")` when not connected. An empty batch sends nothing. A `Batch` is valid only while the closure runs: `addRequest(_:)` throws `internalError` after `withBatch` returns. ## Capabilities and extensions diff --git a/docs/src/migration.src.md b/docs/src/migration.src.md index be6a4d2f..62dcecba 100644 --- a/docs/src/migration.src.md +++ b/docs/src/migration.src.md @@ -20,22 +20,34 @@ each change that breaks source code. | -32042 error decoding | If the data cannot be represented entirely by `urlElicitationRequired`, decodes as `serverError` and keeps `data` | Match `errorCode == .urlElicitationRequired` to handle both cases | | `HTTPResponse` | `.data` and `.error` have new associated values | Update patterns | | `Client.Capabilities.experimental` | `[String: String]?` became `[String: Value]?` | Pass `Value`s | -| `OAuthAuthorizationError` | A struct with a `code`, not an enum; eight new codes | Read details from properties instead of binding associated values | +| `OAuthAuthorizationError` | A struct with a `code`, not an enum; twelve new codes; `tokenRequestFailed(statusCode:oauthError:)` takes `Int?`; URLs in descriptions are redacted | Read details from properties instead of binding associated values | | `GrantType`, `TokenEndpointAuthentication`, `PrivateKeyJWTSigningAlgorithm` | Structs, not enums; new grant type `.jwtBearer` | Add a `default` to `switch` statements; write `.ES256` instead of `init(rawValue:)` | | `BearerTokenValidationResult`, `Elicitation.Mode`, `ToolChoice.Mode` | Structs, not enums; `Mode(rawValue:)` is not optional | Add a `default` to `switch` statements; drop the optional binding | | Roots, sampling and logging | Deprecated by the specification (SEP-2577): the entry points are `@available(*, deprecated)`, and a notice is logged once when the peer declares them | Nothing now; plan the migration in [rough_edges.md](rough_edges.md#deprecated-by-the-specification) | | `includeContext` | `.thisServer` and `.allServers` are deprecated (SEP-2596) | Omit `includeContext`, or use `.none` | | `ToolChoice(mode:)` | Takes a `Mode`; the initializer with an optional mode is deprecated | Pass a mode. `.init(mode: .none)` is now the `none` mode, not `nil` (`auto`) | | Content blocks, `InputRequest`, `InputResponse`, `CreateElicitation.Parameters` | New case `.unknown` for kinds from a later revision | Add it, or a `default`, to `switch` statements | -| `HTTPClientAuthorizer` | `authorizationHeader(for:)` became `authorizationHeaders(for:method:)`; new requirement `handleChallenge(statusCode:headers:endpoint:operationKey:sentAuthorization:session:)`, returning `HTTPChallengeResult`, with a default that calls the Bool method | Update custom authorizers | +| `HTTPClientAuthorizer` | Not class-bound (`Sendable`); `authorizationHeaders(for:method:) async throws` replaces `authorizationHeader(for:)`; `prepare(for:session:)` replaces `prepareAuthorization(for:session:)` and its thrown errors fail the request; `handleChallenge(_:session:)` takes `HTTPAuthorizationChallenge` and returns `HTTPChallengeResult`; `didReceiveResponse(headers:for:)` is `async`; `validateEndpointSecurity(for:)` is removed from `HTTPClientAuthorizer` and `OAuthAuthorizer` | Update custom authorizers; rename `prepareAuthorization(for:session:)` to `prepare(for:session:)` (it still compiles without being called) and remove `validateEndpointSecurity(for:)` | +| `OAuthTokenStorage` | Replaces `TokenStorage` and `InMemoryTokenStorage` (`InMemoryOAuthTokenStorage`); not class-bound; resource-keyed `async throws` `load(for:)`, `save(_:for:)`, `clear(for:)` | Update custom token stores; set `endpointOverrides.resource` for persistence across launches | +| `HTTPClientTransport` `requestModifier` | `(URLRequest) -> URLRequest` became `@Sendable (inout URLRequest) async throws -> Void` | Mutate the request in place and drop `return` | | `Client` convenience methods | Return the result type, not a tuple; `startToolCall` replaces the `RequestContext` overload of `callTool`; `initialize()` is removed | Read the result's properties | | Peer result decoding | An undecodable result, including a server-to-client or task result, throws `ResponseDecodingError` with the expected type, raw result and decoding error. It is separate from `MCPError` | Catch this error to inspect a malformed result; use a `Method` with `Result == Value` for raw access | | `Client.connect(transport:)` | Returns `Client.ConnectionInfo`, whose `serverInfo` is optional | Unwrap `serverInfo` | | `Version.latest` | Renamed `Version.latestHandshake`; the old name is deprecated | Rename | -| `Tool.Content` | `annotations` and `_meta` default to `nil`; the deprecated short forms are removed | Use `.text(text:)`, `.image(data:mimeType:)`, `.audio(data:mimeType:)` | +| `Tool.Content`, `Prompt.Message.Content`, `Sampling` content blocks | `image` and `audio` take unlabeled `Data` instead of base64 `String`; `Tool.Content` `annotations` and `_meta` default to `nil` and the deprecated 0.12 short forms are removed; deprecated `data: String` construction shims remain | Pass `Data` with `.image(_:mimeType:)` / `.audio(_:mimeType:)`; update `case .image(let d, ...)` patterns to expect `Data` | +| `Resource.Content` | `body: Resource.Content.Body` (`.text(String)` or `.blob(Data)`) replaces stored `text` and `blob`; deprecated `text` and `blob` accessors remain; items with both or neither fail decoding | Switch on `body` instead of reading `text` and `blob` | | `HTTPClientTransport` errors | HTTP statuses and OAuth failures are `transportError` with `HTTPStatusError` or `OAuthAuthorizationError`, not `internalError` with a message | Match the typed errors | +| `Transport` protocol | `logger` is `nonisolated`; `send(_:options:)` with `TransportSendOptions` replaces `send(_:)`; `receive()` is `async`; `HTTPContextProviding` removed (`httpRequestContext(for:)` → `httpRequest(for:)`); `HTTPClientTransport.updateNegotiatedProtocolVersion(_:)` → `didNegotiate(protocolVersion:)` | Update custom transports; wrap transports with `TransportWrapper` | +| HTTP request validation | `HTTPRequestValidationPipeline` and `validationPipeline:` removed; `validate` methods and `TokenValidator` are `async` | Pass `validators:` (defaulting to `defaultValidators`) and mark custom validators `async` | +| `NetworkTransport` | `HeartbeatConfiguration`, `BufferConfiguration`, and old 5-arg `init` removed; reconnection off by default; heartbeats no longer sent | Use `init(connection:maximumMessageLength:connectionTimeout:reconnection:logger:)`; opt in to reconnection if needed | +| `MCPError.isResourceTemporarilyUnavailable(_:)` | Removed; transports handle `EAGAIN` internally | Remove calls | +| `Server.waitUntilCompleted()` | Now `async throws`; `Server.start` throws on overlapping starts or a `stop()` while connecting | Add `try` and handle or propagate transport and start errors | +| `Client.withBatch` and `Client.Batch` | `withBatch(body:)` becomes generic `@discardableResult withBatch(isolation:body:)`; `Client.Batch` is a `Sendable` struct whose `addRequest(_:)` throws after return | Trailing-closure calls compile unchanged; drop `nonisolated(unsafe)` workarounds and avoid escaping `Batch` | +| `Server.cancelRequest(_:reason:)` | Deprecated; `requestSampling`, `requestElicitation`, and `listRoots` withdraw on task cancellation | Cancel the task awaiting the server-to-client request instead | +| Resource subscriptions | Strict `Client` requires `resources.subscribe: true` (`false` throws -32601); `subscribedResourceURIs` lists handshake subscriptions; public `init(uri:)` on subscribe/unsubscribe `Parameters` | Declare `resources: .init(subscribe: true)` for strict clients | +| `Icon.Theme`, `Response` decoding, `TaskSnapshot` | Unknown icon `theme` strings decode as `nil`; `Response` decoding reports the failing coding path; `TaskSnapshot` equality ignores wire generation | Treat `Icon.theme == nil` as usable with any theme (unknown themes are omitted on re-encode) | | `Server.start(transport:)` | Keeps handlers registered before it; answers `logging/setLevel` and filters `log` when the server declares `logging` | Remove workarounds | -| `OAuthWWWAuthenticateParsing` | New requirement `parseChallenge(scheme:from:)`, with a default | Nothing | +| `OAuthScopeSelecting`, `OAuthWWWAuthenticateParsing` | Both refine `Sendable`; `OAuthWWWAuthenticateParsing` adds `parseChallenge(scheme:from:)` with a default | Conform custom implementations to `Sendable` | | `Server` | Serves 2026-07-28 requests by default | Nothing, or opt out | | `Client` | Connects at 2026-07-28 by default, with a fallback to `initialize` | Nothing, or opt out | | `Version.supported` | Lists 2026-07-28 | Read `Version.handshake` for the `initialize` revisions | @@ -47,12 +59,15 @@ each change that breaks source code. | Sampling with tools | The client refuses tools without `sampling.tools`, and tool messages that break the rules, with -32602; `requestSampling` refuses them before it sends | Declare `sampling.tools` when the sampling handler takes tools | | `.none(clientID:)` | A plain client ID is pre-registered: no dynamic registration | Pass `""` to register | | OAuth loopback URLs | A URL a server names may be on a loopback host only when that server is; otherwise `privateIPAddressBlocked`, also from `OAuthTokenExchange.tokenEndpoint(issuer:)` | Set `endpointOverrides` for a local authorization server used with a remote MCP endpoint | +| OAuth canonical resource URI | Normalized per RFC 3986 §6 (lowercase scheme/host, dot segments collapsed, trailing slash stripped, hostless URLs rejected), including `endpointOverrides.resource` | Pass a custom `OAuthMetadataDiscovering` wrapper if your server requires a trailing slash | +| HTTP redirects | `Authorization`, `Proxy-Authorization`, `Cookie`, and `Mcp-Session-Id` stay same-origin (also separated from `httpAdditionalHeaders`); non-HTTP(S), `https`→`http`, and remote↔loopback/unspecified hops are refused; credential-less `401`/`403` fails with `protectedResourceMismatch` | Configure the final origin as `endpoint`, or handle `protectedResourceMismatch` | | `StatelessHTTPServerTransport` with an `initializeHook` | Handshake requests other than `initialize` are refused with -32600 unless a `statelessRequestHook` is set | Set a `statelessRequestHook` | | Terminated stateful HTTP session | After a session ends and validation passes, requests without a session ID receive 400 instead of 404; requests with any session ID receive 404 | Route a new sessionless `initialize` to a new transport and `Server` | -| `data:` URL strings | Arrive as sent instead of rewritten as base64 `data:` URLs; prose such as `data: 3 rows, 2 columns` is no longer a `data:` URL | Nothing | +| `Value.data` and `data:` URLs | `Value.data` is removed (all JSON strings decode as `.string`); `DataURL` replaces the `Data` data-URL helpers (deprecated shims remain for `Value.dataValue`, `Data.isDataURL(string:)`, `Data.parseDataURL(_:)`, `Data.dataURLEncoded(mimeType:)`) | Remove `case .data` branches and parse strings explicitly with `DataURL(_:)` | | HTTP transports | New error bodies, status codes and streaming | See below | | `HTTPClientTransport` | Default per-host connection limit 64; POST streams resume per stream; SSE on Linux | Raise `httpMaximumConnectionsPerHost` in custom configurations | -| `StdioTransport`, `NetworkTransport` | A received message longer than 16 MiB ends the receive stream with `internalError` | Make sure the peer sends no message longer than 16 MiB; `StdioTransport` has no setting that raises the limit. For `NetworkTransport`, raise `maxReceiveBufferSize` or use `BufferConfiguration.unlimited` | +| `StdioTransport`, `NetworkTransport` | A received message longer than 16 MiB ends the receive stream with `internalError`; stdio read errors finish with `transportError` | Make sure the peer sends no message longer than 16 MiB; `StdioTransport` has no setting that raises the limit. For `NetworkTransport`, pass `maximumMessageLength:` (`Int.max` for no limit) | +| Exact code-point matching | `ID`, `ProgressToken`, task IDs/owners, method names, SEP-2243 headers/keys, subscription URIs, and `RequestState` audiences compare by exact Unicode scalars | Send matching Unicode scalar spellings (canonically equivalent forms no longer match) | | Package | Requires Swift 6.1 tools; depends on swift-crypto and Yams, no longer on eventsource; swift-docc-plugin `from: "1.4.0"` instead of its `main` branch | Use Xcode 16.3 or later; resolve packages again | | Platforms | Minimums raised to macOS 15, Mac Catalyst 18, iOS 18, tvOS 18, watchOS 11, visionOS 2 | Raise your deployment targets, or stay on 0.12 to keep older ones | @@ -198,11 +213,18 @@ After: %include Examples/Snippets/Guides/Migration.swift migration-oauth-error -Eight codes are new: `authorizationResponseIssuerMismatch`, +Twelve codes are new: `authorizationResponseIssuerMismatch`, `authorizationResponseMissingIssuer`, `assertionProviderMissing`, `issuedTokenTypeMismatch`, `authorizationServerNotConfigured`, -`assertionAudienceMismatch`, `dpopRequired` and `dpopAlgorithmUnsupported`. -More can appear in a minor release, so a `switch` needs a `default`. See +`assertionAudienceMismatch`, `dpopRequired`, `dpopAlgorithmUnsupported`, +`authorizationEndpointMissing`, `authorizationEndpointInvalid`, +`registrationRequestFailed`, and `registrationResponseInvalid`. +`tokenRequestFailed(statusCode:oauthError:)` (like +`registrationRequestFailed(statusCode:oauthError:)`) now takes +`statusCode: Int?` (`nil` when the response is not an HTTP response). Error +descriptions and messages redact URL user information, queries, and fragments +(including redirect URI mismatches and challenge endpoints). More codes can +appear in a minor release, so a `switch` needs a `default`. See [Authorization](#authorization). ### Open structs @@ -295,18 +317,68 @@ version when the server sent no `io.modelcontextprotocol/serverInfo`; now which every request carries in `_meta`, instead of changing `configuration.logLevel`. -### `Tool.Content` +### `Tool.Content`, `Prompt.Message.Content` and `Sampling` content blocks -The `text`, `image` and `audio` cases have default values for `annotations` -and `_meta`, so `.text(text: "Hello")` is the case itself. The deprecated -helpers that took `metadata:` or unlabeled values (`.text(_:)`, -`.text(text:metadata:)`, `.image(_:_:metadata:)`, +The `Tool.Content` `text`, `image` and `audio` cases have default values for +`annotations` and `_meta`, so `.text(text: "Hello")` is the case itself. The +deprecated 0.12 helpers that took `metadata:` or unlabeled values +(`.text(_:)`, `.text(text:metadata:)`, `.image(_:_:metadata:)`, `.image(data:mimeType:metadata:)`, `.audio(_:_:metadata:)`, `.audio(data:mimeType:metadata:)`) are removed: write `.text(text: "Hello")`, and `_meta:` where you passed `metadata:`. +The `image` and `audio` cases of `Tool.Content`, `Prompt.Message.Content`, +`Sampling.Message.Content.ContentBlock` and +`Sampling.ToolResultContent.ContentBlock`, along with the convenience +factories `Sampling.Message.Content.image(_:mimeType:)` and +`.audio(_:mimeType:)`, now take unlabeled `Data` instead of a base64-encoded +`String` (`data:`). Deprecated `data: String` static forwarding factories +remain for 0.12.1 construction call sites (decoding leniently and falling back +to empty `Data()` on invalid base64). + +> Warning: Positional patterns such as `case .image(let d, let mimeType, _, _)` +> or `case .image(let d, let mimeType)` still compile, but `d` now binds `Data` +> instead of a base64 `String`. Labeled patterns such as +> `case .image(data: let s, ...)` fail to compile and should be updated to bind +> `Data`. + +On the wire, `data` still encodes as standard padded base64 (RFC 4648 §4) and +decodes leniently with respect to ASCII whitespace and omitted trailing `=` +padding. Per the MCP specification, non-standard URL-safe base64 (`-`, `_`) or +invalid base64 throws `DecodingError.dataCorrupted` and fails decoding of the +containing message or result. + %include Examples/Snippets/Guides/Migration.swift migration-content +### `Resource.Content` + +`Resource.Content` replaces its stored `text: String?` and `blob: String?` +properties with `body: Resource.Content.Body` (`.text(String)` or +`.blob(Data)`), and exposes `Resource.Content(uri:mimeType:body:_meta:)` +alongside the `.text(...)` and `.binary(...)` factories. Deprecated `text` and +`blob` computed properties remain as forwarding shims (`blob` encodes +`.blob(Data)` as standard base64). + +Per the MCP specification, a resource contents item with both `text` and +`blob`, with neither, or with a `blob` that is not standard RFC 4648 §4 base64 +(including URL-safe `-` and `_`) throws `DecodingError.dataCorrupted` and +fails decoding of the containing result, including embedded resources. + +### `Value.data` and `DataURL` + +`Value.data(mimeType:_:)` is removed so `Value` represents only the JSON data +model. Every JSON string, including `data:` URLs, now decodes as +`Value.string` and arrives as sent rather than being rewritten as base64. +Parse and format `data:` URLs explicitly with the new `DataURL` type +(`Codable`, `Hashable`, `Sendable`). + +Deprecated 0.12.1 forwarding shims remain for `Value.dataValue`, +`Data.isDataURL(string:)`, `Data.parseDataURL(_:)` and +`Data.dataURLEncoded(mimeType:)`. Remove `case .data` branches from `switch` +statements over `Value`, and switch callers to `DataURL`: + +%include Examples/Snippets/Guides/Migration.swift migration-data-url + ### HTTP client errors `HTTPClientTransport` throws `MCPError.transportError(_:)` with a typed error @@ -341,31 +413,315 @@ authentication challenges; read the values from `headers`. ### `HTTPClientAuthorizer` -`authorizationHeader(for endpoint: URL) -> String?` is replaced by -`authorizationHeaders(for url: URL, method: String) throws -> [String: String]`, -so that an authorizer can sign the request (a DPoP proof covers the method and -the URL). Return `["Authorization": value]` where the old method returned -`value`, and `[:]` for `nil`. The transport now sets these headers after the -`requestModifier`, for the final URL and method; they replace an -`Authorization` header the modifier set. A thrown error fails the request with -`transportError(_:)` carrying that error. - -The transport now calls the new requirement -`handleChallenge(statusCode:headers:endpoint:operationKey:sentAuthorization:session:)` -with the `Authorization` header the challenged request carried. It returns an -`HTTPChallengeResult`: `retry`, as the Bool method returns, and -`isDPoPNonceRetry`, whether the retry only answers a DPoP `use_dpop_nonce` -challenge, which the transport allows once per request without counting it -against `maxAuthorizationAttempts`. Its default calls -`handleChallenge(statusCode:headers:endpoint:operationKey:session:)` and reads -the nonce challenge with `DefaultOAuthWWWAuthenticateParser`, so custom -authorizers compile and behave as before. An authorizer that implements it can -tell a challenge for a token another request has already replaced from one for -the current token, and decide which challenge is a nonce retry. - -`OAuthAccessToken` has a new stored property, `keyThumbprint`, with a -defaulted initializer parameter; tokens saved by the previous release decode -with `nil`. +`HTTPClientAuthorizer` is no longer class-bound (`Sendable`, not +`AnyObject`): classes, structs, and actors can conform (an actor declares +`maxAuthorizationAttempts` `nonisolated`). + +- `authorizationHeader(for endpoint: URL) -> String?` is replaced by + `authorizationHeaders(for url: URL, method: String) async throws -> [String: String]`, + so an authorizer can load tokens asynchronously and sign each request (a DPoP + proof covers the method and the URL). Return `["Authorization": value]` where + the old method returned `value`, and `[:]` for `nil`. The transport sets + these headers after `requestModifier`, for the final URL and method, and + calls the method again on every same-origin redirect; returned headers + replace any of the same name. A thrown error fails the request with + `transportError(_:)` carrying that error. +- `prepareAuthorization(for:session:)` is renamed to + `prepare(for endpoint: URL, session: URLSession) async throws`, with an empty + default implementation. **Rename it in custom authorizers**: a type that + still implements `prepareAuthorization(for:session:)` continues to compile + because of the default, but the transport will never call it. Errors thrown + by `prepare(for:session:)` now fail the request with + `MCPError.transportError(_:)` (`CancellationError` is thrown as is), where + the previous release ignored them; `OAuthAuthorizer.prepare` still ignores + failed proactive renewals itself. +- `handleChallenge(_ challenge: HTTPAuthorizationChallenge, session: URLSession) async throws -> HTTPChallengeResult` + replaces `handleChallenge(statusCode:headers:endpoint:operationKey:session:)` + and `handleChallenge(statusCode:headers:endpoint:operationKey:sentAuthorization:session:)`. + `HTTPAuthorizationChallenge` carries `statusCode`, `headers`, `endpoint`, + `operationKey`, `sentAuthorization`, and `value(forHeader:)`, and redacts + header values, `sentAuthorization`, and URL userinfo, query, and fragment in + its descriptions and mirror. `HTTPChallengeResult` provides `.retry`, + `.retryWithDPoPNonce`, and `.unhandled`; `HTTPChallengeResult.init(shouldRetry:isDPoPNonceRetry:)` + sets `isDPoPNonceRetry` to `false` when `shouldRetry` is `false`. The + transport allows one `isDPoPNonceRetry` per request without counting it + against `maxAuthorizationAttempts`. `maxAuthorizationAttempts` (on + `HTTPClientAuthorizer` and `OAuthConfiguration.RetryPolicy`) counts total + attempts for one request, including the initial attempt (`1` allows no + non-nonce retry; the default `3` allows up to `2` retries). +- `didReceiveResponse(headers:for:)` is now `async` and receives the URL that + answered, after any redirects. +- `validateEndpointSecurity(for:)` is removed from both `HTTPClientAuthorizer` + and `OAuthAuthorizer`: `HTTPClientTransport` always checks that the endpoint + (and the URL after `requestModifier`) is `https`, or `http` on a loopback + host, without a fragment, before calling the authorizer. +- `OAuthScopeSelecting` and `OAuthWWWAuthenticateParsing` now refine + `Sendable`, because `OAuthAuthorizer` calls them from several tasks at once. +- `OAuthAccessToken` has a new stored property, `keyThumbprint`, with a + defaulted initializer parameter; tokens saved by the previous release decode + with `nil`. + +### `OAuthTokenStorage` + +`TokenStorage` and `InMemoryTokenStorage` are replaced by `OAuthTokenStorage` +(not class-bound, `: Sendable`) and `InMemoryOAuthTokenStorage`. Tokens are now +keyed by canonical resource `URL` (RFC 8707 §2) so one store can serve +authorizers for multiple servers, and every method is `async throws`: storage +errors fail the request with `MCPError.transportError(_:)`. + +Before: + +```swift +final class KeychainTokenStorage: TokenStorage { + func save(_ token: OAuthAccessToken) { ... } + func load() -> OAuthAccessToken? { ... } + func clear() { ... } +} +``` + +After: + +```swift +struct KeychainTokenStorage: OAuthTokenStorage { + func save(_ token: OAuthAccessToken, for resource: URL) async throws { ... } + func load(for resource: URL) async throws -> OAuthAccessToken? { ... } + func clear(for resource: URL) async throws { ... } +} +``` + +The resource key can change once the authorizer reads the server's protected +resource metadata (for example, from `https://mcp.example.com/mcp` to +`https://mcp.example.com`). For a store that persists tokens across launches, +set `OAuthConfiguration.EndpointOverrides(resource:)` to the server's resource +so the first request after launch finds its token immediately. + +### `HTTPClientTransport` `requestModifier` + +`HTTPClientTransport.init`'s `requestModifier` changed from +`(URLRequest) -> URLRequest` to +`@Sendable (inout URLRequest) async throws -> Void` (default `{ _ in }`). It +runs after the transport's headers and before the authorizer's headers and +`Mcp-Session-Id`. An error it throws fails the request with +`MCPError.transportError(_:)`, and its time does not count against +`Client.Configuration.discoveryTimeout`. + +Before: + +```swift +let transport = HTTPClientTransport( + endpoint: endpoint, + requestModifier: { request in + var modified = request + modified.setValue("value", forHTTPHeaderField: "X-Custom") + return modified + } +) +``` + +After: + +```swift +let transport = HTTPClientTransport( + endpoint: endpoint, + requestModifier: { request in + request.setValue("value", forHTTPHeaderField: "X-Custom") + } +) +``` + +### `Transport` protocol + +`Transport` is frozen for 1.0 with `TransportSendOptions`, `TransportWrapper`, +and six defaulted protocol hooks replacing concrete transport downcasts in +`Client` and `Server`: + +- `Transport.logger` is now `nonisolated`. +- `send(_ data: Data, options: TransportSendOptions) async throws` replaces + `send(_ data: Data) async throws` as the protocol requirement. A default + extension provides `send(_ data: Data)` forwarding with empty options, so + call sites passing only `Data` still compile. +- `receive()` is now `async` (existing `await transport.receive()` calls still + compile). +- Six hooks with default implementations handle optional transport features: + `didNegotiate(protocolVersion:)`, `abandonRequest(_:)`, + `authorizationEnd(of:)`, `prepare(servingProtocolVersions:)`, + `isSessionless`, and `httpRequest(for:)`. Wrap another transport with + `TransportWrapper` to forward every hook automatically. +- `HTTPContextProviding` is removed: implement `Transport.httpRequest(for:)` + directly. `httpRequestContext(for:)` is renamed to `httpRequest(for:)` on + `StatefulHTTPServerTransport` and `StatelessHTTPServerTransport`. +- `HTTPClientTransport.updateNegotiatedProtocolVersion(_:)` is renamed to + `didNegotiate(protocolVersion:)`. + +Before: + +```swift +actor CustomTransport: Transport, HTTPContextProviding { + let logger: Logger + func send(_ data: Data) async throws { ... } + func receive() -> AsyncThrowingStream { ... } + func httpRequestContext(for id: ID) async -> HTTPRequest? { ... } +} +``` + +After: + +```swift +actor CustomTransport: Transport { + nonisolated let logger: Logger + func send(_ data: Data, options: TransportSendOptions) async throws { ... } + func receive() async -> AsyncThrowingStream { ... } + func httpRequest(for id: ID) async -> HTTPRequest? { ... } +} +``` + +### Async HTTP request validation + +`HTTPRequestValidationPipeline` is removed, and HTTP request validation is now +asynchronous so token and request validators can perform async work (such as +JWKS fetches or remote introspection) without blocking threads: + +- `StatefulHTTPServerTransport.init` and `StatelessHTTPServerTransport.init` + take `validators: [any HTTPRequestValidator] = defaultValidators` instead of + `validationPipeline:`. +- `HTTPRequestValidator.validate(_:context:)`, + `BearerTokenValidator.TokenValidator`, and + `StandardValidationPipeline.validate(_:context:)` are now `async`. +- Built-in SDK validators other than `BearerTokenValidator` (which awaits its + token validator) continue to run inline without suspending on the transport + actor; custom async validators suspend. + +Before: + +```swift +let transport = StatefulHTTPServerTransport( + validationPipeline: StandardValidationPipeline(validators: [ + OriginValidator.localhost(), + BearerTokenValidator( + resourceMetadataURL: metadataURL, + resourceIdentifier: resourceURL, + tokenValidator: { token, _, _ in .valid(BearerTokenInfo()) } + ), + ]) +) +// Or, for defaults: +let defaults = StatefulHTTPServerTransport(validationPipeline: nil) +``` + +After: + +```swift +let transport = StatefulHTTPServerTransport( + validators: [ + OriginValidator.localhost(), + BearerTokenValidator( + resourceMetadataURL: metadataURL, + resourceIdentifier: resourceURL, + tokenValidator: { token, _, _ in .valid(BearerTokenInfo()) } + ), + ] +) +// Or, for defaults (omit `validators:` or pass `StatefulHTTPServerTransport.defaultValidators`): +let defaults = StatefulHTTPServerTransport() +``` + +### `NetworkTransport` and `MCPError.isResourceTemporarilyUnavailable` + +- `NetworkTransport.HeartbeatConfiguration`, `NetworkTransport.BufferConfiguration`, + and `NetworkTransport.init(connection:logger:heartbeatConfig:reconnectionConfig:bufferConfig:)` + are removed. +- Use `NetworkTransport.init(connection:maximumMessageLength:connectionTimeout:reconnection:logger:)`: + - `maximumMessageLength` defaults to 16 MiB (`Int.max` removes the limit). + - `connectionTimeout` defaults to `.seconds(30)` (must be positive) and caps + both `connect()` and reconnections. + - `reconnection` defaults to `.disabled` (reconnection was on by default in + 0.12.1). Pass `.default` (or `NetworkTransport.ReconnectionConfiguration(...)`) + to opt back in. + - `NetworkTransport` no longer sends heartbeats (it still skips heartbeats + received from 0.12 peers). +- `MCPError.isResourceTemporarilyUnavailable(_:)` is removed: transports handle + `EAGAIN` internally, and `Client` and `Server` no longer retry `receive()` + after it. + +Before: + +```swift +let transport = NetworkTransport( + connection: connection, + heartbeatConfig: .disabled, + reconnectionConfig: .default, + bufferConfig: .unlimited +) +``` + +After: + +```swift +let transport = NetworkTransport( + connection: connection, + maximumMessageLength: .max, + connectionTimeout: .seconds(30), + reconnection: .default +) +``` + +### `Server.waitUntilCompleted()` + +`Server.waitUntilCompleted()` is now `async throws`. Every call without `try` +no longer compiles: add `try`, then handle or propagate the error. + +Before: + +```swift +try await server.start(transport: transport) +await server.waitUntilCompleted() +``` + +After: + +```swift +try await server.start(transport: transport) +try await server.waitUntilCompleted() +``` + +- It returns normally when the receive stream finishes (for example at the end + of standard input), when the stream throws `MCPError.connectionClosed` (the + peer closed the connection), or after `stop()` once the transport is + disconnected. +- It throws any other error the receive stream throws (for example + `MCPError.transportError` when a stdio read fails or a `NetworkTransport` + loses its connection), and it throws `start()`'s error when called during or + after a failed `start()`. +- As before, cancelling the calling task does not end the wait: call `stop()` + from a cancellation handler, and the wait returns once `stop()` has + disconnected the transport. +- `Server.start` throws `MCPError.internalError` if called while the server is + already starting or running (leaving the active run unaffected), or if + `stop()` is called while `connect()` is pending and `connect()` succeeds + (ending the run normally once `stop()` disconnects). + +### `Client.withBatch(isolation:body:)` and `Client.Batch` + +`Client.withBatch(body:)` took an `@escaping @Sendable` closure returning +`Void`, which prevented mutating local variables or actor state in Swift 6, and +`Client.Batch` was an `actor` that kept registering unsent requests if it +escaped `withBatch`. It is now: + +```swift +@discardableResult +public func withBatch( + isolation: isolated (any Actor)? = #isolation, + body: (Batch) async throws -> R +) async throws -> R +``` + +- Trailing-closure call sites compile unchanged, and a single-expression body + ending in `batch.addRequest(...)` needs no `_ =`. +- `body` inherits the caller's actor isolation and can return a value directly, + so `nonisolated(unsafe)` workarounds and collector actors can be removed. +- `Client.Batch` is now a `Sendable` struct instead of an `actor`. Calling + `addRequest(_:)` after `withBatch` returns now throws + `MCPError.internalError("Batch.addRequest(_:) was called after withBatch returned")`. ### Platforms @@ -407,9 +763,22 @@ these releases. `Server.Configuration` gained `protocolVersions`, `cacheHints` and `defaultCacheHint`; `Client.Configuration` gained `protocolMode`, `logLevel`, -`discoveryTimeout`, `multiRoundTrip` and `maxContextInclusion`. A missing key decodes to the default -of its initializer parameter, so JSON encoded by the previous release, -`{"strict":true}`, still decodes. +`discoveryTimeout`, `multiRoundTrip`, `tasks` and `maxContextInclusion`. A +missing key decodes to the default of its initializer parameter, so JSON +encoded by the previous release, `{"strict":true}`, still decodes. + +`Client.Configuration` and `Client.Configuration.Tasks` encode their durations +as whole-millisecond JSON keys (`discoveryTimeoutMs`, `minimumPollIntervalMs`, +`maximumPollIntervalMs`, `defaultPollIntervalMs` and `requestedTimeToLiveMs`) +instead of Swift `Duration`'s `[high, low]` attosecond representation. +`discoveryTimeoutMs: null` disables the timeout while an absent key keeps the +10-second default. Configurations saved by a prerelease under the old keys +(`discoveryTimeout`, `minimumPollInterval`, `maximumPollInterval`, +`defaultPollInterval`, `requestedTTL`) still decode. `TaskRecord` and +`CacheHint` pin their `CodingKeys`, and task RFC 3339 timestamps (`createdAt`, +`lastUpdatedAt`) clamp store dates outside +`1970-01-01T00:00:00Z...9999-12-31T23:59:59Z` (and `NaN` to the epoch) so +encoded timestamps are always valid four-digit-year dates. ### Sampling handlers see `includeContext` capped at `none` @@ -479,21 +848,16 @@ or a shorter `discoveryTimeout`. ### `data:` URL strings -The SDK no longer rewrites a `data:` URL string when it passes a message -through `Value`: the client and server message decoders, batches, -type-erased requests and responses, handler results and `_meta` accessors -keep the string as written. Error data that a server sends also keeps it, -but a decoded `MCPError` holds `.data(mimeType:_:)` in its `data`. A text -block, a URI or an icon `src` such as `data:,hi` arrives as sent; the -previous release delivered `data:text/plain;base64,aGk=`. A `Value` field the -application decodes, such as a tool argument or `structuredContent`, still -holds `.data(mimeType:_:)` for such a string, which encodes as a base64 -`data:` URL. - -A string is a `data:` URL only when its media type is empty or -`type/subtype` with RFC 2045 tokens, as RFC 2397 requires. Text such as -`data: 3 rows, 2 columns` now stays `.string`, and `Data.isDataURL(string:)` -and `Data.parseDataURL(_:)` refuse it. +Because `Value.data` is removed (see [`Value.data` and `DataURL`](#valuedata-and-dataurl)), +the SDK no longer parses or rewrites `data:` URL strings automatically anywhere +— not in messages, tool arguments, `structuredContent`, `_meta`, or +`MCPError.data`. A `data:` URL string such as `data:,hi` arrives verbatim as +`Value.string` instead of being rewritten as `data:text/plain;base64,aGk=`. + +`DataURL` (and the deprecated `Data.isDataURL(string:)` and +`Data.parseDataURL(_:)` shims) accepts a string as a `data:` URL only when its +media type is empty or `type/subtype` made of RFC 2045 tokens (RFC 2397 §3), +so prose such as `data: 3 rows, 2 columns` is rejected. ### Handlers @@ -548,11 +912,27 @@ and `Data.parseDataURL(_:)` refuse it. - A request is registered before `send(_:)` returns. `cancelRequest(_:reason:)` right after `send` always ends the request; a request cancelled before it was sent is not sent. -- `withBatch(body:)` requests get the 2026-07-28 `_meta` envelope, header - parameters and the multi round-trip loop. On a stateless connection they - are sent one by one. When the closure throws, its requests fail. When the - connection closes or is replaced while the closure runs, the batch is not - sent and `withBatch` throws `connectionClosed`. +- `withBatch(isolation:body:)` requests get the 2026-07-28 `_meta` envelope, + header parameters and the multi round-trip loop. On a stateless connection + they are sent one by one. When the closure throws, its requests fail. When + the connection closes or is replaced while the closure runs, the batch is not + sent and `withBatch` throws `connectionClosed` (even if the closure returns + normally). +- In strict mode (`Client.Configuration.strict`), `subscribeToResource(uri:)` + (both revisions) and `unsubscribeFromResource(uri:)` (handshake revisions) + now require the server to declare `resources.subscribe: true` and throw + `MCPError.methodNotFound` (-32601) when `subscribe` is `false` or omitted. + 0.12.1 only checked that `resources.subscribe` was non-`nil`, so `false` was + accepted. +- `Client.subscribedResourceURIs` now lists active handshake subscriptions + (added when `resources/subscribe` succeeds, removed when + `resources/unsubscribe` succeeds, and cleared on disconnect or reconnect) as + well as 2026-07-28 listen-stream subscriptions. Internally subscriptions are + tracked by exact Unicode scalars so canonically equivalent spellings stay + independent; the returned `Set` merges canonically equivalent + spellings into one entry while both remain subscribed. +- `ResourceSubscribe.Parameters` and `ResourceUnsubscribe.Parameters` now have + public `init(uri:)` initializers. - `.stateless(version)` no longer retries with another version on -32022: it connects at `version` or throws. @@ -627,7 +1007,8 @@ The specification's rules for sampling with tools (SEP-1577) are checked: `StatefulHTTPServerTransport` keeps at most `eventStoreCapacity` events (default 1000) and `eventStoreByteCapacity` bytes (default 16 MiB) per session for `Last-Event-ID` replay. The previous release kept every event until the -session ended. +session ended. Emitted event counters start at `1`, so a `Last-Event-ID` with +counter `0` is rejected with HTTP 400. ### Server default handlers @@ -645,6 +1026,39 @@ session ended. kept every started `Server` alive, so a server per session leaked one per session. +### Server-to-client request cancellation + +- `Server.requestSampling`, both `requestElicitation` overloads, and + `listRoots` now withdraw the outgoing request with `notifications/cancelled` + and throw `CancellationError` when the task awaiting them is cancelled. The + withdrawal waits for an in-flight request send to finish (skipping + `notifications/cancelled` if the request send fails) and finishes sending + before the awaiting handler resumes. If the client has already answered, the + answer is returned and no `notifications/cancelled` is sent. +- Over HTTP, after the client cancels the parent request whose handler awaits + one of these methods, the parent request's stream is already closed: + `StatefulHTTPServerTransport` sends `notifications/cancelled` on the + session's standalone GET stream (or stores it for replay when no GET stream + is open), and `StatelessHTTPServerTransport` drops it cleanly. On stdio, + `InMemoryTransport`, and `NetworkTransport`, the withdrawal arrives on the + connection as usual. +- `Server.cancelRequest(_:reason:)` is deprecated; cancel the task awaiting + `requestSampling`, `requestElicitation`, or `listRoots` instead. + +### Icon themes, response errors, and task equality + +- `Icon` decodes an unrecognized `theme` string as `nil` instead of failing the + enclosing tool, resource, or prompt listing. `Icon.Theme` remains frozen in + 1.x; treat `theme == nil` as usable with any theme. Because unrecognized + themes decode as `nil`, such an icon compares equal to one with no theme and + omits `theme` if re-encoded. +- `Response.init(from:)` re-decodes a present `result` or `error` member on + failure so `DecodingError` reports the failing coding path (such as + `result.tools[0].name`) instead of a generic root `"Invalid response"` error. +- `TaskSnapshot` equality and hashing ignore its internal wire-generation + field, so a task decoded from 2025-11-25 compares equal to the same task + constructed with `init`. + ### HTTP client transport - A non-2xx response with a JSON-RPC error body for the request (same ID) is @@ -681,20 +1095,87 @@ session ended. transport to reconnect. The previous release raised an exception at the next send on Apple platforms. `disconnect()` also ends a notification's POST still waiting for its response. - -### Stdio and network transports +- `Mcp-Session-Id` on a reply to a 2026-07-28 request, or on a transport + configured for 2026-07-28, is ignored and does not open a standalone GET + stream. When a transport configured for 2026-07-28 falls back to `initialize` + against a handshake-only server, it still records `Mcp-Session-Id` from the + `initialize` reply and opens the GET stream once `didNegotiate` switches to + the handshake revision. +- Redirect handling: + - `Authorization`, `Proxy-Authorization`, `Cookie`, and `Mcp-Session-Id` are + sent only on same-origin redirects and stripped once a redirect goes to + another origin (and stay stripped on any later hop, including a chain back + to the initial origin). Credentials in + `URLSessionConfiguration.httpAdditionalHeaders` are separated by + `HTTPClientTransport.init` so they apply only to same-origin MCP requests + and never reach cross-origin redirects or the authorizer's own token, + discovery, or registration requests; `ServerCard.fetch` and OAuth + discovery/token requests apply the same separation. + - With an authorizer, each same-origin redirect calls + `authorizationHeaders(for:method:)` again for the target URL and method (so + DPoP proofs are freshly signed for the new hop and no stale `Authorization` + header is carried when the authorizer returns empty); `DPoP` headers are + stripped when not re-signed. + - Redirects to non-HTTP(S) schemes, `https` to `http` downgrades, and hops + crossing between remote and loopback or unspecified hosts (such as + `localhost`, `*.localhost`, `127.0.0.0/8`, `::1`, `0.0.0.0`, `::`, and + IPv4-mapped/translated forms) are refused. Non-loopback private network + addresses (RFC 1918) remain allowed for MCP requests. + - A `401` or `403` after a cross-origin redirect (which carried no + credentials, including chains that return to the original origin) fails + immediately with `OAuthAuthorizationError.protectedResourceMismatch` + without calling `handleChallenge(_:session:)`. + - A `404` from a redirected hop that did not carry `Mcp-Session-Id` does not + mark a live session expired (`HTTPStatusError.isSessionExpired` is `true` + only when `Mcp-Session-Id` was sent on that hop). + - On Linux, `HTTPClientTransport` follows up to 20 redirects itself, + preserving request bodies on 307 and 308 redirects and stripping + representation headers (`Content-Type`, `Content-Length`, + `Content-Encoding`, `Content-Language`, `Content-Location`) and `Host` when + 301, 302, or 303 rewrite a request to `GET`. + +### Stdio, network, and in-memory transports - A received message longer than 16 MiB, the limit of an SSE line on the HTTP client transport, ends the receive stream of `StdioTransport` and `NetworkTransport` with `internalError`. That closes the connection: a `Client` fails its pending requests with the error, and `NetworkTransport` cancels its `NWConnection`. The previous release buffered the message however - long it grew. A `NetworkTransport` whose - `BufferConfiguration.maxReceiveBufferSize` is larger than 16 MiB accepts - messages up to that size, and one with `BufferConfiguration.unlimited` keeps - no limit. `StdioTransport` has no setting that raises or removes the limit, - so a peer that sends a longer message over stdio, such as a large resource or - image as base64, ends the connection. + long it grew. On `NetworkTransport`, pass `maximumMessageLength:` to raise + the limit (`Int.max` removes it). `StdioTransport` has no setting that raises + or removes the limit, so a peer that sends a longer message over stdio, such + as a large resource or image as base64, ends the connection. +- `StdioTransport` no longer changes `O_NONBLOCK` on its descriptors and uses + dispatch-source readiness instead of polling. Read errors (such as `EIO` or + `ECONNRESET`) finish its receive stream with `MCPError.transportError` + instead of ending the stream like end of input. +- `NetworkTransport` reconnection is off by default; `connectionTimeout` + (30 seconds by default) bounds `connect()` and reconnects, and `.waiting` + states do not consume retry attempts. A graceful peer close (final content + context) finishes the stream with `MCPError.connectionClosed`, while a + non-final completed context (such as a UDP datagram or WebSocket message) + keeps the stream open. With reconnection off, a lost connection finishes the + stream with `MCPError.transportError` carrying the `NWError`; a failed send + does not trigger reconnection. +- Every SDK transport (`HTTPClientTransport`, `StdioTransport`, + `NetworkTransport`, and `InMemoryTransport`) serves a single connection: + `connect()` after `disconnect()` throws `internalError` (create a new + transport to reconnect), and sends after `disconnect()` or peer close throw + `MCPError.connectionClosed`. Disconnected `InMemoryTransport` pairs clear + their peer reference so both actors deallocate. + +### Exact code-point matching and 32-bit safety + +- JSON-RPC `ID`, `ProgressToken`, task IDs and owners, method names, SEP-2243 + `Mcp-Method`/`Mcp-Name`/`Mcp-Param-*` headers and schema argument keys, + resource subscription URIs, and `RequestState` audiences now compare by exact + Unicode scalars rather than Swift canonical `String` equivalence. Canonically + equivalent spellings (such as `"K"` vs `"\u{212A}"`, or NFC vs NFD forms) no + longer match each other, and a `tools/call` argument key that matches a + header-annotated schema property only by canonical equivalence is rejected + with -32020. +- Wire-controlled integers that exceed `Int` bounds on 32-bit platforms + saturate instead of trapping. ### Authorization @@ -729,12 +1210,12 @@ session ended. for less than the window is renewed halfway between its issue and 30 seconds before its expiry. The previous release refreshed before every request while the token was within the window, also after a failure; -- handle concurrent challenges one at a time. `InMemoryTokenStorage` is now - thread-safe; custom `TokenStorage` implementations are called from several - tasks. A challenge that waited for one that failed and left no usable - token fails with the same error instead of running the flow again (one - prompt for a cancelled authorization), and a waiting request can be - cancelled; +- handle concurrent challenges one at a time. `InMemoryOAuthTokenStorage` + (replacing `InMemoryTokenStorage`) is thread-safe and keyed per resource; + custom `OAuthTokenStorage` implementations are called from several tasks. A + challenge that waited for one that failed and left no usable token fails with + the same error instead of running the flow again (one prompt for a cancelled + authorization), and a waiting request can be cancelled; - register again on the next flow when dynamic client registration throws. The previous release did not try again until the authorizer was recreated; - treat a `.none(clientID:)` client ID that is not empty and not a URL as @@ -777,7 +1258,23 @@ session ended. swift-crypto, so they work on Linux. `pkceS256Unavailable` and `cryptographyUnavailable` are no longer thrown; - read a `DPoP` challenge (RFC 9449) for `resource_metadata`, `scope` and - `error` when the response has no `Bearer` challenge. + `error` when the response has no `Bearer` challenge; +- canonicalize resource URIs per RFC 3986 §6 (lowercase scheme and host, no + userinfo, default port, query, fragment, dot segments, or trailing slash, + uppercase percent-encoding, and rejecting hostless URLs such as `https:///`), + including `endpointOverrides.resource`. For a server where a trailing slash is + significant, pass a custom `OAuthMetadataDiscovering` wrapper around + `DefaultOAuthMetadataDiscovery` to `OAuthAuthorizer`. When discovery changes + the resource key, a token reloaded under the new key is used only if issued + by an authorization server listed in the protected resource metadata, bound + to the configured DPoP signing key (when DPoP-bound), and DPoP-bound when + the resource metadata sets `dpop_bound_access_tokens_required` (including + raising `dpopRequired` when DPoP is not configured); +- normalize DPoP nonce storage keys by origin (ASCII-lowercased `encodedHost` + with default ports `443` and `80` omitted); +- compute `private_key_jwt` `iat` and `exp` claims as `Int64` `NumericDate`s + (safe past 2038 on 32-bit platforms) and reject non-finite or out-of-range + dates and lifetimes. ### Package @@ -799,11 +1296,12 @@ released `MCP` version now resolves. These commits on `main` (`a0ae212..234e412`) are part of 1.0.0: -- `Data.parseDataURL(_:)` takes `;base64` from the header only: - `data:text/plain,hello;base64,world` is a text URL, where the previous - release returned `nil` (#309). A payload without `;base64` decodes every - percent-escaped byte, so `%FF` no longer makes it fail (#310). `Value` - decodes such strings as `.data(mimeType:_:)`. +- `DataURL` (and the deprecated `Data.parseDataURL(_:)` shim) takes `;base64` + from the header only: `data:text/plain,hello;base64,world` is a text URL, + where the previous release returned `nil` (#309). A payload without + `;base64` decodes every percent-escaped byte, so `%FF` no longer makes it + fail (#310). Because `Value.data` is removed, `Value` keeps these strings as + `.string` until parsed with `DataURL(_:)`. - `client_secret_basic` percent-encodes the client ID and secret (`application/x-www-form-urlencoded`, RFC 6749 §2.3.1) before the Base64 step; the previous release sent them verbatim, so a credential with `:`, @@ -823,35 +1321,29 @@ These commits on `main` (`a0ae212..234e412`) are part of 1.0.0: process exited. After five consecutive empty reads on a connection that is no longer ready, the receive stream finishes with `connectionClosed` and the connection is cancelled, where the receive loop - ended and `receive()` kept waiting (#283). The transport then also counts - as disconnected and stops its heartbeats, which the previous release kept - sending to the closed connection (#326). + ended and `receive()` kept waiting (#283). Heartbeats are no longer sent in + 1.0.0 (#326). - `NetworkTransport` clears the connection's state update handler on the actor's executor when a connection attempt ends. The previous release also cleared it from the state stream's termination callback, on any thread, a data race (#301). -- `NetworkTransport.connect()` retries by dialing a fresh connection to the - same endpoint instead of restarting the cancelled `NWConnection`, which the - platform does not allow, so a retry now completes. `connect()` no longer - blocks indefinitely on an unreachable peer: a `.waiting` connection counts as - a failed attempt, so the configured `maxAttempts` and backoff apply and - `connect()` throws once they are exhausted. Code that connected while offline - and relied on `NWConnection` waiting for connectivity fails instead. - `disconnect()` stops a `connect()` in progress. A second `connect()` while - one is in progress throws instead of replacing the first one's connection, - and that includes a `connect()` stopped by `disconnect()` until it has - returned, which can take the rest of its backoff. A `connect()` after that - dials a fresh connection. A retry dials `connection.endpoint`, so it is for - outbound (client) connections; a connection accepted from an `NWListener` - cannot be rebuilt this way. +- `NetworkTransport.connect()` retries (when reconnection is enabled) by + dialing a fresh connection to the same endpoint instead of restarting the + cancelled `NWConnection`, which the platform does not allow, so a retry now + completes. `connect()` no longer blocks indefinitely on an unreachable peer: + `connectionTimeout` (30 seconds by default) bounds the dial while `.waiting` + states wait without consuming retry attempts. `disconnect()` stops a + `connect()` in progress, and `connect()` after `disconnect()` throws + `internalError` (create a new transport to reconnect). A second `connect()` + while one is in progress throws instead of replacing the first one's + connection. A retry dials `connection.endpoint`, so it is for outbound + (client) connections; a connection accepted from an `NWListener` cannot be + rebuilt this way. - `StdioTransport.disconnect()` waits for the read loop and the sends in - progress, then turns `O_NONBLOCK` off again on each descriptor that was - blocking at `connect()` and still refers to the same file, and then - finishes the receive stream. The previous release left both descriptors - non-blocking, which also affects other users of the process's stdin and - stdout. A send in progress throws `transportError` (ENOTCONN) before its - next write once `disconnect()` is called, and `connect()` waits for a - `disconnect()` in progress (#297). + progress, then finishes the receive stream; in 1.0.0, `StdioTransport` never + changes `O_NONBLOCK` on its descriptors (#297). A send in progress throws + `connectionClosed` once `disconnect()` is called, and `connect()` after + `disconnect()` throws `internalError`. Three commits add API, listed in [New opt-in features](#new-opt-in-features): `Server.init` takes `description`, `websiteUrl` and `icons` (#258), @@ -889,11 +1381,12 @@ CODEOWNERS changed (#155, #294, #306, #308, #318, #320, #331, #333). | Sealed request state | `Server.init(requestStateProtection:)`, `RequestStateProtection`, `AESGCMRequestStateCodec`, `RequestStateCodec` | [server.md](server.md#protecting-requeststate) | | Cache hints | `CacheableResult`, `ttlMs`, `cacheScope`, `CacheHint`, `Server.Configuration.cacheHints` | [server.md](server.md#cacheable-results) | | Result type | `ResultType`, `resultType` on the three input-capable results | [server.md](server.md#multi-round-trip-requests) | -| Request headers (SEP-2243) | `MCPRequestHeaders`, `Tool.headerParameters()`, `Transport.send(_:additionalHeaders:)`, with a default, and `HTTPClientTransport.send(_:additionalHeaders:)` | [protocol.md](protocol.md#request-headers-sep-2243), [custom transports](protocol.md#custom-transports) | +| Request headers (SEP-2243) | `MCPRequestHeaders`, `Tool.headerParameters()`, `TransportSendOptions.headers`, `Transport.send(_:options:)` | [protocol.md](protocol.md#request-headers-sep-2243), [custom transports](protocol.md#custom-transports) | | HTTP routing | `HTTPRequest.statelessProtocolVersion` | [protocol.md](protocol.md#routing-both-eras-on-one-endpoint) | -| Per-request transport streams | `Transport.send(_:relatedRequestID:)`, with a default | [protocol.md](protocol.md#custom-transports) | +| Per-request transport streams | `TransportSendOptions.relatedRequestID`, `Transport.send(_:options:)` | [protocol.md](protocol.md#custom-transports) | +| Wrapping transports | `TransportWrapper` | [custom transports](protocol.md#custom-transports) | +| Async HTTP validators | `StatefulHTTPServerTransport(validators:)`, `StatelessHTTPServerTransport(validators:)`, `defaultValidators` | [protocol.md](protocol.md#transports) | | Gate requests without `initialize` | `statelessRequestHook` of `Server.start(transport:initializeHook:statelessRequestHook:)`, `Server.StatelessRequestHook` | [server.md](server.md#the-initialize-hook) | -| Abort a request's POST | `HTTPClientTransport.cancelRequest(_:)` | [protocol.md](protocol.md#http-client) | | Capability extensions | `extensions` on both capability structs | [server.md](server.md#capabilities-and-extensions) | | Log level order | `LogLevel: Comparable` | [server.md](server.md#logging) | | OAuth | `OAuthConfiguration.ApplicationType`, `OAuthAuthorizationCodeFlow.ExpectedIssuer` | [protocol.md](protocol.md#authorization) | @@ -902,4 +1395,5 @@ CODEOWNERS changed (#155, #294, #306, #308, #318, #320, #331, #333). | Replay store size | `StatefulHTTPServerTransport(eventStoreCapacity:)` | [protocol.md](protocol.md#transports) | | Server metadata | `Server.init(name:version:title:description:websiteUrl:icons:instructions:capabilities:configuration:requestStateProtection:)`: sent in the `initialize` result and, at 2026-07-28, in `_meta["io.modelcontextprotocol/serverInfo"]` of every result, with `data:` icon URLs as written | [server.md](server.md#creating-a-server) | | `Value` | `Value.numberValue` (`.int` or `.double` as `Double`); `Value.init(_:)` takes any `Encodable`, not only `Codable` | [server.md](server.md#calling-tools) | +| `data:` URLs | `DataURL` (`init(_:)`, `init(data:mimeType:)`, `Codable`) | [server.md](server.md#calling-tools) | diff --git a/docs/src/protocol.src.md b/docs/src/protocol.src.md index 529a90af..20a144a5 100644 --- a/docs/src/protocol.src.md +++ b/docs/src/protocol.src.md @@ -157,7 +157,7 @@ A transport moves JSON-RPC messages between a client and a server. In the SDK a | `StatefulHTTPServerTransport` | server | handshake | One instance per `Mcp-Session-Id`. | | `StatelessHTTPServerTransport` | server | 2026-07-28 (and sessionless handshake use) | One instance for all requests. | | `InMemoryTransport` | both | both | Same process; tests and embedding. | -| `NetworkTransport` | both | both | Network.framework `NWConnection`; Apple platforms only. | +| `NetworkTransport` | both | both | Network.framework `NWConnection`; Apple platforms only. A peer on the local network needs Local Network access (`NSLocalNetworkUsageDescription`); on watchOS, use `HTTPClientTransport`. | The HTTP server transports do not open sockets. They take a framework-neutral `HTTPRequest` and return an `HTTPResponse`; an adapter for your HTTP framework converts between the two. [`Examples/http-server/main.swift`](../Examples/http-server/main.swift) is a complete adapter for SwiftNIO that serves both eras. @@ -169,13 +169,13 @@ A server started by its client reads requests from stdin and writes responses to %include Examples/Snippets/Protocol/Transports.swift transport-stdio-server -`waitUntilCompleted()` returns when the message loop ends, which happens when stdin closes. +`waitUntilCompleted()` returns when the message loop ends, which happens when stdin closes, and throws `MCPError.transportError` with the error when a read from stdin fails. The SDK has no process-launching transport. A client starts the server itself and passes the pipe file descriptors to `StdioTransport(input:output:logger:)`: %include Examples/Snippets/Protocol/Transports.swift transport-stdio-client -`send` fails with `MCPError.transportError` (ENOTCONN) before `connect()` or after `disconnect()`. `connect()` makes the descriptors non-blocking; `disconnect()` waits for the read loop and the sends in progress, then makes blocking again each descriptor that was blocking and still refers to the same file. The protocol era is independent of stdio: with `.automatic` the client sends `server/discover` over the pipe like any other request. +`send` fails with `MCPError.connectionClosed` after `disconnect()`, and with `MCPError.transportError` (ENOTCONN) before `connect()`. The transport never changes the descriptors' flags, and works with blocking and non-blocking descriptors alike. On a pipe, a socket or a terminal it waits until the descriptor is ready before each read and write; the wait blocks no thread, and an idle transport never wakes up. A regular file or a device such as `/dev/null` is read and written directly. The read or write itself runs on the transport's actor, so on a blocking descriptor that another process reads or writes too, or on a terminal that reports room for less than `PIPE_BUF` bytes, one call can block and hold up the transport until it returns. `disconnect()` ends a read or a send that is waiting, waits for the read loop and the sends in progress, and leaves the descriptors open. The end of the input finishes the receive stream normally; a read that fails, for example with `EIO`, finishes it by throwing `MCPError.transportError` with the error, and the client fails its pending requests with that error instead of `MCPError.connectionClosed`. Sends still work after either, until `disconnect()`. The protocol era is independent of stdio: with `.automatic` the client sends `server/discover` over the pipe like any other request. ### HTTP client @@ -188,12 +188,12 @@ What the transport sends depends on the era of each message: | | Handshake connection | 2026-07-28 connection | |---|---|---| | `MCP-Protocol-Version` | negotiated version, after `initialize` | from the message's `_meta` | -| `Mcp-Session-Id` | the ID the server returned on `initialize` | never; `useStatelessProtocol(_:)` drops it | +| `Mcp-Session-Id` | the ID the server returned on `initialize` | never; `didNegotiate(protocolVersion:)` drops it | | `Mcp-Method`, `Mcp-Name`, `Mcp-Param-*` | not sent | sent (see [request headers](#request-headers-sep-2243)) | | GET stream | opened when `streaming` is `true` | closed and never opened | | `Last-Event-ID` resumption | on the GET stream and on POST response streams | not used: a response stream that ends early fails its request | -The client switches the transport when the connection opens: `Client` calls `updateNegotiatedProtocolVersion(_:)` after `initialize` and `useStatelessProtocol(_:)` after `server/discover`. +The client switches the transport when the connection opens: `Client` calls the transport's `didNegotiate(protocolVersion:)` after `initialize` and after `server/discover`. At 2026-07-28 the transport then drops the session ID and the GET stream. On handshake connections with `streaming: true`, the transport waits up to `sseInitializationTimeout` (10 s) for a session ID, then opens the GET stream for server-initiated messages. When the stream ends it reconnects after the server's SSE `retry:` interval (3000 ms by default) and sends `Last-Event-ID` with the last event ID it saw. A 405 on GET stops the stream, and so does a 404 on a GET that carried the session ID: the stream is not reopened, and the session ID is kept. The next request carries it, receives the server's 404, drops the session and reports `isSessionExpired`. A line, or the data of one event, over 16 MiB ends the stream, and the next GET opens a fresh stream without `Last-Event-ID`, since a replay would repeat the event; that event is lost. @@ -213,7 +213,7 @@ Without a JSON-RPC error for the request, the transport throws `MCPError.transpo | 404 | To a POST that carried the session ID: `isSessionExpired` is `true` (for each such POST in flight), the session ID is dropped and the GET stream stops. To the GET stream: the stream stops, and the session ID is kept for the next request | | 405 | On the GET stream, the stream stops; a 405 to a POST does not stop it | -To add headers to every request (an API key, a user agent), pass `requestModifier`. For OAuth, pass an `authorizer` (see [Authorization](#authorization)). +To add headers to every request (an API key, a user agent), pass `requestModifier`. It changes each request in place, and it may suspend and throw: an error fails the request with `MCPError.transportError(_:)`. It runs after the transport's headers and before the authorizer's, which it can't replace. It sees the current `Mcp-Session-Id`, but the transport sets that header again after the modifier and the authorizer, since another request may have replaced or dropped the session meanwhile. Like the authorizer's, its time doesn't count against `discoveryTimeout`, so it can wait for the user, for example to unlock a Keychain item. For OAuth, pass an `authorizer` (see [Authorization](#authorization)). ### Stateful HTTP server @@ -229,7 +229,7 @@ To add headers to every request (an API key, a user agent), pass `requestModifie Requests whose `MCP-Protocol-Version` is a stateless revision get 400 with -32022 and `data.supported` set to the handshake revisions, so a client in `.automatic` mode falls back to `initialize`. -The default validation pipeline is `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .sseRequired)`, `ContentTypeValidator()`, `ProtocolVersionValidator()`, `SessionValidator()`. Pass `validationPipeline:` to replace it, for example to add authentication or allow other hosts. `sessionIDGenerator:` replaces the UUID generator; IDs must be visible ASCII (0x21-0x7E) or the transport answers 500. `retryInterval:` sets the SSE `retry:` field of the priming event; priming events are sent at 2025-03-26 through 2025-11-25. +The default validators, `StatefulHTTPServerTransport.defaultValidators`, are `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .sseRequired)`, `ContentTypeValidator()`, `ProtocolVersionValidator()`, `SessionValidator()`. Pass `validators:` to replace them, for example to add authentication or allow other hosts. The transport runs them in order, and the first that returns a response ends the request. A validator may suspend (`validate` is `async`), but the built-in ones other than `BearerTokenValidator` run without suspending, so with them each request is handled without other requests in between. While a validator suspends, the transport handles other requests: it validates a request again when its session is created, or dropped by a refused `initialize`, meanwhile, and answers a request whose session ended meanwhile as one on a terminated session. A `notifications/cancelled` whose validators finish before those of the request it cancels is ignored. `sessionIDGenerator:` replaces the UUID generator; IDs must be visible ASCII (0x21-0x7E) or the transport answers 500. `retryInterval:` sets the SSE `retry:` field of the priming event; priming events are sent at 2025-03-26 through 2025-11-25. Your HTTP layer keeps one transport and one `Server` per session and routes by `Mcp-Session-Id`. The snippet leaves out what a deployed router needs: create a session only for a POST `initialize`, cap the number of sessions, and close idle ones, as [`Examples/http-server/main.swift`](../Examples/http-server/main.swift) does: @@ -242,10 +242,11 @@ Validation errors: | Status | Cause | |---|---| | 400 | Empty or invalid JSON-RPC body; missing `Mcp-Session-Id`, including after termination; request before `initialize`; second `initialize`; unsupported `MCP-Protocol-Version` (-32022); a stateless request (-32022). | -| 404 | Unknown or expired session ID, including any ID sent after the session ended. A transport stopped before a session existed answers 400, as before `initialize`. | +| 404 | Unknown or expired session ID, including any ID sent after the session ended, and a request whose session ended while its validators ran. A transport stopped before a session existed answers 400, as before `initialize`. | | 403, 421 | `Origin` or `Host` not allowed by `OriginValidator`. | | 406 | POST `Accept` lacks `application/json` or `text/event-stream`; GET `Accept` lacks `text/event-stream`. | | 415 | `Content-Type` is not `application/json`. | +| 503 | A POST, GET or DELETE whose session was created, or dropped by a refused `initialize`, during each of three runs of its validators. | ### Stateless HTTP server @@ -260,9 +261,9 @@ Validation errors: - A POSTed `notifications/cancelled` is honored only when it carries the same `Authorization` header as exactly one request in flight with that id (compared by value: `1` and `"1"` differ). The cancelled request's HTTP response then ends without a JSON-RPC response: 202 Accepted when no reply was sent yet, or the end of its SSE stream. - An open SSE reply carries a `: keep-alive` comment every `keepAliveInterval` (15 seconds; `nil` turns it off), so that idle listen streams survive client and proxy timeouts. - At 2026-07-28 JSON-RPC errors get an HTTP status: 404 for -32601; 400 for -32600, -32602, -32020, -32021 and -32022; 200 otherwise. -- After `disconnect()` every request gets 404; a request in flight at that moment gets 503. +- After `disconnect()` every request gets 404, also one whose validators were still running; a request in flight at that moment gets 503. -The default pipeline is `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .jsonOnly)`, `ContentTypeValidator()`, `ProtocolVersionValidator()`. The transport accepts the versions in `Version.stateless + Version.handshake`; the `Server` then applies its own `protocolVersions`. +The default validators, `StatelessHTTPServerTransport.defaultValidators`, are `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .jsonOnly)`, `ContentTypeValidator()`, `ProtocolVersionValidator()`; pass `validators:` to replace them. The transport accepts the versions in `Version.stateless + Version.handshake`; the `Server` then applies its own `protocolVersions`. A 2026-07-28 request over HTTP needs these headers and `_meta` keys: @@ -301,7 +302,7 @@ At 2026-07-28 the HTTP transports mirror parts of the body in headers so that pr | `Mcp-Name` | `params.name` (`tools/call`, `prompts/get`) or `params.uri` (`resources/read`) | those methods | | `Mcp-Param-` | a `tools/call` argument whose input schema property has `"x-mcp-header": ""` | `tools/call` | -The client adds `Mcp-Method` and `Mcp-Name` in `HTTPClientTransport` when `Version.profile(for:).usesStandardHeaders` is `true`. It adds `Mcp-Param-*` from the schemas it saw in `tools/list` results, and passes them to the transport's `send(_:additionalHeaders:)` (see [custom transports](#custom-transports)); call `listTools()` before `callTool` to get them. Values that are empty, contain characters outside printable ASCII, have a leading or trailing space, or look like an encoded value are sent as `=?base64??=`. Annotated properties must be `string`, `integer` or `boolean`, reached only through `properties`, with header names made of token characters and unique without regard to case. At 2026-07-28 a tool with an invalid annotation is dropped from `tools/list` results, by the server before it sends them and by the client when it receives them, with a logged warning. +The client adds `Mcp-Method` and `Mcp-Name` in `HTTPClientTransport` when `Version.profile(for:).usesStandardHeaders` is `true`. It adds `Mcp-Param-*` from the schemas it saw in `tools/list` results, and passes them to the transport in `send(_:options:)`'s `options.headers` (see [custom transports](#custom-transports)); call `listTools()` before `callTool` to get them. Values that are empty, contain characters outside printable ASCII, have a leading or trailing space, or look like an encoded value are sent as `=?base64??=`. Annotated properties must be `string`, `integer` or `boolean`, reached only through `properties`, with header names made of token characters and unique without regard to case. At 2026-07-28 a tool with an invalid annotation is dropped from `tools/list` results, by the server before it sends them and by the client when it receives them, with a logged warning. `MCPRequestHeaders` exposes the codec for custom transports and gateways: @@ -317,13 +318,35 @@ On the server, `StatelessHTTPServerTransport` checks `Mcp-Method` and `Mcp-Name` ### Custom transports -A transport is an actor with a `logger`, `connect()`, `disconnect()`, `send(_:)` and `receive()`. Each `Data` value is one complete JSON-RPC message or batch. `receive()` returns the same stream every time; finish it when the connection ends so the client or server loop exits. +A transport is an actor with a `nonisolated` `logger`, `connect()`, `disconnect()`, `send(_:options:)` and `receive()`. Each `Data` value is one complete JSON-RPC message or batch, without framing. `Client` and `Server` rely on this contract: + +- `connect()` throws when the transport is already connected, and after `disconnect()`: a transport serves one connection. +- `disconnect()` can be called any number of times, also before `connect()`, and finishes the stream `receive()` returns. +- `send(_:options:)` throws `MCPError.connectionClosed` after `disconnect()`, and once the transport knows the peer can no longer read. +- `receive()` returns the same stream on every call. Iterate it from one task only: two concurrent iterators of an `AsyncThrowingStream` trap. The client and server iterate it themselves; a wrapper that taps it iterates the wrapped transport's stream and returns its own. +- The end of the stream, normally or with an error, means the peer sends nothing more: the client stops reading and disconnects, and the server stops reading. A transport may still send, as `StdioTransport` does after the end of its input. %include Examples/Snippets/Protocol/Transports.swift transport-custom -`send(_:relatedRequestID:)` has a default implementation that calls `send(_:)`. The server passes the id of the request whose handler produced a notification or a server-to-client request. Override it when your transport has a stream per request, as the HTTP server transports do. To expose HTTP details to handlers, also conform to `HTTPContextProviding` and return the `HTTPRequest` for a request id. +`send(_:options:)` gets what the transport needs besides the bytes, in `TransportSendOptions`: + +- `relatedRequestID`: the server passes the id of the request whose handler produced a notification or a server-to-client request. A transport with a stream per request, as the HTTP server transports have, delivers the message on that request's stream. +- `headers`: at 2026-07-28 the client passes the `Mcp-Param-*` headers of a `tools/call` (see [request headers](#request-headers-sep-2243)). A Streamable HTTP transport sends them on the request's POST, as `HTTPClientTransport` does. A server that serves 2026-07-28 answers a call without its headers with -32020. -`send(_:additionalHeaders:)` also has a default implementation, which ignores the headers and calls `send(_:)`. At 2026-07-28 the client passes the `Mcp-Param-*` headers of a `tools/call` to it (see [request headers](#request-headers-sep-2243)), and only when there are headers to send. A Streamable HTTP transport sends them on the request's POST, as `HTTPClientTransport` does; a transport that wraps another one forwards them. A server that serves 2026-07-28 answers a call without its headers with -32020. +A transport that is not HTTP ignores both. `send(_:)`, without options, is a convenience that calls `send(_:options:)`. + +The client and server also call hooks on every transport. Each has a default implementation that does nothing; implement the ones that apply: + +| Hook | Called by | For | +|---|---|---| +| `didNegotiate(protocolVersion:)` | client, after `initialize` and `server/discover` | the version header; dropping the session at 2026-07-28 | +| `abandonRequest(_:)` | client, when a 2026-07-28 request is cancelled or `server/discover` times out | closing the request's exchange; return `true` when that tells the server, so the client sends no `notifications/cancelled` | +| `authorizationEnd(of:)` | client, while `server/discover` waits | not counting a sign-in against `discoveryTimeout` | +| `prepare(servingProtocolVersions:)` | server, in `start(transport:)` before `connect()` | the versions -32022 lists | +| `isSessionless` | server | serving each handshake request on its own, without `initialize` | +| `httpRequest(for:)` | server, before each handler | `HandlerContext.httpContext` | + +A transport that wraps another one, to log or count messages, adopts `TransportWrapper`: it forwards every requirement and hook to `wrapped`, so the wrapped transport keeps its behavior. Implement only what the wrapper changes, with the exact signature from `Transport`: a method whose signature only nearly matches a requirement compiles and is never called. [Troubleshooting](troubleshooting.md#recording-the-messages) has an example. ### Concurrency @@ -396,7 +419,7 @@ By default any caller may listen to any list change and resource URI. To restric Most clients do not call `listen` directly: - At 2026-07-28 the client keeps one background stream for the list kinds that have a registered handler and that the server declares, and for the subscribed resources. When the filter changes, the client opens the new stream and cancels the old one after the new one is acknowledged; if the new one fails, the old one stays. Until the old stream ends, its notifications that the client still wants are delivered, so one sent during the replacement may arrive twice. A stream that ends is reopened with a backoff from 1 to 60 seconds that keeps growing while streams end within a minute, even after being acknowledged; a failed reopen keeps the subscribed resources. That includes a stream the server ends with its result, for example when it stops for a restart. -- `subscribeToResource(uri:)` adds the URI to that stream at 2026-07-28 and waits for an acknowledgement that names it; on handshake connections it sends `resources/subscribe`. `unsubscribeFromResource(uri:)` replaces the stream with one without the URI, or sends `resources/unsubscribe`. `subscribedResourceURIs` lists the URIs the open stream serves. +- `subscribeToResource(uri:)` adds the URI to that stream at 2026-07-28 and waits for an acknowledgement that names it; on handshake connections it sends `resources/subscribe`. `unsubscribeFromResource(uri:)` replaces the stream with one without the URI, or sends `resources/unsubscribe`. `subscribedResourceURIs` lists the URIs the open stream serves, or on handshake connections the URIs whose `resources/subscribe` succeeded and that were not unsubscribed. - `disconnect()` cancels the stream. ### Closing a stream @@ -427,9 +450,9 @@ Pass an `HTTPClientAuthorizer` to `HTTPClientTransport(endpoint:authorizer:)`. T What happens on a request: -1. Before the first request, `validateEndpointSecurity` requires the MCP endpoint to be `https`, or `http` on a loopback host. -2. Before every request, the authorizer refreshes a token that expires within `proactiveRefreshWindowSeconds` (60 s). A token issued for less than the window is refreshed halfway through the time it is sent (until 30 s before it expires), so it is not refreshed on every request. Each token is tried once; when that fails, the next 401 recovers. The transport then sets the authorizer's headers, after `requestModifier`: `Authorization: Bearer `, or for a [DPoP](#dpop) token `Authorization: DPoP ` and a proof. -3. On 401 or 403 the transport calls `handleChallenge`. The authorizer parses `WWW-Authenticate`, discovers metadata and gets a token, and the transport retries. It sends one request at most `RetryPolicy.maxAuthorizationAttempts` (3) times. A 403 with `error="insufficient_scope"` requests the union of the current and the challenged scopes, up to `maxScopeUpgradeAttempts` (2) times per resource, method and scope set. +1. Before every request, and before each GET of an SSE stream, the transport requires the MCP endpoint to be `https`, or `http` on a loopback host, and fails the request with `insecureOAuthEndpoint` otherwise; it runs this check itself, whatever the authorizer is. Then it calls the authorizer's `prepare(for:session:)`, whose error fails the request too. `OAuthAuthorizer` refreshes a token that expires within `proactiveRefreshWindowSeconds` (60 s). A token issued for less than the window is refreshed halfway through the time it is sent (until 30 s before it expires), so it is not refreshed on every request. Each token is tried once; a failed refresh is ignored, and the next 401 recovers. +2. The transport builds the request, runs `requestModifier`, checks the final URL as in step 1 (a modifier that points a request at cleartext `http` gets no token, and the request fails unsent), then sets the headers of `authorizationHeaders(for:method:)` for the final URL and method: `Authorization: Bearer `, or for a [DPoP](#dpop) token `Authorization: DPoP ` and a proof. `OAuthAuthorizer` attaches a token only to a URL its resource covers; once it has read the protected resource metadata, a URL outside the resource fails with `protectedResourceMismatch`. When neither `endpointOverrides.resource` nor the metadata names a resource, the resource is the MCP endpoint: a URL on its origin (for example one `requestModifier` gives another path) uses the endpoint's token, and a URL on another origin fails with `protectedResourceMismatch`. +3. On 401 or 403 the transport calls `handleChallenge(_:session:)` with an `HTTPAuthorizationChallenge`: the status, the response headers, the endpoint, the JSON-RPC method and the `Authorization` header the request carried. The authorizer parses `WWW-Authenticate`, discovers metadata and gets a token, and the transport retries while the `HTTPChallengeResult` says so (`.retry`, `.retryWithDPoPNonce`; `.unhandled` fails the request). It sends one request at most `RetryPolicy.maxAuthorizationAttempts` (3) times. A 403 with `error="insufficient_scope"` requests the union of the current and the challenged scopes, up to `maxScopeUpgradeAttempts` (2) times per resource, method and scope set. Discovery follows the MCP authorization spec: protected resource metadata (RFC 9728) from the challenge's `resource_metadata` or the well-known URLs, then authorization server metadata (RFC 8414, then OpenID Connect discovery). Tokens are bound to the resource with the RFC 8707 `resource` parameter. `EndpointOverrides` skips parts of discovery. @@ -456,13 +479,15 @@ How the client identifies itself, with `.none(clientID:)`: - **Dynamic client registration (RFC 7591).** Otherwise, with an empty client ID or a CIMD URL the server does not accept, when the server has a `registration_endpoint`, the authorizer registers with `client_name` (`clientName`, default `"mcp-swift-sdk"`), the redirect URI, the grant and response types, and `application_type` (SEP-837). `applicationType: nil` sends `web` for the authorization code grant with an `https` redirect URI on a non-loopback host, else `native`. The registered credentials replace `authentication` for this authorizer. A registration that fails with an error is tried again in the next flow. Without a `registration_endpoint`, an empty client ID fails with `registrationInformationRequired` before any token request, and the next flow checks the metadata again. - **Pre-registration.** Pass `.clientSecretBasic`, `.clientSecretPost` or `.privateKeyJWT`; no registration happens. -Tokens are kept in a `TokenStorage`. The default `InMemoryTokenStorage` loses them when the process exits. Implement the protocol to persist them, for example in the Keychain. Its methods may be called from several tasks at once: +Tokens are kept in an `OAuthTokenStorage`, one per protected resource: the authorizer stores each token under the canonical URI it sent as the RFC 8707 `resource` (`endpointOverrides.resource`, else the `resource` of the protected resource metadata, else the MCP endpoint), so one storage can serve authorizers for several servers. The canonical URI has a lowercase scheme and host, and no user information, default port, query, dot segments or trailing slash: `https://MCP.example.com:443/mcp/` becomes `https://mcp.example.com/mcp`. This also holds for `endpointOverrides.resource`. For a server whose trailing slash is significant, pass `OAuthAuthorizer(configuration:metadataDiscovery:)` an `OAuthMetadataDiscovering` that wraps `DefaultOAuthMetadataDiscovery` and returns its `canonicalResourceURI(from:)` with the slash; matching ignores trailing slashes, so only the `resource` sent and the storage key change. The default `InMemoryOAuthTokenStorage` loses them when the process exits. Implement the protocol to persist them, in the Keychain rather than `UserDefaults` or a file, since a token carries its refresh token. Its methods are `async throws`: an error fails the request that needed the token, and `MCPError.transportError(_:)` carries it. The authorizer calls them from several tasks at once, and writes one token at a time: %include Examples/Snippets/Protocol/Authorization.swift auth-token-storage %include Examples/Snippets/Protocol/Authorization.swift auth-authorizer-storage -Use one `OAuthAuthorizer` per transport. Requests of a transport run concurrently: the authorizer handles one challenge or proactive refresh at a time, and a request whose 401, or 403 for the same scopes, arrives while another is handled retries with the token that one obtained, so concurrent challenges cause one refresh or sign-in. The authorizer compares a challenge with the token the challenged request carried, so a late 401 for a token another request already replaced retries with the new one instead of starting over. When the challenge being handled fails and leaves no usable token other than the one the waiting requests carried (the user cancelled the authorization, the grant was refused), the requests that waited for it fail with its error instead of each starting the flow again; a later request starts a new flow. A request cancelled while it waits stops waiting. +Until the authorizer has read the protected resource metadata, the key is the MCP endpoint (or `endpointOverrides.resource`); after it, the metadata's `resource`, for example `https://mcp.example.com` for the endpoint `https://mcp.example.com/mcp`. So after a relaunch the first request goes out without a stored token; its 401 reads the metadata and finds the token under the resource, without a new sign-in. To send the token on the first request, set `endpointOverrides.resource` to the server's resource. Finish a `save` even when the calling task is cancelled: the authorization server may have rotated the refresh token, and a token that is not saved can cost the user another sign-in. + +Use one `OAuthAuthorizer` per MCP server, and the same one for every transport to that server: two authorizers for one server don't coordinate their sign-ins, even with one storage. Requests run concurrently: the authorizer handles one challenge or proactive refresh at a time, and a request whose 401, or 403 for the same scopes, arrives while another is handled retries with the token that one obtained, so concurrent challenges cause one refresh or sign-in. The authorizer compares a challenge with the token the challenged request carried, so a late 401 for a token another request already replaced retries with the new one instead of starting over. When the challenge being handled fails and leaves no usable token other than the one the waiting requests carried (the user cancelled the authorization, the grant was refused), the requests that waited for it fail with its error instead of each starting the flow again; a later request starts a new flow. A request cancelled while it waits stops waiting. `accessTokenProvider` lets the app supply a token it got elsewhere. The SDK calls it after discovery with an `AccessTokenProviderContext` (resource, endpoints, scopes); return `nil` to run the configured grant. The provider and the `authorizationDelegate` run while the authorizer handles a challenge, and the transport's other challenges wait for them: they must not send requests through the transport they authorize. @@ -474,7 +499,7 @@ Issuer checks and authorization server changes: - A refresh token is sent only to the server that issued it. A token without a recorded server is refreshed only at a configured `authorizationServerURL` or `tokenEndpoint`. - For 2025-03-26 servers that publish no metadata at all, the authorizer falls back to `/authorize`, `/token` and `/register` at the server origin, with S256. It does so only on first discovery, and only when every metadata URL answers 404 or 410; a network error, a cancelled request or another status fails the request instead. -Errors reach the caller as `MCPError.transportError(_:)` with the `OAuthAuthorizationError` (or the error a custom authorizer threw; a `CancellationError` is thrown as is), or with an `HTTPStatusError` of 401 or 403 when retries run out. +Errors reach the caller as `MCPError.transportError(_:)` with the `OAuthAuthorizationError` (or the error of the token storage, of the `requestModifier`, or of a custom authorizer; a `CancellationError` is thrown as is), or with an `HTTPStatusError` of 401 or 403 when retries run out. #### Enterprise-managed authorization @@ -514,8 +539,8 @@ With `dpop` set, tokens are sender-constrained (RFC 9449, SEP-1932): the authori - Every token request (authorization code, refresh, client credentials, jwt-bearer) carries a `DPoP` proof: an ES256 JWS with `typ` `dpop+jwt`, the public key as `jwk`, and the claims `jti`, `htm`, `htu` (the URL without user information, query and fragment) and `iat`. - A `token_type` of `DPoP` is presented as `Authorization: DPoP ` with a new proof per request, which also carries `ath`, the hash of the token. A `Bearer` answer means the server does not bind tokens: the token is used as a Bearer token, unless the protected resource sets `dpop_bound_access_tokens_required`, which fails with `dpopRequired`. -- A `use_dpop_nonce` error, from the token endpoint (400) or from the MCP server (401 with a `DPoP` challenge), is retried once with the `DPoP-Nonce` the server sent; this retry does not count against `maxAuthorizationAttempts`. A 401 `use_dpop_nonce` without a `DPoP-Nonce` header is an ordinary challenge and counts, and so does one that arrives without a valid DPoP token, which `OAuthAuthorizer` answers with a new token. The authorizer, not the transport, decides that a challenge is a nonce retry: `OAuthAuthorizer` reads it with its `challengeParser` and reports it as `HTTPChallengeResult.isDPoPNonceRetry`; a custom `HTTPClientAuthorizer` that implements only the Bool `handleChallenge` gets the reading of `DefaultOAuthWWWAuthenticateParser`. A `DPoP-Nonce` in any MCP server response is kept for the origin the request went to; the MCP server's token is kept. -- The stored token records the key's thumbprint (`OAuthAccessToken.keyThumbprint`). A token bound to another key is discarded. Persist the key with the tokens (`P256.Signing.PrivateKey.rawRepresentation`) to use them after a relaunch, or keep it in the Secure Enclave: `DPoP(key:)` takes any `DPoPSigningKey`, which `SecureEnclave.P256.Signing.PrivateKey` is on Apple platforms. The key signs synchronously for every request, and the transport waits for it, so a key behind a network call (a remote HSM, a key service) slows every request. +- A `use_dpop_nonce` error, from the token endpoint (400) or from the MCP server (401 with a `DPoP` challenge), is retried once with the `DPoP-Nonce` the server sent; this retry does not count against `maxAuthorizationAttempts`. A 401 `use_dpop_nonce` without a `DPoP-Nonce` header is an ordinary challenge and counts, and so does one that arrives without a valid DPoP token, which `OAuthAuthorizer` answers with a new token. The authorizer, not the transport, decides that a challenge is a nonce retry: `OAuthAuthorizer` reads it with its `challengeParser` and reports it as `HTTPChallengeResult.isDPoPNonceRetry`; a custom `HTTPClientAuthorizer` returns `.retryWithDPoPNonce` for such a challenge. A `DPoP-Nonce` in any MCP server response is kept for the origin the request went to; the MCP server's token is kept. +- The stored token records the key's thumbprint (`OAuthAccessToken.keyThumbprint`). A token bound to another key is discarded. Persist the key with the tokens (`P256.Signing.PrivateKey.rawRepresentation`) to use them after a relaunch, or keep it in the Secure Enclave: `DPoP(key:)` takes any `DPoPSigningKey`, which `SecureEnclave.P256.Signing.PrivateKey` is on Apple platforms. The key signs once for every request, and the request waits for the signature, which may be `async`; a signing error fails the request. A key behind a network call (a remote HSM, a key service) slows every request. - With `dpop`, an authorization server whose `dpop_signing_alg_values_supported` lacks ES256 fails with `dpopAlgorithmUnsupported`, and a `Bearer` token for a resource with `dpop_bound_access_tokens_required` fails with `dpopRequired`. Without `dpop`, such a resource fails with `dpopRequired` before the grant. - Tokens from `accessTokenProvider` are always Bearer tokens. - When the MCP server sends both a `Bearer` and a `DPoP` challenge, `OAuthAuthorizer` reads the `error` and `scope` of the one for the scheme the request used (RFC 9449 §7.2), so a 403 `insufficient_scope` in the `DPoP` challenge steps up a DPoP token. @@ -523,14 +548,14 @@ With `dpop` set, tokens are sender-constrained (RFC 9449, SEP-1932): the authori ### Server -A protected server puts two validators in front of its transport's pipeline: +A protected server puts two validators in front of its transport's other validators: - `ProtectedResourceMetadataValidator` answers GET `/.well-known/oauth-protected-resource` (and paths below it) with an `OAuthProtectedResourceServerMetadata` document. Put it first, so discovery needs no token. -- `BearerTokenValidator` requires `Authorization: Bearer`. Your `tokenValidator` closure verifies the token (signature, introspection) and returns a `BearerTokenValidationResult`. With `.valid(BearerTokenInfo)` the validator also rejects an `expiresAt` in the past and an `audience` that does not match `resourceIdentifier`; set both fields. Pass `requiresAuthentication:` to exempt requests. +- `BearerTokenValidator` requires `Authorization: Bearer`. Your `tokenValidator` closure verifies the token (signature, introspection) and returns a `BearerTokenValidationResult`. The closure is `async`: it can call an introspection endpoint (RFC 7662) or fetch signing keys without blocking a thread, and the transport handles other requests while it waits. It does not throw: map a failed call to a result, usually `.invalidToken`. With `.valid(BearerTokenInfo)` the validator also rejects an `expiresAt` in the past and an `audience` that does not match `resourceIdentifier`; set both fields. Pass `requiresAuthentication:` to exempt requests. %include Examples/Snippets/Protocol/Authorization.swift auth-server-pipeline -Pass the pipeline to the transport. The stateless transport takes the same validators; use `AcceptHeaderValidator(mode: .jsonOnly)` and leave out `SessionValidator`. +Pass the validators to the transport. The stateless transport takes the same validators; use `AcceptHeaderValidator(mode: .jsonOnly)` and leave out `SessionValidator`. To reuse a group of validators as one, wrap them in `StandardValidationPipeline(validators:)`, itself a validator. %include Examples/Snippets/Protocol/Authorization.swift auth-server-transport @@ -572,7 +597,7 @@ A malicious server can point OAuth discovery at internal addresses. `OAuthAuthor - **HTTPS.** The MCP endpoint, resource metadata URLs and authorization server endpoints must be `https`; `http` is accepted only for loopback hosts (`localhost`, `127.0.0.1`, `::1`), and for authorization server endpoints not at all by default. URLs with fragments are rejected. - **Private addresses.** `OAuthURLValidator.isPrivateIPHost` parses literal IP hosts with `inet_pton` and rejects `0.0.0.0/8`, `10.0.0.0/8`, `100.64.0.0/10`, `169.254.0.0/16` (cloud metadata), `172.16.0.0/12`, `192.0.0.0/24`, `192.168.0.0/16`, `198.18.0.0/15`, `224.0.0.0/4`, `240.0.0.0/4`, `::`, `fc00::/7`, `fe80::/10`, `fec0::/10` and `ff00::/8`, in any spelling: bracketed, zoned (`%en0`), and IPv4 addresses embedded as IPv4-mapped, IPv4-compatible or NAT64 IPv6. Numeric hosts that are not a canonical dotted quad (`167772161`, `10.1`, `0x0a.0.0.1`, `012.0.0.1`) are rejected too. It never rejects host names or loopback addresses. It is applied to the challenge's `resource_metadata` URL, authorization server candidates (skipped; when every candidate is refused, discovery throws the first refusal, `privateIPAddressBlocked` or `insecureAuthorizationServerEndpoint`), the authorization, token and registration endpoints, and the token endpoint an identity provider's metadata names (`privateIPAddressBlocked`). - **Loopback hosts.** A URL a server names may be on a loopback host (`localhost`, a name under `.localhost`, `127.0.0.0/8`, `::1`) only when that server is on one too: the challenge's `resource_metadata` URL and the resource's authorization servers when the MCP endpoint is, and the authorization, token and registration endpoints when the selected authorization server is. Otherwise they are refused like private addresses, before any request. URLs set in `endpointOverrides` may be on loopback; the servers a configured `protectedResourceMetadataURL` lists still follow the MCP endpoint, so set `authorizationServerURL` for a local authorization server. The token endpoint that an identity provider's metadata names (`OAuthTokenExchange.tokenEndpoint(issuer:)`, which `enterpriseManaged` uses with `.issuer`) follows that provider's issuer. Redirects follow the same rule. -- **Redirects.** Metadata discovery follows a redirect only to an `https` URL, or from loopback `http` to loopback `http`, whose host is not a private address, and to a loopback host (`localhost`, a name under `.localhost`, `127.0.0.0/8`, `::1`) only from a loopback host. Each hop is checked against the one before it. Token and registration requests, which carry credentials, follow no redirects. +- **Redirects.** Metadata discovery follows a redirect only to an `https` URL, or from loopback `http` to loopback `http`, whose host is not a private address, and to a loopback host (`localhost`, a name under `.localhost`, `127.0.0.0/8`, `::1`) only from a loopback host. Each hop is checked against the one before it. Token and registration requests, which carry credentials, follow no redirects. `HTTPClientTransport` follows the redirects of MCP requests to `http` and `https` URLs, except to a loopback host from a remote host, from `https` to `http`, or from a loopback host to `http` on a host that is not a loopback host; `Authorization`, `Proxy-Authorization`, `Cookie` and `Mcp-Session-Id` (of the request, the `requestModifier` or the configuration's `httpAdditionalHeaders`) go to the same origin (scheme, host and port) only (with an authorizer, a same-origin hop has the authorizer's `Authorization` for the new URL or none, not one the `requestModifier` or the configuration set), `DPoP` goes on no redirect, and a hop through another origin removes them for the rest of the chain. A 401 or 403 that such a hop leads to fails the request with `protectedResourceMismatch` instead of reaching the authorizer. OAuth discovery and server card fetches apply the same rule to their session's headers. What the SDK does not do: it checks literal IP addresses only, so a host name that resolves to a private address passes, and DNS rebinding is not prevented. On Linux (swift-corelibs-foundation), which has no per-task delegates, each OAuth request runs in a session with the caller session's configuration and the redirect check as its delegate. Run clients that connect to untrusted servers behind an egress proxy or firewall that blocks internal ranges. @@ -583,7 +608,7 @@ On the server side, `OriginValidator` protects local servers against DNS rebindi An attacker who learns a session ID could send requests in another user's session. - `StatefulHTTPServerTransport` generates session IDs with `UUID()` (`UUIDSessionIDGenerator`) and rejects IDs outside visible ASCII. A custom `SessionIDGenerator` must produce unguessable IDs. -- The SDK does not bind a session to a user. Put `BearerTokenValidator` in every session's pipeline so each request is authenticated, and in your session router record the token subject when the session is created and reject later requests whose subject differs. +- The SDK does not bind a session to a user. Put `BearerTokenValidator` in every session's validators so each request is authenticated, and in your session router record the token subject when the session is created and reject later requests whose subject differs. - At 2026-07-28 there are no sessions: every request is authenticated on its own. ### Issuer mix-up @@ -634,7 +659,7 @@ Details: - In a multi round-trip exchange, `cancelRequest` with the first request id cancels the current round. - Over stateless HTTP the transport cancels a handler only after its reply has become an SSE stream, which happens when the handler sends a notification for the request and the client accepts SSE. A reply still pending as a JSON body is not cancelled when the client goes away; the handler runs to completion and the response is discarded. -- The server can cancel its own requests to the client (sampling, elicitation, roots) with `Server.cancelRequest(_:reason:)`, which sends `notifications/cancelled`. These requests exist only on handshake connections. +- The server withdraws its own requests to the client (sampling, elicitation, roots) when the task that awaits them is cancelled: it sends `notifications/cancelled` on the route of the request. After the client cancelled the request whose handler awaits them, the HTTP server transports have closed that route: `StatefulHTTPServerTransport` sends the notification on the session's GET stream, or stores it for replay when none is open, and `StatelessHTTPServerTransport` doesn't send it. These requests exist only on handshake connections. - `RequestContext.value` throws `CancellationError` after a cancellation; `MCPError` is not used. ### Ping @@ -645,7 +670,7 @@ Details: %include Examples/Snippets/Protocol/Utilities.swift ping -The server answers `ping` with an empty result. `Server` has no method to ping the client, and the SDK has no keep-alive timer. `NetworkTransport` has its own heartbeat (`HeartbeatConfiguration`), which is not an MCP message. +The server answers `ping` with an empty result. `Server` has no method to ping the client, and the SDK has no keep-alive timer. `NetworkTransport` sends no heartbeat either; it skips the heartbeat frames a 0.12 `NetworkTransport` sends, so call `Client.ping()` periodically to check a connection. ### Progress diff --git a/docs/src/protocol_versions.src.md b/docs/src/protocol_versions.src.md index 0184a449..8e585df2 100644 --- a/docs/src/protocol_versions.src.md +++ b/docs/src/protocol_versions.src.md @@ -214,7 +214,7 @@ On a stateless connection the client: `_meta` win. `logLevel` comes from `Client.logLevel`, which starts as `Configuration.logLevel`; - sends no `Mcp-Session-Id` and opens no GET stream over HTTP - (`HTTPClientTransport.useStatelessProtocol(_:)`), and adds the `Mcp-Method`, + (`HTTPClientTransport.didNegotiate(protocolVersion:)`), and adds the `Mcp-Method`, `Mcp-Name` and `Mcp-Param-*` headers; - sends `server/discover` for `ping()`; - stores the level of `setLoggingLevel(_:)` in `Client.logLevel` instead of diff --git a/docs/src/quick_start.src.md b/docs/src/quick_start.src.md index ba013165..69a5202b 100644 --- a/docs/src/quick_start.src.md +++ b/docs/src/quick_start.src.md @@ -46,7 +46,8 @@ until standard input closes should see is a result with `isError: true` instead; see [server.md](server.md#errors-and-iserror). - `start(transport:)` connects the transport and returns. The server handles messages in a background task; `waitUntilCompleted()` waits until that task - ends. + ends, and throws when reading standard input failed, so the server exits + with status 1. - The server serves both protocol eras: `initialize` clients and stateless 2026-07-28 clients. See [protocol_versions.md](protocol_versions.md). diff --git a/docs/src/server.src.md b/docs/src/server.src.md index 3422e3c5..e27b6902 100644 --- a/docs/src/server.src.md +++ b/docs/src/server.src.md @@ -78,15 +78,15 @@ A tool is a function the client's model can call. A server lists its tools in a There is one handler per method. A server with several tools switches on `params.name`. `params.arguments` is a `[String: Value]?`; read it with `stringValue`, `intValue`, `doubleValue`, `numberValue` (an integer or a double, as `Double`), `boolValue`, `arrayValue` and `objectValue`. -A string argument that is a whole `data:` URL, such as `data:image/png;base64,iVBORw0K...`, arrives as `.data(mimeType:_:)`, not as `.string`. Its `stringValue` is `nil`. Read the MIME type and the bytes with `dataValue`. Both are what the client sent, and the SDK does not check that the bytes match the MIME type. Check the content and the size before you store, serve or decode them. +A string argument is a `.string`, also a `data:` URL such as `data:image/png;base64,iVBORw0K...`. To read its bytes, parse it with `DataURL(_:)`, which returns `nil` for anything that isn't a `data:` URL. The MIME type and the bytes are what the client sent, and the SDK does not check that they match: check the content and the size before you store, serve or decode them. A `Codable` arguments type can declare a `DataURL` property, which decodes and validates the string. -The rules for a `data:` URL (RFC 2397): +`DataURL(_:)` follows RFC 2397, narrowly: - It starts with `data:` in lowercase. -- Before the first `,`, it has an optional media type `type/subtype`, then an optional `;charset=`, then an optional `;base64`. The type, the subtype and the charset have no spaces, so prose such as `data: 3 rows, 2 columns` stays `.string`. -- The payload after that `,` decodes: valid base64, or text where every `%` starts a `%XX` escape. +- Before the first `,`, it has an optional media type `type/subtype`, then an optional `;charset=`, then an optional `;base64` (`charset` and `base64` in any ASCII case). The type, the subtype and the charset have no spaces, so prose such as `data: 3 rows, 2 columns` is not a `data:` URL. +- The payload after that `,` decodes: base64 (whitespace and missing `=` padding are accepted), or text where every `%` starts a `%XX` escape. -Other strings stay `.string`. The MIME type is `text/plain` for an empty media type. `;charset=` stays in the MIME type only for a `text/` or empty media type. To get a `data:` URL again, call `Data.dataURLEncoded(mimeType:)`. It returns the base64 form, not always the spelling the client sent: `data:,hi` becomes `data:text/plain;base64,aGk=`. +The MIME type is `text/plain` for an empty media type, and keeps `;charset=` only for a `text/` or empty media type. Its type, subtype and parameter names are lowercase (ASCII only). `DataURL(data:mimeType:)` and the `mimeType` setter also remove ASCII whitespace at either end of the media type, around each `;` and around the first `=` of each parameter, so `text/html; charset=utf-8` becomes `text/html;charset=utf-8`; `DataURL(_:)` rejects whitespace in the URL header and normalizes case and the default `text/plain`. `DataURL(data:mimeType:).description` makes a `data:` URL in base64 form, so it is not always the spelling the client sent: `data:,hi` becomes `data:text/plain;base64,aGk=`. %include Examples/Snippets/Server/Tools.swift tools-call @@ -97,9 +97,9 @@ Other strings stay `.string`. The MIME type is `text/plain` for an empty media t | Case | Wire `type` | Use | | --- | --- | --- | | `.text(text:annotations:_meta:)` | `text` | Text for the model | -| `.image(data:mimeType:annotations:_meta:)` | `image` | Base64-encoded image | -| `.audio(data:mimeType:annotations:_meta:)` | `audio` | Base64-encoded audio | -| `.resource(resource:annotations:_meta:)` | `resource` | An embedded resource, with its text or blob | +| `.image(_:mimeType:annotations:_meta:)` | `image` | Image bytes, sent base64 | +| `.audio(_:mimeType:annotations:_meta:)` | `audio` | Audio bytes, sent base64 | +| `.resource(resource:annotations:_meta:)` | `resource` | An embedded resource, with its text or bytes | | `.resourceLink(uri:name:title:description:mimeType:annotations:)` | `resource_link` | A link the client may read with `resources/read` | %include Examples/Snippets/Server/Tools.swift tools-content @@ -108,7 +108,7 @@ The factories with a `metadata:` label, such as `.text(_:metadata:)`, are deprec ### Structured content -A tool with an `outputSchema` returns its data in `structuredContent`. `CallTool.Result(content:structuredContent:isError:_meta:)` takes any `Codable` value and throws if it cannot be encoded. It converts the value with `Value(_:)`, so a string field that is a whole `data:` URL is sent in base64 form: `data:,hi` becomes `data:text/plain;base64,aGk=`. A `Value` that you pass is kept as is. Send the same data as text too, for clients that read only `content`. +A tool with an `outputSchema` returns its data in `structuredContent`. `CallTool.Result(content:structuredContent:isError:_meta:)` takes any `Codable` value and throws if it cannot be encoded. It converts the value with `Value(_:)`, which sends strings as written. A `Value` that you pass is kept as is. Send the same data as text too, for clients that read only `content`. %include Examples/Snippets/Server/Tools.swift tools-structured @@ -187,8 +187,8 @@ A message is `.user(_:)` or `.assistant(_:)` with one `Prompt.Message.Content`. | Case | Wire `type` | | --- | --- | | `.text(text:)` | `text` | -| `.image(data:mimeType:)` | `image` (base64) | -| `.audio(data:mimeType:)` | `audio` (base64) | +| `.image(_:mimeType:)` | `image` (bytes, sent base64) | +| `.audio(_:mimeType:)` | `audio` (bytes, sent base64) | | `.resource(resource:annotations:_meta:)` | `resource` | | `.resourceLink(uri:name:title:description:mimeType:annotations:)` | `resource_link` | @@ -206,7 +206,7 @@ A resource is data identified by a URI that the client can read, such as a file ### Binary resources -`Resource.Content.text(_:uri:mimeType:_meta:)` sends `text`. `Resource.Content.binary(_:uri:mimeType:_meta:)` takes `Data` and sends it base64-encoded in `blob`. Clients decode `blob` themselves. +`Resource.Content.text(_:uri:mimeType:_meta:)` sends `text`. `Resource.Content.binary(_:uri:mimeType:_meta:)` takes `Data` and sends it base64-encoded in `blob`. Clients get the bytes from `body`. ### Resource templates @@ -232,7 +232,7 @@ A client can ask to be told when a resource changes. The two eras use different ## List-changed notifications -A server whose tools, prompts or resources change at run time tells clients with `notifications/tools/list_changed`, `notifications/prompts/list_changed` or `notifications/resources/list_changed`. The SDK does not send them for you: call `notify` after each change. Declare `listChanged: true` on the matching capability. +A server whose tools, prompts or resources change at run time tells clients with `notifications/tools/list_changed`, `notifications/prompts/list_changed` or `notifications/resources/list_changed`. The SDK does not send them for you: call `notify` after each change. Declare `listChanged: true` on the matching capability: the flag says the server sends the notification, not that the list changed. %include Examples/Snippets/Server/Notifications.swift list-changed @@ -278,7 +278,7 @@ The pieces: | `requestState` | A string the handler writes and reads as plaintext. The SDK seals it on the way out. | | `resultType` | `.inputRequired` on such results, `.complete` otherwise | -A `data:` URL string in an answer arrives as `.data`, as in [tool arguments](#calling-tools): in the `content` of an elicitation, for example text that a user typed into a form, and in the `input` of a sampling tool use. The same applies to the results of `requestElicitation` and `requestSampling`. +A `data:` URL string in an answer arrives as a `.string`, as in [tool arguments](#calling-tools): in the `content` of an elicitation, for example text that a user typed into a form, and in the `input` of a sampling tool use. The same applies to the results of `requestElicitation` and `requestSampling`. A result may carry `requestState` without input requests. The client then retries with the state and no responses, which lets a long operation continue in steps. @@ -624,7 +624,7 @@ Read capabilities from the context, not from what one client sent earlier: at 20 ### HTTP context -`httpContext` is the originating `HTTPRequest` (method, headers, body, path) when the transport conforms to `HTTPContextProviding`. `StatefulHTTPServerTransport` and `StatelessHTTPServerTransport` do; `StdioTransport` and `InMemoryTransport` do not, so it is `nil` there. `HTTPRequest.header(_:)` looks headers up case-insensitively and joins repeated ones; `headerValues(_:)` returns the value of each field line. +`httpContext` is the originating `HTTPRequest` (method, headers, body, path), from the transport's `httpRequest(for:)`. `StatefulHTTPServerTransport` and `StatelessHTTPServerTransport` return it; `StdioTransport` and `InMemoryTransport` return `nil`. `HTTPRequest.header(_:)` looks headers up case-insensitively and joins repeated ones; `headerValues(_:)` returns the value of each field line. %include Examples/Snippets/Server/Context.swift http-context @@ -662,7 +662,7 @@ At 2026-07-28 the SDK answers -32601 for the methods of an undeclared capability ## Lifecycle -`start(transport:initializeHook:statelessRequestHook:)` registers the built-in handlers, connects the transport and starts the receive loop. It returns once the loop is running. `waitUntilCompleted()` returns when the loop ends, for example when the transport closes. `stop()` ends the listen streams, cancels the loop, fails pending server-to-client requests with -32603 "Server disconnected" and disconnects the transport. +`start(transport:initializeHook:statelessRequestHook:)` registers the built-in handlers, connects the transport and starts the receive loop. It returns once the loop is running. `waitUntilCompleted()` returns when the loop ends normally: when the transport finishes its receive stream, for example when stdin closes, when the stream throws `MCPError.connectionClosed` because the peer closed the connection, and after `stop()`. It throws any other error the stream throws, for example `MCPError.transportError` when a read from stdin fails, so a stdio server can exit with a failure status. Every caller gets the same outcome, and a call after the end gets it at once. Each `start` begins a new run, after any `stop()` in progress has disconnected its transport: from then on a call waits for that run, and a call before then gets the stopped run's outcome. When `start` throws after beginning a run, for example because the transport fails to connect, the wait throws the same error until the next `start`; a `start` while a run is already active throws without affecting it. A `stop()` while `start` is still connecting ends the run normally instead, and `start` throws. Cancelling the caller doesn't end the wait: to stop the server on cancellation, call `stop()` from a cancellation handler, as below, and the wait returns once `stop()` has disconnected the transport. `stop()` ends the listen streams, cancels the loop, fails pending server-to-client requests with -32603 "Server disconnected" and disconnects the transport. A `stop()` or `start` called while a `stop()` is in progress waits until that one has disconnected the transport. %include Examples/Snippets/Server/Server.swift lifecycle-run @@ -707,9 +707,10 @@ struct MCPService: Service { func run() async throws { try await server.start(transport: StdioTransport()) - // Returns when the transport closes, or after `stop()`. - await withTaskCancellationOrGracefulShutdownHandler { - await server.waitUntilCompleted() + // Returns when the transport closes, or once `stop()` has disconnected it; throws + // when the transport fails. + try await withTaskCancellationOrGracefulShutdownHandler { + try await server.waitUntilCompleted() } onCancelOrGracefulShutdown: { Task { await server.stop() } } diff --git a/docs/src/troubleshooting.src.md b/docs/src/troubleshooting.src.md index c15eb8b4..eaa218ea 100644 --- a/docs/src/troubleshooting.src.md +++ b/docs/src/troubleshooting.src.md @@ -37,7 +37,9 @@ The loggers do not print message bodies. To see them, wrap the transport: Pass `WireLog(transport, logger:)` to `connect(transport:)` or `start(transport:)` instead of the transport. Each line is the direction and -the JSON message. +the JSON message. `WireLog` adopts `TransportWrapper`, which forwards +everything it doesn't implement to the wrapped transport, so an HTTP +transport behind it keeps its headers and sessions. ### HTTP traffic @@ -143,9 +145,10 @@ missing from the list that caller sees is refused when headers are sent. `Client` with `HTTPClientTransport` sends these headers itself. A mismatch usually means a proxy changed or removed headers, or a hand-built request. -A custom or wrapping transport receives the `Mcp-Param-*` headers through -`send(_:additionalHeaders:)`; one that keeps the default implementation drops -them. +A custom or wrapping transport receives the `Mcp-Param-*` headers in +`options.headers` of `send(_:options:)`, and must pass `options` on; a wrapper +that adopts `TransportWrapper` and doesn't implement `send(_:options:)` forwards +them unchanged. Values that are not printable ASCII are sent as `=?base64??=`; build them with `MCPRequestHeaders.encode(_:)`. @@ -199,11 +202,12 @@ Server transports: | 415 | both | A POST whose `Content-Type` is not `application/json`. | | 421 | both | A `Host` header that the `OriginValidator` does not allow. | | 503 | stateless | The transport stopped before the server answered. | +| 503 | stateful | A POST, GET or DELETE whose session was created, or dropped by a refused `initialize`, during each of three runs of its validators. | -The stateless transport's default pipeline is `OriginValidator.localhost()`, +The stateless transport's default validators are `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .jsonOnly)`, `ContentTypeValidator()` and -`ProtocolVersionValidator()`. Behind a proxy or on a public host, pass a -pipeline with `OriginValidator(allowedHosts:allowedOrigins:)` listing the +`ProtocolVersionValidator()`. Behind a proxy or on a public host, pass +`validators:` with `OriginValidator(allowedHosts:allowedOrigins:)` listing the public host names and the browser origins you allow. A server behind a proxy is often an internal service that a web page visited by an employee can reach through DNS rebinding; the Host and Origin checks stop that, and the MCP @@ -284,13 +288,38 @@ as `Authentication required` and `Access forbidden`). | `The protected resource requires DPoP-bound tokens` | `dpopRequired` | The protected resource metadata has `dpop_bound_access_tokens_required: true`; set `OAuthConfiguration.dpop`. With it set, the authorization server issued a Bearer token: configure it to issue DPoP-bound tokens. | | `The authorization server does not accept ES256 DPoP proofs` | `dpopAlgorithmUnsupported` | `dpop_signing_alg_values_supported` lacks `ES256`, the only algorithm the SDK signs with. | | `Token request failed with status 400 (oauth_error: use_dpop_nonce)` | `tokenRequestFailed` | The token endpoint asked for a nonce twice in a row, or sent no `DPoP-Nonce` header. | -| `Token response is invalid` | `tokenResponseInvalid` | Among other causes: a `token_type` other than `Bearer`, or `DPoP` for a request without `dpop`. | +| `Token response is invalid` | `tokenResponseInvalid` | Among other causes: a body that is not a token response, a `token_type` other than `Bearer`, or `DPoP` for a request without `dpop`. | +| `Client registration failed with status` | `registrationRequestFailed` | The registration endpoint (RFC 7591) refused the client; `oauthError` has its `error`, such as `invalid_redirect_uri`. A status of `unknown` means the response was not HTTP. | +| `Client registration response is invalid` | `registrationResponseInvalid` | The registration endpoint answered 2xx without a client information response, for example without `client_id`. | +| `Authorization server metadata is missing authorization_endpoint` | `authorizationEndpointMissing` | `grantType` is `.authorizationCode`, and the metadata names no authorization endpoint. | +| `Authorization endpoint cannot be made into an authorization request URL` | `authorizationEndpointInvalid` | The metadata's `authorization_endpoint` is not a URL that the authorization request's query can be added to. The error names it without user information, query or fragment, or as `` when it can't be read. Fix the metadata. | A DPoP client that keeps asking for authorization after a relaunch has stored tokens bound to a key it no longer has: the authorizer discards a token whose `keyThumbprint` differs from the configured key's, with its refresh token. Persist the key with the tokens. +`HTTPClientTransport` follows redirects to `http` and `https` URLs. It doesn't +follow one to another scheme, to a loopback host from a remote host, from +`https` to `http`, or from a loopback host to `http` on a host that is not a +loopback host: the request fails with the 3xx's `HTTPStatusError`, and the +transport logs a warning with the reason. On the same origin (scheme, host and +port) the request keeps `Proxy-Authorization`, `Cookie` and `Mcp-Session-Id`, +from the transport, the `requestModifier` or the configuration's +`httpAdditionalHeaders`. Without an authorizer it keeps `Authorization` too; +with one, it gets the authorizer's headers for the new URL, with a new DPoP +proof, since no redirect keeps the first request's `DPoP`, and no +`Authorization` when the authorizer has none for it, even if the +`requestModifier` or the configuration set one: a 401 there is a challenge for +the endpoint, as for any request. A redirect to another origin removes those +headers, for that hop and every later one, including a hop back to the first +origin. With an authorizer, the 401 or 403 the request then gets fails it with +`protectedResourceMismatch`, whose description names the URL the server +redirected to: configure that URL as the endpoint. Without an authorizer, the +request fails with that `HTTPStatusError`. An error the authorizer throws while +the transport follows a redirect fails the request with that error, and the +transport logs a warning naming the redirect's target. + Issuer mismatches are configuration errors on the server side: the issuer in the metadata must equal the URL that serves it, with no other normalization. The previous release accepted such metadata; see diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index fd78028e..dfcde1c0 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -52,51 +52,46 @@ The loggers do not print message bodies. To see them, wrap the transport: ```swift /// Wraps a transport and records every message it sends and receives. -actor WireLog: Transport { +/// +/// `TransportWrapper` forwards everything else to `wrapped`, so the wrapped +/// transport keeps its behavior, such as the headers of an HTTP transport. +actor WireLog: TransportWrapper { + nonisolated let wrapped: any Transport nonisolated let logger: Logger - private let base: any Transport private(set) var lines: [String] = [] + /// The stream `receive()` returns, made by its first call. + private var tapped: AsyncThrowingStream? - init(_ base: any Transport, logger: Logger) { - self.base = base + init(_ wrapped: any Transport, logger: Logger) { + self.wrapped = wrapped self.logger = logger } - func connect() async throws { try await base.connect() } - func disconnect() async { await base.disconnect() } - - func send(_ data: Data) async throws { - record("send", data) - try await base.send(data) - } - - func send(_ data: Data, relatedRequestID: ID?) async throws { + func send(_ data: Data, options: TransportSendOptions) async throws { record("send", data) - try await base.send(data, relatedRequestID: relatedRequestID) + try await wrapped.send(data, options: options) } - /// Forwards the `Mcp-Param-*` headers of a `tools/call` at 2026-07-28. - func send(_ data: Data, additionalHeaders: [String: String]) async throws { - record("send", data) - try await base.send(data, additionalHeaders: additionalHeaders) - } - - func receive() -> AsyncThrowingStream { - let base = self.base - return AsyncThrowingStream { continuation in - let task = Task { - do { - for try await data in await base.receive() { - self.record("receive", data) - continuation.yield(data) - } - continuation.finish() - } catch { - continuation.finish(throwing: error) + /// Returns the same stream on every call, as `Transport` requires. + func receive() async -> AsyncThrowingStream { + if let tapped { return tapped } + let (stream, continuation) = AsyncThrowingStream.makeStream() + // Stored before the await, so a concurrent call gets the same stream. + tapped = stream + let messages = await wrapped.receive() + let task = Task { + do { + for try await data in messages { + self.record("receive", data) + continuation.yield(data) } + continuation.finish() + } catch { + continuation.finish(throwing: error) } - continuation.onTermination = { _ in task.cancel() } } + continuation.onTermination = { _ in task.cancel() } + return stream } private func record(_ direction: String, _ data: Data) { @@ -109,7 +104,9 @@ actor WireLog: Transport { Pass `WireLog(transport, logger:)` to `connect(transport:)` or `start(transport:)` instead of the transport. Each line is the direction and -the JSON message. +the JSON message. `WireLog` adopts `TransportWrapper`, which forwards +everything it doesn't implement to the wrapped transport, so an HTTP +transport behind it keeps its headers and sessions. ### HTTP traffic @@ -228,9 +225,10 @@ missing from the list that caller sees is refused when headers are sent. `Client` with `HTTPClientTransport` sends these headers itself. A mismatch usually means a proxy changed or removed headers, or a hand-built request. -A custom or wrapping transport receives the `Mcp-Param-*` headers through -`send(_:additionalHeaders:)`; one that keeps the default implementation drops -them. +A custom or wrapping transport receives the `Mcp-Param-*` headers in +`options.headers` of `send(_:options:)`, and must pass `options` on; a wrapper +that adopts `TransportWrapper` and doesn't implement `send(_:options:)` forwards +them unchanged. Values that are not printable ASCII are sent as `=?base64??=`; build them with `MCPRequestHeaders.encode(_:)`. @@ -284,11 +282,12 @@ Server transports: | 415 | both | A POST whose `Content-Type` is not `application/json`. | | 421 | both | A `Host` header that the `OriginValidator` does not allow. | | 503 | stateless | The transport stopped before the server answered. | +| 503 | stateful | A POST, GET or DELETE whose session was created, or dropped by a refused `initialize`, during each of three runs of its validators. | -The stateless transport's default pipeline is `OriginValidator.localhost()`, +The stateless transport's default validators are `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .jsonOnly)`, `ContentTypeValidator()` and -`ProtocolVersionValidator()`. Behind a proxy or on a public host, pass a -pipeline with `OriginValidator(allowedHosts:allowedOrigins:)` listing the +`ProtocolVersionValidator()`. Behind a proxy or on a public host, pass +`validators:` with `OriginValidator(allowedHosts:allowedOrigins:)` listing the public host names and the browser origins you allow. A server behind a proxy is often an internal service that a web page visited by an employee can reach through DNS rebinding; the Host and Origin checks stop that, and the MCP @@ -382,13 +381,38 @@ as `Authentication required` and `Access forbidden`). | `The protected resource requires DPoP-bound tokens` | `dpopRequired` | The protected resource metadata has `dpop_bound_access_tokens_required: true`; set `OAuthConfiguration.dpop`. With it set, the authorization server issued a Bearer token: configure it to issue DPoP-bound tokens. | | `The authorization server does not accept ES256 DPoP proofs` | `dpopAlgorithmUnsupported` | `dpop_signing_alg_values_supported` lacks `ES256`, the only algorithm the SDK signs with. | | `Token request failed with status 400 (oauth_error: use_dpop_nonce)` | `tokenRequestFailed` | The token endpoint asked for a nonce twice in a row, or sent no `DPoP-Nonce` header. | -| `Token response is invalid` | `tokenResponseInvalid` | Among other causes: a `token_type` other than `Bearer`, or `DPoP` for a request without `dpop`. | +| `Token response is invalid` | `tokenResponseInvalid` | Among other causes: a body that is not a token response, a `token_type` other than `Bearer`, or `DPoP` for a request without `dpop`. | +| `Client registration failed with status` | `registrationRequestFailed` | The registration endpoint (RFC 7591) refused the client; `oauthError` has its `error`, such as `invalid_redirect_uri`. A status of `unknown` means the response was not HTTP. | +| `Client registration response is invalid` | `registrationResponseInvalid` | The registration endpoint answered 2xx without a client information response, for example without `client_id`. | +| `Authorization server metadata is missing authorization_endpoint` | `authorizationEndpointMissing` | `grantType` is `.authorizationCode`, and the metadata names no authorization endpoint. | +| `Authorization endpoint cannot be made into an authorization request URL` | `authorizationEndpointInvalid` | The metadata's `authorization_endpoint` is not a URL that the authorization request's query can be added to. The error names it without user information, query or fragment, or as `` when it can't be read. Fix the metadata. | A DPoP client that keeps asking for authorization after a relaunch has stored tokens bound to a key it no longer has: the authorizer discards a token whose `keyThumbprint` differs from the configured key's, with its refresh token. Persist the key with the tokens. +`HTTPClientTransport` follows redirects to `http` and `https` URLs. It doesn't +follow one to another scheme, to a loopback host from a remote host, from +`https` to `http`, or from a loopback host to `http` on a host that is not a +loopback host: the request fails with the 3xx's `HTTPStatusError`, and the +transport logs a warning with the reason. On the same origin (scheme, host and +port) the request keeps `Proxy-Authorization`, `Cookie` and `Mcp-Session-Id`, +from the transport, the `requestModifier` or the configuration's +`httpAdditionalHeaders`. Without an authorizer it keeps `Authorization` too; +with one, it gets the authorizer's headers for the new URL, with a new DPoP +proof, since no redirect keeps the first request's `DPoP`, and no +`Authorization` when the authorizer has none for it, even if the +`requestModifier` or the configuration set one: a 401 there is a challenge for +the endpoint, as for any request. A redirect to another origin removes those +headers, for that hop and every later one, including a hop back to the first +origin. With an authorizer, the 401 or 403 the request then gets fails it with +`protectedResourceMismatch`, whose description names the URL the server +redirected to: configure that URL as the endpoint. Without an authorizer, the +request fails with that `HTTPStatusError`. An error the authorizer throws while +the transport follows a redirect fails the request with that error, and the +transport logs a warning naming the redirect's target. + Issuer mismatches are configuration errors on the server side: the issuer in the metadata must equal the URL that serves it, with no other normalization. The previous release accepted such metadata; see diff --git a/fuzz/Sources/FuzzDecode/main.swift b/fuzz/Sources/FuzzDecode/main.swift index e54283d9..bbd47a68 100644 --- a/fuzz/Sources/FuzzDecode/main.swift +++ b/fuzz/Sources/FuzzDecode/main.swift @@ -34,8 +34,10 @@ public func fuzz(_ start: UnsafeRawPointer, _ count: Int) -> CInt { probe(SubscriptionsListen.Parameters.self, data) probe(Client.Capabilities.self, data) probe(Server.Capabilities.self, data) + probe(DataURL.self, data) if let header = String(data: data, encoding: .utf8) { _ = MCPRequestHeaders.decode(header) + _ = DataURL(header).map { DataURL($0.description) } } return 0 } diff --git a/interop/swift-client/main.swift b/interop/swift-client/main.swift index 95cab278..fe9ab80d 100644 --- a/interop/swift-client/main.swift +++ b/interop/swift-client/main.swift @@ -216,8 +216,8 @@ struct Battery: Sendable { await check(id) { let result = try await callTool(name) try require(kinds(result.content) == [kind], "kinds \(kinds(result.content))") - if case .image(let data, let mime, _, _) = result.content[0] { return "\(mime), \(data.count) b64" } - if case .audio(let data, let mime, _, _) = result.content[0] { return "\(mime), \(data.count) b64" } + if case .image(let data, let mime, _, _) = result.content[0] { return "\(mime), \(data.count) bytes" } + if case .audio(let data, let mime, _, _) = result.content[0] { return "\(mime), \(data.count) bytes" } if case .resource(let resource, _, _) = result.content[0] { return resource.uri } return kind } @@ -300,13 +300,13 @@ struct Battery: Sendable { } await check("resource-static-text") { let contents = try await client.readResource(uri: "test://static-text").contents - try require(contents.first?.text?.isEmpty == false, "no text") - return contents[0].text! + guard case .text(let text)? = contents.first?.body, !text.isEmpty else { throw Failure("no text") } + return text } await check("resource-static-binary") { let contents = try await client.readResource(uri: "test://static-binary").contents - try require(contents.first?.blob?.isEmpty == false, "no blob") - return "\(contents[0].mimeType ?? "?"), \(contents[0].blob!.count) b64" + guard case .blob(let data)? = contents.first?.body, !data.isEmpty else { throw Failure("no blob") } + return "\(contents[0].mimeType ?? "?"), \(data.count) bytes" } await check("resource-templates-list") { let templates = try await client.listResourceTemplates().templates.map(\.uriTemplate) @@ -315,8 +315,10 @@ struct Battery: Sendable { } await check("resource-template-read") { let contents = try await client.readResource(uri: "test://template/42/data").contents - try require(contents.first?.text?.contains("42") == true, "text \(contents.first?.text ?? "nil")") - return contents[0].text! + guard case .text(let text)? = contents.first?.body, text.contains("42") else { + throw Failure("body \(contents.first.map { "\($0.body)" } ?? "nil")") + } + return text } await check("unknown-resource") { do {