Ask the user in the middle of a call
閱讀約需 99 分鐘 分鐘,9 節 中共有 6 個範例。
此部分尚未翻譯,因此以英文呈現。
By the end of this chapter you can make the shop's refund tool stop in the middle of a call, ask the person at the host to confirm a refund, and carry on with the answer, using Model Context Protocol elicitation inside a Multi Round-Trip Request on a server that keeps no call open while it waits. This chapter's claims are true of revision 2026-07-28 of the specification and of mcp 2.3.0, the Python SDK.
At the shop, where refunds come in as tickets for the support team's host, the refund policy requires a support lead to confirm any refund above €150.00 before it's issued. The shop's API enforces that limit by holding such a refund with the status needs_confirmation. In Design tools a model can use, the issue_refund tool passes that hold back to the model and stops there, so a refund the model was right to make waits until someone finds it in the back office.
The person who could confirm the refund is already at the host, reading the conversation. The tool needs a way to put one question to that person in the middle of the call and carry on with the answer. The Model Context Protocol (MCP) has a name for that, elicitation: a structured question that a server sends and the client shows the user. At the pinned revision, the question travels inside a Multi Round-Trip Request, a pattern in which one call can end with a question instead of a result. The server answers the call with an input request instead of a result, and the client calls again with the answer.
Each server example in this chapter runs itself, as the earlier chapters' examples do. Run with no arguments, the file starts a client, and that client launches the same file with --serve over stdio. The shop's API runs on loopback beside them.
此部分尚未翻譯,因此以英文呈現。
See why a stateless server can't wait for an answer
Before the pinned revision, a server that needed the user's input sent its own request to the client, elicitation/create, and waited for the reply while the tool call stayed open. The pinned revision removed that pattern. The specification says servers MUST send their requests to the client, elicitation/create among them, through the Multi Round-Trip Request pattern. It calls the old pattern a breaking change that is no longer supported (Multi Round-Trip Requests). Elicitation is one of the requests this chapter uses, and it isn't deprecated. The other two, sampling/createMessage and roots/list, are deprecated, and Replace sampling, roots and logging gives their replacements: a direct call to a model provider's API, and tool parameters, resource URIs or server configuration (deprecated features).
The reason is statelessness. At the pinned revision there's no handshake and no session, and each request carries its own version and capabilities in _meta (Carry the version and capabilities on every request). A request that waits on a reply from the client ties one server process to one open connection for as long as a person takes to answer. The specification's aim is a server that can ask for input without a shared storage layer across server instances or stateful load balancing (Multi Round-Trip Requests). The proposal behind the change, SEP-2322, says that Streamable HTTP then depends less on long-lived streams, which cause problems in many environments (SEP-2322).
The Python SDK still offers the old call. ctx.elicit() sends elicitation/create as a request from the server, and on a connection at the pinned revision it fails with NoBackChannelError, an Invalid Request error, because the protocol forbids server-initiated requests there (mcp/shared/transport_context.py, mcp/shared/exceptions.py).
The first attempt at a confirmation is written that way. Its server takes chapter 3's tools from a shared module, lib.confirmations, which holds what this chapter's servers have in common: those tools, the key that protects round-trip state, and a record of answers already used. Its issue_refund calls chapter 3's version, which posts the refund to the shop's API. If the API holds the refund, the tool calls ctx.elicit() and waits. The client has an elicitation callback that plays a scripted user, who would release the refund if asked. The client quotes order O-2289, whose whole refund is above the limit, and calls issue_refund.
1"""The 2025 way to confirm a refund, which fails at revision 2026-07-28: issue_refund calls ctx.elicit() and waits,2but the protocol gives the server no channel back to the client. The printed error code and the count of questions3the user saw show the failure, before anyone is asked."""4import asyncio5import sys67from mcp import Client, MCPError8from mcp.server.mcpserver import Context9from mcp.types import ElicitResult10from pydantic import BaseModel1112from lib import confirmations, loopback, shop_api, shop_tools1314server, held = confirmations.shop_server() # chapter 3's other tools; held is chapter 3's issue_refund15asked = [] # every question that reached the user161718class Release(BaseModel):19 release: bool202122@server.tool(title="Issue a refund", description=shop_tools.DESCRIPTIONS["issue_refund"], annotations=held.annotations)23async def issue_refund(quote_id: confirmations.QuoteId, ctx: Context) -> shop_tools.Refund:24 refund = held.fn(quote_id)25 if refund.status == "needs_confirmation": # ask, and hold the call open until the answer comes back26 answer = await ctx.elicit(f"Refund {refund.amount} on order {refund.order_id}?", Release)27 if answer.action == "accept" and answer.data.release:28 return confirmations.release(refund)29 return refund303132async def say_yes(context, params) -> ElicitResult: # a scripted user, who would release the refund33 asked.append(params.message)34 return ElicitResult(action="accept", content={"release": True})353637async def main() -> None:38 with loopback.serve(shop_api.create_app()) as base_url:39 async with Client(confirmations.launch(__file__, base_url), elicitation_callback=say_yes) as client: # starts this file with --serve40 print("protocol revision:", client.protocol_version)41 quote = (await client.call_tool("quote_refund", {"order_id": "O-2289"})).structured_content42 try:43 await client.call_tool("issue_refund", {"quote_id": quote["quote_id"]})44 except MCPError as error:45 print("error code:", error.error.code)46 print("error message:", error.error.message)47 print("questions the user saw:", len(asked))484950server.run() if "--serve" in sys.argv else asyncio.run(main()) # the client runs this file with --serve; run directly, it starts the client
python refund-needs-confirmation.pyprotocol revision: 2026-07-28
error code: -32600
error message: Cannot send 'elicitation/create': this transport context has no back-channel for server-initiated requests.
questions the user saw: 0
The call failed with JSON-RPC error -32600, Invalid Request, and the message "Cannot send 'elicitation/create': this transport context has no back-channel for server-initiated requests." The scripted user was asked 0 questions. Nobody saw the refund. Because the failure is a protocol error, not a tool result, the model never saw it either (Report failures as tool results). The refund stays held in the shop's API, as it did in chapter 3.
The tool's own logic isn't what failed. It asked the protocol for something the pinned revision doesn't have, a channel from server to client in the middle of a call. Any code that waits inside a tool call for an answer runs into the same wall, whatever SDK it uses.
Working rule: Never wait inside a tool call for something only the client can give you. On a connection at the pinned revision, treat every call to ctx.elicit() or ctx.elicit_url() as a bug, and return an input request instead, as the next section does. Keep the old call only on a server that must also answer 2025-era clients, and only behind a check of ctx.protocol_version (Serve old and new clients through the window).
此部分尚未翻譯,因此以英文呈現。
Return an input request instead of a result
The call that failed in the previous section needed a channel the protocol doesn't have. A Multi Round-Trip Request turns the question around. Instead of a result, the server returns an InputRequiredResult, whose resultType is "input_required", and the call ends there. Two fields carry the rest. inputRequests maps keys the server chooses to the requests it needs answered, and requestState is an opaque string the client must send back. The server MUST include at least one of the two (Multi Round-Trip Requests; schema, InputRequiredResult).
Three rules limit what a server may ask, and when. Only tools/call, prompts/get and resources/read may answer with an input request, and servers MUST NOT send one on any other request. A server MUST NOT include an elicitation/create request unless the client declared the elicitation capability (Multi Round-Trip Requests). And because every result at the pinned revision carries resultType, a client treats a missing one, which an older server sends, as "complete", and treats any other unrecognized value as invalid (overview).
issue_refund still calls chapter 3's version first, so the shop's API decides, with the policy's limit, whether a refund needs confirming, and the server never repeats the limit. Within one server process, chapter 3's tool returns the same refund for the same quote_id every time, which makes calling it on every round safe. Across processes, that doesn't hold, as What goes wrong in production explains under "Records that only one process sees." When the API holds the refund, the tool checks that the client declared form-mode elicitation, then builds the input request by hand: one ElicitRequest under the key confirm, whose form is one required yes-or-no field, release, and whose message names the amount and the order. Its requestState is the refund's ID. When the retry arrives, the tool checks that the state names the refund it found, and it uses the state as the key of its record of answers.
The server passes request_state_security= to MCPServer, with the policy that confirmations.state_security() builds, so that several replicas can later share one key. In these examples that policy is the SDK's default, a key made when the process starts. A client declares elicitation by passing a callback, and calls the tool through client.session.call_tool(..., allow_input_required=True), which hands back the input request instead of answering it.
1"""issue_refund answers a held refund with an input request instead of a result, which asks a person to confirm it.2The prose's points rest on the result type line, the one input request under confirm with its message, and the3assert, which fails the run if the SDK doesn't seal the request state."""4import asyncio5import sys67from mcp import Client8from mcp.server.mcpserver import Context9from mcp.server.mcpserver.exceptions import ToolError10from mcp.types import ElicitRequest, ElicitRequestFormParams, InputRequiredResult1112from lib import confirmations, loopback, shop_api, shop_tools1314server, held = confirmations.shop_server() # chapter 3's other tools; held is chapter 3's issue_refund15answered = confirmations.OnceOnly() # the round-trip states already answered, so a replayed answer fails161718@server.tool(title="Issue a refund", description=shop_tools.DESCRIPTIONS["issue_refund"], annotations=held.annotations)19def issue_refund(quote_id: confirmations.QuoteId, ctx: Context) -> shop_tools.Refund | InputRequiredResult:20 refund = held.fn(quote_id) # the same quote_id always gives the same refund21 if refund.status != "needs_confirmation":22 return refund23 answer = (ctx.input_responses or {}).get("confirm") # the answer comes back under the key the tool asked with24 if answer is None or ctx.request_state != refund.refund_id: # first round, or a question never asked25 confirmations.require_elicitation(ctx, "form") # ask only what the client declared it can show26 ask = ElicitRequestFormParams(requested_schema=confirmations.RELEASE_FORM, message=f"Refund {refund.amount} on "27 f"order {refund.order_id}? It is above the policy limit, so a lead must confirm it.")28 return InputRequiredResult(input_requests={"confirm": ElicitRequest(params=ask)},29 request_state=refund.refund_id) # the refund's ID rides in the state the SDK seals30 if answer.action != "accept" or not (answer.content or {}).get("release"):31 raise ToolError(f"Nobody confirmed refund {refund.refund_id}, so the shop's API still holds it.")32 if not answered.claim(ctx.request_state): # sealing can't stop a replay; this record does33 raise ToolError(f"Refund {refund.refund_id} was already confirmed. Don't send the same answer again.")34 return confirmations.release(refund)353637async def main() -> None:38 with loopback.serve(shop_api.create_app()) as base_url:39 async with Client(confirmations.launch(__file__, base_url), # starts this file with --serve over stdio40 elicitation_callback=confirmations.say_yes) as client: # declares elicitation41 quote = (await client.call_tool("quote_refund", {"order_id": "O-2289"})).structured_content42 result = await client.session.call_tool("issue_refund", {"quote_id": quote["quote_id"]},43 allow_input_required=True) # return the input request, not an answer to it44 print("result type:", result.result_type)45 for key, request in result.input_requests.items():46 print(f"input request {key}:", request.method, request.params.mode)47 print("message:", request.params.message)48 # the SDK's sealed-token prefix: a request state that starts with it was sealed on its way out49 assert result.request_state.startswith("v1.")505152server.run() if "--serve" in sys.argv else asyncio.run(main()) # the client runs this file with --serve; run directly, it starts the client
python refund-asks-to-confirm.pyresult type: input_required
input request confirm: elicitation/create form
message: Refund 180.00 on order O-2289? It is above the policy limit, so a lead must confirm it.
The call came back with result type input_required, and its one input request is elicitation/create form. The message reads "Refund 180.00 on order O-2289? It is above the policy limit, so a lead must confirm it." That is the question the host's user would see.
The question goes to whoever sits at the host, so the answer is only as trustworthy as the host. An accept doesn't show that a support lead answered, or that a person did at all, since this chapter's scripted callbacks answer by code. Servers MUST also bind elicitation requests to the client and user identity, the specification adds (elicitation). Over stdio, as here, the user is the host's local user, who launched the server, and the server has no other identity to bind to, so the shop trusts the host to put the question to a lead. Over HTTP, the server binds the question to the authenticated caller, and the SDK's seal already includes the OAuth caller, so another user's retry fails. A server that needs a lead also checks for refunds:write, the scope only support leads hold, which already gates issue_refund (Scope tools by what the token allows; Draw the trust boundaries).
The requestState the client received isn't the refund ID the tool returned. The example asserts that the string starts with the SDK's v1. token prefix, so the SDK sealed it on its way out. MCPServer encrypts every outgoing requestState with AES-256-GCM and verifies each one that comes back. The seal binds it to the method, the tool's name, a digest of the arguments, the server's name and, when OAuth is in use, the caller (mcp/server/request_state.py). The tool itself reads and writes plaintext, while the client receives a token it can neither read nor change. The specification says clients MUST NOT inspect, parse, modify or make assumptions about requestState (Multi Round-Trip Requests), and the seal makes that hold whatever a client intends.
After this answer, nothing waits on the server. No call stays open, and no connection is held for the lead. The shop's API still holds the refund, as it did before the tool asked, and if no one ever answers, it stays held. For a step that pays money out, that is the safe default.
Between the rounds, the server keeps two records, both in its own memory. The retry finds the refund through chapter 3's quote store, not through the state, and checks the answer against the record of answered states that Keep round-trip state tamper-proof explains. A retry that reaches another process finds neither record, and Run replicas without sticky sessions moves both into storage every replica shares.
Working rule: When a tool can't finish without the user, return an InputRequiredResult with one input request per question and a requestState that says what the retry must finish. Check the client's declared capabilities before you ask. Put in the state only what the tool needs to carry on, and let the SDK seal it. Make every side effect before the question either idempotent or harmless when no one answers, because the client may never call again.
此部分尚未翻譯,因此以英文呈現。
Resume the call with the answer
The input request in the previous section ended the first call, so the client finishes the work by sending the same request again. The retry repeats the method, the tool and the arguments, adds inputResponses keyed like the input requests, and echoes the requestState back exactly. The specification says the JSON-RPC id MUST be different on the retry, because the two calls are independent requests, and that a requestState MUST NOT be used for any other request the client sends (Multi Round-Trip Requests). The server may then finish, or answer with another input request.
The second round is where a lead's yes becomes a refund. The tool from the previous section reads the answer under confirm in ctx.input_responses, gets the refund again from chapter 3's tool, and checks that ctx.request_state holds that refund's ID. Only an accept with release set makes it ask the shop's API to release the held refund, POST /refunds/{refund_id}/confirm, and return the refund. Anything else leaves the refund held.
The loop runs twice, once by hand and once through the SDK. The file launches the server through lib.wire, the book's relay that records every JSON-RPC message, and plays the lead with a scripted answer. For order O-2289 it drives the loop by hand: one call, then one retry carrying the answer and the state. For order O-1145 it calls Client.call_tool, with an elicitation callback that prints the question and answers yes.
1"""Finish the refund that refund-asks-to-confirm asks about, by retrying with the answer and the echoed requestState:2first by hand, so both requests show on the wire, then with Client.call_tool, which runs the loop itself. The point3rests on the trace lines, which show two requests each time, with different IDs, and only the retry sending the answer."""4import asyncio5import pathlib67from mcp import Client8from mcp.types import ElicitResult910from lib import confirmations, loopback, shop_api, wire1112LOG = pathlib.Path("refund-confirmed-round-trip.jsonl") # every line the relay copies13YES = ElicitResult(action="accept", content={"release": True}) # the scripted user's answer141516async def say_yes(context, params) -> ElicitResult:17 print("user was asked:", params.message)18 return YES192021async def main() -> None:22 LOG.unlink(missing_ok=True)23 with loopback.serve(shop_api.create_app()) as base_url:24 server = wire.relay(confirmations.launch("refund-asks-to-confirm.py", base_url), log=str(LOG)) # the relay copies each message to LOG25 async with Client(server, elicitation_callback=say_yes) as client:26 quote = (await client.call_tool("quote_refund", {"order_id": "O-2289"})).structured_content27 arguments = {"quote_id": quote["quote_id"]}28 first = await client.session.call_tool("issue_refund", arguments, allow_input_required=True) # the input request, not a result29 # the retry repeats the arguments, adds the answer under the request's key, and echoes the state back30 done = await client.session.call_tool("issue_refund", arguments, input_responses={"confirm": YES},31 request_state=first.request_state, allow_input_required=True)32 print("by hand:", done.structured_content["refund_id"], done.structured_content["status"])33 quote = (await client.call_tool("quote_refund", {"order_id": "O-1145"})).structured_content34 done = await client.call_tool("issue_refund", {"quote_id": quote["quote_id"]})35 print("by Client.call_tool:", done.structured_content["refund_id"], done.structured_content["status"])36 calls, results = [], {} # the issue_refund requests, in order, and each one's resultType37 for direction, message in wire.read_trace(str(LOG)):38 if message.get("method") == "tools/call" and message["params"]["name"] == "issue_refund":39 calls.append(message)40 elif direction == "in" and "result" in message: # a server's response, matched to its request by JSON-RPC id41 results[message["id"]] = message["result"]["resultType"]42 for label, message in zip(["by hand, call", "by hand, retry", "Client.call_tool, call", "Client.call_tool, retry"],43 calls):44 sent = " and ".join(key for key in ("inputResponses", "requestState") if key in message["params"])45 print(f"{label}: id {message['id']}, sends {sent or 'arguments only'}, gets {results[message['id']]}")46 LOG.unlink()4748asyncio.run(main())
python refund-confirmed-round-trip.pyby hand: R-0111 requested
user was asked: Refund 343.49 on order O-1145? It is above the policy limit, so a lead must confirm it.
by Client.call_tool: R-0112 requested
by hand, call: id 4, sends arguments only, gets input_required
by hand, retry: id 5, sends inputResponses and requestState, gets complete
Client.call_tool, call: id 7, sends arguments only, gets input_required
Client.call_tool, retry: id 8, sends inputResponses and requestState, gets complete
Driving the loop by hand works, and the trace shows the two requests behind it. The refund for order O-2289 came back as R-0111 requested, where requested is the status of a released refund, no longer held. The first call was id 4, sends arguments only, gets input_required, and the retry was id 5, sends inputResponses and requestState, gets complete. The two JSON-RPC IDs differ, and only the retry carries the answer and the state.
Client.call_tool hid the same loop. Its callback was asked "Refund 343.49 on order O-1145? It is above the policy limit, so a lead must confirm it." and answered yes, the call returned R-0112 requested, and the caller saw one call and one result. The wire still carried two requests: id 7, sends arguments only, gets input_required, then id 8, sends inputResponses and requestState, gets complete. The SDK's client sends each input request to the matching callback, retries with the answers and the state, and stops after input_required_max_rounds, 10 by default, raising InputRequiredRoundsExceededError (mcp/client/_input_required.py). A round that carries only a requestState, with no questions, is also legal. The schema's example of one is titled load shedding (schema). For such a round the SDK's client waits 50 milliseconds before retrying, doubling the wait each time up to 250 milliseconds.
A retry repeats the original request, so it isn't a fresh tool call. In the SDK, the digest of the arguments sits inside the sealed state, so a retry that changes them fails, as Keep round-trip state tamper-proof shows. A client that wants different arguments makes another call and gets another question.
Working rule: Use Client.call_tool with an elicitation callback in a host, and let the SDK run the rounds. Drive the loop yourself with client.session.call_tool(..., allow_input_required=True) only when the host must keep the state across a restart or show each round, and then repeat the arguments exactly. On the server, read the answer and the state together. When your server always sends a state, treat an answer that arrives without it, or with a state for another record, as a question never asked.
此部分尚未翻譯,因此以英文呈現。
Ask for structured input with elicitation
The confirmation in the previous section asks one yes-or-no question, and elicitation can ask for more. It has two modes (elicitation). In form mode, the server sends a message and a schema, the client renders a form, and the answer returns through the client. In URL mode, the server sends the user to a web page, not a form (the next subsection).
A form's schema is a flat object with primitive properties only: strings, including the formats email, uri, date and date-time; numbers and integers; booleans; and single- or multiple-choice enums. Any of these can carry a default. The user answers accept with the content, decline for an explicit no, or cancel for a dismissed form. Servers MUST handle both refusals. The client MUST show which server is asking, offer decline and cancel, and let the user review a form before it's sent (elicitation; Answer input requests for the user).
The SDK offers a shorter route. A tool parameter declared as Annotated[T, Resolve(fn)] is filled by running fn. When fn returns Elicit(message, Model), the SDK renders the pydantic model as the form, checks the client's capability, returns the input request, and fills it in on the retry. Annotate the parameter as ElicitationResult[Model] and the tool receives all three outcomes to branch on. A plain Model turns decline and cancel into a tool error (mcp/server/mcpserver/resolve.py).
Only the person who opens a returned parcel knows whether the item inside arrived damaged or wrong, and whether it can go back on sale. The policy's reason also decides whether shipping is refunded. The tool record_return asks with a resolver, for the line of KG-1043 on order O-1145. The form has three fields: reason, one of the refund policy's five reasons; restock, a boolean; and an optional free-text note of at most 200 characters. A scripted user accepts, declines, then cancels, and a client without a callback calls last.
1"""record_return asks the person who opened a returned parcel what they found, through a form that a resolver builds2and sends. The point rests on the three answer lines, accept, decline and cancel, and on the error a client without3an elicitation callback gets, which names a missing capability rather than a tool failure."""4import asyncio5from typing import Annotated, Literal67from mcp import Client, MCPError8from mcp.server.mcpserver import AcceptedElicitation, Elicit, ElicitationResult, MCPServer, Resolve9from mcp.types import ElicitResult10from pydantic import BaseModel, Field1112server = MCPServer("shop-returns", version="0.5.0")13Reason = Literal["damaged in transit", "wrong item sent", "missing part", "arrived late", "changed mind"] # the refund policy's five reasons141516class Inspection(BaseModel): # the form: a flat object with primitive fields only17 reason: Reason = Field(description="The refund policy's reason that fits what you found")18 restock: bool = Field(description="The item can go back on sale")19 note: str | None = Field(default=None, max_length=200, description="Anything the refund should say") # a default makes the field optional on the form202122def ask(order_id: str, sku: str) -> Elicit[Inspection]:23 return Elicit(f"You opened the return of {sku} from order {order_id}. What did you find?", Inspection)242526@server.tool(description="Record what a returned item was like when its parcel was opened. The user fills in a form.")27def record_return(order_id: str, sku: str, found: Annotated[ElicitationResult[Inspection], Resolve(ask)]) -> str: # the SDK runs ask(), sends the form as an input request, and fills found in on the retry28 if isinstance(found, AcceptedElicitation):29 return f"Recorded: {found.data.reason}, restock {found.data.restock}."30 return ("The user declined: don't record this return, and don't ask again." if found.action == "decline"31 else "The user closed the form without answering: ask again later.")323334SCRIPT = [ElicitResult(action="accept", content={"reason": "damaged in transit", "restock": False}),35 ElicitResult(action="decline"), ElicitResult(action="cancel")] # the scripted user's three answers36forms = [] # each form the user was shown373839async def scripted_user(context, params) -> ElicitResult:40 forms.append(params.requested_schema)41 return SCRIPT.pop(0)424344async def main() -> None:45 arguments = {"order_id": "O-1145", "sku": "KG-1043"}46 async with Client(server, elicitation_callback=scripted_user) as client:47 for action in ("accept", "decline", "cancel"):48 print(f"{action}:", (await client.call_tool("record_return", arguments)).content[0].text)49 print("form fields:", ", ".join(forms[0]["properties"]))50 print("required:", ", ".join(forms[0]["required"]))51 async with Client(server) as client: # no elicitation_callback, so no elicitation capability52 try:53 await client.call_tool("record_return", arguments)54 except MCPError as error:55 print("client without elicitation:", error.error.code)565758asyncio.run(main())
python elicit-a-refund-reason.pyaccept: Recorded: damaged in transit, restock False.
decline: The user declined: don't record this return, and don't ask again.
cancel: The user closed the form without answering: ask again later.
form fields: reason, restock, note
required: reason, restock
client without elicitation: -32021
The pydantic model gives note a default, so it's the only optional field. The client received the fields reason, restock, note, and only reason, restock are required.
Each string tells the model what to do next. Accept gave "Recorded: damaged in transit, restock False." Decline gave "The user declined: don't record this return, and don't ask again." Cancel gave "The user closed the form without answering: ask again later." A decline stands, and a cancel leaves the question open.
A client without a callback declares no elicitation capability, so the SDK refuses its call with JSON-RPC error -32021, Missing Required Client Capability, before the tool runs (mcp/server/mcpserver/resolve.py). The shop's issue_refund makes the same check by hand.
Working rule: Use form mode for answers only the person at the host can give, and keep each form to the few fields the tool acts on, with enums wherever the answer is one of a known set. Declare forms with a resolver and a pydantic model, and take ElicitationResult when decline and cancel should lead different ways. Build the input request by hand only when you need to control the state yourself.
將敏感步驟交給 URL 處理
表單的回答會經過用戶端,也可能出現在模型面前。伺服器不得(MUST NOT)將表單模式用於密碼、API 金鑰、存取權杖或付款憑證,而且必須(MUST)對這些資料使用 URL 模式(elicitation)。URL 模式會傳送一則訊息和一個 URL。用戶端不得(MUST NOT)預先擷取該 URL 或其中繼資料,不得(MUST NOT)在未取得使用者明確同意時開啟它,而且必須(MUST)顯示完整的 URL。該頁面的開啟方式讓用戶端與模型都看不到它。伺服器不會把個人資料和憑證放進 URL,也絕不傳送能自行讓使用者登入的 URL,並且必須(MUST)確保完成流程的使用者就是發起流程的那一位。
URL 模式並不是用戶端取得 MCP 伺服器授權的方式;那部分由從資源找出授權伺服器說明。URL 模式服務的是伺服器自身的需求,例如第三方服務或付款。在 URL 模式中,accept 只表示使用者已同意進行這項互動,並不表示互動已經完成(elicitation)。所固定的修訂版移除了 elicitationId 欄位和 notifications/elicitation/complete 通知。變更記錄對於需要在多次重試之間比對同一流程的伺服器,建議的做法是把自己的識別碼編碼在 requestState 中(changelog)。
付款發生在核准釋出之後。pay_refund 會把已釋出的退款(狀態為 requested 的退款)退回訂單所用的信用卡,而付款服務商只會在主管本人的帳戶下付款,且須在服務商的頁面登入。這個工具會為流程產生一個隨機 ID,放入 requestState,並把主管導向 https://pay.fernhill.example/connect/ 加上該 ID 的位址,其網域是永遠不會解析的保留網域。記憶體中的一個集合代替服務商對已完成流程的紀錄,範例在第三次呼叫之前把這個流程加入其中。
1"""pay_refund sends the support lead to the payment provider's page to connect an account, through URL mode, so the2sign-in stays out of the client. The point rests on the after-accept line, which still asks, and the after-sign-in3line, which completes only once the provider has recorded the flow as finished."""4import asyncio5import secrets67from mcp import Client8from mcp.server.mcpserver import Context, MCPServer9from mcp.types import ElicitRequest, ElicitRequestURLParams, ElicitResult, InputRequiredResult1011from lib import confirmations1213server = MCPServer("shop-payments", version="0.5.0")14finished: set[str] = set() # flows the payment provider reports finished; it would tell the server, not the client151617@server.tool(description="Pay out a released refund through the shop's payment provider, by its refund_id.")18def pay_refund(refund_id: str, ctx: Context) -> str | InputRequiredResult:19 flow = ctx.request_state or secrets.token_urlsafe(16) # the server's own ID for this flow, carried in requestState; 16 random bytes, so it can't be guessed20 if flow in finished:21 return f"Paid {refund_id} through the payment provider"22 answer = (ctx.input_responses or {}).get("connect")23 if answer is not None and answer.action != "accept":24 return f"Not paid: the user didn't connect a payment account. {refund_id} stays released, unpaid."25 confirmations.require_elicitation(ctx, "url")26 ask = ElicitRequestURLParams(url=f"https://pay.fernhill.example/connect/{flow}",27 message="To pay refunds, connect your payment provider account on its own page.")28 return InputRequiredResult(input_requests={"connect": ElicitRequest(params=ask)}, request_state=flow)293031async def main() -> None:32 async with Client(server, elicitation_callback=confirmations.say_yes) as client: # declares form and url33 def call(state=None, answers=None):34 return client.session.call_tool("pay_refund", {"refund_id": "R-0111"}, input_responses=answers,35 request_state=state, allow_input_required=True)36 first = await call()37 request = first.input_requests["connect"].params38 print("first call:", first.result_type, request.mode)39 print("url:", request.url.rsplit("/", 1)[0] + "/…") # cut before the last slash, so the flow's ID isn't printed40 accepted = {"connect": ElicitResult(action="accept")} # the scripted user agrees to open the page41 second = await call(first.request_state, accepted)42 print("after accept:", second.result_type, second.input_requests["connect"].params.mode)43 finished.add(request.url.rsplit("/", 1)[1]) # the flow's ID is what follows the last slash; the provider records it when the lead signs in44 third = await call(second.request_state, accepted)45 print("after sign-in:", third.result_type, third.content[0].text)4647asyncio.run(main())
python elicit-by-url.pyfirst call: input_required url
url: https://pay.fernhill.example/connect/…
after accept: input_required url
after sign-in: complete Paid R-0111 through the payment provider
第一次呼叫回傳 input_required url,URL 為 https://pay.fernhill.example/connect/…,在隨機 ID 之前截斷。在模擬的使用者接受之後,重試仍然回傳 input_required url,因為接受只代表主管同意開啟該頁面。待服務商記錄了登入之後,下一次重試便得到 complete Paid R-0111 through the payment provider。
此範例省略了檢查登入者是否就是被詢問的那個人的步驟。該檢查需要來自以 PKCE 取得權杖的呼叫者身分。
**實用原則:**任何機密資料,以及任何讓人登入另一項服務的步驟,都要透過 URL 模式處理,絕不經由表單。把流程自己的 ID 放進 requestState,將 accept 視為「使用者已前往該頁面」,並且在每次重試時依據伺服器自己的紀錄判斷流程是否已完成。檢查完成流程的人就是發起流程的人。
確保往返狀態無法遭竄改
以答案繼續呼叫中已確認的退款,取決於用戶端是否送回它所收到的 requestState,而沒有任何規定要求用戶端必須誠實。規格將 requestState 視為受攻擊者控制的輸入,伺服器也必須如此看待。當狀態會影響授權、資源存取或商業邏輯時,伺服器必須保護其完整性(例如使用 HMAC 或 AEAD),並拒絕未通過檢查的狀態。為了縮小重放攻擊的範圍,伺服器還應該將狀態綁定到已驗證的使用者、設定較短的有效期限,並將它與其來源請求綁在一起。這些作法都無法使狀態成為單次使用。若某個狀態必須至多只能使用一次,就必須在伺服器端強制執行這項不變條件(Multi Round-Trip Requests)。
SDK 的封緘(seal)涵蓋了第一部分,並且盡可能少向用戶端透露資訊。無論是權杖被更動、已過期、屬於另一個請求或呼叫者,或是使用了未知的金鑰,用戶端得到的都是同一個 JSON-RPC 錯誤:-32602,「Invalid or expired requestState」。真正的原因只會寫入伺服器的日誌(mcp/server/request_state.py),因此用戶端無法從失敗的嘗試中得知任何資訊。不過,封緘不會記錄它已接受過的權杖,所以第二部分必須由伺服器負責。
重放的確認等同於第二次放款,因此工具必須拒絕它。這次,用戶端以三種錯誤方式送出以答案繼續呼叫中的重試,接著送出正確的一次,再送出一次正確的:
- 將封緘後的
requestState更動一個字元; - 帶有劇本設定之主角所回答的「是」,但沒有狀態,彷彿是在回答伺服器從未提出的問題;
- 狀態正確,但使用另一筆報價的
quote_id; - 作為誠實的重試;
- 將同一個誠實的重試再送出第二次。
1"""Send issue_refund's retry wrongly, then rightly, then again: a changed requestState, an answer with no state, and a2state with other arguments; then an honest retry, and its replay. The seal refuses the changed and the mismatched state,3the tool asks again for the answer with no state, and its own once-only record refuses the replay."""4import asyncio56from mcp import Client, MCPError7from mcp.types import ElicitResult89from lib import confirmations, loopback, shop_api1011YES = ElicitResult(action="accept", content={"release": True}) # the scripted user's answer121314async def retry(client: Client, label: str, quote_id: str, state: str | None) -> None:15 try:16 result = await client.session.call_tool("issue_refund", {"quote_id": quote_id}, input_responses={"confirm": YES},17 request_state=state, allow_input_required=True)18 except MCPError as error:19 print(f"{label}:", error.error.code, error.error.message)20 return21 if result.result_type == "input_required":22 print(f"{label}: input_required, the server asks again")23 elif result.is_error:24 print(f"{label}: tool error,", result.content[0].text)25 else:26 print(f"{label}: refund", result.structured_content["refund_id"], result.structured_content["status"])2728async def main() -> None:29 with loopback.serve(shop_api.create_app()) as base_url:30 async with Client(confirmations.launch("refund-asks-to-confirm.py", base_url),31 elicitation_callback=confirmations.say_yes) as client:32 quotes = [(await client.call_tool("quote_refund", {"order_id": order})).structured_content["quote_id"]33 for order in ("O-2289", "O-1145")]34 first = await client.session.call_tool("issue_refund", {"quote_id": quotes[0]}, allow_input_required=True)35 state = first.request_state36 # swaps the character at index 20 for another, so the seal no longer matches the token37 changed = state[:20] + ("A" if state[20] != "A" else "B") + state[21:]38 await retry(client, "one character changed", quotes[0], changed)39 await retry(client, "answer without state", quotes[0], None)40 await retry(client, "state with other arguments", quotes[1], state)41 await retry(client, "honest retry", quotes[0], state)42 await retry(client, "same retry again", quotes[0], state)434445asyncio.run(main())
python tampered-round-trip-state.pyone character changed: -32602 Invalid or expired requestState
answer without state: input_required, the server asks again
state with other arguments: -32602 Invalid or expired requestState
honest retry: refund R-0111 requested
same retry again: tool error, Error executing tool issue_refund: Refund R-0111 was already confirmed. Don't send the same answer again.
被更動的權杖得到 -32602 Invalid or expired requestState,被替換的引數也得到相同的結果:-32602 Invalid or expired requestState。SDK 為每種情況記錄不同的原因,字元被更動記為 seal,其他引數則記為 request binding,而用戶端兩者都看不到(mcp/server/request_state.py)。沒有狀態的答案得到 input_required, the server asks again。工具將對從未提出之問題的回答視為沒有回答,而規格指出,缺少答案的伺服器應該再次詢問,而不是回傳錯誤(Multi Round-Trip Requests)。
誠實的重試釋出了退款:refund R-0111 requested。同一個重試再次送出時通過了封緘,因為它沒有任何改變。伺服器自己的已回答狀態紀錄則拒絕了它,並回傳工具錯誤「tool error, Error executing tool issue_refund: Refund R-0111 was already confirmed. Don't send the same answer again.」。該紀錄是 confirmations.OnceOnly,也就是在伺服器記憶體中以鎖保護的一組狀態,工具會在要求商店的 API 釋出任何款項之前先檢查它。在它之後,API 對同一筆退款的第二次釋出會回應 409,因此即使伺服器遺失了紀錄,也不會付款兩次。
實用原則: 讓 SDK 封緘每一個 requestState,並且對涉及金錢、存取權或資料的狀態,絕不要關閉封緘。保持狀態精簡且不透明:放的是 ID,而不是整筆紀錄。對於任何必須只發生一次的步驟,請在伺服器上自行保存已回答狀態的紀錄,並在副作用發生之前檢查,而不是之後。
此部分尚未翻譯,因此以英文呈現。
Choose elicitation or a tool argument
Each question in this chapter could have been a tool argument instead: confirmed: true on issue_refund (Return an input request instead of a result), or reason on record_return (Ask for structured input with elicitation). A tool argument costs no extra round trip and no user interface, but the model fills it in. Elicitation costs a round trip and a person's attention, and only the host's user is meant to answer it. The question to ask, then, is who can know the value.
This is a rule of thumb, not a measurement. If the model can read the value from the conversation, make it an argument. If only the person at the host can give it, elicit it. If it is a secret, or a sign-in to another service, use URL mode.
| What the tool needs | In the shop | Use |
|---|---|---|
| A value in the ticket | the order ID a customer wrote | a tool argument |
| A decision the policy gives a person | releasing a refund above the limit | a form |
| A fact only the person present has | what a returned parcel held | a form |
| A secret or a sign-in | the lead's payment provider account | URL mode |
A confirmed argument on issue_refund would let the model confirm its own refund, a decision the refund policy keeps for a person. The order ID goes the other way. Asking the lead to retype an ID the customer already wrote adds a step and a chance for a typo, and the model can read the ID. When a value could come from either place, take the argument and let the tool check it, as chapter 3's tools check every ID's format.
Elicitation is the server asking the user through the host. It isn't the host's own consent, the step where the host asks the user before a tool with side effects runs, which Ask for consent before side effects builds. The shop's confirmation is the server's own check, and a careful host still asks before it calls issue_refund at all.
Working rule: Make a value a tool argument when the model can know it, and validate it in the tool. Elicit it when only the person can give it, or when the policy says a person must decide, and never accept that kind of value as an argument. Use URL mode for every secret. When you aren't sure, ask who would be at fault if the value were wrong.
正式環境中會出什麼問題
這個確認機制在一台 stdio 伺服器、一個用戶端,以及一位立即作答的腳本化主管之下運作良好。真實的主管需要時間,伺服器會重新啟動,用戶端也各不相同,因此這個模式會以幾種可辨認的方式失效。
以已失效的金鑰封存的狀態。MCPServer 的預設金鑰在程序啟動時產生,只存在於其記憶體中(mcp/server/request_state.py)。如果伺服器在提問與回答之間重新啟動,或重試的請求送到另一個副本,伺服器就無法開啟該狀態,主管的回答會以 -32602 失敗。需要留意的徵兆是「Invalid or expired requestState」在部署之後增加,或隨副本數量增加。請透過 RequestStateSecurity(keys=[...]) 讓每個副本使用相同的金鑰。confirmations.state_security() 是來自 改為回傳輸入請求而非結果 的封存政策,它會從 SHOP_REQUEST_STATE_KEY 建立這些金鑰。第一把金鑰負責封存,所有金鑰都能開啟,因此金鑰可以輪替而不會丟失回答(在沒有黏性工作階段的情況下執行多個副本)。
**主管的回應慢於狀態的存活時間。**SDK 的狀態預設每一輪維持 600 秒。主管讀完問題、接了一通電話,十五分鐘後才回答,同樣會得到 -32602,而伺服器的紀錄會寫著 expired。請將 ttl= 設為一個人合理所需的最長時間,並讓主機把這個錯誤轉為一次全新的呼叫,重新提問。
**只有單一程序看得到的紀錄。**重試需要第一輪留下的兩筆紀錄,而兩者都存放在單一伺服器的記憶體中:第 3 章的報價儲存區(重試透過它找到退款),以及 confirmations.OnceOnly,也就是 確保往返狀態無法被竄改 中已回答狀態的紀錄。在兩個副本之後,送到另一個副本的重試會以「There is no quote」失敗,而送到該副本的重播回答則會通過一次性檢查。請像 在沒有黏性工作階段的情況下執行多個副本 那樣,把兩筆紀錄都放在共用儲存空間中,並在其後保留商店 API 本身的 409 檢查。
**來自非主管者的回答。**工具會在主機送出任何 accept 時放行退款,而主機可能以程式碼自動回答。在 stdio 上,伺服器能檢查的僅止於此。在 HTTP 上,請將每個問題綁定到已驗證的呼叫者,並檢查呼叫者的權杖帶有 refunds:write,這是只有客服主管才擁有的範圍(依權杖允許的內容限定工具範圍)。
**無法提問的用戶端。**如果主機的用戶端沒有 elicitation 回呼,就不會宣告 elicitation 能力(mcp/client/session.py),呼叫會以 -32021,Missing Required Client Capability 失敗。解析器的檢查在工具之前執行;像 issue_refund 那種手工建立的檢查則在工具內部執行,也就是在第 3 章的工具已保留退款之後(confirmations.require_elicitation)。徵兆是某一個主機出現該錯誤,而其他主機沒有。服務真人的主機應宣告 elicitation 並顯示問題(為使用者回應輸入請求)。若伺服器的工具有安全的預設行為,例如讓退款維持保留狀態,則可以回傳該預設值作為結果,而不是失敗。
**會變動的 URL 模式流程。**規格將 URL 模式標示為設計在未來修訂中可能變動的功能(elicitation),而所鎖定的修訂版本已經移除了其中兩個部分。請將 URL 模式的程式碼集中在一處,並對照每個修訂版本的變更紀錄加以檢查。
**永不結束的迴圈。**使用者放棄的 URL 模式流程在每次重試時都會再次提問,而 SDK 的用戶端在 10 輪之後會以 InputRequiredRoundsExceededError 停止。請在 requestState 中計算每個流程的輪數,並在數輪之後回傳一個說明該步驟尚未完成的結果。
**同一伺服器上的舊用戶端。**回傳給以 2025 握手連線之用戶端的 InputRequiredResult,到達時會是 -32603,「Handler returned an invalid result」。SDK 會依 2025 年的 CallToolResult 檢查結果,而它要求有 content(mcp/server/runner.py;多輪往返請求)。同時服務兩者的伺服器要檢查 ctx.protocol_version,或使用解析器,由它為每個連線挑選正確的路徑(mcp/server/mcpserver/resolve.py)。透過過渡期同時服務新舊用戶端 涵蓋這兩種做法。
**無人調查的拒絕。**每個被拒絕的狀態都給用戶端相同的訊息,因此唯一的原因紀錄是伺服器的日誌,位於記錄器 mcp.server.request_state 之下。請輸出該日誌,並針對 seal 與 request binding 設定警示,它們表示有人更動了權杖,並與 expired 分開處理,後者通常表示對方是個動作較慢的人。
**實用原則:**在伺服器上線到正式環境之前,請讓會提問的伺服器的各個副本共用一把可輪替的金鑰,將狀態的存活時間設為人所需的時間,並把報價儲存區與每一筆一次性紀錄移到共用儲存空間。凡傳輸層有呼叫者之處,都要將每個問題綁定到呼叫者。接著依記錄的原因觀察 -32602,依主機觀察 -32021,並觀察每次呼叫的輪數。
本章的決定
- 由商店的 API 決定哪些退款需要確認。
issue_refund會先呼叫第 3 章的版本,只有在 API 將該筆退款保留時才發出詢問,因此政策的上限只存在於一處。 - **先保留退款,再提出問題,**因此無人回答的問題會讓退款維持保留狀態,如同第 3 章。
- **確認是手工建構的輸入請求:**在鍵
confirm下的一個表單模式 elicitation,並以退款的 ID 作為requestState,重試時會拿它與所找到的退款核對。退回包裹的表單則使用 resolver,因為 SDK 的能力檢查與繪製能省下程式碼。 - **SDK 會封緘每一個
requestState,**所用的金鑰可由部署透過confirmations.state_security()或SHOP_REQUEST_STATE_KEY注入,否則使用與行程同壽命的金鑰。 - **回答在伺服器端只能使用一次,**透過
confirmations.OnceOnly在放行前檢查,後方再以 API 的 409 把關。 - **缺少伺服器狀態的回答,或帶有另一筆退款狀態的回答,視同從未提出的問題,**工具會再次詢問。
- **伺服器不會保持任何呼叫開啟,但會保存兩份紀錄:**第 3 章的報價儲存區與一次性紀錄,兩者在此都放在記憶體中,並於第 6 章跨複本共用。
- **在 stdio 上,由主機端的使用者負責確認。**透過 HTTP 時,問題會綁定到已驗證的呼叫者,並由
refunds:write(只有客服主管才持有的範圍)管控該工具(依權杖允許的內容限定工具範圍)。 - **拒絕與取消的走向不同:**拒絕即為定案,取消則讓問題保持開啟。
- **機密與登入透過 URL 模式處理,**並將流程的 ID 放在
requestState中,而accept絕不算作完成。 - API 新增了兩個端點,
POST /refunds/{refund_id}/confirm與POST /refunds/{refund_id}/cancel,它們只作用於被保留的退款,否則回應 409。 - **模型可讀取的值仍作為工具引數,**只有人才能提供的值則透過 elicitation 取得。
本章,於本版次中
版次 2026.11.14範例於 2026年11 月 19 通過測試本章 6 個範例 個範例中有 6 個通過
譯自英文書,版次 2026.11.14。