Skip to content

[P2] base: protocol profiles, error data, envelope _meta and result types - #369

Merged
jeanmatthieu merged 4 commits into
rel/1.0.0from
conformance/p2-foundations
Nov 25, 2026
Merged

jeanmatthieu merged 4 commits into
rel/1.0.0from
conformance/p2-foundations

Conversation

@jeanmatthieu

@jeanmatthieu jeanmatthieu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor
Part P2 of P0–P35, merged into rel/1.0.0 in order (previous: P1 (#370) · next: P3 (#368))
Branch conformance/p2-foundations
Base conformance/p1-legacy-reliability (stacked: GitHub retargets this PR to rel/1.0.0 when the previous part merges)
Commits 2169166 base: protocol profiles, error data, envelope _meta and result types
0cf6d89 base: review fixes
5b1f661 base: second-pass review fixes
1f74115 base: third-pass review fixes
Size 23 files, +1481 / -159

Summary

Adds the base types that the 2026-07-28 server and client in later PRs build on: a per-revision feature profile, JSON-RPC error data with the new protocol error codes, _meta on request and notification envelopes, typed accessors for the io.modelcontextprotocol/* meta keys, capability extensions, and SEP-2549 cache hints on list and read results. The PR does not change negotiation: Version.supported and Version.latest still name handshake revisions only, and 2025-11-25 remains the latest. Cache hints and cache scopes received from a peer are decoded leniently, so an unknown or malformed hint does not fail a result.

Motivation

The 2026-07-28 revision (SEP-2575) removes the initialize handshake. Each request carries its protocol version, client capabilities, client info and log level in params._meta. The revision also adds error codes -32020 (header mismatch), -32021 (missing required client capabilities) and -32022 (unsupported protocol version). SEP-2164 moves resource-not-found to -32602 with data.uri. Results carry resultType (SEP-2322) and the cache hints ttlMs and cacheScope (SEP-2549). SEP-2133 adds extensions to both capability sets. Before this PR the SDK compared version strings directly, had no data member on most errors, and could not attach _meta to an envelope.

Changes

Versioning (Sources/MCP/Base/Versioning.swift)

  • Named revisions: Version.v2024_11_05, v2025_03_26, v2025_06_18, v2025_11_25, v2026_07_28.
  • Version.handshake lists the revisions that use initialize, newest first. Version.stateless lists the revisions without a handshake: [v2026_07_28].
  • Version.supported is now Set(handshake). Version.latest is the explicit constant v2025_11_25.
  • negotiate(clientRequestedVersion:) (internal) returns only handshake revisions.
  • Version.profile(for:) returns a ProtocolProfile with the flags usesInitializeHandshake, usesRequestMeta, usesResultType, usesSessions, allowsServerRequests, usesSubscriptionsListen, usesStandardHeaders and allowsPrimingEvents. The profile compares YYYY-MM-DD versions as strings, so an unknown future version gets the profile of the newest known revision before it. Any other string gets the profile of Version.latest.

Errors (Sources/MCP/Base/Error.swift)

  • New property MCPError.data, the JSON-RPC data member. Standard cases carry {"detail": ...}.
  • New cases:
    • resourceNotFound(uri:message:): -32602 with {"uri": ...}.
    • headerMismatch(_:): -32020.
    • missingRequiredClientCapabilities(_:message:): -32021 with {"requiredCapabilities": ...}.
    • unsupportedProtocolVersion(supported:requested:): -32022 with {"supported": [...], "requested": ...}.
  • serverError(code:message:) becomes serverError(code:message:data:), with data defaulting to nil.
  • Encoding writes code, message and data (from data) for every case.
  • Decoding:
    • -32602 with data.uri and no data.detail decodes as resourceNotFound.
    • Legacy -32002 with data.uri also decodes as resourceNotFound. Other -32002 errors decode as serverError.
    • -32020, -32021 and -32022 decode into their new cases.
    • -32000 and -32001 decode as serverError instead of connectionClosed and transportError.
    • Any other code decodes as serverError with its data.
  • Equatable and Hashable cover the new cases and the data of serverError.

Envelopes (Sources/MCP/Base/Messages.swift)

  • Request._meta and Message._meta (both Metadata?): encoded into params._meta and filled from it on decode. When the parameters encode their own _meta, the keys are merged and the parameters win on a conflict. Parameters that do not encode as an object throw EncodingError.invalidValue. Empty parameters with _meta encode as an object.
  • Method.request(id:_meta:), Method.request(id:_:_meta:) and Message.init(method:params:_meta:) take _meta.

Meta keys (Sources/MCP/Base/MetaKeys.swift, new)

  • MetaKey.protocolVersion, clientCapabilities, clientInfo, logLevel, serverInfo and subscriptionID, each holding an io.modelcontextprotocol/* key.
  • Typed Metadata accessors: protocolVersion, clientCapabilities, clientInfo, logLevel and serverInfo. Each returns nil when the key is absent or invalid.

Results (Sources/MCP/Base/Results.swift, new)

  • ResultType (string-backed, with .complete and .inputRequired).
  • CacheScope (open string-backed struct, with .public and .private).
  • CacheableResult protocol (ttlMs, cacheScope).
  • ttlMs and cacheScope properties and initializer parameters, with CacheableResult conformance, on ListTools.Result, ListPrompts.Result, ListResources.Result, ListResourceTemplates.Result and ReadResource.Result (Sources/MCP/Server/{Tools,Prompts,Resources}.swift). Both are omitted from the wire when nil, and decoded leniently (see Review fixes).

Capabilities

  • Client.Capabilities.extensions: [String: Value]? (new). Client.Capabilities.experimental changes from [String: String]? to [String: Value]? (Sources/MCP/Client/Client.swift).
  • Server.Capabilities.experimental and Server.Capabilities.extensions, both [String: Value]? (new, Sources/MCP/Server/Server.swift).

Transports

  • StatefulHTTPServerTransport reads allowsPrimingEvents from the profile instead of comparing the version with "2025-03-26".

Fixtures

  • Sources/MCPConformance/Server/main.swift: an unknown resource throws MCPError.resourceNotFound(uri:).

Docs

  • README.md: a table of the protocol error cases with their codes and data. The resource example throws resourceNotFound(uri:).

Review fixes

Envelopes

  • Sources/MCP/Base/Messages.swift, Sources/MCP/Base/Value.swift: merging _meta into the parameters went through Value, whose decoder turns a string that looks like a data: URL into .data and re-encodes it, so a non-base64 data: URI (for example a resources/read URI or a tool argument) was sent base64-encoded. The merge now uses Value.preservingStrings(_:) (internal), which sets a decoder userInfo flag (CodingUserInfoKey.valuePreservesStrings) under which Value keeps every string a .string.

Results

  • Sources/MCP/Base/Results.swift: CacheScope was a closed enum, so a peer's unknown scope failed the whole result. It is now a RawRepresentable struct like ResultType (Codable, ExpressibleByStringLiteral, CustomStringConvertible), with static .public and .private.
  • ttlMs and cacheScope are decoded leniently on every cacheable result (decodeTTL(forKey:), decodeCacheScope(forKey:) on KeyedDecodingContainer, internal): a fractional ttlMs is rounded down; a negative, non-numeric or out-of-range ttlMs, and a non-string cacheScope, are ignored instead of failing the result.

Versioning

  • Sources/MCP/Base/Versioning.swift: ProtocolProfile compared any string with the revision dates, so a version such as "garbage" sorted above 2026-07-28 and got the stateless profile. Only YYYY-MM-DD strings are ordered now (Version.isDateVersion(_:), internal); any other string gets the profile of Version.latest.

API changes

Added

Symbol Notes
Version.v2024_11_05 ... Version.v2026_07_28 Revision constants
Version.handshake, Version.stateless Revision lists, newest first
Version.profile(for:), ProtocolProfile Per-revision feature flags
MCPError.data JSON-RPC data member
MCPError.resourceNotFound(uri:message:) -32602, data.uri
MCPError.headerMismatch(_:) -32020
MCPError.missingRequiredClientCapabilities(_:message:) -32021
MCPError.unsupportedProtocolVersion(supported:requested:) -32022
Request._meta, Message._meta Sent as params._meta
_meta: parameter on Method.request(...) and Message.init(method:params:_meta:) Defaults to nil
MetaKey Reserved _meta keys
Metadata.protocolVersion, .clientCapabilities, .clientInfo, .logLevel, .serverInfo Typed accessors
ResultType, CacheScope, CacheableResult Result types and SEP-2549 hints. ResultType and CacheScope are open string-backed structs
ttlMs, cacheScope on ListTools.Result, ListPrompts.Result, ListResources.Result, ListResourceTemplates.Result, ReadResource.Result Optional, omitted when nil
Client.Capabilities.extensions SEP-2133
Server.Capabilities.experimental, Server.Capabilities.extensions [String: Value]?

Changed

Symbol Change
MCPError Four new cases. Exhaustive switch statements without default no longer compile. breaking
MCPError.serverError(code:message:) Now serverError(code:message:data:). Construction still compiles because data has a default. Pattern matches with two bindings no longer compile. breaking
MCPError decoding of -32000 / -32001 Decodes as serverError instead of connectionClosed / transportError. breaking for code that matches those cases on errors received from a peer
MCPError decoding of -32602 with data.uri Decodes as resourceNotFound instead of invalidParams
MCPError encoding of serverError The wire message is the raw message, not "Server error: <message>". data is encoded
Client.Capabilities.experimental [String: String]? becomes [String: Value]?. breaking
Version.latest Explicit constant. Value unchanged (2025-11-25)
Request, Message equality and hashing Include _meta

Removed: none.

Behavior changes

  • Errors received with code -32000 or -32001 are surfaced as serverError(code:message:data:). The SDK still uses connectionClosed and transportError for its own local transport failures.
  • serverError errors sent by the SDK carry the handler's message verbatim and any data.
  • Encoded list and read results contain ttlMs and cacheScope only when set. Nothing sets them yet. P3 ([P3] server: serve 2026-07-28 stateless requests #368) fills them for stateless requests.
  • Decoded list and read results accept any cacheScope string and ignore a ttlMs or cacheScope of the wrong type or range.
  • Strings in request and notification parameters are sent as given when _meta is merged, including strings that look like data: URLs.
  • Version.profile(for:) gives a version that is not YYYY-MM-DD the 2025-11-25 (handshake) profile.
  • Negotiation does not change. initialize never negotiates 2026-07-28.

Conformance

Baselines are unchanged, as expected for type-only changes.

Leg Before (P1) After
2025-11-25 0 / 0 0 / 0
2026-07-28 108 / 47 108 / 47
default 106 / 46 106 / 46

Tests

  • Tests/MCPTests/ProtocolFoundationsTests.swift (new):
    • MCPErrorWireTests: new codes, data.uri, legacy -32002, -32022 and -32021 round-trips, header mismatch, serverError data, -32000/-32001 decoding, URL elicitation round-trip.
    • EnvelopeMetaTests: _meta encoding and merge precedence, decoding, notification round-trip, typed accessors; strings that look like data: URLs (plain and base64) are sent as given when _meta is merged.
    • CapabilityExtensionsTests: extensions and object-valued experimental.
    • ResultTypeAndCacheTests: hints omitted when unset, round-trip on every cacheable result, resultType default; an unknown cacheScope and a fractional ttlMs decode, and negative, non-numeric, out-of-range or non-string hints are ignored.
  • Tests/MCPTests/VersioningTests.swift, ProtocolProfileTests: the revision lists are disjoint and ordered, stateless revisions are never negotiated, and the profile flags are correct for handshake, pre-2025-03-26 and 2026-07-28-or-later revisions. A version that is not a date gets the handshake profile.
  • Tests/MCPTests/WireGoldenTests.swift (new): raw JSON exchanges against a Server:
    • a legacy initialize negotiates a handshake revision and omits 2026 members;
    • resource-not-found is -32602 with data.uri;
    • an unknown method is -32601;
    • request _meta reaches typed parameters unchanged.
  • Tests/MCPTests/Helpers/WireExchange.swift (new): drives a server over MockTransport with raw JSON. expectWire is a subset matcher with an "<any>" wildcard, and expectWireLacks checks that members are absent.

swift test: 622 tests pass.

Review notes

  • The new MCPError cases, the serverError signature change, the -32000/-32001 decoding change and the Client.Capabilities.experimental type change are source-breaking. docs/migration.md (P10 ([P10] docs: go-sdk layout, feature guides, design notes and process docs #362)) covers them.
  • resourceNotFound and invalidParams share code -32602. A -32602 error decodes as resourceNotFound only when data has uri and no detail. invalidParams always encodes detail when it has one, so both cases round-trip.
  • ProtocolProfile compares version strings, so code that varies by revision reads a flag. Unknown future dates get the 2026-07-28 profile; strings that are not dates get the Version.latest profile.
  • MetaKey.subscriptionID is defined here but first used in P6 ([P6] subscriptions/listen: notification streams at 2026-07-28 (SEP-2575) #365).
  • ResultType and CacheScope are RawRepresentable structs, not enums, so unknown values decode without failing.

Verification

export npm_config_registry=https://registry.npmjs.org
swift test
swift build
scripts/run-conformance.sh --spec-version 2025-11-25 --bin-path $(swift build --show-bin-path)
scripts/run-conformance.sh --spec-version 2026-07-28 --bin-path $(swift build --show-bin-path)
scripts/run-conformance.sh --bin-path $(swift build --show-bin-path)

Every branch of the stack builds and passes swift test; at this branch, 622 swift-testing tests plus the XCTest cases, all passed. The three conformance legs pass at their baselines.


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.

Adds the base types that the 2026-07-28 server and client build on: a
per-revision feature profile, JSON-RPC error `data` with the new
protocol error codes, `_meta` on request and notification envelopes,
typed accessors for the `io.modelcontextprotocol/*` meta keys,
capability extensions, and SEP-2549 cache hints on list and read
results. It does not change negotiation: `Version.supported` and
`Version.latest` still name handshake revisions only, and 2025-11-25
remains the latest. Cache hints and cache scopes received from a peer
are decoded leniently, so an unknown or malformed hint does not fail a
result.
- Keep data: URL strings as written when the SDK passes a message
  through Value: the client and server message decoders, batch items,
  type-erased requests and responses, handler results, _meta accessors
  and error data no longer rewrite them as base64 data: URLs. Typed
  handler and result decodes are unchanged, so a Value field still
  holds .data, and a server error's data keeps decoding it that way.
- Decode a standard error without data.detail so that it equals the
  error that was sent: the case's own message text is dropped instead
  of being kept as the detail, and resourceNotFound and
  missingRequiredClientCapabilities keep a nil message.
- Decide the initialize stream's priming event by the revision the
  session is negotiated to, so a client asking for 2026-07-28 and
  negotiated down is primed again; a client older than every served
  revision is still not primed.
- Document that a decoded request or notification holds params._meta
  in _meta as well, and that parameters are re-encoded through Value
  when _meta is set, so numbers must fit Int or Double.
- StdioTransport (main's #297): record st_dev and st_ino with
  UInt64(truncatingIfNeeded:). A socket's st_dev is negative on Darwin, and
  Node.js gives a child process socket pairs as stdin and stdout, so a
  server it launched trapped in connect(). StdioTransportTests: dup2 onto
  the output descriptor without closing it first, so a test running in
  parallel cannot be given that number in between.
- A -32021 error whose data.requiredCapabilities is missing or cannot
  be decoded now decodes as serverError(code: -32021, message:, data:)
  instead of missingRequiredClientCapabilities with an empty capability
  set, which read as "nothing to declare" and dropped the peer's data.
  Matching by MCPError.Code.missingRequiredClientCapabilities still
  works. The 2026-07-28 MissingRequiredClientCapabilitiesError carries
  data.requiredCapabilities.
- WireExchange.send now throws WireExchange.Timeout when the server
  sends fewer messages than expected before the deadline. It recorded
  an issue and returned the shorter reply, so a caller that indexed
  reply[0] trapped and took the whole test run down instead of failing
  the one test.

@canarik canarik left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thank you @jeanmatthieu

canarik
canarik previously approved these changes Nov 25, 2026
Base automatically changed from conformance/p1-legacy-reliability to rel/1.0.0 November 25, 2026 12:29
@jeanmatthieu
jeanmatthieu dismissed canarik’s stale review November 25, 2026 12:29

The base branch was changed.

@jeanmatthieu
jeanmatthieu merged commit 39b9b62 into rel/1.0.0 Nov 25, 2026
@jeanmatthieu
jeanmatthieu deleted the conformance/p2-foundations branch November 25, 2026 12:34
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