Skip to content

[P5] http: standard and custom request headers at 2026-07-28 (SEP-2243) - #366

Merged
jeanmatthieu merged 5 commits into
rel/1.0.0from
conformance/p5-headers
Nov 25, 2026
Merged

jeanmatthieu merged 5 commits into
rel/1.0.0from
conformance/p5-headers

Conversation

@jeanmatthieu

@jeanmatthieu jeanmatthieu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor
Part P5 of P0–P35, merged into rel/1.0.0 in order (previous: P4 (#367) · next: P6 (#365))
Branch conformance/p5-headers
Base conformance/p4-client (stacked: GitHub retargets this PR to rel/1.0.0 when the previous part merges)
Commits fc28751 http: standard and custom request headers at 2026-07-28 (SEP-2243)
0dfe8a9 http: review fixes
4002d74 http: second-pass review fixes
8f6ffd3 http: pass SEP-2243 request headers through Transport
476ddf5 http: third-pass review fixes
Size 16 files, +1589 / -68

Summary

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.

Motivation

  • SEP-2243 (2026-07-28): HTTP requests name their method and target in headers so that gateways can route without reading the body. Servers must reject mismatches with -32020; clients must mirror designated arguments and ignore tools whose annotations are invalid.
  • Conformance scenarios: server http-header-validation, http-custom-header-server-validation; client http-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; returns nil unless the payload is canonical Base64 (re-encodes to the same text) and valid UTF-8.
  • render(_:): strings as-is, booleans as true/false, integers (including integral doubles below 2^53) in decimal; nil otherwise.
  • nameValue(method:params:): params.name for tools/call and prompts/get, params.uri for resources/read.
  • Parameter (headerName, path, type, fieldName) and InvalidAnnotation.
  • parameters(in:): walks properties from the schema root (no $ref); rejects an empty or non-string name, a name with characters outside RFC 9110 tchar, a type other than string/integer/boolean, and case-insensitive duplicates.
  • parameterHeaders(_:arguments:): headers for present, non-null, primitive arguments.
  • Internal 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): adds Mcp-Method and, where defined, Mcp-Name (encoded) when Version.profile(for:).usesStandardHeaders holds for the request's version. New send(_:additionalHeaders:); send(_:) forwards to it.
  • StatelessHTTPServerTransport (Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift): standardHeaderError checks requests and notifications before dispatch. A missing Mcp-Method, a method that differs (case-sensitive, surrounding whitespace ignored), or a missing or mismatched Mcp-Name is answered with HTTP 400 and MCPError.headerMismatch (-32020).

Client (Sources/MCP/Client/Client.swift)

  • toolHeaderParameters cache, filled by recordTools from every ListTools.Result received on a stateless connection (hook in the request task of send).
  • Tools whose annotations fail headerParameters() are removed from the returned ListTools.Result and logged.
  • tools/call on a stateless connection computes Mcp-Param-* headers from the cache and sends them through HTTPClientTransport.send(_:additionalHeaders:) (downcast; other transports get none).

Server (Sources/MCP/Server/Server.swift)

  • parameterHeaderError: for stateless tools/call over HTTP at a revision with standard headers, reads the tool's input schema by paging the registered tools/list handler (up to 100 pages; cached, see Review fixes) and validates the Mcp-Param-* headers. Skipped when the call has no arguments and no Mcp-Param-* header. A mismatch is rejected with -32020.
  • droppingInvalidHeaderTools: stateless tools/list results omit tools with invalid annotations (logged as a warning).

Fixtures

  • Sources/MCPConformance/Server/main.swift: tool test_x_mcp_header (region mirrored as Region, level unannotated).
  • Sources/MCPConformance/Client/main.swift: scenarios http-standard-headers (calls every tool, reads every resource, gets every prompt, with stub arguments for required properties), http-custom-headers (calls context.toolCalls from MCP_CONFORMANCE_CONTEXT), http-invalid-tool-headers (calls every listed tool).

Baselines

  • conformance-baseline.2026-07-28.yml, conformance-baseline.yml regenerated.

Docs

  • README.md: "Request Headers" section with the header table, encoding rules, server checks and an annotated Tool example.

Review fixes

Server (Sources/MCP/Server/Server.swift)

  • The Mcp-Param-* check paged tools/list (up to 100 handler calls) on every tools/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 sends ToolListChangedNotification or the tools/list handler is replaced; a failed pass is not cached.
  • The check failed open: an unlisted tool, an invalid schema or a failing tools/list skipped it. Now a call with Mcp-Param-* headers is refused with -32020 when the tool is not listed, tools/list fails 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.
  • The check ran before the handler task, so it could not be cancelled and ran for clients the stateless request hook refuses. It now runs in the handler task, after the hook.
  • Tool names in log metadata are sanitized (MCPRequestHeaders.sanitized).

Base types (Sources/MCP/Base/Transports/MCPRequestHeaders.swift)

  • parameters(in:) had no bound on annotation count or properties depth, and the duplicate check was quadratic. It now throws above maxAnnotations (64) annotations or maxSchemaDepth (32) levels, and checks duplicates with a set.
  • InvalidAnnotation descriptions 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.
  • Internal nameValue(method:name:uri:); the public nameValue(method:params:) forwards to it.

Transports

  • HTTPClientTransport: the standard headers were computed from a second JSON decode of the body. OutgoingMessage now records the method as sent and the Mcp-Name value from its one parse; operationKey is the trimmed method used for authorization.
  • StatelessHTTPServerTransport: standardHeaderError decoded the body again. JSONRPCMessageFields.requestFields(in:) now returns RequestFields (id, method, Mcp-Name value, _meta version) from its one decode.

Client (Sources/MCP/Client/Client.swift)

  • toolHeaderParameters only grew. A tools/list without a cursor now replaces it; connect and disconnect clear 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"]
    end
Loading

API changes

Added

Symbol Notes
MCPRequestHeaders method, name, parameterPrefix, schemaKeyword
MCPRequestHeaders.encode(_:), decode(_:), render(_:) value encoding
MCPRequestHeaders.nameValue(method:params:) Mcp-Name source
MCPRequestHeaders.Parameter, MCPRequestHeaders.InvalidAnnotation
MCPRequestHeaders.parameters(in:), parameterHeaders(_:arguments:) annotation rules
MCPRequestHeaders.maxAnnotations, maxSchemaDepth 64 and 32; parameters(in:) throws above them
Tool.headerParameters() throws MCPRequestHeaders.InvalidAnnotation
HTTPClientTransport.send(_:additionalHeaders:) send(_:) forwards to it

Changed

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.

  • Client requests carry Mcp-Method, Mcp-Name and Mcp-Param-*.
  • Client.listTools() on a stateless connection can return fewer tools than the server listed: tools with invalid x-mcp-header annotations are dropped.
  • StatelessHTTPServerTransport rejects requests and notifications with a missing or mismatched Mcp-Method/Mcp-Name (400, -32020).
  • Server rejects stateless tools/call requests whose Mcp-Param-* headers do not match the arguments (-32020), and omits invalid tools from stateless tools/list.
  • A stateless tools/call with arguments or Mcp-Param-* headers runs the tools/list handler (all pages, at most 100) once; later calls use the cached schemas until the server sends ToolListChangedNotification or the handler is replaced. The lookup runs in the handler task, after the stateless request hook.
  • The Mcp-Param-* check fails closed: headers for an unlisted tool, a failing tools/list or a reached page cap give -32020, and so does a call with arguments or headers to a tool with an invalid annotation.
  • Schemas with more than 64 annotations or properties nested deeper than 32 levels are invalid.

Conformance

Baseline entries (server / client), alpha.11:

Leg Before (P4) After (P5)
2025-11-25 0 / 0 0 / 0
2026-07-28 25 / 38 18 / 31
default 51 / 42 43 / 35
  • Cleared: all http-header-validation and http-custom-header-server-validation server entries; all http-custom-headers and http-invalid-tool-headers client entries. Default leg also clears tasks-request-headers:tasks-headers-reject-mismatched-method (extension).
  • The header scenarios are not in the scored 2026-07-28 sets; the tier score is unchanged: server 26/37 (the rest is server-stateless listen and ten input-required-result-* MRTR scenarios), client 11/32 (auth and sep-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 through properties, invalid annotations, Mcp-Param headers for present non-null arguments.
  • Tests/MCPTests/StatelessServerTests.swift ("Stateless HTTP Tests"): Mcp-Method/Mcp-Name must match the body, Mcp-Param headers must match annotated arguments, stateless tools/list omits invalid tools. The statelessRequest helper now derives Mcp-Method/Mcp-Name from the body.
  • Tests/MCPTests/ClientStatelessTests.swift (HTTPClientTransportTests extension): stateless requests carry Mcp-Method, Mcp-Name and Mcp-Param headers; handshake requests carry none.
  • Review fixes:
    • Tests/MCPTests/StatelessServerTests.swift, new suite "Mcp-Param schema lookup": tools/list runs 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 failing tools/list and a reached page cap refuse calls with headers; a client refused by the stateless hook does not reach tools/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: OutgoingMessage keeps the method as sent, trims operationKey, reads the Mcp-Name value.
  • 715 swift-testing tests pass, plus XCTest.

Review notes

  • The server has no tool registry, so Mcp-Param-* validation reads the schemas from the user's tools/list handler, with the request's _meta and handler context. The first call that needs them costs up to 100 handler calls; the result is cached until the server sends ToolListChangedNotification or 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 _meta and context and shared by all callers.
  • Validation compares the decoded header with the rendered argument as exact strings.
  • Mcp-Param-* headers are only sent through HTTPClientTransport; the client downcasts the connection. A custom HTTP transport would need send(_:additionalHeaders:) itself.
  • The client's parameter cache is filled only from tools/list results received on a stateless connection; a tools/call for a tool never listed sends no Mcp-Param-* headers.
  • withBatch bypasses the header logic in send(_:); fixed in P11 ([P11] fix: request lifecycle, server replies, OAuth hardening #360) (conformance/p11-fixes).
  • parameters(in:) does not follow $ref and only walks the properties chain from the schema root; annotations under items, allOf and similar keywords are not read.
  • Empty values are always Base64-wrapped because some HTTP stacks drop empty header values.

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.

swift build
swift test
BIN=$(swift build --show-bin-path)
scripts/run-conformance.sh --spec-version 2026-07-28 --bin-path "$BIN"
scripts/run-conformance.sh --spec-version 2025-11-25 --bin-path "$BIN"
scripts/run-conformance.sh --bin-path "$BIN"
scripts/run-conformance.sh --requirements 2026-07-28 --bin-path "$BIN"

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.

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

@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

Base automatically changed from conformance/p4-client to rel/1.0.0 November 25, 2026 12:35
@jeanmatthieu
jeanmatthieu dismissed canarik’s stale review November 25, 2026 12:35

The base branch was changed.

@jeanmatthieu
jeanmatthieu merged commit 284b4dc into rel/1.0.0 Nov 25, 2026
@jeanmatthieu
jeanmatthieu deleted the conformance/p5-headers branch November 25, 2026 12:36
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