Repository navigation
MCP Swift SDK 1.0.0 - #372
Open
jeanmatthieu wants to merge 278 commits into
Open
jeanmatthieu wants to merge 278 commits into
jeanmatthieu wants to merge 278 commits into
Conversation
Brings the OAuth client in line with the 2026-07-28 authorization requirements. Authorization server metadata is used only when its `issuer` matches the issuer the well-known URL was built from, the `iss` of the authorization response is checked (RFC 9207), dynamic registration sends `application_type`, and a rejected token triggers a fresh read of the protected resource metadata so the client follows a resource to a new authorization server. A 2025-03-26 server without any metadata gets the default `/authorize`, `/token` and `/register` endpoints at its origin. A rejected token is refreshed at its issuing server before the metadata is read again; a transient discovery failure keeps the cached state instead of falling back to default endpoints; concurrent challenges run one flow. With it, the 2026-07-28 baseline is empty and the tier score is 100% for client and server at 2025-11-25 and 2026-07-28.
- Pass the Authorization value of the challenged request to the authorizer (new HTTPClientAuthorizer requirement with a default that calls the existing method; POST and GET paths), so a late 401 for a token another request already replaced retries with the new token instead of clearing it and starting a new authorization. - Refresh a refreshed token again after re-reading the resource metadata when the resource still names the same server; previously a token obtained by refresh was never refreshed and its refresh token was deleted on the next 401. The refresh-first step still skips a refreshed token, so the metadata is read again first. - Fail the challenge and keep the stored tokens when the authorization server metadata is unavailable (network error, unexpected status) or the read is cancelled, instead of clearing them. - Fail challenges that waited for a challenge that ended with an error and left no usable token with that error, instead of starting the same flow again (one prompt for a cancelled authorization); a 403 that waited for a token with the required scopes retries with it. - Reset the dynamic client registration attempt when registration throws, so the next flow registers again. - Make waiters of the authorizer gate cancellable, and document that an access token provider or authorization delegate must not send requests through the transport it authorizes.
PKCE.makeChallenge(from:) hashed with CryptoKit and threw pkceS256Unavailable where CryptoKit is missing, so on Linux every authorization_code flow failed before it started. Three tests fail on Linux because of it: "The authorizer passes the metadata issuer and its iss support to the flow" with pkceS256Unavailable, and two OAuthAuthorizerStateTests that wait for the flow to start and hit their one-minute limit. The MCP target already depends on swift-crypto, whose SHA256 has the same API on every platform, so makeChallenge uses it. It keeps `throws` for source compatibility and no longer throws; the doc comments of makeChallenge and pkceS256Unavailable say so. The authorization_code challenge test in OAuthAuthorizerTests, gated on CryptoKit, now runs on Linux too.
- Fail a challenge that waited for one that ended with an error when the only stored token is the one the challenged request carried, not only when no unexpired token is stored. A failed 403 insufficient_scope step-up keeps the narrower token, so a waiting 403 for the same token presented a second authorization prompt after the user cancelled the first; a 401 whose handler threw before clearing the token repeated the failing calls. - Keep the selected authorization server, its metadata and the stored token when re-read resource metadata lists another server but endpointOverrides.authorizationServerURL configures the server. The override decides the server whatever the resource lists, so the SEP-2352 migration check does not apply; it cleared the token before a 403 step-up read the granted scopes, and before a 401 could refresh it. - Reject an authorization response whose iss is given more than once or without a value (RFC 9207 §2.4; RFC 6749 §3.1 sends a parameter at most once). The first iss alone was checked, and a valueless iss counted as absent. - Compare a root issuer with and without its trailing slash by checking that the shorter one is a bare origin, instead of rebuilding the origin from percentEncodedHost, whose spelling of an IPv6 host depends on the Foundation version (RFC 8414 §3.3). - Give operationKey a nil default on the sentAuthorization overload of OAuthAuthorizer.handleChallenge, as on the other overload (additive). - Wait for the authorizer gate to hold the expected waiters in the OAuthAuthorizerStateTests waiter tests instead of fixed sleeps.
Reorganizes the repository after go-sdk and writes the documentation to the same depth: a feature-by-feature guide set in `docs/` that follows the specification, design notes in `design/`, process documents at the root, and runnable examples. Every code block in the guides is copied from compiled, tested sources under `Examples/Snippets` by `scripts/weave.swift`, and CI fails when the generated docs drift. The root README shrinks from 1,950 to 161 lines and is generated the same way. The guides and design notes describe the SDK at this point, including the automatic fallback, header parameter checks, listen streams, multi round-trip bounds, OAuth concurrency and the conformance runner. No public API changes. They also cover the client transport's stream resumption and stateless mode, and `CLAUDE.md` adds guidance for coding agents. The HTTP example bounds sessions and request bodies and binds its Host and Origin checks to its port, and the advice to disable the Origin check behind a proxy is replaced.
- Count initialize requests still being handled toward the example router's 100-session limit; the check ran before the awaits that create the session, so concurrent initializes all passed it. - Start the shared stateless server in the routing snippet with one task that every stateless request awaits; a start failure answers 500 and the next request tries again, instead of being swallowed with the server marked started. - Document that a refused initialize is stored by the session router and the example, and how its slot is freed. - Write each SSE chunk in the example NIO adapter only after the previous write completed, so a slow client applies backpressure instead of growing NIO's outbound buffer. - weave.swift reports a snippet region without // endsnippet instead of copying to the end of the file, and a generated docs/*.md file whose source no longer exists. - Describe behavior changed by earlier fixes: data: strings kept on the SDK's own Value hops, the parameter header check without a tools/list handler and the single parse of a stateless POST, delivery from a replaced listen stream, kept subscriptions and growing backoff, the end of a cancelled stateless request's HTTP response, and the OAuth challenge flow (repeated refresh, unavailable metadata, waiters of a failed challenge, 403 waiters, the sent token, registration retry, callbacks that must not use the transport they authorize). - server.md: the Server.init table names description, websiteUrl and icons (main's #258), which every stateless result repeats in serverInfo; the Value accessors include numberValue (main's #226).
- The SessionRouter snippet and the protocol guide say that the snippet is a sketch without a session limit, an initialize-only check or an idle reaper, and point to Examples/http-server/main.swift, which has all three. The snippet's comment no longer promises that the router closes idle sessions. - The server guide says that a RequestStateProtection.consume hook that throws fails the round with -32603 (the hook becomes async throws in conformance/p7-mrtr; the guide starts here).
…onalHeaders:) The guides said the client sends the SEP-2243 Mcp-Param-* headers only through HTTPClientTransport. With the Transport requirement send(_:additionalHeaders:) (and its default, which ignores the headers), any transport receives them; a Streamable HTTP transport sends them on the request's POST and a wrapping transport forwards them. - protocol: the request headers section names send(_:additionalHeaders:), and the custom transports section describes the requirement and its default next to send(_:relatedRequestID:). - client, troubleshooting: a custom or wrapping transport gets the headers through send(_:additionalHeaders:); keeping the default drops them (-32020 from a conforming server). - migration: the new-API table lists Transport.send(_:additionalHeaders:). - The WireLog snippet forwards the headers, so wrapping a transport for logging no longer breaks annotated tool calls. - design/request_headers.md: the Sending row names the requirement.
- The protocol and protocol-versions guides and the design note list the stateless checks in the order StatelessRequests.classify runs them: the version is served (-32022) before clientCapabilities and clientInfo are checked (-32602), and an unserved handshake revision also gets -32022. - The server guide says how the statelessRequestHook refuses a request: it runs before each stateless request with Server.currentHandlerContext set and nil client info when the request carries none, and an MCPError it throws goes back as is, any other error as -32600. The guides and design note name start by its full signature, start(transport:initializeHook:statelessRequestHook:). The -32022 refusal of stateless requests on a server with only an initialize hook is documented in conformance/p11-fixes, the .stateless(v) row there too, and the reopening of streams the server ends with its result in conformance/p18-linux.
The release step that ROADMAP.md listed as remaining. `Client.Configuration.protocolMode` defaults to `.automatic`, so a client connects with `server/discover` at 2026-07-28 and falls back to `initialize` for older servers, and `Version.supported` lists 2026-07-28. `Version.latest` stays 2025-11-25. `StatefulHTTPServerTransport` now validates `MCP-Protocol-Version` against `Version.handshake` explicitly, so its behavior does not change with `Version.supported`. Docs, snippets and tests are updated to the new defaults. Custom validation pipelines stay on the handshake revisions too: `HTTPValidationContext` defaults `supportedProtocolVersions` to `Version.handshake` instead of the widened `Version.supported`. The guides state the cost of the new default against handshake-only servers: one extra request per connection.
- Say in the protocol versions guide and the migration guide that a server which does not answer requests sent before initialize delays an .automatic connect by up to discoveryTimeout (10 seconds by default), and that .handshake or a shorter timeout avoids the wait. - Pin the CompletionTests clients to the handshake, check that they negotiate 2025-11-25, and add a completion case with the default mode that runs at 2026-07-28, so both paths stay covered after the flip. - Run the initialize-hook rejection tests with a client in both the handshake and the default mode: a default client against a server with only an initialize hook falls back to initialize and is refused there, instead of connecting statelessly past the hook. - Name the release in VERSIONING.md, the docs index and the design note instead of "this major version".
- StatefulHTTPServerTransport validates a sessionless request against Version.handshake, the revisions it serves, instead of Version.supported, which now lists 2026-07-28. A custom validator sees the same versions as before this change, and the context no longer follows Version.supported. Test: "A stateless request is validated against the handshake revisions". - The migration guide names the calls that behave differently on a stateless connection (notifyRootsChanged(), setLoggingLevel(_:), ping(), notifications) and links the full lists in client.md and protocol_versions.md.
- The protected-pipeline snippet test builds its HTTPValidationContext with the default supported versions, the handshake revisions, instead of Version.supported, which now lists 2026-07-28. It matches what StatefulHTTPServerTransport passes to the pipeline.
- The Clients section of the protocol versions guide linked the migration guide "for opting in", but .automatic is now the default. The link points at "Clients connect at 2026-07-28" and says it explains how to keep the handshake behavior.
Fixes ten of the 13 bugs found while writing the documentation, plus one of the API warts listed in `docs/rough_edges.md`. The client registers a request before `send(_:)` returns and runs its handlers outside the receive loop, `withBatch` goes through the same path as `send`, the server stops answering notifications and unreadable messages with random ids, sessionless servers handle `initialize` correctly, the replay store is bounded, and the OAuth client treats a plain client ID as pre-registered and checks redirects and the registration endpoint. The other three were fixed earlier; the migration and server guides now describe them. It also bounds server-to-client requests (4 at once, 64 waiting), delivers responses without waiting for unrelated notification handlers, makes the replay store per stream with a byte cap, parses IP literals with `inet_pton`, and applies the redirect checks on Linux. Docs, design notes and the migration guide describe the new behavior.
- Let the input-request bridge send elicitation, sampling and roots
requests behind StatelessHTTPServerTransport: a sessionless handshake
request carries no capabilities, so the client answers instead of the
server refusing with -32021 up front.
- Gate sessionless handshake requests: behind
StatelessHTTPServerTransport no session ties a request to the
initialize that passed the initialize hook, so the stateless request
hook runs before every request other than initialize, and with only
an initialize hook such requests are refused with -32600.
- Send list-changed and resource-updated notifications from a handshake
handler behind StatelessHTTPServerTransport on that request's stream;
2026-07-28 handlers still deliver them only through listen streams.
- Never send notifications/cancelled for initialize: cancelling connect
forgets the request locally, as the 2025-11-25 cancellation rules
require.
- Keep a cancelled server-to-client handler counted against
maxConcurrentServerRequests until it returns, and answer a server
ping at once with an empty result outside that limit instead of
queueing it (it was answered with -32601).
- Decode -32603 without data.detail like the other standard codes, so
"Internal error: x" becomes internalError("x") instead of repeating
the prefix.
- Document that a notification handler must not await a request with a
progress token sent outside a notification handler, and the hook,
slot and ping behavior, in the guides.
- Stop the message loop when the transport finishes its receive stream, normally or with an error. It called receive() again and spun on the already finished stream (stdio server exit), so pending requests and connect() waited forever. The client now runs the same teardown as disconnect() (listen stream and its retry, subscribe waiters, round trips, server-to-client handlers, inbound queue, unsent requests), disconnects the transport and fails every pending request with connectionClosed, or with the stream's error (wrapped in transportError unless it is an MCPError). - Rethrow that error from server/discover in .automatic instead of falling back to initialize on a closed connection, so connect() fails with it whether the server exits before answering initialize or server/discover. - Track a connection generation: an old message loop never tears down a newer connection, a batch built for a closed or replaced connection throws connectionClosed and is not sent, and the listen backoff does not reopen a stream once its connection closed. - connect(transport:) on a connected client releases the previous connection first, failing its requests with "Client disconnected"; the handler that reconnects is not cancelled, and server-to-client requests are answered on the transport they came from. - Document on Transport that finishing the receive stream means the connection is closed, and that disconnect() should finish it. Port of #67.
- isPrivateIPHost blocks IPv4-translated (::ffff:0:0:0/96) and 6to4 (2002::/16) addresses that embed a private IPv4 address, and the local-use NAT64 prefix 64:ff9b:1::/48. - A host that contains ':' but is not an IPv6 address (fc00::1::2), an embedded IPv4 address that is not a canonical dotted quad ([::ffff:012.0.0.1], which inet_pton reads as 12.0.0.1), and brackets around anything but an IPv6 address or unbalanced brackets ([127.0.0.1], [::1) are blocked instead of passing as host names. - A numeric host with a trailing root label (10.0.0.1.) is read as the address resolvers see, so it is blocked like other non-canonical spellings. - OAuthLoopbackHost.isLoopback also accepts [::1]: URLComponents.host keeps the brackets of an IPv6 literal, so http://[::1] was refused as a loopback endpoint, redirect URI and redirect target, while URL.host callers pass ::1. - Tests cover each range edge and neighbour, hosts taken from URLs the way the OAuth flow takes them, and loopback with brackets. Port of #68.
- A reconnect keeps the slots of cancelled server-to-client handlers that are still running until they return, so maxConcurrentServerRequests also holds across connect(transport:), as the client guide says. detachConnection used to clear that accounting. - Discovery redirects reach a loopback host (localhost, a name under .localhost per RFC 6761 section 6.3, 127.0.0.0/8, ::1, also embedded in IPv6) only from a loopback host, and each hop is checked against the previous one (response.url) instead of the first URL of the chain. Before, a public metadata URL could redirect to https://127.0.0.1 and an intermediate https hop could lead to a loopback http URL. - RequestContext.value says that the request is shared: cancelling one awaiting task cancels it for every task that awaits it. A test pins that a second waiter fails too. - The client guide says that queued notifications have no size limit, so a handler that does not return keeps later notifications in memory.
- Behind StatelessHTTPServerTransport, notify(_:to:) from a handler of a handshake request sends the notification on that request's stream only when recipients accepts the request's context. One server serves every client there, so a filter on the caller (for example its principal in httpContext) used to apply to listen streams but not to the caller's own stream. The protocol guide says so. - Cancelling a round of a multi round-trip exchange with cancelRequest sends one notifications/cancelled. Stopping the exchange cancels the round's task, whose cancellation handler cancelled the request again after cancelRequest had already removed it, and sent a second notification. A cancelled task now cancels its request only while it is still pending (2025-11-25 cancellation: notifications reference requests believed to be in progress). - A connect(transport:) whose server/discover fails because another connect replaced its connection throws "Client disconnected" instead of falling back to initialize on the new connection, which sent a second initialize there and downgraded it to 2025-11-25. Discovery also stops before retrying or adopting a result for a replaced connection. - The reconnect-from-a-handler test uses roots/list: a ping runs outside the handler slots, so it did not exercise the spared handler.
…tion Adds the RFC 7523 JWT bearer grant to `OAuthAuthorizer`, an RFC 8693 token exchange client, and a one-call configuration for enterprise-managed authorization (SEP-990). The same grant with a public client covers workload identity federation (SEP-1933). The conformance client fixture drops its hand-written token code and uses the SDK API for `auth/enterprise-managed-authorization` and `auth/wif-jwt-bearer`. The default-leg client baseline goes from 11 to 8 entries. It also sends jwt-bearer assertions only to a configured authorization server unless the caller opts into the discovered one (`allowsDiscoveredAuthorizationServer`), then checks the assertion's audience; it also stops the 2025-03-26 endpoint fallback for this grant, renews tokens without a refresh token before they expire, and discovers the identity provider's token endpoint once.
- Limit proactive renewal: each access token is tried once, so a failed refresh or grant is left to the 401 path instead of being retried before every request; a token issued for less than proactiveRefreshWindowSeconds is renewed halfway through the time it is sent (until the 30 s expiry skew), and one that is never sent is not renewed, so short-lived tokens are not replaced on every request. - With allowsDiscoveredAuthorizationServer and no configured server, refuse an assertion whose aud cannot be read (not a JWT, no aud, no string in an aud array) instead of sending it unchecked; read padded JWT payloads and the string members of a mixed aud array. - Document that endpointOverrides.tokenEndpoint alone fixes where the assertion goes but not the audience asked of the assertion provider, which still comes from discovery; authorizationServerURL fixes both. - Tests that relied on a token shorter than the window being renewed at once now age a stored token into the window; tests that sent a non-JWT assertion to a discovered server send a JWT or pin the server.
- Proactive renewal also runs when only endpointOverrides.tokenEndpoint names the token endpoint: the guard required the authorization server metadata's token_endpoint, which the grants never read when the override is set. Applies to the refresh-token and the jwt-bearer and client_credentials branches. - A proactive renewal cut short by cancellation no longer marks the token as tried, so the next request attempts it again instead of waiting for a 401. - A jwt-bearer grant without a configured authorization server or token endpoint, and without allowsDiscoveredAuthorizationServer, fails with authorizationServerNotConfigured before it fetches the metadata of a server the MCP server named (RFC 7523 §3 audience). Before, discovery ran first: it sent requests to those servers, and its errors hid the configuration error.
- The jwt-bearer grant checks the issuer of a configured authorization server too: its metadata must name endpointOverrides.authorizationServerURL as `issuer` (RFC 8414 §3.3, ID-JAG draft §9.5), or the grant fails with authorizationServerIssuerMismatch before any assertion is made. Before, a configured server was trusted whatever issuer its metadata named, and that issuer became the assertion's audience: enterpriseManaged asked the identity provider for an ID-JAG for it and sent the ID-JAG and the client credentials to the token endpoint the metadata named. Other grants keep trusting a configured server. - A jwt-bearer grant without an assertion provider (and without an accessTokenProvider) fails with assertionProviderMissing before the authorization server metadata is fetched. - Storing a token clears the proactive-renewal mark, so a token that a server issues again with the same value is renewed again before it expires. - enterpriseManaged keeps the identity provider's discovered token endpoint when an exchange is cancelled. - troubleshooting lists authorizationServerNotConfigured and assertionAudienceMismatch; the guides and doc comments say that a configured jwt-bearer server must name itself as issuer. Tests: the pinned-issuer test asserts authorizationServerIssuerMismatch and that nothing goes to the identity provider or the metadata's token endpoint; the missing-provider test pins a server and asserts the case and that no metadata is fetched; new tests cover a reissued token, a cancelled exchange, and a cancelled refresh-token renewal.
Adds opt-in DPoP (RFC 9449) to `OAuthAuthorizer`. With `OAuthConfiguration.dpop` set, every token request carries an ES256 DPoP proof, a `DPoP` token is stored with the key's thumbprint and presented as `Authorization: DPoP <token>` with a per-request proof that includes `ath`, and `use_dpop_nonce` errors from the authorization server and the MCP server are retried once per request with the server's nonce; that retry does not count against `maxAuthorizationAttempts`. A `DPoP-Nonce` in any MCP server response is stored for the origin the request went to, through the new `HTTPClientAuthorizer.didReceiveResponse(headers:for:)`. The key is any `DPoPSigningKey`, including a Secure Enclave key. To sign the method and URL, `HTTPClientAuthorizer.authorizationHeader(for:)` is replaced by `authorizationHeaders(for:method:)` (breaking), which the transport applies after `requestModifier`. The fixture handles `auth/dpop` and `auth/dpop-nonce`; the default-leg client baseline goes from 8 to 0 entries.
- Treat a resource server's use_dpop_nonce as the free nonce retry only when the 401 carries a DPoP-Nonce header (RFC 9449 section 9). Without it the authorizer runs a full challenge flow, which now counts against maxAuthorizationAttempts. - authorizationHeaders discards a stored token for another authorization server or another DPoP key only if storage still holds that token, so a token a concurrent challenge saved after the load is kept. - Document that DPoPSigningKey signs synchronously for every MCP and token request while the transport waits, so a key behind a network call slows every request.
- After a refresh, the stored token keeps the previous refresh token when the response has none (RFC 6749 section 6), so a later 401 can refresh again instead of clearing the tokens and starting a new grant. When neither the refresh request nor the response names a scope, the token keeps the scopes granted before (section 6); when the request named one, an omitted response scope still means the requested one (section 5.1).
HTTPClientTransport decided by itself whether a 401 was a DPoP use_dpop_nonce challenge (RFC 9449 §9), the one retry per request that does not count against maxAuthorizationAttempts. It read the challenge with a fresh DefaultOAuthWWWAuthenticateParser, while OAuthAuthorizer reads it with its injected challengeParser, so with a custom parser the two could disagree. The HTTPClientAuthorizer requirement handleChallenge(statusCode:headers:endpoint:operationKey:sentAuthorization:session:), new in this release, now returns HTTPChallengeResult: whether to retry, and whether the retry is a DPoP nonce retry. Its default calls the Bool handleChallenge (unchanged since 0.12) and classifies the challenge with the default parser as the transport did, so custom authorizers keep their behaviour. OAuthAuthorizer reports the nonce retry it already detects with its challengeParser: a valid DPoP-bound token and a nonce. A use_dpop_nonce it answers with a new token is an ordinary attempt. The transport asks the authorizer first, so it now also calls it for a second nonce challenge before failing the request. The GET stream keeps counting every challenge through an internal Bool overload until it gets the nonce exemption.
- Of a Bearer and a DPoP challenge in one WWW-Authenticate, the authorizer answers the one for the scheme the request used, read from sentAuthorization (the stored token for the Bool method). RFC 9449 section 7.2: a resource that offers both schemes puts the error in the challenge of the mechanism the client used, so a DPoP token's 403 insufficient_scope carried in the DPoP challenge was read from the bare Bearer one and not stepped up. A resource_metadata missing from the answered challenge is taken from the other (RFC 9728 section 5.1). - authorizationHeaders discards a token bound to another DPoP key, or a DPoP token without DPoP, before the expiry check, so an expired one is cleared too, and a refresh never uses the refresh token of such a token: RFC 9449 section 5 has a public client present a proof of the key the refresh token was obtained with. The refresh guard covers prepareAuthorization, which runs before authorizationHeaders. - A use_dpop_nonce challenge is a nonce retry only while the stored DPoP token is bound to the configured key. - Tests: a DPoP token refresh keeps the key binding and sends a proof of that key; the refresh that keeps the previous refresh token also keeps the previously granted, non-empty scopes.
Client.connect in .automatic mode sends server/discover and gives the server discoveryTimeout (10 seconds) to answer before it falls back to initialize. The timer started when the request was dispatched, so it also ran while HTTPClientTransport was inside the authorizer for that request: a 401 on server/discover starts the OAuth flow, and for the authorization_code grant that is a user signing in at a browser. A sign-in longer than 10 seconds was therefore cancelled when the timer fired. The client fell back to initialize, which was challenged again and started a second authorization flow, and the session was pinned to 2025-11-25 even when the server serves 2026-07-28. Found by driving the client against an Inspector test server that serves both eras, with a consent step delayed by 15 seconds; a stalled token endpoint triggers the same path. The timeout exists to detect a server that never answers server/discover (SEP-2575 discovery, falling back to the handshake). Time the client spends authorizing says nothing about that. HTTPClientTransport now records the authorizer calls (prepareAuthorization and handleChallenge) of each request's POST, and Client waits for an authorization in progress and starts the full timeout again when it ends. A server that stays silent after authorization still gets the fallback. Authorization failures are rethrown as before. No public API changes.
…request (#390) fix: Refuse a request whose id is in flight, and answer no cancelled request
…ing decodes as Value.data (#395) fix: Require an RFC 2397 media type in data: URLs, and say when a string decodes as Value.data
…tion VERSIONING.md covered the wire behavior of each negotiated revision, and said nothing about extensions. Every extension in the MCP module was therefore held to the core protocol's promise: a wire change waits for a major release. SEP-3392 gives extensions a lifecycle. A Beta extension may still change, breaking changes included, with Extension Maintainer approval only. A Stable one changes only with a core protocol revision. Under the old rule the SDK could not follow a Beta extension's specification in a minor release, which makes Beta extensions costly to take in at all. The Events extension (SEP-3415, issue #376) shows the problem. It is Beta, its error codes are marked provisional, and ext-events still has open issues about webhook delivery. Shipped under the old rule, a fix the extension makes later would have to wait for 2.0. A new Extensions section keeps the Swift API of every extension under the 1.x promise, and makes the wire behavior depend on the stage: Stable is covered like the core protocol, and Beta may change in a minor release to follow its specification, with release notes. A Swift API that a wire change replaces is deprecated, not removed. At 1.0.0, MCP Apps is Stable, and the Tasks extension, Skills and Server Cards are Beta, as SEP-3392 classifies them. ROADMAP.md lists the Events extension under Planned and in the SEP coverage table, tracked in #376, with 1.0.0 as the goal if it is ready in time and 1.1.0 otherwise. Assisted-by: Claude
Review of the Beta extensions policy found gaps: - Breaking changes still held every wire change of a shipped revision for a major, and Allowed in a minor had no Beta entry. Both now point to the Extensions section. - SEP-3392 asks an extension that makes a breaking change to bump a revision string in its settings object, so that a peer can refuse a revision it does not know. The SDK neither sends nor checks it, so two peers on different revisions of a Beta extension go undetected. The section now says so, and the SEP-3392 row in ROADMAP.md records it as the gap. - The stage table now covers Experimental (the SDK implements none), promotion to Core in a revision R, and archived extensions. - The extensions page, not the specification's directory, is the stage reference until every repository moves: ext-tasks still publishes specification/2026-07-28/ and specification/draft/. The 1.0.0 list becomes a table, adds the Stable ext-auth extensions the SDK implements (OAuth Client Credentials, Enterprise-Managed Authorization), and gives Tasks as Beta, to Core, as the extensions page does. - ROADMAP.md had no row for SEP-3392, and its intro counted 44 SEPs read on 2026-10-28. The index now lists 46, all with a row. Assisted-by: Claude
The SDK neither sends nor checks the revision setting that SEP-3392 asks an extension to add or increment on a breaking change, so two peers on different revisions of a Beta extension go undetected. VERSIONING.md said so without saying whether that would change. ROADMAP.md now plans it: send the revision the SDK implements in each Beta extension's settings object, and do not enable an extension whose peer declares a revision the SDK does not know. The SEP-3392 row and the Extensions section of VERSIONING.md point to the plan. Experimental extensions stay out of scope: the SDK implements none, and taking one in still needs a change to the policy. Assisted-by: Claude
The previous commit dropped it, so Markdown rendered the paragraph about the conformance harness as part of the last list item. Assisted-by: Claude
…ws the wire The Beta exception loosened only the rule on wire behavior. Two other rules still held a Beta wire change that touches typed Swift API for a major: "Changing documented behavior so that working code stops working", because a property that reads a renamed field changes what it returns, and the Deprecation section's "keeps working for at least one minor release", which a deprecated API cannot do once the peer stops sending what it reads. The Extensions section now says what a Beta extension's Swift API keeps: source compatibility, with nothing removed or renamed and no enum case added in a minor release. Values its specification may grow are open types or enums with an unknown case, as the classification rules already require for a set a pending SEP grows, so the rule on adding enum cases needs no exception. Behavior that depends on the wire follows it, with release notes. An API that a change replaces is deprecated, keeps working while the SDK can map the new wire form to it, and otherwise returns nil or an empty value, or throws, until the next major release removes it. The documented-behavior bullet and the Deprecation section point to the section. This paragraph replaces the one-line note on deprecation it subsumes. Assisted-by: Claude
VERSIONING.md says every public enum is one of three kinds and that its documentation says which. Skill.Resources said "Frozen: no case is added in 1.x", but its decoder maps every resources value that is neither a manifest nor "dynamic" to unrecognized(Value), a form from a later revision of the extension included. That is the unknown-case kind, with unrecognized(_:) in the role of the unknown case. Its documentation now says so, and the doc comment of unrecognized(_:) names later revisions next to invalid entries. A host still does not load either. None of the public enums and open types of the Beta extensions were in the classification tables. They now are: - Frozen: ServerCard.FetchResult, whose two cases are the outcomes of HTTP revalidation. - unknown case: Skill.Resources. - Open: TaskStatus, TaskSupport, ServerCard.Remote.TransportType and ServerCard.Input.Format, whose documentation already says a value the SDK does not know decodes as itself. No change to behavior, signatures or the wire. Assisted-by: Claude
Signed-off-by: bbdu3 <ergouyang854@gmail.com>
Signed-off-by: bbdu3 <ergouyang854@gmail.com>
Apple's FoundationModels framework describes structured data with Generable, @generable and @Guide, and runs its own Tool protocol in a LanguageModelSession. An MCP tool and a FoundationModels tool describe the same thing, but bridging them meant hand-writing JSON Schema Values on the server (#135), and decoding an MCP inputSchema into GenerationSchema with JSONDecoder failed on ordinary schemas on the client, because its Codable form is undocumented (#169). The bridge lives in the MCP target, in Sources/MCP/FoundationModels/, behind #if canImport(FoundationModels) and @available(macOS 26.0, iOS 26.0, visionOS 26.0, watchOS 27.0, *), @available(tvOS, unavailable). The deployment targets do not change: FoundationModels is weak-linked, so apps still launch on macOS 15, iOS 18 and visionOS 2. Linux and SDKs without the framework compile it out. Server (#135): - MCP.Tool initializers derive inputSchema and outputSchema from Generable argument and output types, or from an existing FoundationModels.Tool. - CallTool.Parameters.arguments(as:) decodes the arguments into a Generable type and answers -32602 for arguments that do not match, Value.int numbers outside exact Double precision (compared in Int64) and non-finite numbers. - CallTool.Result(_:isError:_meta:) returns a structure as structuredContent plus its JSON as text, leaving out null properties so the result conforms to the derived outputSchema. - FoundationModels.Tool.call(_:) serves tools/call. A tool error becomes an isError result with its LocalizedError description, or "The tool failed." so the bridged localizedDescription does not name module and type. Client (#169): - GenerationSchema(jsonSchema:name:) builds a DynamicGenerationSchema rather than decoding with JSONDecoder. It keeps what a generation schema can express and loosens the rest (pattern, which guided generation rejects, is dropped). Local $ref, anyOf/oneOf with merged sibling properties (also into $ref and nullable-object choices), and items: false are supported. Every choice of a root anyOf/oneOf, nested ones included, must convert to an object. Depth (32) and size (1,024 subschemas) are bounded, including choices that refer to themselves. Anything that cannot be loosened safely throws JSONSchemaError with the JSON Pointer of the subschema. - Client.LanguageModelTool wraps a model-visible MCP.Tool as a FoundationModels.Tool, with an optional approval callback. It sends null for omitted properties that are required and nullable, and returns isError results to the model prefixed with "Error: ". - Client.languageModelTools(approval:) pages tools/list (stopping on repeated or empty cursors and after 100 pages), deduplicates tool names, and leaves out view-only tools and tools whose schema cannot be converted, with a warning. Also: Value <-> GeneratedContent conversions, design/foundation_models.md, server and client guide sections, snippets tested in both eras, and a FoundationModelsExample app that runs the same tools in a local LanguageModelSession and over a stdio MCP server. Value(_ content: GeneratedContent) overloads Value.init(_:), so the existing doc link to the Encodable initializer in Value.swift is disambiguated as Value/init(_:)-(T) for DocC. Fixes #135. Fixes #169. Assisted-by: Claude Assisted-by: Gemini
…with "id": null Follow-up to the review of #375. - Server: a lone response that cannot be read (no `jsonrpc`, or not "2.0") is answered with `"id": null`, as inside a batch. A response's `id` names a request of this server, not one of the peer, so answering with it could fail an unrelated request of the peer. Unreadable messages are logged again, the unreachable `.parseError` catch branch is gone, and a body already decoded as an object is not parsed a second time. - HTTP server transports: an error response with `"id": null`, the answer to a request whose id could not be read (JSON-RPC 2.0 §5), is a response and gets 202 instead of 400 -32600; in a batch it gets no reply. Only an error may carry a null id: a `result` with one still gets -32600. - HTTPClientTransport: the `jsonrpc` check added to JSONRPCMessageKind no longer decides where an SSE stream ends. The transport ends the POST stream on any answer to its request, as before, because `Client` fails the request an unreadable answer names; it no longer resumes the stream and reports a second error for it. - Docs: the protocol guide, the stateless design note and CHANGELOG say which input gets -32700 and which -32600. - Tests name their parameterized cases by their arguments. Assisted-by: Claude
…e client An answer that names a pending request but cannot be read left that request waiting forever, since server-to-client requests have no default timeout. - Server: a response with no `jsonrpc` (or not "2.0"), or an error that does not decode, is still answered with -32600 and `"id": null`, and now also fails the server-to-client request its `id` names, alone or in a batch (Batch.Item.invalidResponse), as Client already does for its requests. - Client: an answer with a `result` or an `error` whose `method` is not a string (`null`, a number) fails the request it names. HTTPClientTransport already treated it as the answer and ended the POST stream, so the request had no stream left to complete on. Assisted-by: Claude
…ncoding The converter tests read a GenerationSchema back by encoding it to JSON, and FoundationModels encodes the same schema differently by OS release. On macOS 26 (the macos-26 runners, and the iOS 26 simulator) a string enum is a $ref to a named $defs entry, a string const is a one-value enum, and a description beside a $ref to a choice is not written. macOS 27 writes them inline. Four tests pinned the macOS 27 form and failed on macOS 26, although the schemas mean the same and the bridge works there: the wire tests, the conversions that must throw, backfill and the end-to-end client/server tests all passed. The converter's output goes to a LanguageModelSession, not on the wire, so its tests now compare the encoding after inlining string enums (enum, const or a choice of constants) and removing their $defs entries. They read a choice's description beside its $ref or on its definition. A test feeds the normalizer both encodings. The tool schemas the server sends are still compared exactly. Assisted-by: Claude
MCP.Tool(arguments:) sends the framework's encoding of the arguments' GenerationSchema as inputSchema. macOS 27 writes a property typed as a @generable enum inline as a string enum. macOS 26 writes some string enums as a $ref to a $defs entry, and no wire test covered an enum-typed property, so the schema a server sends on macOS 26 was unchecked. The new test derives the input schema of a type with a required, an optional and an array-of enum property. It checks that every $ref resolves within the schema, so a client can follow it, and that the schema means the same string enums with the property's description on every OS release. It also checks that a client converts the schema back and that the server decodes matching arguments and rejects an unknown case with -32602.
…tion (#397) docs: Let the wire behavior of Beta extensions follow their specification
Both HTTP server transports answered a POSTed response whose `jsonrpc` is not "2.0" with 400 before it reached `Server`, so the server-to-client request it names (roots/list, sampling, elicitation) still waited forever over Streamable HTTP, though the stream transports now fail it. JSONRPCMessageKind classifies such an answer with a string or integer `id` as `invalidResponse` instead of failing. Each transport runs its validation pipeline (origin, authentication, session) first, then gives the body to the server, which fails the request it names, and answers 400 with -32600 and `"id": null` as before. Before, the 400 came ahead of validation. CHANGELOG: drop the HTTPClientTransport entry. On rel/1.0.0 the client already ended the POST stream on such an answer; only the intermediate commit of this branch changed that. Assisted-by: Claude
Follow-up to the review of this branch.
- Server: the receive loop's fallback decoded a single message as
`[String: Value]` to find its `id`. An answer with a member no `Value`
holds, such as `"result": {"x": 1e400}`, failed that probe: it got -32700
though it is valid JSON, and the request it names kept waiting, while
the same item in a batch failed it. The fallback now classifies the
message as `Server.Batch.Item`, so single messages and batch items share
one classification.
- Server.Batch.Item: the `case nil` branch no longer splits answers from
other items. JSONRPCMessageKind classifies an item with a `result` or an
`error` whenever its `id` can be read, so the `id` there is always `nil`
and both branches gave the same reply.
- HTTPClientTransport: `answeredRequestID(in:)` reads the answer through
JSONRPCMessageKind (`.response` with an id, or `.invalidResponse`)
instead of a separate JSONSerialization probe.
- Tests: the unreadable-answer test covers an error without its `code` and
a number no `Value` holds, alone and in a batch. An HTTP row pins that
an error without its `code` gets 202: the transports read the shape of
a message, and `Server` fails the request it names.
- Docs: over HTTP an invalid request with a `method` keeps its `id`, and a
response whose `jsonrpc` is not "2.0" gets its 400 after validation.
Assisted-by: Claude
Follow-up to the review of this branch.
- classificationError(for:) told valid JSON from invalid JSON with
JSONSerialization, which rejects a number out of range such as `1e400`.
StatelessHTTPServerTransport parses the body with JSONSerialization, so
a body holding one got -32700 though it is valid JSON, where the other
transports answer -32600. It now probes with JSONDecoder, which reads
such a number as valid JSON and still rejects invalid JSON.
- The HTTP server transports log the dropped `"id": null` -32600 that
`Server` sends for each answer it cannot read at debug, not warning:
the POST was already answered.
- Tests: `1e400` joins the invalid ids of both HTTP transports. The 202
for an error without its `code` gets a test of its own on each HTTP
transport, out of the "still accepted" table. A request whose `params`
hold `1e400` keeps its `id` on the stream transports. The null-id result
that a single stream message accepts is recorded with `withKnownIssue`;
its fix belongs to `Response` decoding.
- docs/src/protocol.src.md (and docs/protocol.md):
- "One with a `method`" becomes "One with a string `method`":
`{"jsonrpc":"2.0","id":7,"method":42}` keeps its id on stdio but not
over HTTP.
- "A response that cannot be read always gets `"id": null`" is split by
transport: over HTTP it gets 400 only when its `jsonrpc` is not "2.0",
and 202 when only its content cannot be read.
- An error response with `"id": null` answers no request "unless one has
the id `""`", since `ID` reads `null` as `""`.
- CHANGELOG: a request whose `id` can be read but whose `params` cannot
gets -32600 with its `id`; over stateful HTTP its POST got no answer.
Kept as is: the stateless transport forwards a message whose headers were
not checked byte for byte, as design/request_headers.md describes.
Assisted-by: Claude
feat: Bridge MCP tools and Apple FoundationModels
…d fail requests whose answer cannot be read (#401) fix: Distinguish invalid JSON-RPC messages from JSON parse errors, and fail requests whose answer cannot be read
`NetworkTransport` sends a heartbeat as 12 bytes, 4 magic bytes and an 8-byte timestamp, with no newline, and `receiveLoop()` decided whether bytes were a heartbeat by looking at the first 4 bytes of each read. TCP keeps the bytes of a stream but not the boundaries between sends, so a heartbeat and a message often arrive in the same read. A read that started with a heartbeat was dropped together with the messages after it, a heartbeat at the end of a read was prepended to the next message, and a heartbeat split across two reads left some of its bytes in front of the next message. The timestamp can also hold 0x0A, which cut such a heartbeat in two, and a read that started at U+1F493 inside a message was dropped, because that character encodes to the magic bytes. Fix: append every read to the buffer and recognize a heartbeat only where a message would start, consuming it by its fixed length. A line from the peer that starts with the magic bytes but is shorter than a heartbeat would then be consumed together with the start of the message after it. Fix: take the 12 bytes for a heartbeat only when the two high bytes of the timestamp are zero, which holds for every date before the year 10000 and never for JSON text. The heartbeat bytes on the wire and the public `Heartbeat` API do not change; `Heartbeat` uses one length constant instead of repeated literals. Adds `NetworkTransportTests` for a heartbeat in the same read as messages, for reads that end at every byte of a stream of messages and heartbeats, for a short line that starts with the magic bytes, for bytes that only start like a heartbeat, and for the heartbeat recognition helpers. Without the fix, the first three fail.
… initialize, cancellation and progress The spec moved from spec.modelcontextprotocol.io (no longer resolving) to modelcontextprotocol.io, and 2026-07-28 moved cancellation and progress from basic/utilities to basic/patterns. Every doc-comment spec link points at a live page, with a 2026-07-28 link next to the 2025-11-25 one where the two revisions differ. The comments themselves described only the handshake revisions: - ping, initialize and notifications/initialized do not exist at 2026-07-28 (SEP-2575). The comments say so, and what the SDK does instead: Client.ping() sends server/discover, and .automatic mode tries server/discover before initialize. - Cancelling a request at 2026-07-28 over Streamable HTTP closes its response stream rather than sending notifications/cancelled, and a server sends notifications/cancelled only to tear down a subscriptions/listen stream. - Progress notifications at 2026-07-28 flow only from the server.
The `.unknown` cases on the content blocks and `CreateElicitation.Parameters` said the block "is encoded as received", and the migration guide said the same. `UnknownBlock` decodes into `Value` and re-encodes it, so key order and number formatting can change (`1.0` is written `1`). Anyone who signs, hashes or byte-compares a block passed through needs to know that.
Review follow-up. "The same JSON value" was too strong: `Value.Preserved`
reads a number as an `Int`, then a `Double`, so an integer outside the
`Int` range or a decimal beyond `Double` precision is rounded on the way
back. The list of byte-level changes also left out whitespace and string
escapes (`\u00e9` comes back as `é`, and the client's `JSONEncoder` writes
`/` as `\/`).
The migration paragraph spoke for every unknown kind, but an unknown
`InputRequest` keeps only `method` and `params`, and a request without
`params` (or with `"params": null`) goes back out with `"params": {}`.
It now names blocks and elicitation `params`, and states that exception.
A test pins it, and the test that said "re-encoded as received" is renamed.
Written with AI assistance and reviewed by a human.
…ges (#400) fix: stop NetworkTransport heartbeats from dropping or mangling messages
…403) docs: Say that an unknown block keeps its JSON value, not its bytes
… initialize, cancellation and progress (#402) docs: Link live spec pages, and say what 2026-07-28 changes for ping, initialize, cancellation and progress
akhilcb
approved these changes
Nov 29, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This draft PR merges
rel/1.0.0intomainand becomes the Swift SDK 1.0.0. It is the overview of the release. The work itself is reviewed in 36 stacked PRs, P0 to P35, each with its own description of the design choices behind it. They merge intorel/1.0.0in order, then this PR merges intomain.What 1.0.0 brings
Serverand oneClient. The stateless 2026-07-28 revision (per-request_meta,server/discover,subscriptions/listen, multi round-trip requests, standard and custom request headers, cache hints) is served next to theinitialize-based revisions, 2024-11-05 through 2025-11-25. Servers serve both by default. Clients connect withserver/discoverand fall back toinitializefor older servers. Code that differs per revision readsProtocolProfileflags.@modelcontextprotocol/conformance@0.2.0-alpha.12) passes with an empty baseline: 2025-11-25, 2026-07-28 and the default wire, client and server. The tier score is 100% for clients and servers at 2025-11-25 and at 2026-07-28. A formal verification of the framework against an executable model of the specification found further divergences; P35 fixes them.interop/RESULTS.mdhas the results.io.modelcontextprotocol/tasksextension of SEP-2663 at 2026-07-28), Skills (SEP-2640), Server Cards (SEP-2127) and MCP Apps views (SEP-1865), on the server and the client.application_type, authorization server migration, the JWT bearer grant (RFC 7523), token exchange and enterprise-managed authorization (SEP-990, RFC 8693), workload identity, and DPoP-bound tokens (RFC 9449, SEP-1932).VERSIONING.mddefines it: every public enum is frozen, extensible or an open type, and anapi-breakageCI job compares the public API with the newest release.CHANGELOG.mdlists the breaking changes from 0.12, anddocs/migration.mdshows the before and after code.docs/, design notes indesign/, and a SEP coverage table inROADMAP.mdthat marks each SEP Implemented, Partial, Planned or Not applicable, with the reason.ROADMAP.mdlists what is planned after 1.0.0, such as the MCP Apps View-Host bridge.The PRs, by area
Each area lists the parts a domain expert may want to read first. Every part builds and passes
swift test, and every part after P0 is stacked on the one before it, so its diff shows only its own changes.2026-07-28 stateless protocol
_metaand result typesserver/discoversubscriptions/listennotification streams (SEP-2575)Transports and reliability
disconnect()is releasedAuthorization
application_type, authorization server migration (SEP-2468, SEP-837, SEP-2352)Extensions
Specification features and deprecations
includeContext(SEP-2577, SEP-2596)Conformance, interop and verification
CI and platforms
API stability and release
Documentation
How it merges
rel/1.0.0in stack order, bottom up: P0 to P8, P10, P9, P11 to P35. Each part needs one approval from a code owner.rel/1.0.0, so no part has to be rebased.rel/1.0.0.mainwith a merge commit, andmainis tagged 1.0.0.AI usage disclosure: the changes, the tests, the commit messages and this description were written with Claude Opus 5.5 and reviewed by the authors. Two review-fix commits (in P14 and P35) were also written with Gemini, as their
Assisted-bytrailers say.