Repository navigation
[P7] mrtr: input-required results at 2026-07-28 (SEP-2322) - #364
Merged
Merged
Conversation
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.
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: P6 (#365) · next: P8 (#363))conformance/p7-mrtrconformance/p6-listen(stacked: GitHub retargets this PR torel/1.0.0when the previous part merges)fdb59eemrtr: input-required results at 2026-07-28 (SEP-2322)6c60508mrtr: review fixesf92b391mrtr: second-pass review fixesSummary
Implements multi round-trip requests (SEP-2322). At 2026-07-28 a server cannot send requests to the client, so a
tools/call,prompts/getorresources/readhandler that needs input returns an input-required result; the client fulfills the embedded requests and retries withinputResponsesand the echoedrequestState. The server sealsrequestStatewith 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 insidesend(_:), bounds it in rounds and input requests, and stops it on cancellation or disconnect. Servers can make eachrequestStatetoken single-use. Adds the swift-crypto dependency to both manifests.Motivation
inputRequestsin the result of the originating request, plus an opaquerequestStatethe client echoes.requestStatereturns from the client, so it is untrusted input; the SDK must make tampering, replay against another request and expiry detectable.input-required-result-*scenarios (13 entries) and the clientsep-2322-client-request-statescenario.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,.rootscases andelicitation,sampling,rootsaccessors. Wire form is the plain result, decoded by shape:roots, thenaction, otherwise sampling.InputRequiringResult,InputRespondingParametersandMRTR(carrier methods,maxRounds= 10, state-only backoff 50 ms to 250 ms,inputResponses: nullrejection,resultTypenormalization).Carriers (
Sources/MCP/Server/Tools.swift,Prompts.swift,Resources.swift)CallTool.Parameters,GetPrompt.Parameters,ReadResource.Parameters: newvar inputResponses,var requestStateand defaulted init parameters.GetPrompt.ParametersandReadResource.Parametersget explicitCodableimplementations. An explicitinputResponses: nullfails to decode (answered with -32602).CallTool.Result,GetPrompt.Result,ReadResource.Result: newinputRequests,requestState, computedresultType, andstatic func inputRequired(_:requestState:_meta:).resultType,inputRequests,requestStateand_meta; decoding it does not require the normal content fields.declaredResultTypekeeps a decodedinput_requiredresult with neither field (load shedding). A decodedcompleteis stored asnil, so decoded and constructed results compare equal.Server (
Sources/MCP/Server/Server.swift,Sources/MCP/Server/RequestState.swiftnew)withMethodHandlerwraps the three carriers inserveRoundTrips(nonisolated).requestStateis unsealed and verified before the handler runs; any failure is answered with -32602 "Invalid or expired requestState", and the reason is logged;inputRequestsnorrequestState, fails with -32603;missingRequiredClientCapabilities, listing the required capabilities);requestStateis sealed.inputResponses/requestStateare dropped. The server sendselicitation/create,sampling/createMessageorroots/listconcurrently, 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());nildisables sealing.RequestStateCodecprotocol (seal,unseal),InvalidRequestState.AESGCMRequestStateCodec:v1.+ base64url(key id 4 bytes ‖ nonce 12 ‖ ciphertext ‖ tag 16); the prefix and the key id are bound as associated data;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 leastminimumKeyLength(32) bytes;random().RequestStateProtection(codec,timeToLivedefault 600 s,audiencedefault the server name,principal);init(codec:...),init(keys:...),ephemeral(timeToLive:).RequestStateBoundary: claimsv,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 oniat. Each round seals again with a fresh expiry.Client (
Sources/MCP/Client/Client.swift)send(_:)=dispatch+resolveInputRequestsfor carrier methods whenconfiguration.multiRoundTrip.isEnabled:_meta, the responses and therequestStateechoed verbatim (omitted when absent);multiRoundTrip.maxRoundsretries (default 10).roundTripsmaps the first request id to the current round's id, socancelRequest(firstID)cancels the current round and stops the loop.Client.Configuration.multiRoundTrip/Client.Configuration.MultiRoundTrip(isEnabled:maxRounds:). WithisEnabled = false,send(_:)returns input-required results, andcallTool,getPromptandreadResourcethrowMCPError.invalidRequestfor them.Package
Package.swift:swift-crypto3.0.0..<5.0.0, productCryptoin theMCPtarget.Package.resolvedpins swift-crypto 4.5.2 and swift-asn1 1.7.3.[email protected]too.Fixtures
Sources/MCPConformance/Server/InputRequired.swift(new): eighttest_input_required_result_*tools (elicitation, sampling, list_roots, request_state, multiple_inputs, multi_round, tampered_state, capabilities) and the prompttest_input_required_result_prompt, wired intoSources/MCPConformance/Server/main.swift.Sources/MCPConformance/Client/main.swift: scenariosep-2322-client-request-state; the first elicitation also callstest_mrtr_unrelatedwhile another call is between rounds.Baselines
conformance-baseline.2026-07-28.yml(server list now empty),conformance-baseline.ymlregenerated.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)MultiRoundTrip.maxInputRequests(16): a result with more fails with -32603 before any handler runs.MultiRoundTripdecodes missing keys with their defaults.cancelRequest(_:)only cancelled the current round's request; running input handlers kept running, and a cancel right aftersendcould miss the exchange. The exchange is now registered beforesendreturns;cancelRequestcancels 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)strictmode (-32601). It now refuses input requests for undeclared capabilities with -32021 in both eras.notifications/cancelledto the client) and does not call the handler again.requestStatebinding re-encoded the parameters on every seal and unseal, before the token was authenticated. It is now computed once from the typed parameters (stateBindingon the three carriers) and only for an authenticated token.Request state (
Sources/MCP/Server/RequestState.swift)jticlaim; newRequestStateProtection.consume((tokenID, expiry) async -> Bool) records each verified token and rejects a replay with -32602.nil(default) keeps replays allowed until expiry.Package
[email protected]:swift-crypto3.0.0..<5.0.0and productCrypto, as inPackage.swift.Docs
README.md: bridge backoff, cancellation and errors; -32021 regardless ofstrict;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 resultHandshake (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 1API changes
Added
InputRequest.elicitation,.sampling,.listRoots;method;elicitation(message:requestedSchema:);CodableInputResponse.elicitation,.sampling,.roots; accessors;CodableCallTool.Parameters.inputResponses,.requestStateGetPrompt.Parameters,ReadResource.ParametersCallTool.Result.inputRequests,.requestState,.resultTypeGetPrompt.Result,ReadResource.ResultCallTool.Result.inputRequired(_:requestState:_meta:)GetPrompt.Result,ReadResource.ResultRequestStateCodecAESGCMRequestStateCodecinit(keys:),random(),minimumKeyLengthInvalidRequestStatereasonRequestStateProtectioninit(codec:timeToLive:audience:principal:consume:),init(keys:timeToLive:audience:principal:consume:),ephemeral(timeToLive:)Client.Configuration.multiRoundTripClient.Configuration.MultiRoundTrip(isEnabled:maxRounds:maxInputRequests:); decodes missing keys with defaultsRequestStateProtection.consume(tokenID, expiry) async -> Bool;falserejects a replayed tokenChanged
Server.init(name:version:title:instructions:capabilities:configuration:requestStateProtection:)Client.Configuration.init(strict:protocolMode:logLevel:multiRoundTrip:)CallTool.Parameters.init,GetPrompt.Parameters.init,ReadResource.Parameters.initinputResponses:andrequestState:; source compatibleClient.send(_:)tools/call,prompts/get,resources/read, the returned task spans every roundServer.withMethodHandler(_:handler:)swift-crypto(Crypto), inPackage.swiftand[email protected]Removed
None.
Behavior changes
inputRequired(...)works at both revisions: stateless clients receive the input-required result; handshake clients receive server-to-client requests and the final result.inputResponsesorrequestState; the server drops them.requestStatea client sees is a sealedv1.token, not the handler's string, unlessrequestStateProtection: nil. With the default ephemeral key, state from another process or from before a restart is rejected with -32602.Client.callTool/getPrompt/readResourcetransparently 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.CallTool.Result,GetPrompt.ResultorReadResource.ResultwithresultType: "input_required"no longer requires the content fields.cancelRequestanddisconnect()stop the rounds and cancel running input handlers.strictsays, fails the call with -32603 on a client error, and withdraws outstanding requests when the call is cancelled.RequestStateProtection.consumeset, eachrequestStatetoken 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:
input-required-result-*server entries and the 5sep-2322-client-request-stateclient 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 aretasks-*(extension, not scored).Tests
Tests/MCPTests/MultiRoundTripTests.swift(new):methodandparams; input responses decode by shape; input-required results carryresultTypeand no content; params carryinputResponsesandrequestState, andnullresponses are rejected.Tests/MCPTests/MultiRoundTripTests.swift): each token has its own id and expiry, and the binding is computed only for an authentic token; aconsumehook rejects a replayed token; the client refuses a result with too many input requests before any handler runs;cancelRequestduring a round cancels the running handlers;cancelRequestright aftersendends the exchange before any round;disconnectcancels a round in progress; the bridge waits between state-only rounds, checks capabilities withoutstrict, 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.Review notes
inputRequestsvalues are{method, params},inputResponsesvalues are plain results, andInputRequiredResulthas no content.RequestStateCodecmethods are synchronous; a codec backed by a key service must cache key material.AESGCMRequestStateCodec(keys:)reports bad keys asMCPError.invalidRequest(-32600). Kept and listed indocs/rough_edges.md(P10 ([P10] docs: go-sdk layout, feature guides, design notes and process docs #362)).[email protected]gets swift-crypto too.consume, arequestStatetoken can be replayed until it expires (10 minutes per round by default).MRTR.maxRoundsdoc comment says it applies to the client loop as well, which usesConfiguration.multiRoundTrip.maxRounds; corrected in P10 ([P10] docs: go-sdk layout, feature guides, design notes and process docs #362).withBatchbypassesdispatch, so batched carrier requests get no round loop; fixed in P11 ([P11] fix: request lifecycle, server replies, OAuth hardening #360) (conformance/p11-fixes).dispatchkeeps the previoussendpattern of registering and sending from an unstructured task, so acancelRequestright aftersendcan miss the request; fixed in P11 ([P11] fix: request lifecycle, server replies, OAuth hardening #360). For carrier requests the exchange is already registered beforesendreturns, so such a cancel ends it before any round.multiRoundTrip.isEnabled = falseandsend(_:).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.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.