Repository navigation
MCP Swift SDK 1.0.0 - #372
Open
jeanmatthieu wants to merge 375 commits into
Open
jeanmatthieu wants to merge 375 commits into
jeanmatthieu wants to merge 375 commits into
Conversation
A Server Card is a static document that describes a remote MCP server
before a client connects. The format is the one of the Server Card
extension, modelcontextprotocol/ext-server-card at 526201bb (the
snapshot SEP-2127 cites, and the head of main on 2026-10-28).
ServerCard has the fields of schema.ts. Decoding needs the required
fields and ignores unknown ones; validate() checks the rest: the
$schema value, the reverse-DNS name, version ranges, lengths, URIs and
the remote URL pattern. ServerCard(info:endpoint:protocolVersions:)
builds a card from Server.Info, with name and description overrides,
because Server.Info.name is often not reverse-DNS.
ServerCardValidator serves the card at <endpoint>/server-card as the
extension's discovery.md asks: the card's media type, an ETag, 304 for
a matching If-None-Match, Cache-Control, the CORS headers, HEAD, and
the preflight OPTIONS (If-None-Match is not a CORS-safelisted header).
Applications call response(to:) before their MCP endpoint; in a
transport's pipeline it works too, so the stateless transport passes a
validator's 304 and the stateful transport runs validators for methods
other than GET, POST and DELETE.
ServerCard.fetch sends Accept and If-None-Match, needs https or a
loopback host for the URL and the final URL, refuses bodies over 1 MiB,
and validates. cardURL(forEndpoint:), Remote.url(resolving:) for
{variable} templates, and mismatches(with:) against server/discover,
because a card is advisory. No AI Catalog discovery.
Tests: the extension's valid and invalid examples, copied with their
SHA-256 by scripts/server-card-examples.mjs, the checks, serving and
both transports, and fetching through URLProtocol mocks. The HTTP
example serves a card; the guides and design/server_cards.md describe
it.
- ServerCard.fetch streams the body through the SDK's response body reader and stops after 1 MiB + 1 byte, and refuses a larger Content-Length before reading, instead of buffering the whole response before the size check. - ServerCard.fetch checks each redirect before it is requested, with the OAuth discovery rule (https, or loopback http from loopback http, never a private IP literal); a refused redirect throws insecureURL. StreamingSession takes an optional redirect guard: a task delegate on Apple platforms, the session delegate on swift-corelibs. - The stateful HTTP server transport passes a validator's 304, so a conditional HEAD of the server card is no longer turned into 405. - HEAD of the server card carries Content-Length with the card's length, since its body is empty. - ServerCardValidator.init throws invalidCard when the card does not encode, instead of serving an empty 200 card. - cardURL(forEndpoint:) keeps the endpoint path percent-encoded, so %2F in a segment survives. - Remote.url(resolving:) percent-encodes substituted values except for unreserved characters, so a value cannot add a path, query or user or move the host; a placeholder that starts the URL is inserted as is. - ServerCardTests: the streamed-body test sends 40 MiB and allows up to 20 MiB before the cancellation reaches the mock, and the Content-Length test starts its body 0.2 s after the headers, so a loaded Linux machine does not fail them.
- Remote.url(resolving:) reports the template, not the resolved URL, when the result is not an http or https URL: substituted values can be user secrets (isSecret) and the message reaches logs. - Document that a resolved remote can be plaintext http on any host: the schema allows http:// remotes, and fetch's https rule covers the card, not its remotes. Callers check the scheme before connecting. - Look for x wildcards only in the numeric part of a version, before - or +, so 1.0.0+build.x and 1.0.0-alpha.x are single versions. - validate(), url(resolving:) and ServerCardValidator.init throw untyped errors, as fetch and the rest of the SDK's public API do. The doc still names ServerCardError. - ServerCardError conforms to LocalizedError, with the message as errorDescription, so localizedDescription is not Foundation's generic text.
- Hold the URL passed to fetch to the rules of a redirect target, with loopback hosts allowed: parse it with URLComponents, require a non-empty host, and refuse a private or reserved IP literal (OAuthURLValidator.isPrivateIPHost, which does not block loopback) before any request is made. The URL can come from an AI Catalog, and only the scheme and the loopback exception were checked, so a private or link-local address, an https URL without a host and a bracketed IPv4 or name host were requested. Host names are still not resolved; the documentation says so. - Judge a refused redirect from the hop that sent it (http.url), as OAuthRedirectGuard does, not from the first URL. A chain from loopback http through https back to loopback http was refused by the guard but reported as httpStatus 302 instead of insecureURL. - In Remote.url(resolving:), insert a value as given only when its placeholder starts the template, not whenever nothing was written yet. After a leading placeholder that resolved to nothing, the next value went in unencoded and could set the scheme and host (RFC 3986 §2.1). - Tests: the HEAD 200 and 304 answers of the stateless transport, and the loopback test server closes its socket when binding fails.
MCP Apps lets a tool show its results in an HTML view that the host renders in a sandboxed frame. The wire is the one of the io.modelcontextprotocol/ui extension, modelcontextprotocol/ext-apps at v2.0.4 (7af9a75d), specification/draft/apps.mdx. The SDK implements the wire between server and host, not the View-Host bridge. Types: ExtensionID.ui, UIExtensionSettings (mimeTypes), UIResourceMeta (csp, permissions as presence flags, domain, prefersBorder) and ToolUIMeta (resourceUri, visibility as an open struct). Tool.ui, Resource.ui and Resource.Content.ui read and write _meta.ui; the raw _meta stays the source of truth and keeps unknown keys, and decoding is lenient per field. Tool.ui reads the deprecated flat key _meta["ui/resourceUri"] when _meta.ui has no resourceUri, and never writes it. Tool.isVisibleToModel and isCallableFromApp default to true. Server: withAppResources(_:listInResources:) serves UIResources (a ui:// URI, HTML as text or bytes, one UIResourceMeta on the listing entry and on the content item), and declares the extension and resources. Views and skills now share one internal path for built-in resources: ordered sources answer resources/read before the application's handler and join the first resources/list page, with one cursor for every position. A cursor position that the server cannot advance is dropped, so a stale or crafted cursor cannot page forever. HandlerContext.clientUISettings is the client's declaration, from initialize or from the request's _meta. Client: Client.Capabilities.ui declares the extension. readAppResource(uri:listing:) checks the URI, the MIME type and the body, and returns the effective metadata: the content item's _meta.ui, or else the listing entry's, found in up to 100 pages when not given. UIResourceMeta.CSP.policy() builds the specification's policy, and restrictiveDefault is its policy without csp; origins that could add a directive or a keyword are dropped. Tests: the specification's examples, the accessors, the CSP builder, serving and merging with skills, and reading as a host in both eras. The guides, design/apps.md and ROADMAP (Partial: the bridge is Planned) describe it. The apps profile runs the Swift, Go, Python and TypeScript clients against the Swift everything-server, in both eras, and against the TypeScript server, at 2025-11-25, over HTTP and stdio: 22 cells, all passing. Both servers serve the same fixture: the view ui://interop/weather.html with _meta.ui on the listing entry and on the content item, show_weather, which renders in it, and refresh_weather, for the view only. The Swift fixture is conformance/everything-server/Apps.swift, on withAppResources; the conformance legs do not change. The TypeScript server registers it with the ext-apps server helpers (registerAppResource, registerAppTool, which also writes the deprecated flat key). Each client declares io.modelcontextprotocol/ui with the HTML MIME type and checks the tools' _meta.ui, the listing and content metadata, and that the server saw the declaration (getUiCapability on TypeScript, clientUISettings on Swift). The Swift client uses the SDK's types; the others read the raw _meta. ext-apps is pinned at 1.7.5 in interop/ts-client: 2.x needs the TypeScript SDK v2 packages, which also serve 2025-11-25 only, and 1.7.5 runs on the pinned SDK with the same wire for these checks. It needs Node 20. RESULTS.md and the findings record the run.
- A merged resources/list page (the application's page with views and skills) now has the shortest ttlMs of its pages, and cacheScope private when any page is private, instead of the application's hints covering entries whose own page allowed less caching. - UIResource requires the ui:// scheme in lowercase: views are found by their exact URI, so a view registered as UI://x was not served for a read of ui://x and vice versa. - readAppResource uses the listing entry's metadata only when the content item's _meta.ui is absent or null, as the specification's `??` does; a present but malformed value now gives no metadata and the restrictive default policy, not the listing's possibly looser policy.
- Document that a ResourceListChangedNotification after a second withAppResources needs resources.listChanged: withAppResources declares resources without it, and listen streams carry the notification only when it is declared. - readAppResource returns the view with no metadata, and so the restrictive default policy, when the resources/list fallback fails: the listing only adds metadata, so it should not fail the read. Cancellation still propagates. - AppResourceContents has a public memberwise init, so callers can build one, for example in tests. - CSP.policy() says it uses the declared sources as given: a declared * or scheme-only source allows any origin, and a host that does not trust the declarations filters them first. - The ui setters say which keys they keep: other top-level keys of _meta.ui, with csp and permissions written as modelled; Client.Capabilities.ui replaces the extension's settings object. - Test that a second withAppResources replaces the views for read and list, with skills installed in between, and that the views stay before the skills. - The prerequisites of scripts/run-interop.sh, in its header, interop/README.md and CONTRIBUTING.md, list perl and python3, which the script checks for: perl runs the time limit and python3 the report. Node was already listed except in CONTRIBUTING.md.
- readAppResource refuses a URI that does not start with ui:// in lowercase, without a request, as UIResource does: views are looked up by the exact URI, so UI://x went to the server and failed there with a not-found error or missingContent. - UIExtensionSettings(_:) reads the extension as declared only when its value is an object, as SkillsSettings(_:) does: a null, false, string or array value no longer declares a host that renders views. - The ui setters encode _meta.ui with Value.preservingStrings, and CSP and ToolUIMeta decode their lists as Value.Preserved: a string that is a data: URL, in visibility, a CSP list or domain, stays the string as written instead of being re-encoded, or dropped on read. - A merged resources/list page counts a page without ttlMs or cacheScope with the server's hint for resources/list (cacheHints, else defaultCacheHint, .uncached by default), the hint that page would get alone. An application page that relied on .uncached inherited a skill catalog's public scope and longer ttlMs. The views' page has no hints, so it counts with the same hint. - Tool.ui says that its setter keeps the other top-level keys of _meta.ui, as Resource.ui and Resource.Content.ui say.
An HTTPClientTransport that the application dropped without calling disconnect() was never released. connect() started a task that held the transport while it waited for a session ID, which with streaming: false, or a server that never sends one, it waited for forever; with streaming: true the GET loop held it for its whole life and kept reconnecting with backoff; and nothing cancelled the tasks or invalidated the two URL sessions, which keep their delegates until invalidated. - The session ID wait is a signal the transport owns and the GET loop waits on, with the timeout timer next to it. A session ID, the timeout, disconnect(), useStatelessProtocol(_:), cancellation of the task or the release of the transport ends it, once. connect() starts no task when streaming is false. - The GET loop is a static function over a weak reference: it holds the transport for one step (opening the stream with its authorizer and DPoP retries, handling one event), not while it waits for the session ID, sleeps before reconnecting or waits for the next event. Backoff, consecutive failures, 400/404/405 handling, session expiry, Last-Event-ID and retry: behave as before. - deinit cancels the GET task and the POSTs in flight, ends the session ID wait, finishes the message stream and invalidates both sessions (no task can be creating a URLSession task then: that holds the transport). - Doc comments on the transport, connect() and disconnect(), and on Client and Client.disconnect() (a connected client must be disconnected: its receive loop keeps it and its transport alive); the protocol and client guides, the migration guide and CHANGELOG say the same. Tests: HTTPClientTransportReleaseTests, with a streaming URLProtocol mock: a dropped transport is released without streaming (and its message stream ends), while waiting for a session ID (no GET is sent), while reading an open GET stream (the stream is closed, no further GET), and while waiting to reconnect after a failed GET (no further GET). The suite is in HTTPClientTransportTests.swift: in a separate file, a second URLProtocol subclass compiled in the same frontend batch makes Swift 6.4 reject MockURLProtocol's startLoading.
- A transport dropped without disconnect() stops its GET stream when it is released, not by the next event: the listener holds it only weakly while it waits, so deinit runs at once, cancels the listener and invalidates the session that owns the GET. Fix the doc comments of the type and of connect(), and the guides. - releasedWithOpenStream no longer writes an event after the drop, so it checks that the release itself closes the stream. - connect() after disconnect() throws internalError instead of building new URL sessions: the stream receive() returns is finished by then, so a reconnected transport dropped every message. A transport serves one connection (protocol guide, Transports); the session ID, stateless mode and last event ID would also carry over. The previous release raised at the next send on Apple platforms. The migration guide says so. - disconnect() also cancels POSTs without a request ID (notifications and responses to server requests). They ran in the caller's task, and on Apple platforms a request keeps the sessions valid until its response headers arrive, so such a POST outlived disconnect() until the server answered or the idle timeout. - The HTTPClientTransport docs state the 16 MiB limit on an SSE line and on the data of one event, already in the migration guide.
Cancelling the caller of a tools/call resolves the request's slot at once and leaves the rest (marking the call abandoned, telling the server) to cancelRequest, which runs later on the actor. A response handled in between found the call neither pending for the caller nor abandoned: the slot dropped it, and with it the only copy of the id of the task the server had created, so the task ran on. A heavily loaded visionOS simulator hit it in "Cancelling the caller cancels the task on the server". - ResponseSlot.resolve and AnyPendingRequest.resume report whether their outcome is the one the sender gets. - handleResponse treats a tools/call answer the slot refused as abandoned and sends tasks/cancel for the task in it, as it does for an answer that arrives after cancelRequest. Tests: LateTaskAnswerTests.cancelRacesAnswer, a hand-driven peer that answers each of 500 calls with a task and cancels the caller as it answers; every task must get tasks/cancel. Without the fix about one run in five leaves an orphan on macOS. callerCancellation waits up to 10 s instead of 2 s for the server task to stop.
Building the package scheme for iOS failed: the interop client, the HelloClient example and a docs snippet start a server with Process, which does not exist on iOS, tvOS, watchOS or visionOS (Mac Catalyst is os(iOS)). - The interop client's --stdio, HelloClient and the transport-stdio-client snippet sit behind `#if !(os(iOS) || os(tvOS) || os(watchOS) || os(visionOS))` (the snippet behind `os(macOS)`, like its sibling in Client.swift). There --stdio throws and HelloClient prints why and exits 1; the woven docs are unchanged. - scripts/ci/apple-platform.sh <iOS|tvOS|watchOS|visionOS|macCatalyst> [<destination id>]: xcodebuild build-for-testing of the mcp-swift-sdk-Package scheme (every target, test bundles included) for the device SDK, unsigned, then xcodebuild test on the first simulator -showdestinations offers (this Mac for Mac Catalyst), with the result bundle in .build/apple/<platform>/. A missing SDK or runtime fails with the command that installs it; on Linux the job passes and says so, as fuzz does on macOS. - scripts/ci/jobs gains apple-ios; ci.yml an apple-platforms matrix (iOS) on macos-latest that uploads the result bundle on failure. Another platform is a line in each. Conformance and interop do not run there: their harnesses start the fixtures as host processes. - Two tests that waited a fixed time failed once each under the simulator's load: testServerInitializeMetadata waits for the sent message (MockTransport.waitForSentMessages), and the discovery timeout test waits up to 10 s for its POST to stop. - CONTRIBUTING, CLAUDE.md and CHANGELOG describe the job. Verified with Xcode 27.1: iOS, tvOS, visionOS and Mac Catalyst build for the device and pass on the simulator (1350 tests); watchOS is not installed here. macOS swift test, and build-test on Linux (RHEL UBI 9 through scripts/ci-linux.sh), pass.
AGENTS.md arrived with main (#318) and describes main's tree. Update the facts that the conformance stack changed: - The spec revisions: the SDK serves 2025-11-25 through the handshake and 2026-07-28 per request; code that serves both reads ProtocolProfile flags, and Version.supported lists both eras. - The repository map: conformance/ (fixtures and baselines), interop/, fuzz/, Examples/ with the doc snippets, docs/src/, design/, and scripts/ci/. There is one manifest, Package.swift. - Dependencies (swift-crypto and Yams; no eventsource), toolchains, the iOS simulator job, and the platform gates (SSE streams through the same code everywhere; Crypto with CryptoKit only for Secure Enclave keys; the Process gate). - Commands: the conformance legs, doc coverage, weave, and the CI job runner. - Stability: VERSIONING.md from 1.0.0, the api-breakage job, enum categories, and a deprecated shim that exists (Version.latest). - Concurrency: handlers that Client or Server store on themselves capture self weakly, because a strong capture keeps the server alive; the previous text said the opposite. - Tests and docs: expectWire golden tests, the handshake test configuration, the conformance baselines, the woven guides, the migration guide and CHANGELOG, and ROADMAP's SEP coverage table. - Generated files (docs, README, baselines, interop results) are not edited by hand.
- A connect(transport:) that throws (an HTTP 401 or 5xx, a network error, an unsupported version) releases the connection, as disconnect() does, and waits for the receive loop before it rethrows. Before, the receive loop and the inbound queue kept running and kept the client and the transport alive, and the HTTP transport's GET loop kept reconnecting, although the caller had no connected client. The leak predates this stack (main opened the connection the same way). The client guide and connect(transport:) say a failed connect needs no disconnect(). - The GET stream holds the transport only while it builds each GET and records its reply, no longer while it awaits the authorizer, the response headers or a challenge. openEventStream is a static helper over the weak reference, which the resumption of POST streams uses too, so a transport dropped while its GET waits for headers (up to the request timeout) or for an interactive sign-in is released at once. deinit cancels the GET; a GET being created keeps the sessions valid until its task exists, as at disconnect(). - deinit no longer loops over inFlightPosts: a send() in flight holds the transport, and its entry is gone before send() returns, so the loop cancelled nothing. The type doc and the protocol guide now say a dropped transport stops its GET stream and invalidates its URL sessions, and a send() still running keeps it alive until it finishes or its task is cancelled. - The 16 MiB sentence says what each stream does: a POST's request fails and its stream is not resumed; the GET stream reconnects after its backoff without Last-Event-ID, so it opens a fresh stream. - The static GET loop keeps the fixes of the PRs below: a line or event over 16 MiB drops the stream's resume point, and a 404 is a session expiry only when the GET carried Mcp-Session-Id (sentSessionID). - The reconnect log has willRetryAfter again (the next delay, with backoff), and the exit log says why the loop ended: released, sessionExpired, cancelled or disconnected. - CHANGELOG: connect() after disconnect() throws internalError, and a failed connect(transport:) disconnects the transport. - releasedDuringBackoff: the next waits are 50, 100 and 200 ms.
The late-answer tests drove only the 2026-07-28 shape, where the task is the tools/call result; at 2025-11-25 it is nested in `task`, which handleResponse also reads. A hand-driven peer, LatePeer, now answers in either revision (initialize, a tool that runs only as a task, flat tasks/get and tasks/cancel results at 2025-11-25), and both tests run at both. Dropping the nested lookup fails both 2025-11-25 cases. - cancelRacesAnswer expects every call to have reached the peer and created a task (race.isSettled): a callTool that failed before sending created no task and passed. A one-minute time limit turns a missed cancellation into a failure instead of a hang. At 2025-11-25 it also checks that every call asked for a task. - clientCancelsOrphan waits up to 10 s for each step instead of sharing one 2 s deadline, and checks that tasks/cancel names the late task. - callerCancellation waits for the task to run on the server instead of sleeping 100 ms before it cancels the caller. scripts/ci/apple-platform.sh: a Mac whose Xcode lacks the platform's SDK or a simulator runtime skips the job and says so unless CI is set (GitHub Actions sets it), where it still fails. Before, running every job locally failed on such a Mac. Docs: - CHANGELOG: the tasks/cancel of a call cancelled as its answer arrives joins the tasks feature, which is new in 1.0.0, and says that over HTTPClientTransport at 2026-07-28 an answer not yet read when the cancellation closes the response stream is lost and its task keeps running. The platform line says that CI checks iOS only. - AGENTS.md: withTasks(_:) and withSkills(_:listInResources:) register their defaults, not Server.start; the process snippets gate on canImport(System) && os(macOS) because they also use System's FileDescriptor; swift-nio also backs the HTTP server example. - CLAUDE.md: the job scripts include api-breakage, fuzz and conformance-scripts; the apple-* skip rule.
A formal verification of the framework checked the SDK against an executable model of the MCP specification. Its full-tier run of the Swift harness against c713a2d (spec 2026-07-28, server with protocolVersions: Version.stateless) reported 54 divergences from the model's answers, which come down to twelve root causes. This change fixes the ones that are SDK bugs and that can be fixed without breaking interoperability. The report of the run is the source; each item cites the spec section it follows. Request ids (JSON-RPC 2.0 §5; basic/index.mdx, Requests) - A message with a string method was a request only when its id was a string or an Int: an id of null, 1.5, [], true or 1e20 made it a notification, answered 202 on HTTP and dropped on stdio. Messages are now classified by the presence of id. An invalid id, or a jsonrpc that is not "2.0", gets -32600 (HTTP 400) with "id": null, on both HTTP transports and in the Server's receive loop. A JSON boolean id is refused too, though true as? Int is 1 on Darwin. - Request.init(from:) refuses a null id instead of reading it as "", and "" is a valid id again on the HTTP transports. Message.init(from:) refuses a message with an id member. Missing _meta version and progress tokens (basic/index.mdx, _meta; versioning.mdx; progress.mdx) - A server that serves no handshake revision answers a request without io.modelcontextprotocol/protocolVersion with -32602 and data.supported, not -32022 or -32601: the field is required, not unsupported. A dual-era server still reads such a request as handshake-era. - A progressToken that is not a string or an integer (null, a boolean, a fraction, an object, an array) gets -32602 in both eras instead of being ignored. - Server.start gives a StatelessHTTPServerTransport the versions it serves. The transport validates MCP-Protocol-Version against them, so -32022 lists them, and maps errors to 2026-07-28 HTTP statuses when no handshake revision is served. Authorization (RFC 6750 §3.1; authorization/index.mdx) - BearerTokenValidator answers credentials of another scheme (Basic) with 401 and the Bearer challenge, as it answers no credentials, instead of 400 without one. - A malformed Bearer header and .malformedRequest get 400 with WWW-Authenticate: Bearer error="invalid_request" and resource_metadata. Subscriptions (basic/utilities/cancellation.mdx) - After the result of a subscriptions/listen stream the server closes, the server sends notifications/cancelled for the listen id, on stdio and other message-stream transports. Over HTTP the end of the response remains the teardown. A stream the client cancelled gets neither. Request headers (streamable-http.mdx, Schema Extension and Server Validation; RFC 9110 §5.1, §5.3) - An x-mcp-header annotation off the properties chain (under items, anyOf, $defs or another subschema keyword, or on the root) makes the tool invalid. The client drops the tool and the server hides it. - New public API, additive: HTTPRequest.init(method:headerFields:body: path:) takes the header field lines as received, and headerValues(_:) returns each line's value. header(_:) joins keys that differ only in case, in key order, instead of returning whichever the dictionary lists first. - MCP-Protocol-Version, Mcp-Method, Mcp-Name and Mcp-Param-* sent more than once get -32020 (HTTP 400). Comma-joined values count for the first two, whose values never contain a comma. A repeated handshake version stays -32022. - The SwiftNIO example and the conformance server adapter pass Array(head.headers) to the new initializer. Both had joined repeated lines by exact name only. Client robustness - A response the client cannot decode (an error code that is a string, no jsonrpc) fails the request it names instead of leaving it to wait for its timeout. The warning logs a sanitized prefix, not the whole message. Not changed: - "arguments": null in tools/call and prompts/get is still read as absent. Refusing it, as the schema implies, failed every argument-less call from the Go SDK (v1.8.0 marshals a nil arguments map as null) in the interop matrix. It waits for the Go SDK. PromptTests.testNullArgumentsAreAbsent keeps the lenient read. - The findings that come from the harness adapter and the fixtures (header folding, input validation in the handlers, duplicate member names) are fixed in the harness, not here. Docs: protocol.md (auth responses, listen teardown, adapters), protocol_versions.md, server.md, troubleshooting.md, design/subscriptions.md and CHANGELOG.md. Tests: RequestIDValidationTests (ids and jsonrpc over InMemoryTransport and both HTTP transports); StatelessGatingTests (missing _meta version, progress tokens, served versions in -32022); HTTPServerTransportTests (Bearer challenges); SubscriptionTests (teardown order, client cancel, HTTP); RequestHeadersTests (unreachable annotations, repeated and case-variant headers, header field lines); ClientTests (undecodable responses); PromptTests (null arguments). Existing tests that asserted the old behavior now assert the new one: a Basic header gets 401, and a request without a _meta version to a stateless-only server gets -32602, also in the guide snippet.
- Decode invalid batch items as per-item -32600 replies (JSON-RPC 2.0 §6) so a null id or bad jsonrpc in a batch no longer drops valid requests' replies. - Stop descending past maxSchemaDepth in rejectUnreachableAnnotations instead of throwing when a deep subschema has no x-mcp-header annotations. - Unify InvalidRequestShape into Decodable JSONRPCMessageKind, use HTTPRequest.isRepeated in ProtocolVersionValidator, and remove the unreachable .invalid arm in StatelessHTTPServerTransport. - Align docs and comments on closeSubscriptions() vs stop(), repeated handshake MCP-Protocol-Version (-32022), and undecodable client responses. - Add tests for batch invalid items, deep unannotated schemas, bad jsonrpc with a valid id on StatefulHTTPServerTransport, and malformed incoming messages reusing a pending client request id. Assisted-by: Gemini
- Classify each batch item by its JSONRPCMessageKind (JSON-RPC 2.0 §6). A response in a batch now resumes the server's pending request from the receive loop and gets no reply; before, it took the `id` branch and got a -32600 under its own id, which the peer could match to one of its pending requests. An unreadable response gets an id-null -32600; an item with an id and no method keeps its id-attributed -32600. - Document that misplaced x-mcp-header annotations are looked for down to maxSchemaDepth subschemas and ignored below it, in the parameters(in:) and maxSchemaDepth doc comments, the server guide and CHANGELOG, with tests at depth 32 (rejected) and 33 (ignored). - CHANGELOG: the repeated-header -32020 applies at 2026-07-28, and a repeated handshake MCP-Protocol-Version keeps -32022. stop() sends each listen stream's result, and on message-stream transports its notifications/cancelled, before it disconnects; docs/protocol.md and design/subscriptions.md say the same, matching the stop() of the subscriptions/listen part of the stack. - Batch tests: a notification, an item with an id but no method, an empty method (-32601), batched responses, and a batched response that answers a pending listRoots. A test pins that cancelledRequestID(in:) and JSONRPCMessageKind read every valid id form the same way.
The 1.0.0 stack, P0 to P35, merges into this branch one pull request at a time, with merge commits, before rel/1.0.0 merges into main. This commit changes no file. GitHub opens a pull request only between branches that differ, and the pull request from rel/1.0.0 to main carries the overview of the release.
[P0] conformance: pin harness 0.2.0-alpha.11 and run per-revision legs
…cy-reliability [P1] http: deliver related messages on the request's stream; resume client response streams
[P3] server: serve 2026-07-28 stateless requests
[P4] client: connect with server/discover at 2026-07-28
[P5] http: standard and custom request headers at 2026-07-28 (SEP-2243)
[P6] subscriptions/listen: notification streams at 2026-07-28 (SEP-2575)
[P7] mrtr: input-required results at 2026-07-28 (SEP-2322)
…37/2352) [P8] oauth: issuer checks, application_type, AS migration (SEP-2468/837/2352)
[P10] docs: go-sdk layout, feature guides, design notes and process docs
[P9] versions: make 2026-07-28 the client default
This was referenced Dec 5, 2026
Closed
Check JSON-RPC message kind before decoding stream responses. Cover a null-ID error carrying a method, which otherwise gets accepted without a reply.
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.