Ask the user in the middle of a call

阅读约需 99分钟 分钟,9节中含6个示例。

版次 2026.11.14 示例于 2026年11月19日 通过 70个示例中有70个通过 变化内容

AI 翻译。由人工以英文核验。 我们如何制作图书

译自英文版图书,版次 2026.11.14。 阅读原文

这部分尚未翻译,因此以英文显示。

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

最近一次修改见于版次 2026.11.14

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.

refund-needs-confirmation.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · jsonschema 4.26.0 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""The 2025 way to confirm a refund, which fails at revision 2026-07-28: issue_refund calls ctx.elicit() and waits,but the protocol gives the server no channel back to the client. The printed error code and the count of questionsthe user saw show the failure, before anyone is asked."""import asyncioimport sysfrom mcp import Client, MCPErrorfrom mcp.server.mcpserver import Contextfrom mcp.types import ElicitResultfrom pydantic import BaseModelfrom lib import confirmations, loopback, shop_api, shop_toolsserver, held = confirmations.shop_server()     # chapter 3's other tools; held is chapter 3's issue_refundasked = []                                     # every question that reached the userclass Release(BaseModel):    release: bool@server.tool(title="Issue a refund", description=shop_tools.DESCRIPTIONS["issue_refund"], annotations=held.annotations)async def issue_refund(quote_id: confirmations.QuoteId, ctx: Context) -> shop_tools.Refund:    refund = held.fn(quote_id)    if refund.status == "needs_confirmation":   # ask, and hold the call open until the answer comes back        answer = await ctx.elicit(f"Refund {refund.amount} on order {refund.order_id}?", Release)        if answer.action == "accept" and answer.data.release:            return confirmations.release(refund)    return refundasync def say_yes(context, params) -> ElicitResult:   # a scripted user, who would release the refund    asked.append(params.message)    return ElicitResult(action="accept", content={"release": True})async def main() -> None:    with loopback.serve(shop_api.create_app()) as base_url:        async with Client(confirmations.launch(__file__, base_url), elicitation_callback=say_yes) as client:   # starts this file with --serve            print("protocol revision:", client.protocol_version)            quote = (await client.call_tool("quote_refund", {"order_id": "O-2289"})).structured_content            try:                await client.call_tool("issue_refund", {"quote_id": quote["quote_id"]})            except MCPError as error:                print("error code:", error.error.code)                print("error message:", error.error.message)            print("questions the user saw:", len(asked))server.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.py
protocol 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

最近一次修改见于版次 2026.11.11

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.

refund-asks-to-confirm.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · jsonschema 4.26.0 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""issue_refund answers a held refund with an input request instead of a result, which asks a person to confirm it.The prose's points rest on the result type line, the one input request under confirm with its message, and theassert, which fails the run if the SDK doesn't seal the request state."""import asyncioimport sysfrom mcp import Clientfrom mcp.server.mcpserver import Contextfrom mcp.server.mcpserver.exceptions import ToolErrorfrom mcp.types import ElicitRequest, ElicitRequestFormParams, InputRequiredResultfrom lib import confirmations, loopback, shop_api, shop_toolsserver, held = confirmations.shop_server()     # chapter 3's other tools; held is chapter 3's issue_refundanswered = confirmations.OnceOnly()            # the round-trip states already answered, so a replayed answer fails@server.tool(title="Issue a refund", description=shop_tools.DESCRIPTIONS["issue_refund"], annotations=held.annotations)def issue_refund(quote_id: confirmations.QuoteId, ctx: Context) -> shop_tools.Refund | InputRequiredResult:    refund = held.fn(quote_id)                 # the same quote_id always gives the same refund    if refund.status != "needs_confirmation":        return refund    answer = (ctx.input_responses or {}).get("confirm")   # the answer comes back under the key the tool asked with    if answer is None or ctx.request_state != refund.refund_id:   # first round, or a question never asked        confirmations.require_elicitation(ctx, "form")     # ask only what the client declared it can show        ask = ElicitRequestFormParams(requested_schema=confirmations.RELEASE_FORM, message=f"Refund {refund.amount} on "                                      f"order {refund.order_id}? It is above the policy limit, so a lead must confirm it.")        return InputRequiredResult(input_requests={"confirm": ElicitRequest(params=ask)},                                   request_state=refund.refund_id)   # the refund's ID rides in the state the SDK seals    if answer.action != "accept" or not (answer.content or {}).get("release"):        raise ToolError(f"Nobody confirmed refund {refund.refund_id}, so the shop's API still holds it.")    if not answered.claim(ctx.request_state):              # sealing can't stop a replay; this record does        raise ToolError(f"Refund {refund.refund_id} was already confirmed. Don't send the same answer again.")    return confirmations.release(refund)async def main() -> None:    with loopback.serve(shop_api.create_app()) as base_url:        async with Client(confirmations.launch(__file__, base_url),   # starts this file with --serve over stdio                          elicitation_callback=confirmations.say_yes) as client:      # declares elicitation            quote = (await client.call_tool("quote_refund", {"order_id": "O-2289"})).structured_content            result = await client.session.call_tool("issue_refund", {"quote_id": quote["quote_id"]},                                                     allow_input_required=True)   # return the input request, not an answer to it            print("result type:", result.result_type)            for key, request in result.input_requests.items():                print(f"input request {key}:", request.method, request.params.mode)                print("message:", request.params.message)            # the SDK's sealed-token prefix: a request state that starts with it was sealed on its way out            assert result.request_state.startswith("v1.")server.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.py
result 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

最近一次修改见于版次 2026.11.11

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.

refund-confirmed-round-trip.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · jsonschema 4.26.0 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""Finish the refund that refund-asks-to-confirm asks about, by retrying with the answer and the echoed requestState:first by hand, so both requests show on the wire, then with Client.call_tool, which runs the loop itself. The pointrests on the trace lines, which show two requests each time, with different IDs, and only the retry sending the answer."""import asyncioimport pathlibfrom mcp import Clientfrom mcp.types import ElicitResultfrom lib import confirmations, loopback, shop_api, wireLOG = pathlib.Path("refund-confirmed-round-trip.jsonl")             # every line the relay copiesYES = ElicitResult(action="accept", content={"release": True})    # the scripted user's answerasync def say_yes(context, params) -> ElicitResult:    print("user was asked:", params.message)    return YESasync def main() -> None:    LOG.unlink(missing_ok=True)    with loopback.serve(shop_api.create_app()) as base_url:        server = wire.relay(confirmations.launch("refund-asks-to-confirm.py", base_url), log=str(LOG))   # the relay copies each message to LOG        async with Client(server, elicitation_callback=say_yes) as client:            quote = (await client.call_tool("quote_refund", {"order_id": "O-2289"})).structured_content            arguments = {"quote_id": quote["quote_id"]}            first = await client.session.call_tool("issue_refund", arguments, allow_input_required=True)   # the input request, not a result            # the retry repeats the arguments, adds the answer under the request's key, and echoes the state back            done = await client.session.call_tool("issue_refund", arguments, input_responses={"confirm": YES},                                                  request_state=first.request_state, allow_input_required=True)            print("by hand:", done.structured_content["refund_id"], done.structured_content["status"])            quote = (await client.call_tool("quote_refund", {"order_id": "O-1145"})).structured_content            done = await client.call_tool("issue_refund", {"quote_id": quote["quote_id"]})            print("by Client.call_tool:", done.structured_content["refund_id"], done.structured_content["status"])    calls, results = [], {}                     # the issue_refund requests, in order, and each one's resultType    for direction, message in wire.read_trace(str(LOG)):        if message.get("method") == "tools/call" and message["params"]["name"] == "issue_refund":            calls.append(message)        elif direction == "in" and "result" in message:   # a server's response, matched to its request by JSON-RPC id            results[message["id"]] = message["result"]["resultType"]    for label, message in zip(["by hand, call", "by hand, retry", "Client.call_tool, call", "Client.call_tool, retry"],                              calls):        sent = " and ".join(key for key in ("inputResponses", "requestState") if key in message["params"])        print(f"{label}: id {message['id']}, sends {sent or 'arguments only'}, gets {results[message['id']]}")    LOG.unlink()asyncio.run(main())
输出python refund-confirmed-round-trip.py
by 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

最近一次修改见于版次 2026.11.14

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.

elicit-a-refund-reason.py Python 3.12.15 · mcp 2.3.0 · pydantic 2.14.3 通过
"""record_return asks the person who opened a returned parcel what they found, through a form that a resolver buildsand sends. The point rests on the three answer lines, accept, decline and cancel, and on the error a client withoutan elicitation callback gets, which names a missing capability rather than a tool failure."""import asynciofrom typing import Annotated, Literalfrom mcp import Client, MCPErrorfrom mcp.server.mcpserver import AcceptedElicitation, Elicit, ElicitationResult, MCPServer, Resolvefrom mcp.types import ElicitResultfrom pydantic import BaseModel, Fieldserver = MCPServer("shop-returns", version="0.5.0")Reason = Literal["damaged in transit", "wrong item sent", "missing part", "arrived late", "changed mind"]   # the refund policy's five reasonsclass Inspection(BaseModel):          # the form: a flat object with primitive fields only    reason: Reason = Field(description="The refund policy's reason that fits what you found")    restock: bool = Field(description="The item can go back on sale")    note: str | None = Field(default=None, max_length=200, description="Anything the refund should say")   # a default makes the field optional on the formdef ask(order_id: str, sku: str) -> Elicit[Inspection]:    return Elicit(f"You opened the return of {sku} from order {order_id}. What did you find?", Inspection)@server.tool(description="Record what a returned item was like when its parcel was opened. The user fills in a form.")def 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 retry    if isinstance(found, AcceptedElicitation):        return f"Recorded: {found.data.reason}, restock {found.data.restock}."    return ("The user declined: don't record this return, and don't ask again." if found.action == "decline"            else "The user closed the form without answering: ask again later.")SCRIPT = [ElicitResult(action="accept", content={"reason": "damaged in transit", "restock": False}),          ElicitResult(action="decline"), ElicitResult(action="cancel")]       # the scripted user's three answersforms = []                                                                     # each form the user was shownasync def scripted_user(context, params) -> ElicitResult:    forms.append(params.requested_schema)    return SCRIPT.pop(0)async def main() -> None:    arguments = {"order_id": "O-1145", "sku": "KG-1043"}    async with Client(server, elicitation_callback=scripted_user) as client:        for action in ("accept", "decline", "cancel"):            print(f"{action}:", (await client.call_tool("record_return", arguments)).content[0].text)    print("form fields:", ", ".join(forms[0]["properties"]))    print("required:", ", ".join(forms[0]["required"]))    async with Client(server) as client:            # no elicitation_callback, so no elicitation capability        try:            await client.call_tool("record_return", arguments)        except MCPError as error:            print("client without elicitation:", error.error.code)asyncio.run(main())
输出python elicit-a-refund-reason.py
accept: 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

最近一次修改见于版次 2026.11.11

表单的答案会经过客户端,还可能出现在模型面前。服务器不得(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 的地址,该地址位于一个永远不会解析的保留域名上。一个内存中的集合代替提供方对已完成流程的记录,示例在第三次调用之前把这个流程加入其中。

elicit-by-url.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · jsonschema 4.26.0 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""pay_refund sends the support lead to the payment provider's page to connect an account, through URL mode, so thesign-in stays out of the client. The point rests on the after-accept line, which still asks, and the after-sign-inline, which completes only once the provider has recorded the flow as finished."""import asyncioimport secretsfrom mcp import Clientfrom mcp.server.mcpserver import Context, MCPServerfrom mcp.types import ElicitRequest, ElicitRequestURLParams, ElicitResult, InputRequiredResultfrom lib import confirmationsserver = MCPServer("shop-payments", version="0.5.0")finished: set[str] = set()     # flows the payment provider reports finished; it would tell the server, not the client@server.tool(description="Pay out a released refund through the shop's payment provider, by its refund_id.")def pay_refund(refund_id: str, ctx: Context) -> str | InputRequiredResult:    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 guessed    if flow in finished:        return f"Paid {refund_id} through the payment provider"    answer = (ctx.input_responses or {}).get("connect")    if answer is not None and answer.action != "accept":        return f"Not paid: the user didn't connect a payment account. {refund_id} stays released, unpaid."    confirmations.require_elicitation(ctx, "url")    ask = ElicitRequestURLParams(url=f"https://pay.fernhill.example/connect/{flow}",                                 message="To pay refunds, connect your payment provider account on its own page.")    return InputRequiredResult(input_requests={"connect": ElicitRequest(params=ask)}, request_state=flow)async def main() -> None:    async with Client(server, elicitation_callback=confirmations.say_yes) as client:   # declares form and url        def call(state=None, answers=None):            return client.session.call_tool("pay_refund", {"refund_id": "R-0111"}, input_responses=answers,                                            request_state=state, allow_input_required=True)        first = await call()        request = first.input_requests["connect"].params        print("first call:", first.result_type, request.mode)        print("url:", request.url.rsplit("/", 1)[0] + "/…")   # cut before the last slash, so the flow's ID isn't printed        accepted = {"connect": ElicitResult(action="accept")}     # the scripted user agrees to open the page        second = await call(first.request_state, accepted)        print("after accept:", second.result_type, second.input_requests["connect"].params.mode)        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 in        third = await call(second.request_state, accepted)        print("after sign-in:", third.result_type, third.content[0].text)asyncio.run(main())
输出python elicit-by-url.py
first 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 视为“用户去了那个页面”,并在每次重试时根据服务器自己的记录判断流程是否已经完成。检查完成流程的人就是发起流程的人。

确保往返状态不可篡改

最近一次修改见于版次 2026.11.11

用答案恢复调用中已确认的退款,依赖于客户端把收到的 requestState 原样返回,而没有任何规定要求客户端必须诚实。规范将 requestState 视为攻击者可控的输入,服务器也必须如此看待。当状态会影响授权、资源访问或业务逻辑时,服务器必须保护其完整性(例如使用 HMAC 或 AEAD),并拒绝未通过校验的状态。为缩小重放的范围,服务器还应当把状态绑定到已认证的用户,为其设置较短的有效期,并将其与产生它的请求关联起来。这些措施都不能使状态成为一次性的。如果某个状态必须至多使用一次,服务器必须在服务端强制保证这一约束(Multi Round-Trip Requests)。

SDK 的封印(seal)负责第一部分,并且尽可能少地向客户端透露信息。无论令牌被改动、已过期、属于另一个请求或调用方,还是使用了未知的密钥,客户端得到的都是同一个 JSON-RPC 错误:-32602,“Invalid or expired requestState”。真正的原因只会写入服务器的日志(mcp/server/request_state.py),因此客户端无法从失败的尝试中获知任何信息。不过,封印并不记录它已经接受过的令牌,所以第二部分要由服务器来完成。

重放的确认意味着第二次放款,因此工具必须拒绝这种重放。这一次,客户端以三种错误方式发送用答案恢复调用中的重试,然后正确发送一次,再正确发送一次:

  1. 封印后的 requestState 被改动了一个字符;
  2. 带着脚本化主角的“是”,但没有状态,就像在回答服务器从未提出的问题;
  3. 状态正确,但使用了另一份报价的 quote_id;
  4. 作为一次诚实的重试;
  5. 作为同一次诚实的重试,再发送一次。
tampered-round-trip-state.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · jsonschema 4.26.0 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 通过
"""Send issue_refund's retry wrongly, then rightly, then again: a changed requestState, an answer with no state, and astate with other arguments; then an honest retry, and its replay. The seal refuses the changed and the mismatched state,the tool asks again for the answer with no state, and its own once-only record refuses the replay."""import asynciofrom mcp import Client, MCPErrorfrom mcp.types import ElicitResultfrom lib import confirmations, loopback, shop_apiYES = ElicitResult(action="accept", content={"release": True})     # the scripted user's answerasync def retry(client: Client, label: str, quote_id: str, state: str | None) -> None:    try:        result = await client.session.call_tool("issue_refund", {"quote_id": quote_id}, input_responses={"confirm": YES},                                                request_state=state, allow_input_required=True)    except MCPError as error:        print(f"{label}:", error.error.code, error.error.message)        return    if result.result_type == "input_required":        print(f"{label}: input_required, the server asks again")    elif result.is_error:        print(f"{label}: tool error,", result.content[0].text)    else:        print(f"{label}: refund", result.structured_content["refund_id"], result.structured_content["status"])async def main() -> None:    with loopback.serve(shop_api.create_app()) as base_url:        async with Client(confirmations.launch("refund-asks-to-confirm.py", base_url),                          elicitation_callback=confirmations.say_yes) as client:            quotes = [(await client.call_tool("quote_refund", {"order_id": order})).structured_content["quote_id"]                      for order in ("O-2289", "O-1145")]            first = await client.session.call_tool("issue_refund", {"quote_id": quotes[0]}, allow_input_required=True)            state = first.request_state            # swaps the character at index 20 for another, so the seal no longer matches the token            changed = state[:20] + ("A" if state[20] != "A" else "B") + state[21:]            await retry(client, "one character changed", quotes[0], changed)            await retry(client, "answer without state", quotes[0], None)            await retry(client, "state with other arguments", quotes[1], state)            await retry(client, "honest retry", quotes[0], state)            await retry(client, "same retry again", quotes[0], state)asyncio.run(main())
输出python tampered-round-trip-state.py
one 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

最近一次修改见于版次 2026.11.14

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.

生产环境中会出什么问题

最近一次修改见于版次 2026.11.11

这种确认方式在以下条件下可以正常工作:只有一个 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,这是只有客服主管才拥有的作用域(按令牌允许的范围限定工具)。

**无法提问的客户端。**如果宿主的客户端没有征询回调,它就不会声明征询能力(mcp/client/session.py),调用会以 -32021(Missing Required Client Capability)失败。解析器的检查在工具之前运行;而像 issue_refund 那样手工编写的检查在工具内部运行,此时第 3 章的工具已经暂扣了退款(confirmations.require_elicitation)。其迹象是只有某个宿主出现该错误,而其他宿主没有。面向用户的宿主应当声明征询能力并展示这些问题(为用户回答输入请求)。如果服务器的工具有安全的默认做法,例如让退款保持暂扣,它可以把这个默认结果作为返回值,而不是失败。

**会变化的 URL 模式流程。**规范把 URL 模式标为设计在未来修订中可能改变的特性(征询),而所固定的修订版已经移除了其中两个部分。请把 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,并监控每次调用的轮数。

本章做出的决定

最近一次修改见于版次 2026.11.11
  • 由商店的 API 决定哪些退款需要确认。issue_refund 先调用第 3 章的版本,只有在 API 将退款置于保留状态时才发出询问,因此策略的限额只存在于一处。
  • **先保留退款,再提出问题,**所以无人回答的问题会让退款一直处于保留状态,与第 3 章相同。
  • **确认是一个手工构建的输入请求:**一次表单模式的征询,键为 confirm,以退款的 ID 作为 requestState,重试时据此与所找到的退款核对。退回包裹的表单则使用解析器,因为 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。
  • **模型可以读取的值仍作为工具参数,**只有人才能给出的值则通过征询获得。

本章,在本版次中

版次 2026.11.14示例于 2026年11月19日 通过本章 6个示例 个示例中有 6 个通过

译自英文版图书,版次 2026.11.14。

引用本节

格式

每种格式均引用英文原书,本译本以其为准。

每种格式都会注明该版次。其链接会打开当前版次,节标题处会说明该节文本最后一次修改的时间。访问日期和检索日期即为您打开此页的当天。

本页内容

第 5 章,共 12 章: Ask the user in the middle of a call

  1. See why a stateless server can't wait for an answer
  2. Return an input request instead of a result
  3. Resume the call with the answer
  4. Ask for structured input with elicitation
  5. 将敏感步骤交给 URL
  6. 确保往返状态不可篡改
  7. Choose elicitation or a tool argument
  8. 生产环境中会出什么问题
  9. 本章做出的决定

返回顶部全部章节