Skip to content

[P35] Fix the findings of a formal verification of the framework at 2026-07-28 - #336

Merged
jeanmatthieu merged 3 commits into
rel/1.0.0from
conformance/p35-formal-verification
Nov 25, 2026
Merged

jeanmatthieu merged 3 commits into
rel/1.0.0from
conformance/p35-formal-verification

Conversation

@jeanmatthieu

@jeanmatthieu jeanmatthieu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor
Part P35 of P0–P35, merged into rel/1.0.0 in order (previous: P34 (#337))
Branch conformance/p35-formal-verification
Base conformance/p34-apple-platforms (stacked: GitHub retargets this PR to rel/1.0.0 when the previous part merges)
Commits bfa961d Fix the findings of a formal verification of the framework at 2026-07-28
8be5a71 conformance: review fixes for the formal verification findings
42499b6 conformance: second review fixes for the formal verification findings
Size 29 files, +1565 / -193

Summary

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": null failed 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:

  • Silent drops. Requests whose id was null, fractional, an array, a boolean or above Int.max were taken for notifications: 202 with no body on HTTP, no answer at all on stdio.
  • Wrong codes. -32022 or -32601 where the spec fixes -32602; 400 without a challenge where RFC 6750 fixes 401.
  • Missing MUSTs. No notifications/cancelled on listen teardown over stdio; an x-mcp-header under items or anyOf was not treated as invalid.
  • Nondeterminism. Header lookup depended on dictionary order when two keys differed only in case.

Changes

Request ids (JSON-RPC 2.0 §5; basic/index.mdx, Requests)

  • JSONRPCMessageKind classifies by the presence of id, not its type. A new .invalid case covers an id that is not a string or an Int (booleans included: true as? Int is 1 on Darwin) and a jsonrpc that is not "2.0".
  • Both HTTP transports answer .invalid with 400, -32600 and "id": null. The Server receive loop answers it with -32600 and echoes the id when it is valid.
  • Request.init(from:) refuses a null id (ID still reads null as "", for error responses). Message.init(from:) refuses a message with an id member.
  • "" is a valid id again: JSONRPCMessageFields no longer treats it as "no id".

Missing _meta version and progress tokens (basic/index.mdx, _meta; versioning.mdx; progress.mdx)

  • A server whose protocolVersions has no handshake revision answers a request without io.modelcontextprotocol/protocolVersion (other than initialize) with -32602 and data.supported. 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 (internal). The transport validates MCP-Protocol-Version against 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)

  • BearerTokenValidator answers an empty header, or credentials of another scheme (Basic …), with 401 and the Bearer challenge.
  • A malformed Bearer header (no token, two tokens, two Authorization lines joined) and .malformedRequest get 400 with WWW-Authenticate: Bearer error="invalid_request", error_description, resource_metadata.

Subscriptions (basic/utilities/cancellation.mdx)

  • After the result of a subscriptions/listen stream the server closed, handleRequest sends notifications/cancelled for the listen id, on every transport but StatelessHTTPServerTransport (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. An x-mcp-header off the properties chain, or on the root, throws InvalidAnnotation, so the client drops the tool and the server hides it.
    • Values such as default, const, enum and examples, and property names, are not read as schemas.
    • The scan has the maxSchemaDepth limit.
  • New public API, additive:
    • 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.
  • A repeated MCP-Protocol-Version, Mcp-Method, Mcp-Name or Mcp-Param-* gets -32020 (HTTP 400):
    • Separate lines count for all four.
    • Comma-joined values count for the first two, whose values never contain a comma.
    • A repeated handshake version stays -32022.
  • The SwiftNIO example (Examples/http-server) and the conformance server's 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, an error without a code, no jsonrpc) fails the pending request it names with internalError("The server sent an invalid response"). Before, the request waited for its timeout, which is unbounded by default.
  • The warning logs a sanitized prefix of at most 512 bytes instead of the whole peer-controlled message.

Docs

  • protocol.md: the auth response table, the listen teardown, and how adapters should build an HTTPRequest.
  • protocol_versions.md: stateless-only servers.
  • server.md: x-mcp-header reachability; 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.

  • Requests with an invalid id or jsonrpc get -32600 instead of silence, on the 2025-11-25 stateful transport too: the JSON-RPC rule is the same in every revision.
  • A null request id is refused; a "" id is served over HTTP.
  • A bad progressToken gets -32602 at 2025-11-25 as well as at 2026-07-28.
  • Stateless-only servers answer a missing _meta version with -32602 instead of -32022, and server/discover without one with -32602 instead of -32601.
  • Basic credentials to a BearerTokenValidator get 401 instead of 400.
  • stdio clients of a 2026-07-28 server get a notifications/cancelled after the result of a listen stream the server closes. The Swift client ignores it.
  • Tools with misplaced x-mcp-header annotations disappear from tools/list.

Not changed

  • "arguments": null in tools/call and prompts/get is 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.Arguments is an any with omitempty, and a nil map in it is encoded as null. With the refusal, 7 to 12 basic interop checks per Go-to-Swift leg failed, plus the advanced and session profiles. PromptTests.testNullArgumentsAreAbsent keeps the lenient read until the Go SDK changes.
  • Harness-side findings. Header folding in the harness adapter, input validation in the fixture handlers, and duplicate JSON member names are fixed in the verification harness, not here.

Tests

  • RequestIDValidationTests (new): valid ids ("", "x", 0, -1, 9007199254740993) are echoed; invalid ones (1.5, 5.2, null, [], {}, true, 1e20, and 1e400 on streams) get exactly one -32600 with id: null; a bad jsonrpc gets -32600 with the id. Covers InMemoryTransport, StatelessHTTPServerTransport and StatefulHTTPServerTransport, plus JSONRPCMessageKind itself.
  • StatelessGatingTests: a missing _meta version 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 bare Basic and an empty header get 401 without an error code; Bearer, "Bearer ", "Bearer a b" and "Bearer a, Bearer b" get 400 with the challenge; .malformedRequest gets 400 with its description.
  • SubscriptionTests: a raw peer sees the result, then exactly one notifications/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; an Mcp-Name containing a comma is served.
  • ClientTests (ClientUndecodableResponseTests): three undecodable answers each fail the pending request; one for an unknown id changes nothing.
  • PromptTests.testNullArgumentsAreAbsent.
  • Existing tests that asserted the old behavior now assert the new one:
    • testBearerAuthValidatorMalformedAuthorizationReturns400, where Basic now gets 401;
    • noHandshakeRevisions, which now names a version for its -32022 case;
    • the statelessOnlyServer guide 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 for Mcp-Name and Mcp-Param-*.
  • The listen teardown follows cancellation.mdx's MUST. subscriptions.mdx describes only the closing result; the two pages are consistent if the cancellation follows the result, which is how the formal model reads them.

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):

Job Platform Result
build-test macOS (Xcode toolchain) Pass
build-test Linux (Swift 6.1, RHEL UBI 9, arm64) Pass: 1373 tests, and the hello example
apple-ios iOS simulator Pass: 1276 tests in 141 suites
interop macOS Pass, matches interop/RESULTS.md
interop Linux Pass, matches interop/RESULTS.md
api-breakage macOS Pass (no 1.x release to compare with)

Also run on the same tree:

  • scripts/run-conformance.sh at 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.swift and swift scripts/weave.swift --check: pass.

A first apple-ios run, 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 its Assisted-by trailer says.

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.
varun06
varun06 previously approved these changes Nov 25, 2026

@varun06 varun06 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed already and looking good.

Base automatically changed from conformance/p34-apple-platforms to rel/1.0.0 November 25, 2026 12:56
@jeanmatthieu
jeanmatthieu dismissed varun06’s stale review November 25, 2026 12:56

The base branch was changed.

@jeanmatthieu
jeanmatthieu merged commit 5c3af99 into rel/1.0.0 Nov 25, 2026
@jeanmatthieu
jeanmatthieu deleted the conformance/p35-formal-verification branch November 25, 2026 12:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants