呼び出しの途中でユーザーに尋ねる
読了まで約69 分分、9 節 節の 6 例 例。
この章を読み終えると、ショップの返金ツールを呼び出しの途中で止め、ホストにいる人に返金の確認を求め、その答えを受けて処理を続けられるようになる。ここで用いるのは、待機中に呼び出しを開いたままにしないサーバー上の、Multi Round-Trip Request の内部で使う Model Context Protocol の elicitation である。この章の主張は、仕様のリビジョン 2026-07-28 と、Python SDK である mcp 2.3.0 について成り立つ。
ショップでは、返金がサポートチームのホスト向けにチケットとして届く。返金ポリシーは、150.00ユーロを超える返金については、発行前にサポートリーダーが確認することを求めている。ショップの API は、そのような返金をステータス needs_confirmation で保留にすることで、この上限を強制している。モデルが使えるツールを設計するでは、issue_refund ツールはこの保留をモデルに返してそこで止まる。そのため、モデルが正しく行った返金は、誰かが管理画面でそれを見つけるまで待たされることになる。
返金を確認できる人は、すでにホストで会話を読んでいる。ツールには、呼び出しの途中でその人に一つの質問を投げ、その答えを受けて処理を続ける手段が必要である。Model Context Protocol(MCP)には、この手段を指す elicitation という名前がある。これは、サーバーが送り、クライアントがユーザーに表示する、構造化された質問である。固定されたリビジョンでは、この質問は Multi Round-Trip Request の中を通る。これは、一つの呼び出しが結果ではなく質問で終わりうるパターンである。サーバーは呼び出しに対して結果の代わりに input request を返し、クライアントは答えを添えてもう一度呼び出す。
この章のサーバーの各例は、前の章の例と同じように自力で実行される。引数なしで実行すると、そのファイルはクライアントを起動し、そのクライアントが同じファイルを stdio 経由で --serve を付けて起動する。ショップの API は、それらと並んでループバック上で動作する。
ステートレスなサーバーが回答を待てない理由を確認する
固定されたリビジョンより前は、ユーザーの入力を必要とするサーバーは、自らクライアントへのリクエストである elicitation/create を送り、ツール呼び出しを開いたままその返答を待っていた。固定されたリビジョンはこのパターンを廃止した。仕様は、サーバーがクライアントへ送るリクエストは、elicitation/create も含めて、Multi Round-Trip Request パターンで送らなければならない (MUST) と定めている。仕様は従来のパターンを、もはやサポートされない破壊的変更と呼んでいる (Multi Round-Trip Requests)。エリシテーションはこの章で使うリクエストの一つであり、非推奨ではない。他の二つ、sampling/createMessage と roots/list は非推奨であり、その置き換えは サンプリング、ルート、ログを置き換える に示されている。置き換えとは、モデルプロバイダーの API を直接呼び出すこと、およびツールのパラメーター、リソース URI、サーバー設定である (deprecated features)。
理由はステートレス性にある。固定されたリビジョンにはハンドシェイクもセッションもなく、各リクエストは自身のバージョンとケイパビリティを _meta に載せて運ぶ (すべてのリクエストでバージョンとケイパビリティを運ぶ)。クライアントからの返答を待つリクエストは、人間が答えるまでの間、一つのサーバープロセスを一つの開いた接続に縛りつける。仕様の狙いは、サーバーインスタンス間で共有するストレージ層やステートフルなロードバランシングなしに、入力を求められるサーバーを実現することである (Multi Round-Trip Requests)。この変更の元になった提案 SEP-2322 は、これにより Streamable HTTP が、多くの環境で問題を起こす長寿命のストリームにあまり依存しなくなると述べている (SEP-2322)。
Python SDK は今も従来の呼び出しを提供している。ctx.elicit() は elicitation/create をサーバーからのリクエストとして送る。固定されたリビジョンの接続では、プロトコルがそこでのサーバー起点のリクエストを禁じているため、Invalid Request エラーである NoBackChannelError で失敗する (mcp/shared/transport_context.py、mcp/shared/exceptions.py)。
確認処理の最初の試みは、その方式で書かれている。このサーバーは第3章のツールを共有モジュール lib.confirmations から取り込む。このモジュールには、この章のサーバーに共通するもの、すなわちそれらのツール、往復の状態を保護する鍵、使用済みの回答の記録が入っている。サーバーの issue_refund は第3章のバージョンを呼び出し、それがショップの API へ返金を送信する。API が返金を保留すると、ツールは ctx.elicit() を呼んで待つ。クライアントにはエリシテーションのコールバックがあり、スクリプト化されたユーザーを演じる。このユーザーは、尋ねられれば返金を許可する。クライアントは、全額返金が上限を超える注文 O-2289 を指定して 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
呼び出しは JSON-RPC エラー -32600、すなわち Invalid Request で失敗し、メッセージは「Cannot send 'elicitation/create': this transport context has no back-channel for server-initiated requests.」だった。スクリプト化されたユーザーに尋ねられた質問は 0 件だった。返金を目にした者はいない。この失敗はツールの結果ではなくプロトコルエラーであるため、モデルもこれを見ていない (失敗をツールの結果として報告する)。返金は、第3章と同じくショップの API で保留されたままである。
失敗したのはツール自身のロジックではない。ツールは、固定されたリビジョンにないもの、すなわち呼び出しの途中でのサーバーからクライアントへのチャネルをプロトコルに要求した。ツール呼び出しの中で回答を待つコードは、どの SDK を使っていても同じ壁に突き当たる。
実践ルール: クライアントしか提供できないものを、ツール呼び出しの中で待ってはならない。固定されたリビジョンの接続では、ctx.elicit() や ctx.elicit_url() の呼び出しをすべてバグとして扱い、次の節で行うように、代わりに入力リクエストを返す。従来の呼び出しを残してよいのは、2025年版のクライアントにも応答しなければならないサーバーだけであり、それも ctx.protocol_version の確認の裏に限る (移行期間を通じて旧クライアントと新クライアントに対応する)。
この部分はまだ翻訳されていないため、英語で表示している。
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.
エリシテーションによる構造化入力の要求
前の節の確認は、はい・いいえの質問を一つ尋ねるだけであるが、エリシテーションはそれ以上のことを尋ねられる。エリシテーションには二つのモードがある(エリシテーション)。フォームモードでは、サーバーがメッセージとスキーマを送り、クライアントがフォームを描画し、回答はクライアントを通じて返る。URLモードでは、サーバーはフォームではなくWebページへユーザーを誘導する(次の小節)。
フォームのスキーマは、プリミティブなプロパティのみを持つフラットなオブジェクトである。使えるのは、文字列(フォーマットemail、uri、date、date-timeを含む)、数値と整数、ブール値、および単一選択または複数選択の列挙型である。これらはいずれもdefaultを持てる。ユーザーは、内容を添えてacceptと答えるか、明示的な拒否としてdeclineと答えるか、フォームを閉じた場合はcancelと答える。サーバーは二つの拒否の両方を処理しなければならない(MUST)。クライアントは、どのサーバーが要求しているかを表示し、decline と cancel の選択肢を提示し、送信前にユーザーがフォームを確認できるようにしなければならない(MUST)(エリシテーション、ユーザーへの入力要求への応答)。
SDKはより短い経路を提供する。Annotated[T, Resolve(fn)]と宣言されたツールのパラメータは、fnを実行することで値が埋められる。fnがElicit(message, Model)を返すと、SDKはpydanticモデルをフォームとして描画し、クライアントの機能を確認し、入力要求を返し、再試行時にその回答を埋める。パラメータをElicitationResult[Model]として注釈すると、ツールは三つの結果をすべて受け取って分岐できる。素のModelでは、拒否と取消しはツールエラーになる(mcp/server/mcpserver/resolve.py)。
返品された荷物を開封した人だけが、中の商品が破損していたのか、誤送だったのか、また再販できるのかを知っている。方針上の理由は、送料を返金するかどうかも左右する。ツールrecord_returnは、注文O-1145のKG-1043の明細について、リゾルバで尋ねる。フォームには三つのフィールドがある。返金方針の五つの理由のいずれかであるreason、ブール値のrestock、そして最大200文字の任意の自由記述noteである。スクリプト化されたユーザーは、承諾し、拒否し、取り消す。最後に、コールバックを持たないクライアントが呼び出す。
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
pydanticモデルはnoteにデフォルトを与えているため、これが唯一の任意フィールドである。クライアントが受け取ったフィールドはreason, restock, noteであり、必須なのはreason, restockだけである。
各文字列は、モデルが次に何をすべきかを伝える。承諾は「Recorded: damaged in transit, restock False.」を返し、拒否は「The user declined: don't record this return, and don't ask again.」を返し、取消しは「The user closed the form without answering: ask again later.」を返した。拒否は確定した回答として扱われ、取消しは質問を未解決のまま残す。
コールバックを持たないクライアントはエリシテーション機能を宣言しないため、SDKはツールの実行前に、JSON-RPCエラー-32021(Missing Required Client Capability)でその呼び出しを拒否する(mcp/server/mcpserver/resolve.py)。ショップのissue_refundは、同じ確認を手作業で行う。
実践ルール: フォームモードは、ホスト側の人だけが答えられる事柄に使い、各フォームはツールが実際に使う少数のフィールドに絞り、答えが既知の集合のいずれかである場合は列挙型を使う。フォームはリゾルバとpydanticモデルで宣言し、拒否と取消しで処理を分けたい場合はElicitationResultを受け取る。入力要求を手作業で組み立てるのは、状態を自分で制御する必要がある場合に限る。
機密性の高い手順を URL に送る
フォームの回答はクライアントを通り、場合によってはモデルの目に触れる。サーバーは、パスワード、API キー、アクセストークン、支払い資格情報にフォームモードを使ってはならず(MUST NOT)、これらには URL モードを使わなければならない(MUST)(elicitation)。URL モードはメッセージと URL を送る。クライアントは、その URL やメタデータを事前に取得してはならず(MUST NOT)、ユーザーの明示的な同意なしに開いてはならず(MUST NOT)、完全な URL を表示しなければならない(MUST)。ページは、クライアントにもモデルにも見えない形で開かれる。サーバーは、個人データや資格情報を 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 を続けた URL をリードに送る。URL のドメインは予約済みドメインで、名前解決されることはない。メモリ上の集合が、プロバイダーが持つ完了済みフローの記録の代わりをし、この例は 3 回目の呼び出しの前にこのフローを追加する。
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 でトークンを取得する で得る呼び出し元の ID が必要である。
実践ルール: 秘密にすべきものと、人を別のサービスにサインインさせるものは、フォームではなく URL モードで送る。フロー自身の ID を requestState に入れ、accept は「ユーザーがページへ向かった」と扱い、再試行のたびにフローが完了したかをサーバー自身の記録から判断する。フローを完了する人が開始した人と同一であることを確認する。
ラウンドトリップ状態を改ざんから守る
回答を得て呼び出しを再開するで確定した返金は、クライアントが受け取った requestState をそのまま返すことに依存していたが、クライアントが正直であることを保証する決まりはない。仕様は requestState を攻撃者が制御しうる入力として扱っており、サーバーもそのように扱わなければならない(MUST)。状態が認可、リソースへのアクセス、またはビジネスロジックに影響する場合、サーバーはその完全性を保護し(例: HMAC または AEAD)、検査に失敗した状態を拒否しなければならない(MUST)。リプレイの余地を狭めるため、サーバーは状態を認証済みユーザーに結び付け、有効期限を短く設定し、状態の発生元のリクエストにも結び付けるべきである(SHOULD)。ただし、これらによって状態が一度きりのものになるわけではない。状態を高々一度しか使えないようにする必要があるサーバーは、その不変条件をサーバー側で強制しなければならない(MUST)(Multi Round-Trip Requests)。
SDK の封印(seal)は前半の部分を担い、クライアントに伝える情報を可能な限り少なくする。トークンが変更された場合も、期限切れの場合も、別のリクエストや呼び出し元のものである場合も、未知の鍵を使っている場合も、クライアントが受け取るのは同じ JSON-RPC エラー、-32602、"Invalid or expired requestState" である。本当の理由はサーバーのログ(mcp/server/request_state.py)にだけ送られるので、クライアントは失敗した試行から何も知ることができない。一方、封印は受理済みのトークンの記録を持たないため、後半の部分はサーバーが担うことになる。
確認が再送されれば二度目の支払いになるため、ツールはそれを拒否しなければならない。今回は、クライアントが回答を得て呼び出しを再開するの再試行を、まず三通りの誤った方法で送り、次に正しく送り、さらにもう一度正しく送る。
- 封印された
requestStateの1文字を変更して送る。 - 台本どおりのリードの「はい」だけを状態なしで送る。サーバーが送っていない質問に答えたかのような形である。
- 正しい状態に、別の見積もりの
quote_idを付けて送る。 - 正直な再試行として送る。
- 同じ正直な再試行を2回目として送る。
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 となった。ツールは、尋ねていない質問への回答を回答なしとして扱う。仕様では、回答が欠けているサーバーはエラーを返すのではなく、再度尋ねるべきである(SHOULD)とされている(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 に何かを実行させる前にこれを確認する。その背後では、同じ返金の2回目の実行に対して API が 409 を返すので、記録を失ったサーバーであっても二重に支払うことはない。
実践ルール: すべての requestState を SDK に封印させ、金銭、アクセス、データに関わる状態については封印を決して無効にしないこと。状態は小さく不透明に保つ。レコードそのものではなく 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 サーバー 1 台、クライアント 1 つ、すぐに答えるスクリプト化された責任者という条件では動作する。実際の責任者は答えるまでに時間がかかり、サーバーは再起動し、クライアントもさまざまである。そのため、このパターンはいくつかの見分けやすい形で失敗する。
消えた鍵で封印された状態。 MCPServer の既定の鍵はプロセスの起動時に作られ、そのメモリ内にしか存在しない(mcp/server/request_state.py)。質問から回答までの間にサーバーが再起動した場合や、再試行が別のレプリカに届いた場合、サーバーは状態を開けず、責任者の回答は -32602 で失敗する。注意すべき兆候は、デプロイ後に、またはレプリカ数に応じて「Invalid or expired requestState」が増えることである。RequestStateSecurity(keys=[...]) によって、すべてのレプリカに同じ鍵を与える。confirmations.state_security() は、結果の代わりに入力要求を返すで扱った封印のポリシーであり、SHOP_REQUEST_STATE_KEY からそれらの鍵を作る。最初の鍵が封印し、すべての鍵が開封するので、回答を失わずに鍵をローテーションできる(スティッキーセッションなしでレプリカを運用する)。
状態の有効期間より遅い責任者。 SDK の状態は、既定ではラウンドごとに 600 秒間有効である。質問を読み、電話に出て、15 分後に答えた責任者も同じ -32602 を受け取り、サーバーのログには expired と記録される。ttl= には、人が妥当に要する最長の時間を設定する。そのうえで、ホストがこのエラーを新しい呼び出しに変えるようにし、改めて質問させる。
1 つのプロセスにしか見えない記録。 再試行には最初のラウンドの記録が 2 つ必要であり、どちらも 1 台のサーバーのメモリ内にある。1 つは、再試行が返金を見つけるための第 3 章の見積ストアであり、もう 1 つは、往復する状態を改ざんできないようにするで扱った回答済みの状態の記録である confirmations.OnceOnly である。レプリカが 2 つある環境では、もう一方に届いた再試行は「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 モードを将来のリビジョンで設計が変わる可能性のある機能として示しており(エリシテーション)、固定したリビジョンでは、すでにその部分のうち 2 つが削除されている。URL モードのコードは 1 か所にまとめ、各リビジョンの変更履歴と照らして確認する。
終わらないループ。 ユーザーが放棄した 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 とは別にアラートを設定する。
実践ルール: 質問をするサーバーのレプリカには、ローテーションできる共通の鍵を 1 つ与え、状態の有効期間を人が要する時間に合わせ、見積ストアと一度限りのすべての記録を、本番環境に出す前に共有ストレージへ移す。トランスポートに呼び出し元がある場合は、各質問をその呼び出し元に結び付ける。そのうえで、-32602 は記録された理由別に、-32021 はホスト別に、そして呼び出しごとのラウンド数を監視する。
本章で下した判断
- どの返金に確認が必要かは、店舗の API が決める。
issue_refundはまず第3章のバージョンを呼び出し、API が返金を保留した場合にだけ確認を求める。こうすることで、ポリシーの上限は1か所にまとまる。 - 返金は、質問より先に保留する。 そのため、誰も答えない質問は、第3章と同じく返金を保留のまま残す。
- 確認は、手作りの入力リクエストである。 キー
confirmの下に form モードの elicitation を1つ置き、返金の ID をrequestStateとして持たせる。再試行のときに、見つけた返金とこの値を照合する。返品された荷物のフォームでは、SDK の機能確認とレンダリングがコードを減らしてくれるため、リゾルバを使う。 - SDK はすべての
requestStateを封印する。 封印に使うキーは、デプロイ時にconfirmations.state_security()またはSHOP_REQUEST_STATE_KEYで注入できる。注入しない場合は、プロセスが動いている間だけ存続するキーが使われる。 - 回答はサーバー側で一度限りとする。
confirmations.OnceOnlyを通じて解放の前に検査し、その背後には API の 409 がある。 - サーバーの状態を伴わない回答や、別の返金の状態を伴う回答は、一度も問われなかった質問として扱う。 ツールは改めて質問する。
- サーバーは呼び出しを開いたままにしないが、2つの記録を保持する。 第3章の見積もりストアと、一度限りの記録である。どちらもここではメモリ上に置き、第6章でレプリカ間で共有する。
- stdio では、ホストのユーザーが確認する人になる。 HTTP では、質問を認証済みの呼び出し元に結び付ける。さらに、サポート担当リーダーだけが持つスコープ
refunds:writeでツールを制限する(トークンが許す範囲でツールを制限する)。 - 辞退とキャンセルは、異なる結果になる。 辞退は確定し、キャンセルは質問を未解決のまま残す。
- シークレットとサインインは URL モードで扱う。 フローの ID は
requestStateに入れ、acceptは完了とは見なさない。 - API に2つのエンドポイントを追加した。
POST /refunds/{refund_id}/confirmとPOST /refunds/{refund_id}/cancelであり、どちらも保留中の返金にだけ作用し、それ以外では 409 を返す。 - モデルが読める値はツールの引数のままとし、人だけが与えられる値は elicitation で求める。
この版における本章
第2026.11.14版2026年11月19日時点で例が通過この章の6 例件のうち6件が合格
英語版の書籍(版2026.11.14)から翻訳した。