MCPサーバーがクライアントに頼むとき
MCP サーバーが、ツールの呼び出しを自分だけで終えられないことがあります。モデルの答え (サンプリング)、使ってよいフォルダー (ルート)、人の返事 (エリシテーション) が要るときです。
2026-07-28 の版からは、サーバーは「入力が必要」と答えて頼み、クライアントは足りないものを持ってやり直します。ラボで二回のやり取りを見ます。
このレッスンのゴール
メモ
MCP サーバーの入力の要求に答え、その要求が属する呼び出しをやり直すことができる。
キーワード
| ことば | いみ | れい |
|---|---|---|
| サンプリング | サーバーがクライアントのモデルに答えを頼むこと | |
| ルート | クライアントがサーバーに使わせるフォルダー | file:///home/sam/notes |
| エリシテーション | サーバーが人に情報を尋ねること | |
| 入力の要求 | 終える前にサーバーが頼むもの | |
| リクエストの状態 | クライアントがそのまま返す、中身の見えない文字列 | |
| 非推奨 | まだ動くが、いずれなくなること |
学生が入力するセルは、このプレビューでは空白です。
ウォームアップ
やってみよう
ウォームアップ
4問入力が必要、そして同じ呼び出し
クライアントがツールを呼びます。サーバーは resultType を input_required にし、入力の要求の辞書と、多くの場合リクエストの状態を付けて答えます。
クライアントは答えを一つずつ集め、新しい id で同じ呼び出しを送り直します。答えは inputResponses に入れ、状態は変えずに返します。サーバーは二つの間に何も覚えないので、どのコピーのサーバーでも呼び出しを終えられます。
一つの呼び出しに二つのリクエスト
sequenceDiagram
participant P as 人
participant C as クライアント
participant S as サーバー
participant M as モデル
C->>S: tools/call id 1
S-->>C: input_required サンプリングの要求と requestState
C->>P: 要求を見せる
P-->>C: 同意する
C->>M: 質問
M-->>C: 答え
C->>S: tools/call id 2 inputResponses と requestState
S-->>C: complete 結果確認
やってみよう
確認
3問試そう: 再試行を組み立てる
# クライアントの助けが要るツール呼び出しは、二つのリクエストになります。
first = {"id": 1, "params": {"name": "explain_word", "arguments": {"word": "token"}}}
answer = {"resultType": "input_required", "requestState": "abc|123",
"inputRequests": {"model": {"method": "sampling/createMessage"}}}
retry = {"id": 2, "params": dict(first["params"])}
retry["params"]["inputResponses"] = {"model": {"role": "assistant", "content": {"type": "text", "text": "文章の小さなかけら"}}}
retry["params"]["requestState"] = answer["requestState"]
print("最初の id", first["id"], "再試行の id", retry["id"])
print("頼まれたキー:", list(answer["inputRequests"]))
print("答えたキー:", list(retry["params"]["inputResponses"]))
# 再試行で requestState を忘れさせてみましょう。サーバーはどうすべきですか。
三種類の要求、うち二つは非推奨
サンプリングでは、サーバーが自分のモデルの鍵なしに、クライアントのモデルを使えます。人は先に要求を見て、断ることができるべきです。ルートは、サーバーが触れてよいフォルダーを伝えます。エリシテーションは、クライアントを通して人に質問します。
2026-07-28 の版は、サンプリングとルートを非推奨にしました。少なくとも一年はまだ動きます。新しいサーバーはモデルの提供元を直接呼び、フォルダーはツールの引数で受け取ります。
入力を頼むサーバーを書く(1)
docker exec tools sh -c "mkdir -p mcp && printf '%s\n' '\"\"\"A server whose tools need something from the client first: the answer of a model, or the roots.\"\"\"' 'import hmac' 'import json' 'import posixpath' 'KEY = b\"only-the-server-knows\"' '' '' 'def seal(data):' ' text = json.dumps(data)' ' return text + \"|\" + hmac.new(KEY, text.encode(), \"sha256\").hexdigest()[:16]' '' '' 'def unseal(state):' ' text, mac = state.rsplit(\"|\", 1)' ' if hmac.compare_digest(mac, hmac.new(KEY, text.encode(), \"sha256\").hexdigest()[:16]):' ' return json.loads(text)' ' return None' 'def reply(msg_id, result):' ' return {\"jsonrpc\": \"2.0\", \"id\": msg_id, \"result\": result}' '' '' 'def done(msg_id, text, failed=False):' ' return reply(msg_id, {\"resultType\": \"complete\", \"isError\": failed,' ' \"content\": [{\"type\": \"text\", \"text\": text}]})' '' '' 'def needs(msg_id, asks, state=None):' > mcp/asker.py"ここでは表示のみで、実行されません。「ラボを開始」を押すと、自分のラボのターミナルに入力できます。
入力を頼むサーバーを書く(2)
docker exec tools sh -c "printf '%s\n' ' result = {\"resultType\": \"input_required\", \"inputRequests\": asks}' ' if state:' ' result[\"requestState\"] = state' ' return reply(msg_id, result)' 'def handle(msg):' ' p = msg[\"params\"]' ' got = p.get(\"inputResponses\", {})' ' if p[\"name\"] == \"explain_word\":' ' word = p[\"arguments\"][\"word\"]' ' if \"model\" not in got:' ' if \"sampling\" not in p[\"_meta\"][\"io.modelcontextprotocol/clientCapabilities\"]:' ' return done(msg[\"id\"], \"this client cannot ask a model\", True)' ' text = {\"type\": \"text\", \"text\": \"What is a \" + word + \"?\"}' ' ask = {\"method\": \"sampling/createMessage\", \"params\": {\"messages\": [{\"role\": \"user\", \"content\": text}],' ' \"systemPrompt\": \"Answer in one sentence.\", \"maxTokens\": 60}}' >> mcp/asker.py"ここでは表示のみで、実行されません。「ラボを開始」を押すと、自分のラボのターミナルに入力できます。
入力を頼むサーバーを書く(3)
docker exec tools sh -c "printf '%s\n' ' return needs(msg[\"id\"], {\"model\": ask}, seal({\"word\": word}))' ' if unseal(p.get(\"requestState\", \"x|y\")) is None:' ' return {\"jsonrpc\": \"2.0\", \"id\": msg[\"id\"], \"error\": {\"code\": -32602, \"message\": \"requestState failed its check\"}}' ' return done(msg[\"id\"], word + \": \" + got[\"model\"][\"content\"][\"text\"])' ' if p[\"name\"] == \"read_note\":' ' if \"roots\" not in got:' ' return needs(msg[\"id\"], {\"roots\": {\"method\": \"roots/list\", \"params\": {}}})' ' path = posixpath.normpath(p[\"arguments\"][\"path\"])' ' for root in got[\"roots\"][\"roots\"]:' ' folder = root[\"uri\"][len(\"file://\"):]' ' if path.startswith(folder + \"/\"):' ' return done(msg[\"id\"], \"opened \" + path)' ' return done(msg[\"id\"], \"refused: \" + path + \" is outside every root\", True)' >> mcp/asker.py"ここでは表示のみで、実行されません。「ラボを開始」を押すと、自分のラボのターミナルに入力できます。
答えるクライアントを書く(1)
docker exec tools sh -c "mkdir -p mcp && printf '%s\n' '\"\"\"A client that answers the input requests of a server and retries the same call with a new id.\"\"\"' 'import json' 'import asker' 'import llm' 'CAPS = {\"sampling\": {}, \"roots\": {}}' 'ROOTS = {\"roots\": [{\"uri\": \"file:///home/sam/notes\", \"name\": \"Notes\"}]}' 'calls = 0' '' '' 'def call(tool, arguments, responses=None, state=None):' ' global calls' ' calls += 1' ' p = {\"name\": tool, \"arguments\": arguments, \"_meta\": {\"io.modelcontextprotocol/clientCapabilities\": CAPS}}' ' if responses:' ' p[\"inputResponses\"] = responses' ' if state:' ' p[\"requestState\"] = state' ' return asker.handle({\"jsonrpc\": \"2.0\", \"id\": calls, \"method\": \"tools/call\", \"params\": p})' 'def sample(ask):' ' \"\"\"The person sees the request first. Here they say yes. A real host shows it and waits.\"\"\"' > mcp/askclient.py"ここでは表示のみで、実行されません。「ラボを開始」を押すと、自分のラボのターミナルに入力できます。
答えるクライアントを書く(2)
docker exec tools sh -c "printf '%s\n' ' print(\" the person is shown:\", ask[\"params\"][\"messages\"][0][\"content\"][\"text\"], \"and agrees\")' ' chat = [{\"role\": \"system\", \"content\": ask[\"params\"][\"systemPrompt\"]}]' ' chat.append({\"role\": \"user\", \"content\": ask[\"params\"][\"messages\"][0][\"content\"][\"text\"]})' ' text = llm.chat(chat, max_tokens=ask[\"params\"][\"maxTokens\"])[\"choices\"][0][\"message\"][\"content\"]' ' return {\"role\": \"assistant\", \"content\": {\"type\": \"text\", \"text\": text}, \"model\": \"lab\", \"stopReason\": \"endTurn\"}' 'first = call(\"explain_word\", {\"word\": \"token\"})[\"result\"]' 'print(\"1. id 1 answered:\", json.dumps(first)[:150], \"...\")' 'answers = {\"model\": sample(first[\"inputRequests\"][\"model\"])}' 'again = call(\"explain_word\", {\"word\": \"token\"}, answers, first[\"requestState\"])' 'print(\"2. id 2, the retry:\", again[\"result\"][\"content\"][0][\"text\"])' >> mcp/askclient.py"ここでは表示のみで、実行されません。「ラボを開始」を押すと、自分のラボのターミナルに入力できます。
答えるクライアントを書く(3)
docker exec tools sh -c "printf '%s\n' 'changed = first[\"requestState\"].replace(\"token\", \"password\")' 'again = call(\"explain_word\", {\"word\": \"password\"}, answers, changed)' 'print(\"3. id 3, with the state changed by the client:\", again[\"error\"][\"message\"])' 'print(\"4. id 4 answered:\", call(\"read_note\", {\"path\": \"/home/sam/notes/monday.txt\"})[\"result\"][\"inputRequests\"])' 'for path in [\"/home/sam/notes/monday.txt\", \"/home/sam/notes/../.ssh/id_rsa\"]:' ' result = call(\"read_note\", {\"path\": path}, {\"roots\": ROOTS})[\"result\"]' ' print(\"5. id\", calls, result[\"content\"][0][\"text\"], \"isError\", result[\"isError\"])' >> mcp/askclient.py"ここでは表示のみで、実行されません。「ラボを開始」を押すと、自分のラボのターミナルに入力できます。
二回のやり取りを動かす
docker exec tools python3 mcp/askclient.pyここでは表示のみで、実行されません。「ラボを開始」を押すと、自分のラボのターミナルに入力できます。
askclient.py の表示
| リクエスト | 起きたこと |
|---|---|
| id 1 explain_word | sampling/createMessage の要求付きの input_required |
| 人 | 「What is a token?」を見せられて同意する |
| id 2 再試行 | token: A token is a small piece of text, often part of a word. |
| id 3 状態を変更 | requestState failed its check |
| id 4 read_note | roots/list の要求付きの input_required |
| id 5 と 6 | opened /home/sam/notes/monday.txt、refused /home/sam/.ssh/id_rsa |
学生が入力するセルは、このプレビューでは空白です。
実行の確認
やってみよう
実行の確認
3問よくある間違い
注意
クライアントはサンプリングの要求をすぐモデルに渡すべきだ、と思う人が多くいます。質問はサーバーが書いたものなので、人が先に見るべきです。サーバーはモデルに何でも頼めます。要求を見せ、断れるようにし、返す前に答えも見せましょう。
要求と頼む内容を結ぼう
やってみよう
読み込み中…
答えはここで採点され、保存されません。アカウントがあれば、結果が残ります。
課題: 答えてやり直す
入力の要求の、クライアント側を書きましょう。
pending(result) はサーバーが頼んだキーを並べます。retry(original, new_id, responses, state) は、元のリクエストを変えずに再試行のリクエストを作ります。inside_roots(path, roots) は、posixpath.normpath で整えたパスが、どれかのルートの中にあるかを答えます。
import posixpath
def pending(result):
# The keys of result["inputRequests"], sorted, when result["resultType"] is
# "input_required". Otherwise an empty list.
return []
def retry(original, new_id, responses, state):
# A new request: the original with id new_id, and params holding everything the
# original params held plus "inputResponses": responses, and "requestState": state
# only when state is not None. Do not change the original.
return original
def inside_roots(path, roots):
# roots: a list like [{"uri": "file:///home/sam/notes", "name": "Notes"}].
# True when path, after posixpath.normpath, is inside one root folder.
return True
終わりのクイズ
やってみよう