Repository navigation
[P5] http: standard and custom request headers at 2026-07-28 (SEP-2243) - #366
Merged
Merged
Conversation
Implements the SEP-2243 request headers of the Streamable HTTP transport at 2026-07-28: `Mcp-Method`, `Mcp-Name` and `Mcp-Param-<Name>` for tool arguments annotated with `x-mcp-header`. The client sends them and drops tools with invalid annotations; the server rejects requests whose headers do not match the body with HTTP 400 and -32020 and leaves tools with invalid annotations out of `tools/list`. A new public `MCPRequestHeaders` namespace holds the names, the value encoding and the annotation rules, so both sides share one implementation. The server reads the tool schemas for the `Mcp-Param-*` check in one pass through `tools/list`, caches them until the tool list changes, and fails closed when it cannot check. Annotation parsing is bounded in count and depth.
- StatelessHTTPServerTransport parses a POST body once with JSONSerialization and re-serializes it, then classifies the message, checks Mcp-Method, Mcp-Name and the _meta version, and dispatches from that one form. Parsers resolve duplicate member names differently (JSONSerialization keeps the last on Linux, JSONDecoder the first), so the headers could be checked against one value while the server ran another. Notifications and responses are forwarded in that form only when their headers were checked; otherwise byte for byte. - A tools/call that carries Mcp-Param-* headers is refused with -32020 when the server has no tools/list handler, as the check already fails closed when a tool's schema cannot be found.
- Document the precedence of send(_:additionalHeaders:): a header named there replaces one the transport sets before it, such as Mcp-Method, and the requestModifier and the authorizer's headers are applied after it. No behaviour change.
At 2026-07-28 the client sent the Mcp-Param-* headers of a tools/call only when its connection downcast to HTTPClientTransport. A wrapping transport (a logger, a decorator) or a custom Streamable HTTP transport received the call through send(_:) without them, and a conforming server then answered -32020 (HeaderMismatch), because the spec requires clients to mirror x-mcp-header arguments (2026-07-28 Streamable HTTP, "Custom Headers from Tool Parameters"). Transport gains the requirement send(_:additionalHeaders:), with a default in the protocol extension that ignores the headers and calls send(_:), the same pattern as send(_:relatedRequestID:). HTTPClientTransport's existing method is its implementation. Client calls it on any transport when a request has headers, and send(_:) otherwise, as before. Public API: additive. The new requirement has a default, so existing conformers compile unchanged. The new test wraps an InMemoryTransport and checks that the wrapper receives the Mcp-Param-* headers of a stateless tools/call; it fails with the downcast.
- Client.recordTools emptied the tool header record on a first page and refilled it tool by tool, awaiting the transport's logger after each invalid tool. Actor reentrancy at that await let a tools/call for a tool later on the page find no entry and go out without its Mcp-Param-* headers, which a 2026-07-28 server refuses with -32020 (SEP-2243, Server Behavior for Custom Headers). The record is now built locally and assigned once, before the warnings are logged. - recordTools reads Version.profile(for:).usesStandardHeaders, the flag for SEP-2243 headers, instead of isStateless, and its doc comment no longer repeats itself. No behaviour change: both flags are true from 2026-07-28. - The doc comment of HTTPClientTransport.send(_:additionalHeaders:) now says that Mcp-Session-Id, too, is added after the extra headers. No behaviour change. Test: ClientToolHeaderCacheTests "Every valid tool of a page is recorded before an invalid one is reported" reads the record from the log handler while the warning is logged; it fails without the fix. The MockTransport helpers of ClientDiscoveryNegotiationTests moved to file scope so both suites use them.
This was referenced Nov 25, 2026
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: P4 (#367) · next: P6 (#365))conformance/p5-headersconformance/p4-client(stacked: GitHub retargets this PR torel/1.0.0when the previous part merges)fc28751http: standard and custom request headers at 2026-07-28 (SEP-2243)0dfe8a9http: review fixes4002d74http: second-pass review fixes8f6ffd3http: pass SEP-2243 request headers through Transport476ddf5http: third-pass review fixesSummary
Implements the SEP-2243 request headers of the Streamable HTTP transport at 2026-07-28:
Mcp-Method,Mcp-NameandMcp-Param-<Name>for tool arguments annotated withx-mcp-header. The client sends them and drops tools with invalid annotations; the server rejects requests whose headers do not match the body with HTTP 400 and -32020 and leaves tools with invalid annotations out oftools/list. A new publicMCPRequestHeadersnamespace holds the names, the value encoding and the annotation rules, so both sides share one implementation.The server reads the tool schemas for the
Mcp-Param-*check in one pass throughtools/list, caches them until the tool list changes, and fails closed when it cannot check. Annotation parsing is bounded in count and depth.Motivation
http-header-validation,http-custom-header-server-validation; clienthttp-standard-headers,http-custom-headers,http-invalid-tool-headers.Changes
Base types (
Sources/MCP/Base/Transports/MCPRequestHeaders.swift, new)MCPRequestHeaders.method,.name,.parameterPrefix,.schemaKeyword("x-mcp-header").encode(_:): values that are empty, not printable ASCII, have a leading or trailing space, or already look like=?base64?...?=are sent as=?base64?<Base64 of UTF-8>?=.decode(_:): trims whitespace, unwraps the Base64 form; returnsnilunless the payload is canonical Base64 (re-encodes to the same text) and valid UTF-8.render(_:): strings as-is, booleans astrue/false, integers (including integral doubles below 2^53) in decimal;nilotherwise.nameValue(method:params:):params.namefortools/callandprompts/get,params.uriforresources/read.Parameter(headerName,path,type,fieldName) andInvalidAnnotation.parameters(in:): walkspropertiesfrom the schema root (no$ref); rejects an empty or non-string name, a name with characters outside RFC 9110tchar, a type other thanstring/integer/boolean, and case-insensitive duplicates.parameterHeaders(_:arguments:): headers for present, non-null, primitive arguments.validate(_:arguments:header:): a header must be present exactly when its argument is present and not null, and its decoded value must equal the rendered argument.Tool.headerParameters().Transports
HTTPClientTransport(Sources/MCP/Base/Transports/HTTPClientTransport.swift): addsMcp-Methodand, where defined,Mcp-Name(encoded) whenVersion.profile(for:).usesStandardHeadersholds for the request's version. Newsend(_:additionalHeaders:);send(_:)forwards to it.StatelessHTTPServerTransport(Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift):standardHeaderErrorchecks requests and notifications before dispatch. A missingMcp-Method, a method that differs (case-sensitive, surrounding whitespace ignored), or a missing or mismatchedMcp-Nameis answered with HTTP 400 andMCPError.headerMismatch(-32020).Client (
Sources/MCP/Client/Client.swift)toolHeaderParameterscache, filled byrecordToolsfrom everyListTools.Resultreceived on a stateless connection (hook in the request task ofsend).headerParameters()are removed from the returnedListTools.Resultand logged.tools/callon a stateless connection computesMcp-Param-*headers from the cache and sends them throughHTTPClientTransport.send(_:additionalHeaders:)(downcast; other transports get none).Server (
Sources/MCP/Server/Server.swift)parameterHeaderError: for statelesstools/callover HTTP at a revision with standard headers, reads the tool's input schema by paging the registeredtools/listhandler (up to 100 pages; cached, see Review fixes) and validates theMcp-Param-*headers. Skipped when the call has no arguments and noMcp-Param-*header. A mismatch is rejected with -32020.droppingInvalidHeaderTools: statelesstools/listresults omit tools with invalid annotations (logged as a warning).Fixtures
Sources/MCPConformance/Server/main.swift: tooltest_x_mcp_header(regionmirrored asRegion,levelunannotated).Sources/MCPConformance/Client/main.swift: scenarioshttp-standard-headers(calls every tool, reads every resource, gets every prompt, with stub arguments for required properties),http-custom-headers(callscontext.toolCallsfromMCP_CONFORMANCE_CONTEXT),http-invalid-tool-headers(calls every listed tool).Baselines
conformance-baseline.2026-07-28.yml,conformance-baseline.ymlregenerated.Docs
README.md: "Request Headers" section with the header table, encoding rules, server checks and an annotatedToolexample.Review fixes
Server (
Sources/MCP/Server/Server.swift)Mcp-Param-*check pagedtools/list(up to 100 handler calls) on everytools/call. It now reads every tool's parameters in one pass and caches them (toolHeaderCache); concurrent calls share the pass (toolHeaderLoad). The cache is cleared when the server sendsToolListChangedNotificationor thetools/listhandler is replaced; a failed pass is not cached.tools/listskipped it. Now a call withMcp-Param-*headers is refused with -32020 when the tool is not listed,tools/listfails or the page cap is reached; a call with arguments or headers to a tool hidden for an invalid annotation is refused with -32020. A call to an unlisted tool with arguments and no headers passes.MCPRequestHeaders.sanitized).Base types (
Sources/MCP/Base/Transports/MCPRequestHeaders.swift)parameters(in:)had no bound on annotation count orpropertiesdepth, and the duplicate check was quadratic. It now throws abovemaxAnnotations(64) annotations ormaxSchemaDepth(32) levels, and checks duplicates with a set.InvalidAnnotationdescriptions quoted the peer's annotation value (control characters included). They now name the property path, with characters outside printable ASCII replaced by?and truncated to 128 characters.nameValue(method:name:uri:); the publicnameValue(method:params:)forwards to it.Transports
HTTPClientTransport: the standard headers were computed from a second JSON decode of the body.OutgoingMessagenow records the method as sent and theMcp-Namevalue from its one parse;operationKeyis the trimmed method used for authorization.StatelessHTTPServerTransport:standardHeaderErrordecoded the body again.JSONRPCMessageFields.requestFields(in:)now returnsRequestFields(id, method,Mcp-Namevalue,_metaversion) from its one decode.Client (
Sources/MCP/Client/Client.swift)toolHeaderParametersonly grew. Atools/listwithout a cursor now replaces it;connectanddisconnectclear it. Tool names in log metadata are sanitized.Docs
README.md: schema caching and invalidation, fail-closed rules, the annotation limits.Diagram
flowchart TD subgraph Client R["Request with _meta version"] --> P{"usesStandardHeaders?"} P -->|no| SEND["POST"] P -->|yes| H1["Mcp-Method = method"] H1 --> H2["Mcp-Name = name or uri, encoded"] H2 --> T{"tools/call with cached x-mcp-header params?"} T -->|yes| H3["Mcp-Param-Name = rendered argument, encoded"] T -->|no| SEND H3 --> SEND end subgraph Server SEND --> V1{"StatelessHTTPServerTransport: Mcp-Method and Mcp-Name match?"} V1 -->|no| E["400, -32020"] V1 -->|yes| V2{"Server: tools/call Mcp-Param-* match the schema from tools/list?"} V2 -->|no| E V2 -->|yes| OK["handler"] endAPI changes
Added
MCPRequestHeadersmethod,name,parameterPrefix,schemaKeywordMCPRequestHeaders.encode(_:),decode(_:),render(_:)MCPRequestHeaders.nameValue(method:params:)Mcp-NamesourceMCPRequestHeaders.Parameter,MCPRequestHeaders.InvalidAnnotationMCPRequestHeaders.parameters(in:),parameterHeaders(_:arguments:)MCPRequestHeaders.maxAnnotations,maxSchemaDepthparameters(in:)throws above themTool.headerParameters()MCPRequestHeaders.InvalidAnnotationHTTPClientTransport.send(_:additionalHeaders:)send(_:)forwards to itChanged
None.
Removed
None.
Behavior changes
All changes apply only to revisions whose profile has
usesStandardHeaders(2026-07-28); handshake connections send and check no SEP-2243 headers.Mcp-Method,Mcp-NameandMcp-Param-*.Client.listTools()on a stateless connection can return fewer tools than the server listed: tools with invalidx-mcp-headerannotations are dropped.StatelessHTTPServerTransportrejects requests and notifications with a missing or mismatchedMcp-Method/Mcp-Name(400, -32020).Serverrejects statelesstools/callrequests whoseMcp-Param-*headers do not match the arguments (-32020), and omits invalid tools from statelesstools/list.tools/callwith arguments orMcp-Param-*headers runs thetools/listhandler (all pages, at most 100) once; later calls use the cached schemas until the server sendsToolListChangedNotificationor the handler is replaced. The lookup runs in the handler task, after the stateless request hook.Mcp-Param-*check fails closed: headers for an unlisted tool, a failingtools/listor a reached page cap give -32020, and so does a call with arguments or headers to a tool with an invalid annotation.propertiesnested deeper than 32 levels are invalid.Conformance
Baseline entries (server / client), alpha.11:
http-header-validationandhttp-custom-header-server-validationserver entries; allhttp-custom-headersandhttp-invalid-tool-headersclient entries. Default leg also clearstasks-request-headers:tasks-headers-reject-mismatched-method(extension).server-statelesslisten and teninput-required-result-*MRTR scenarios), client 11/32 (auth andsep-2322-client-request-state).Tests
Tests/MCPTests/RequestHeadersTests.swift(new, "Request Header Tests"): as-is vs Base64 values, decode trimming and literal values, malformed Base64, argument rendering, annotation discovery throughproperties, invalid annotations,Mcp-Paramheaders for present non-null arguments.Tests/MCPTests/StatelessServerTests.swift("Stateless HTTP Tests"):Mcp-Method/Mcp-Namemust match the body,Mcp-Paramheaders must match annotated arguments, statelesstools/listomits invalid tools. ThestatelessRequesthelper now derivesMcp-Method/Mcp-Namefrom the body.Tests/MCPTests/ClientStatelessTests.swift(HTTPClientTransportTestsextension): stateless requests carryMcp-Method,Mcp-NameandMcp-Paramheaders; handshake requests carry none.Tests/MCPTests/StatelessServerTests.swift, new suite "Mcp-Param schema lookup":tools/listruns once for many calls and again after the list changes; concurrent calls share one pass; an unlisted tool does not page again; headers for an unlisted tool are refused, arguments alone pass; a tool hidden for an invalid annotation is refused; a failingtools/listand a reached page cap refuse calls with headers; a client refused by the stateless hook does not reachtools/list.Tests/MCPTests/ClientStatelessTests.swift, new suite "Client tool header cache": a first page replaces earlier tools, disconnect clears them.Tests/MCPTests/RequestHeadersTests.swift: annotation count and depth limits; error descriptions name the escaped, truncated path and not the annotation.Tests/MCPTests/ClientConnectionFailureTests.swift:OutgoingMessagekeeps the method as sent, trimsoperationKey, reads theMcp-Namevalue.Review notes
Mcp-Param-*validation reads the schemas from the user'stools/listhandler, with the request's_metaand handler context. The first call that needs them costs up to 100 handler calls; the result is cached until the server sendsToolListChangedNotificationor the handler is replaced. A server whose tool list changes without that notification checks against stale schemas. The lookup is skipped when there is nothing to compare. The cache is filled with the first caller's_metaand context and shared by all callers.Mcp-Param-*headers are only sent throughHTTPClientTransport; the client downcasts the connection. A custom HTTP transport would needsend(_:additionalHeaders:)itself.tools/listresults received on a stateless connection; atools/callfor a tool never listed sends noMcp-Param-*headers.withBatchbypasses the header logic insend(_:); fixed in P11 ([P11] fix: request lifecycle, server replies, OAuth hardening #360) (conformance/p11-fixes).parameters(in:)does not follow$refand only walks thepropertieschain from the schema root; annotations underitems,allOfand similar keywords are not read.Verification
Every branch of the stack builds and passes
swift test; all conformance legs pass at their baselines. On this branch, 715 swift-testing tests plus XCTest, all passed.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.