Skip to content

[P7] mrtr: input-required results at 2026-07-28 (SEP-2322) - #364

Merged
jeanmatthieu merged 3 commits into
rel/1.0.0from
conformance/p7-mrtr
Nov 25, 2026
Merged

jeanmatthieu merged 3 commits into
rel/1.0.0from
conformance/p7-mrtr

Conversation

@jeanmatthieu

@jeanmatthieu jeanmatthieu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor
Part P7 of P0–P35, merged into rel/1.0.0 in order (previous: P6 (#365) · next: P8 (#363))
Branch conformance/p7-mrtr
Base conformance/p6-listen (stacked: GitHub retargets this PR to rel/1.0.0 when the previous part merges)
Commits fdb59ee mrtr: input-required results at 2026-07-28 (SEP-2322)
6c60508 mrtr: review fixes
f92b391 mrtr: second-pass review fixes
Size 19 files, +2559 / -64

Summary

Implements multi round-trip requests (SEP-2322). At 2026-07-28 a server cannot send requests to the client, so a tools/call, prompts/get or resources/read handler that needs input returns an input-required result; the client fulfills the embedded requests and retries with inputResponses and the echoed requestState. The server seals requestState with AES-256-GCM and verifies every echo, and bridges the same handlers to handshake clients by sending the requests itself. The client runs the round loop inside send(_:), bounds it in rounds and input requests, and stops it on cancellation or disconnect. Servers can make each requestState token single-use. Adds the swift-crypto dependency to both manifests.

Motivation

  • SEP-2322 (2026-07-28): server-to-client requests (sampling, elicitation, roots) are replaced by inputRequests in the result of the originating request, plus an opaque requestState the client echoes.
  • requestState returns from the client, so it is untrusted input; the SDK must make tampering, replay against another request and expiry detectable.
  • One handler should serve both 2025-11-25 and 2026-07-28 clients.
  • Conformance: the server input-required-result-* scenarios (13 entries) and the client sep-2322-client-request-state scenario.

Changes

Base types (Sources/MCP/Base/MultiRoundTrip.swift, new)

  • InputRequest: .elicitation(CreateElicitation.Parameters), .sampling(CreateSamplingMessage.Parameters), .listRoots; method; elicitation(message:requestedSchema:) for a form elicitation. Wire form {method, params}; unknown methods fail to decode.
  • InputResponse: .elicitation, .sampling, .roots cases and elicitation, sampling, roots accessors. Wire form is the plain result, decoded by shape: roots, then action, otherwise sampling.
  • Internal InputRequiringResult, InputRespondingParameters and MRTR (carrier methods, maxRounds = 10, state-only backoff 50 ms to 250 ms, inputResponses: null rejection, resultType normalization).

Carriers (Sources/MCP/Server/Tools.swift, Prompts.swift, Resources.swift)

  • CallTool.Parameters, GetPrompt.Parameters, ReadResource.Parameters: new var inputResponses, var requestState and defaulted init parameters. GetPrompt.Parameters and ReadResource.Parameters get explicit Codable implementations. An explicit inputResponses: null fails to decode (answered with -32602).
  • CallTool.Result, GetPrompt.Result, ReadResource.Result: new inputRequests, requestState, computed resultType, and static func inputRequired(_:requestState:_meta:).
    • An input-required result encodes only resultType, inputRequests, requestState and _meta; decoding it does not require the normal content fields.
    • A private declaredResultType keeps a decoded input_required result with neither field (load shedding). A decoded complete is stored as nil, so decoded and constructed results compare equal.

Server (Sources/MCP/Server/Server.swift, Sources/MCP/Server/RequestState.swift new)

  • withMethodHandler wraps the three carriers in serveRoundTrips (nonisolated).
  • Stateless requests:
    • an incoming requestState is unsealed and verified before the handler runs; any failure is answered with -32602 "Invalid or expired requestState", and the reason is logged;
    • a result with content and input, or an input-required result with neither inputRequests nor requestState, fails with -32603;
    • input requests for capabilities the client did not declare fail with -32021 (missingRequiredClientCapabilities, listing the required capabilities);
    • outgoing requestState is sealed.
  • Handshake requests: client-sent inputResponses/requestState are dropped. The server sends elicitation/create, sampling/createMessage or roots/list concurrently, then calls the handler again with the responses and the handler's state. At most 10 handler calls; then -32603.
  • Server.init(..., requestStateProtection: RequestStateProtection? = .ephemeral()); nil disables sealing.
  • RequestStateCodec protocol (seal, unseal), InvalidRequestState.
  • AESGCMRequestStateCodec:
    • token v1. + base64url(key id 4 bytes ‖ nonce 12 ‖ ciphertext ‖ tag 16); the prefix and the key id are bound as associated data;
    • key = HKDF-SHA256 of each secret (info mcp/request-state/v1/aes-256-gcm); key id = SHA-256(label ‖ key) prefix 4 bytes;
    • keys[0] seals, every key unseals (rotation); secrets of at least minimumKeyLength (32) bytes; random().
  • RequestStateProtection (codec, timeToLive default 600 s, audience default the server name, principal); init(codec:...), init(keys:...), ephemeral(timeToLive:).
  • Internal RequestStateBoundary: claims v, iat, exp, m (method), t (tool or prompt name, or resource URI), a (SHA-256 prefix 16 bytes of the sorted-keys JSON arguments), aud, p (salted principal hash, optional, compared in constant time), s (the handler's plaintext). 60 s tolerated skew on iat. Each round seals again with a fresh expiry.

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

  • send(_:) = dispatch + resolveInputRequests for carrier methods when configuration.multiRoundTrip.isEnabled:
    • fulfills input requests concurrently through the registered request handlers (sampling, elicitation, roots); a missing handler fails with -32601;
    • retries with a new request id, the same _meta, the responses and the requestState echoed verbatim (omitted when absent);
    • state-only rounds back off from 50 ms, doubling to 250 ms;
    • fails with -32603 after multiRoundTrip.maxRounds retries (default 10).
  • roundTrips maps the first request id to the current round's id, so cancelRequest(firstID) cancels the current round and stops the loop.
  • Client.Configuration.multiRoundTrip / Client.Configuration.MultiRoundTrip(isEnabled:maxRounds:). With isEnabled = false, send(_:) returns input-required results, and callTool, getPrompt and readResource throw MCPError.invalidRequest for them.

Package

  • Package.swift: swift-crypto 3.0.0..<5.0.0, product Crypto in the MCP target. Package.resolved pins swift-crypto 4.5.2 and swift-asn1 1.7.3. [email protected] too.

Fixtures

  • Sources/MCPConformance/Server/InputRequired.swift (new): eight test_input_required_result_* tools (elicitation, sampling, list_roots, request_state, multiple_inputs, multi_round, tampered_state, capabilities) and the prompt test_input_required_result_prompt, wired into Sources/MCPConformance/Server/main.swift.
  • Sources/MCPConformance/Client/main.swift: scenario sep-2322-client-request-state; the first elicitation also calls test_mrtr_unrelated while another call is between rounds.

Baselines

  • conformance-baseline.2026-07-28.yml (server list now empty), conformance-baseline.yml regenerated.

Docs

  • README.md: "Input Requests" section (server handler, sealing, shared keys and rotation, client loop, manual rounds with the loop disabled); notes in "Sampling" and the stateless section pointing to it.

Review fixes

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

  • A result could carry any number of input requests. New MultiRoundTrip.maxInputRequests (16): a result with more fails with -32603 before any handler runs. MultiRoundTrip decodes missing keys with their defaults.
  • cancelRequest(_:) only cancelled the current round's request; running input handlers kept running, and a cancel right after send could miss the exchange. The exchange is now registered before send returns; cancelRequest cancels the task that runs the rounds (and with it the running handlers) and sends nothing when no round is in flight. Rounds check cancellation before and after the handlers.
  • disconnect() did not stop exchanges between rounds. It now cancels every round task and clears the exchange state.

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

  • The handshake bridge retried a state-only result at once; it now waits 50 ms, doubling up to 250 ms, as a 2026-07-28 client does.
  • The bridge checked client capabilities only in strict mode (-32601). It now refuses input requests for undeclared capabilities with -32021 in both eras.
  • A client error to a bridged request was passed through; it now fails the call with -32603.
  • Cancelling a bridged call left its requests outstanding. The server now withdraws them (notifications/cancelled to the client) and does not call the handler again.
  • A batch was handled on the receive loop, so a batched carrier request that needed bridged input deadlocked the connection. Batches now run in their own task.
  • The requestState binding re-encoded the parameters on every seal and unseal, before the token was authenticated. It is now computed once from the typed parameters (stateBinding on the three carriers) and only for an authenticated token.

Request state (Sources/MCP/Server/RequestState.swift)

  • A token could be echoed any number of times until it expired. Tokens now carry a random jti claim; new RequestStateProtection.consume ((tokenID, expiry) async -> Bool) records each verified token and rejects a replay with -32602. nil (default) keeps replays allowed until expiry.

Package

Docs

  • README.md: bridge backoff, cancellation and errors; -32021 regardless of strict; consume; a principal taken from authenticated identity instead of a client-set header; maxInputRequests; cancellation and disconnect of rounds.

Diagram

Stateless (2026-07-28) round trip:

sequenceDiagram
    participant C as Client
    participant S as Server
    participant H as Handler
    C->>S: tools/call id 1
    S->>H: params
    H-->>S: inputRequired confirm, state s1
    S->>S: check capabilities, seal s1
    S-->>C: resultType input_required, inputRequests, sealed token
    C->>C: run elicitation handler
    C->>S: tools/call id 2, inputResponses, token
    S->>S: unseal, verify binding and expiry
    S->>H: params with responses, requestState s1
    H-->>S: content
    S-->>C: complete result
Loading

Handshake (2025-11-25) bridge, same handler:

sequenceDiagram
    participant C as Client
    participant S as Server
    participant H as Handler
    C->>S: tools/call id 1
    S->>H: params
    H-->>S: inputRequired confirm
    S->>C: elicitation/create
    C-->>S: elicitation result
    S->>H: params with inputResponses
    H-->>S: content
    S-->>C: result for id 1
Loading

API changes

Added

Symbol Notes
InputRequest .elicitation, .sampling, .listRoots; method; elicitation(message:requestedSchema:); Codable
InputResponse .elicitation, .sampling, .roots; accessors; Codable
CallTool.Parameters.inputResponses, .requestState also on GetPrompt.Parameters, ReadResource.Parameters
CallTool.Result.inputRequests, .requestState, .resultType also on GetPrompt.Result, ReadResource.Result
CallTool.Result.inputRequired(_:requestState:_meta:) also on GetPrompt.Result, ReadResource.Result
RequestStateCodec protocol
AESGCMRequestStateCodec init(keys:), random(), minimumKeyLength
InvalidRequestState reason
RequestStateProtection init(codec:timeToLive:audience:principal:consume:), init(keys:timeToLive:audience:principal:consume:), ephemeral(timeToLive:)
Client.Configuration.multiRoundTrip Client.Configuration.MultiRoundTrip(isEnabled:maxRounds:maxInputRequests:); decodes missing keys with defaults
RequestStateProtection.consume (tokenID, expiry) async -> Bool; false rejects a replayed token

Changed

Symbol Change
Server.init(name:version:title:instructions:capabilities:configuration:requestStateProtection:) new defaulted parameter; source compatible
Client.Configuration.init(strict:protocolMode:logLevel:multiRoundTrip:) new defaulted parameter; source compatible
CallTool.Parameters.init, GetPrompt.Parameters.init, ReadResource.Parameters.init new defaulted inputResponses: and requestState:; source compatible
Client.send(_:) for tools/call, prompts/get, resources/read, the returned task spans every round
Server.withMethodHandler(_:handler:) carrier handlers run through the round-trip logic
Package dependencies adds swift-crypto (Crypto), in Package.swift and [email protected]

Removed

None.

Behavior changes

  • A handler returning inputRequired(...) works at both revisions: stateless clients receive the input-required result; handshake clients receive server-to-client requests and the final result.
  • Handshake clients cannot inject inputResponses or requestState; the server drops them.
  • At 2026-07-28 the requestState a client sees is a sealed v1. token, not the handler's string, unless requestStateProtection: nil. With the default ephemeral key, state from another process or from before a restart is rejected with -32602.
  • Client.callTool/getPrompt/readResource transparently fulfill input requests with the registered handlers. A server that asks for input the client has no handler for now fails the call with -32601.
  • Decoding a CallTool.Result, GetPrompt.Result or ReadResource.Result with resultType: "input_required" no longer requires the content fields.
  • The client fails a call whose result carries more than 16 input requests (-32603). cancelRequest and disconnect() stop the rounds and cancel running input handlers.
  • The handshake bridge waits between state-only rounds (50 ms to 250 ms), refuses undeclared capabilities with -32021 whatever strict says, fails the call with -32603 on a client error, and withdraws outstanding requests when the call is cancelled.
  • A server batch no longer blocks the connection while one of its requests waits for bridged input.
  • With RequestStateProtection.consume set, each requestState token is accepted once; a client that retries a round after a lost response must start the request again.

Conformance

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

Leg Before (P6) After (P7)
2025-11-25 0 / 0 0 / 0
2026-07-28 13 / 31 0 / 26
default 38 / 35 25 / 30
  • Cleared: the 13 input-required-result-* server entries and the 5 sep-2322-client-request-state client entries. The remaining 2026-07-28 client entries are all OAuth (P8 ([P8] oauth: issuer checks, application_type, AS migration (SEP-2468/837/2352) #363)); the remaining default-leg server entries are tasks-* (extension, not scored).
  • Tier score 2026-07-28: server 37/37 (100%), client 12/32 (all failures are auth). Tier score 2025-11-25: 100% client and server.

Tests

  • Tests/MCPTests/MultiRoundTripTests.swift (new):
    • "Multi Round-Trip Wire Format": input requests encode as method and params; input responses decode by shape; input-required results carry resultType and no content; params carry inputResponses and requestState, and null responses are rejected.
    • "Request State Protection": the AES-GCM codec round-trips and rejects modified tokens; key rotation (every key unseals, the first seals); sealed state bound to the request, time window, audience and principal.
    • "Multi Round-Trip Requests": the client fulfills and retries until complete; the server seals and rejects modified state; without protection the state crosses the wire as written; -32021 for unfulfillable input requests; content plus input requests is a server error; the client stops after the configured rounds; a missing client handler fails the call; the server bridge fulfills requests for handshake clients; the bridge stops after the round limit.
  • Review fixes (Tests/MCPTests/MultiRoundTripTests.swift): each token has its own id and expiry, and the binding is computed only for an authentic token; a consume hook rejects a replayed token; the client refuses a result with too many input requests before any handler runs; cancelRequest during a round cancels the running handlers; cancelRequest right after send ends the exchange before any round; disconnect cancels a round in progress; the bridge waits between state-only rounds, checks capabilities without strict, fails the call with -32603 on a client error, withdraws its input request on cancellation; a batched call that needs bridged input does not block the connection.
  • 763 swift-testing tests pass, plus XCTest.

Review notes

  • Wire format follows the harness's draft schema: inputRequests values are {method, params}, inputResponses values are plain results, and InputRequiredResult has no content.
  • The handshake bridge follows the Go SDK (at most 10 handler calls, then -32603); the Python SDK answers -32603 instead. The client limit is configurable.
  • The token format matches the Python SDK; the claims envelope differs slightly.
  • RequestStateCodec methods are synchronous; a codec backed by a key service must cache key material.
  • AESGCMRequestStateCodec(keys:) reports bad keys as MCPError.invalidRequest (-32600). Kept and listed in docs/rough_edges.md (P10 ([P10] docs: go-sdk layout, feature guides, design notes and process docs #362)).
  • The branch builds with both manifests: [email protected] gets swift-crypto too.
  • Without consume, a requestState token can be replayed until it expires (10 minutes per round by default).
  • The MRTR.maxRounds doc comment says it applies to the client loop as well, which uses Configuration.multiRoundTrip.maxRounds; corrected in P10 ([P10] docs: go-sdk layout, feature guides, design notes and process docs #362).
  • withBatch bypasses dispatch, so batched carrier requests get no round loop; fixed in P11 ([P11] fix: request lifecycle, server replies, OAuth hardening #360) (conformance/p11-fixes).
  • dispatch keeps the previous send pattern of registering and sending from an unstructured task, so a cancelRequest right after send can miss the request; fixed in P11 ([P11] fix: request lifecycle, server replies, OAuth hardening #360). For carrier requests the exchange is already registered before send returns, so such a cancel ends it before any round.
  • Not done: resuming rounds across client processes is left to callers, via multiRoundTrip.isEnabled = false and send(_:).

Verification

Every branch of the stack builds and passes swift test; all conformance legs pass at their baselines. On this branch, 763 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 --mode server --bin-path "$BIN"
scripts/run-conformance.sh --spec-version 2026-07-28 --mode client --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"
scripts/run-conformance.sh --requirements 2025-11-25 --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 multi round-trip requests (SEP-2322). At 2026-07-28 a server
cannot send requests to the client, so a `tools/call`, `prompts/get` or
`resources/read` handler that needs input returns an input-required
result; the client fulfills the embedded requests and retries with
`inputResponses` and the echoed `requestState`. The server seals
`requestState` with AES-256-GCM and verifies every echo, and bridges the
same handlers to handshake clients by sending the requests itself. The
client runs the round loop inside `send(_:)`, bounds it in rounds and
input requests, and stops it on cancellation or disconnect. Servers can
make each `requestState` token single-use. Adds the swift-crypto
dependency to both manifests.
- Do not send a bridged input request once its carrier is cancelled:
  ask() checks cancellation before sending, and send() records each
  request until its pending response is registered, so a withdraw that
  runs before registration removes the record and the request is never
  sent; a withdraw after registration still sends
  notifications/cancelled. Other server-to-client requests are
  unchanged.
- Record the request items of a batch in startingRequests before the
  batch task starts, as for single requests, so a cancellation that
  arrives before a later item runs is honored. Placeholders for invalid
  items are not recorded.
- Document the description, websiteUrl and icons parameters that main's
  #258 added to Server.init, next to requestStateProtection.
- An input-required result whose inputRequests is empty and that has no
  requestState is a server error (-32603), as one with neither field is.
  It asks for nothing, so the client (or the handshake bridge) would
  retry the same request until the round limit. SEP-2322 requires at
  least one of the two fields in every InputRequiredResult.
- RequestStateProtection.consume is async throws. A throw (a replay store
  that cannot be reached) fails the round with -32603 and is logged as an
  error, instead of forcing the hook to fail open or report a replay
  (-32602). The type is new in this release; non-throwing closures still
  convert.
- The principal doc comment says what nil means on a server with several
  users: state can be echoed by another user for the same request until
  it expires.
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/p6-listen to rel/1.0.0 November 25, 2026 12:37
@jeanmatthieu
jeanmatthieu dismissed canarik’s stale review November 25, 2026 12:37

The base branch was changed.

@jeanmatthieu
jeanmatthieu merged commit d22f860 into rel/1.0.0 Nov 25, 2026
@jeanmatthieu
jeanmatthieu deleted the conformance/p7-mrtr branch November 25, 2026 12:37
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