Repository navigation
[P35] Fix the findings of a formal verification of the framework at 2026-07-28 - #336
Merged
Merged
Conversation
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.
This was referenced Nov 25, 2026
varun06
previously approved these changes
Nov 25, 2026
varun06
left a comment
Contributor
There was a problem hiding this comment.
Reviewed already and looking good.
Base automatically changed from
conformance/p34-apple-platforms
to
rel/1.0.0
November 25, 2026 12:56
varun06
approved these changes
Nov 25, 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.
rel/1.0.0in order (previous: P34 (#337))conformance/p35-formal-verificationconformance/p34-apple-platforms(stacked: GitHub retargets this PR torel/1.0.0when the previous part merges)bfa961dFix the findings of a formal verification of the framework at 2026-07-288be5a71conformance: review fixes for the formal verification findings42499b6conformance: second review fixes for the formal verification findingsSummary
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 the head of P34 at the time (spec 2026-07-28) reported 54 divergences from the model's answers, which come down to twelve root causes. This PR fixes the ones that are SDK bugs and that can be fixed without breaking interoperability. Each fix cites the spec or RFC section it follows.
One finding is deliberately not fixed. Refusing
"arguments": nullfailed every argument-less call from the Go SDK in the interop matrix, so it waits for the Go SDK.Motivation
The SDK's own conformance suite and interop matrix passed, but the formal verification found:
idwasnull, fractional, an array, a boolean or aboveInt.maxwere taken for notifications: 202 with no body on HTTP, no answer at all on stdio.notifications/cancelledon listen teardown over stdio; anx-mcp-headerunderitemsoranyOfwas not treated as invalid.Changes
Request ids (JSON-RPC 2.0 §5; basic/index.mdx, Requests)
JSONRPCMessageKindclassifies by the presence ofid, not its type. A new.invalidcase covers an id that is not a string or anInt(booleans included:true as? Intis 1 on Darwin) and ajsonrpcthat is not"2.0"..invalidwith 400, -32600 and"id": null. TheServerreceive loop answers it with -32600 and echoes the id when it is valid.Request.init(from:)refuses anullid (IDstill readsnullas"", for error responses).Message.init(from:)refuses a message with anidmember.""is a valid id again:JSONRPCMessageFieldsno longer treats it as "no id".Missing
_metaversion and progress tokens (basic/index.mdx,_meta; versioning.mdx; progress.mdx)protocolVersionshas no handshake revision answers a request withoutio.modelcontextprotocol/protocolVersion(other thaninitialize) with -32602 anddata.supported. A dual-era server still reads such a request as handshake-era.progressTokenthat 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.startgives aStatelessHTTPServerTransportthe versions it serves (internal). The transport validatesMCP-Protocol-Versionagainst them, so -32022 lists them. When the server serves no handshake revision, errors get their 2026-07-28 HTTP status, so the -32602 above is a 400 even without a version header.Authorization (RFC 6750 §3.1)
BearerTokenValidatoranswers an empty header, or credentials of another scheme (Basic …), with 401 and the Bearer challenge.Authorizationlines joined) and.malformedRequestget 400 withWWW-Authenticate: Bearer error="invalid_request", error_description, resource_metadata.Subscriptions (basic/utilities/cancellation.mdx)
subscriptions/listenstream the server closed,handleRequestsendsnotifications/cancelledfor the listen id, on every transport butStatelessHTTPServerTransport(there the end of the response is 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)
MCPRequestHeaders.parameters(in:)also scans every subschema keyword, 2020-12 and draft-07. Anx-mcp-headeroff thepropertieschain, or on the root, throwsInvalidAnnotation, so the client drops the tool and the server hides it.default,const,enumandexamples, and property names, are not read as schemas.maxSchemaDepthlimit.HTTPRequest.init(method:headerFields:body:path:)takes the header field lines as received. Names fold case-insensitively, and repeated values join with", ".HTTPRequest.headerValues(_:)returns each line's value.HTTPRequest.header(_:)joins keys that differ only in case, in key order. Before, it returned whichever the dictionary listed first.MCP-Protocol-Version,Mcp-Method,Mcp-NameorMcp-Param-*gets -32020 (HTTP 400):Examples/http-server) and the conformance server's adapter passArray(head.headers)to the new initializer. Both had joined repeated lines by exact name only.Client robustness
codethat is a string, an error without acode, nojsonrpc) fails the pending request it names withinternalError("The server sent an invalid response"). Before, the request waited for its timeout, which is unbounded by default.Docs
protocol.md: the auth response table, the listen teardown, and how adapters should build anHTTPRequest.protocol_versions.md: stateless-only servers.server.md:x-mcp-headerreachability;headerValues(_:).troubleshooting.md: the new -32602 messages.design/subscriptions.md: the stream-end table.CHANGELOG.md: Features and Fixes.Behavior changes
All of these are wire behavior. None changes a public signature.
idorjsonrpcget -32600 instead of silence, on the 2025-11-25 stateful transport too: the JSON-RPC rule is the same in every revision.nullrequest id is refused; a""id is served over HTTP.progressTokengets -32602 at 2025-11-25 as well as at 2026-07-28._metaversion with -32602 instead of -32022, andserver/discoverwithout one with -32602 instead of -32601.Basiccredentials to aBearerTokenValidatorget 401 instead of 400.notifications/cancelledafter the result of a listen stream the server closes. The Swift client ignores it.x-mcp-headerannotations disappear fromtools/list.Not changed
"arguments": nullintools/callandprompts/getis still read as absent. Refusing it is what the schema implies, but Go SDK v1.8.0 sends it for every call without arguments:CallToolParams.Argumentsis ananywithomitempty, and a nil map in it is encoded asnull. With the refusal, 7 to 12 basic interop checks per Go-to-Swift leg failed, plus the advanced and session profiles.PromptTests.testNullArgumentsAreAbsentkeeps the lenient read until the Go SDK changes.Tests
RequestIDValidationTests(new): valid ids ("","x",0,-1,9007199254740993) are echoed; invalid ones (1.5,5.2,null,[],{},true,1e20, and1e400on streams) get exactly one -32600 withid: null; a badjsonrpcgets -32600 with the id. CoversInMemoryTransport,StatelessHTTPServerTransportandStatefulHTTPServerTransport, plusJSONRPCMessageKinditself.StatelessGatingTests: a missing_metaversion in six request shapes, the dual-era case, and the HTTP 400; invalid and valid progress tokens in both eras; -32022 lists the served versions.HTTPServerTransportTests:Basic, a bareBasicand an empty header get 401 without an error code;Bearer,"Bearer ","Bearer a b"and"Bearer a, Bearer b"get 400 with the challenge;.malformedRequestgets 400 with its description.SubscriptionTests: a raw peer sees the result, then exactly onenotifications/cancelled, then the answer to a later request; a client-cancelled stream sees nothing; over HTTP the stream ends with the result and no cancellation.RequestHeadersTests: unreachable annotations under eight keywords, in$defs, and on the root; non-schema values ignored; case-variant keys in both insertion orders; repeated headers as comma-joined values, case-variant keys and separate field lines; anMcp-Namecontaining a comma is served.ClientTests(ClientUndecodableResponseTests): three undecodable answers each fail the pending request; one for an unknown id changes nothing.PromptTests.testNullArgumentsAreAbsent.testBearerAuthValidatorMalformedAuthorizationReturns400, whereBasicnow gets 401;noHandshakeRevisions, which now names a version for its -32022 case;statelessOnlyServerguide snippet test, which now expects -32602.Review notes
HTTPRequest(method:headers:…)stays the general-purpose initializer. Adapters that keep it lose only the exact repeat check forMcp-NameandMcp-Param-*.Verification
Run on the first commit of this PR, before the review fixes and the last restack, through the CI job scripts (
scripts/ci/run-jobs.sh,scripts/ci-linux.sh):build-testbuild-testapple-iosinteropinterop/RESULTS.mdinteropinterop/RESULTS.mdapi-breakageAlso run on the same tree:
scripts/run-conformance.shat 2025-11-25, at 2026-07-28 and at the default wire: all pass, no baseline changes.swift package generate-documentation --target MCP --warnings-as-errors,swift scripts/doc-coverage.swiftandswift scripts/weave.swift --check: pass.A first
apple-iosrun, made while the Linux and interop jobs loaded the machine, failed two timing-sensitive task cancellation tests (cancelledCreation,expiresWhileDelivering). Both pass when the job runs alone. This PR does not change the task or cancellation path: a valid notification still goes to the same handler.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. One review-fix commit (
8be5a71) was also written with Gemini, as itsAssisted-bytrailer says.