Repository navigation
[P2] base: protocol profiles, error data, envelope _meta and result types - #369
Merged
Merged
Conversation
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.
This was referenced Nov 25, 2026
Merged
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
canarik
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: P1 (#370) · next: P3 (#368))conformance/p2-foundationsconformance/p1-legacy-reliability(stacked: GitHub retargets this PR torel/1.0.0when the previous part merges)2169166base: protocol profiles, error data, envelope _meta and result types0cf6d89base: review fixes5b1f661base: second-pass review fixes1f74115base: third-pass review fixesSummary
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
datawith the new protocol error codes,_metaon request and notification envelopes, typed accessors for theio.modelcontextprotocol/*meta keys, capability extensions, and SEP-2549 cache hints on list and read results. The PR does not change negotiation:Version.supportedandVersion.lateststill 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
initializehandshake. Each request carries its protocol version, client capabilities, client info and log level inparams._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 withdata.uri. Results carryresultType(SEP-2322) and the cache hintsttlMsandcacheScope(SEP-2549). SEP-2133 addsextensionsto both capability sets. Before this PR the SDK compared version strings directly, had nodatamember on most errors, and could not attach_metato an envelope.Changes
Versioning (
Sources/MCP/Base/Versioning.swift)Version.v2024_11_05,v2025_03_26,v2025_06_18,v2025_11_25,v2026_07_28.Version.handshakelists the revisions that useinitialize, newest first.Version.statelesslists the revisions without a handshake:[v2026_07_28].Version.supportedis nowSet(handshake).Version.latestis the explicit constantv2025_11_25.negotiate(clientRequestedVersion:)(internal) returns only handshake revisions.Version.profile(for:)returns aProtocolProfilewith the flagsusesInitializeHandshake,usesRequestMeta,usesResultType,usesSessions,allowsServerRequests,usesSubscriptionsListen,usesStandardHeadersandallowsPrimingEvents. The profile comparesYYYY-MM-DDversions as strings, so an unknown future version gets the profile of the newest known revision before it. Any other string gets the profile ofVersion.latest.Errors (
Sources/MCP/Base/Error.swift)MCPError.data, the JSON-RPCdatamember. Standard cases carry{"detail": ...}.resourceNotFound(uri:message:): -32602 with{"uri": ...}.headerMismatch(_:): -32020.missingRequiredClientCapabilities(_:message:): -32021 with{"requiredCapabilities": ...}.unsupportedProtocolVersion(supported:requested:): -32022 with{"supported": [...], "requested": ...}.serverError(code:message:)becomesserverError(code:message:data:), withdatadefaulting tonil.code,messageanddata(fromdata) for every case.data.uriand nodata.detaildecodes asresourceNotFound.data.urialso decodes asresourceNotFound. Other -32002 errors decode asserverError.serverErrorinstead ofconnectionClosedandtransportError.serverErrorwith itsdata.EquatableandHashablecover the new cases and thedataofserverError.Envelopes (
Sources/MCP/Base/Messages.swift)Request._metaandMessage._meta(bothMetadata?): encoded intoparams._metaand 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 throwEncodingError.invalidValue. Empty parameters with_metaencode as an object.Method.request(id:_meta:),Method.request(id:_:_meta:)andMessage.init(method:params:_meta:)take_meta.Meta keys (
Sources/MCP/Base/MetaKeys.swift, new)MetaKey.protocolVersion,clientCapabilities,clientInfo,logLevel,serverInfoandsubscriptionID, each holding anio.modelcontextprotocol/*key.Metadataaccessors:protocolVersion,clientCapabilities,clientInfo,logLevelandserverInfo. Each returnsnilwhen the key is absent or invalid.Results (
Sources/MCP/Base/Results.swift, new)ResultType(string-backed, with.completeand.inputRequired).CacheScope(open string-backed struct, with.publicand.private).CacheableResultprotocol (ttlMs,cacheScope).ttlMsandcacheScopeproperties and initializer parameters, withCacheableResultconformance, onListTools.Result,ListPrompts.Result,ListResources.Result,ListResourceTemplates.ResultandReadResource.Result(Sources/MCP/Server/{Tools,Prompts,Resources}.swift). Both are omitted from the wire whennil, and decoded leniently (see Review fixes).Capabilities
Client.Capabilities.extensions: [String: Value]?(new).Client.Capabilities.experimentalchanges from[String: String]?to[String: Value]?(Sources/MCP/Client/Client.swift).Server.Capabilities.experimentalandServer.Capabilities.extensions, both[String: Value]?(new,Sources/MCP/Server/Server.swift).Transports
StatefulHTTPServerTransportreadsallowsPrimingEventsfrom the profile instead of comparing the version with"2025-03-26".Fixtures
Sources/MCPConformance/Server/main.swift: an unknown resource throwsMCPError.resourceNotFound(uri:).Docs
README.md: a table of the protocol error cases with their codes anddata. The resource example throwsresourceNotFound(uri:).Review fixes
Envelopes
Sources/MCP/Base/Messages.swift,Sources/MCP/Base/Value.swift: merging_metainto the parameters went throughValue, whose decoder turns a string that looks like adata:URL into.dataand re-encodes it, so a non-base64data:URI (for example aresources/readURI or a tool argument) was sent base64-encoded. The merge now usesValue.preservingStrings(_:)(internal), which sets a decoderuserInfoflag (CodingUserInfoKey.valuePreservesStrings) under whichValuekeeps every string a.string.Results
Sources/MCP/Base/Results.swift:CacheScopewas a closed enum, so a peer's unknown scope failed the whole result. It is now aRawRepresentablestruct likeResultType(Codable,ExpressibleByStringLiteral,CustomStringConvertible), with static.publicand.private.ttlMsandcacheScopeare decoded leniently on every cacheable result (decodeTTL(forKey:),decodeCacheScope(forKey:)onKeyedDecodingContainer, internal): a fractionalttlMsis rounded down; a negative, non-numeric or out-of-rangettlMs, and a non-stringcacheScope, are ignored instead of failing the result.Versioning
Sources/MCP/Base/Versioning.swift:ProtocolProfilecompared any string with the revision dates, so a version such as"garbage"sorted above 2026-07-28 and got the stateless profile. OnlyYYYY-MM-DDstrings are ordered now (Version.isDateVersion(_:), internal); any other string gets the profile ofVersion.latest.API changes
Added
Version.v2024_11_05...Version.v2026_07_28Version.handshake,Version.statelessVersion.profile(for:),ProtocolProfileMCPError.datadatamemberMCPError.resourceNotFound(uri:message:)data.uriMCPError.headerMismatch(_:)MCPError.missingRequiredClientCapabilities(_:message:)MCPError.unsupportedProtocolVersion(supported:requested:)Request._meta,Message._metaparams._meta_meta:parameter onMethod.request(...)andMessage.init(method:params:_meta:)nilMetaKey_metakeysMetadata.protocolVersion,.clientCapabilities,.clientInfo,.logLevel,.serverInfoResultType,CacheScope,CacheableResultResultTypeandCacheScopeare open string-backed structsttlMs,cacheScopeonListTools.Result,ListPrompts.Result,ListResources.Result,ListResourceTemplates.Result,ReadResource.ResultnilClient.Capabilities.extensionsServer.Capabilities.experimental,Server.Capabilities.extensions[String: Value]?Changed
MCPErrorswitchstatements withoutdefaultno longer compile. breakingMCPError.serverError(code:message:)serverError(code:message:data:). Construction still compiles becausedatahas a default. Pattern matches with two bindings no longer compile. breakingMCPErrordecoding of -32000 / -32001serverErrorinstead ofconnectionClosed/transportError. breaking for code that matches those cases on errors received from a peerMCPErrordecoding of -32602 withdata.uriresourceNotFoundinstead ofinvalidParamsMCPErrorencoding ofserverErrormessageis the raw message, not"Server error: <message>".datais encodedClient.Capabilities.experimental[String: String]?becomes[String: Value]?. breakingVersion.latest2025-11-25)Request,Messageequality and hashing_metaRemoved: none.
Behavior changes
serverError(code:message:data:). The SDK still usesconnectionClosedandtransportErrorfor its own local transport failures.serverErrorerrors sent by the SDK carry the handler's message verbatim and anydata.ttlMsandcacheScopeonly when set. Nothing sets them yet. P3 ([P3] server: serve 2026-07-28 stateless requests #368) fills them for stateless requests.cacheScopestring and ignore attlMsorcacheScopeof the wrong type or range._metais merged, including strings that look likedata:URLs.Version.profile(for:)gives a version that is notYYYY-MM-DDthe 2025-11-25 (handshake) profile.initializenever negotiates 2026-07-28.Conformance
Baselines are unchanged, as expected for type-only changes.
Tests
Tests/MCPTests/ProtocolFoundationsTests.swift(new):MCPErrorWireTests: new codes,data.uri, legacy -32002, -32022 and -32021 round-trips, header mismatch,serverErrordata, -32000/-32001 decoding, URL elicitation round-trip.EnvelopeMetaTests:_metaencoding and merge precedence, decoding, notification round-trip, typed accessors; strings that look likedata:URLs (plain and base64) are sent as given when_metais merged.CapabilityExtensionsTests:extensionsand object-valuedexperimental.ResultTypeAndCacheTests: hints omitted when unset, round-trip on every cacheable result,resultTypedefault; an unknowncacheScopeand a fractionalttlMsdecode, 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 aServer:initializenegotiates a handshake revision and omits 2026 members;data.uri;_metareaches typed parameters unchanged.Tests/MCPTests/Helpers/WireExchange.swift(new): drives a server overMockTransportwith raw JSON.expectWireis a subset matcher with an"<any>"wildcard, andexpectWireLackschecks that members are absent.swift test: 622 tests pass.Review notes
MCPErrorcases, theserverErrorsignature change, the -32000/-32001 decoding change and theClient.Capabilities.experimentaltype change are source-breaking.docs/migration.md(P10 ([P10] docs: go-sdk layout, feature guides, design notes and process docs #362)) covers them.resourceNotFoundandinvalidParamsshare code -32602. A -32602 error decodes asresourceNotFoundonly whendatahasuriand nodetail.invalidParamsalways encodesdetailwhen it has one, so both cases round-trip.ProtocolProfilecompares 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 theVersion.latestprofile.MetaKey.subscriptionIDis defined here but first used in P6 ([P6] subscriptions/listen: notification streams at 2026-07-28 (SEP-2575) #365).ResultTypeandCacheScopeareRawRepresentablestructs, not enums, so unknown values decode without failing.Verification
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.