モデルが使えるツールを設計する

読了まで約77 分分、10 節 節の 7 例 例。

第2026.11.14版 2026年11月19日時点で例が通過 70 例中 70 例が合格 変更点

AIによる翻訳。英語版は人による検証済みである。 当社の書籍の作り方

英語版の書籍(版2026.11.14)から翻訳した。 原文を読む

この章を終えると、ショップの API を、モデルが名前、説明、入力スキーマ、結果、エラーを手がかりに行動できる Model Context Protocol のツールへ変換できるようになる。また、ある説明を一つ変更したときに、モデルが選ぶツールがどう変わるかを測定できるようになる。以下の内容は、仕様のリビジョン 2026-07-28 と、Python SDK の mcp 2.3.0 に対して成り立つ。

この章のツールはどれも、モデルがショップの顧客チケットの一つに答えるのを助けるために存在する。ショップのサーバー shop-support には、今のところツールが一つしかない。1 つのエンドポイントをツールとして包むで作った get_order_status である。MCP が API に加えるものではリソースとプロンプトも追加したが、ツール一つではほとんどのチケットに答えられない。顧客は、どの注文がどれだったのか、返金するといくらになるのか、返金してほしい、ある商品の在庫があるのか、といったことも尋ねる。

Model Context Protocol (MCP) サーバーのツールは、モデルから見えるショップの唯一の部分である。モデルはショップのコードも API も読まない。モデルは各ツールの名前、説明、入力スキーマを読み、ツールを一つ選んで引数を埋める。そして、返ってきたものをエラーも含めて読む。したがってツールとは、質問を返せない読み手のために設計するインターフェースであり、定義のどの部分も、その読み手を助ける場所にも誤解させる場所にもなりうる。

この章では、これらのチケットに対応するツール一式を作り、設計上の選択を一つずつテストする。

この部分はまだ翻訳されていないため、英語で表示している。

Shape tools around tasks, not endpoints

最終変更:版2026.11.14

The shop's API has five endpoints for orders, stock and new refunds, and the quickest way to give a model all five is one tool per endpoint. Generators that turn an API's routes into MCP tools do exactly that. Tools shaped like the API suit a programmer who already knows the workflow. A model has to rebuild the workflow from the tools' names every time: look this up, then compute that, then post it.

The alternative is to shape each tool around a task the model performs for the person it's helping. A task tool may call one endpoint, combine two, or split one in two, and it hides the steps a model would get wrong. Tools are model-controlled: the model decides which to call and with what (server features). The shape of the tools decides which decisions are left to the model.

This chapter rebuilds shop-support in lib.shop_tools, a shared module, so that every example and every later chapter uses the same five tools. The book still calls it the shop's server. Its resource and prompt return in Serve data as resources and prompts. Each of its tools serves one kind of ticket:

  • find_orders searches one customer's orders by status or by the date placed. It calls the API's order list and adds a date filter the API doesn't have.
  • get_order_status looks up one order by its ID, as in chapter 1.
  • quote_refund works out what a refund would be, and changes nothing.
  • issue_refund makes the refund from a quote. Above the policy's limit the shop's API holds it for a person (Return an input request instead of a result); within the limit, nothing in this chapter asks anyone. Consent is the host asking the user before a call that changes something, and it arrives in Ask for consent before side effects.
  • check_stock reports one product's stock in each warehouse.

The module also holds endpoint_tools(), the list a one-tool-per-endpoint generator writes for the same API, so the two shapes can be compared. Both lists print with each tool's required arguments. Then ticket T-0024, "please refund the aluminium muffin tray on o2415", runs both ways.

tools-from-endpoints.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 合格
"""Two tool lists for the same API, one tool per endpoint as a generator writes them and the shop's five task tools, thenticket T-0024's refund both ways. The point rests on two printed lines: the endpoint tool records the amount the modelsent, and quote_refund's amount is the server's own figure, which the code asserts is within the limit."""import asyncioimport httpx2from mcp import Clientfrom lib import loopback, shop_api, shop_toolsasync def main() -> None:    for tool in shop_tools.endpoint_tools():        print("endpoint tool:", tool.name, tool.input_schema["required"])    with loopback.serve(shop_api.create_app()) as base_url:        async with Client(shop_tools.server_params(base_url)) as client:            print("protocol revision:", client.protocol_version)            for tool in (await client.list_tools()).tools:                print("task tool:", tool.name, tool.input_schema.get("required", []))  # .get: no "required" key if none            # T-0024: "please refund the aluminium muffin tray on o2415". The endpoint tool post_refunds forwards            # its arguments to POST /refunds, so the amount is whatever the model sends, such as the order's total.            order = httpx2.get(f"{base_url}/orders/O-2415", headers={"X-API-Key": shop_api.DEMO_API_KEY}).json()            refund = httpx2.post(f"{base_url}/refunds", headers={"X-API-Key": shop_api.DEMO_API_KEY},                                 json={"order_id": "O-2415", "amount": order["total"], "reason": "damaged"})            print("post_refunds status:", refund.status_code)            print("post_refunds amount:", refund.json()["amount"])            quote = await client.call_tool("quote_refund", {"order_id": "O-2415", "sku": "KG-1050",                                                            "reason": "arrived damaged"})            print("quote_refund amount:", quote.structured_content["amount"])            print("quote_refund within limit:", quote.structured_content["within_limit"])            assert quote.structured_content["within_limit"]  # the muffin tray's line is under the refund policy's limitasyncio.run(main())
出力python tools-from-endpoints.py
endpoint tool: get_orders []
endpoint tool: get_orders_by_order_id ['order_id']
endpoint tool: get_stock_by_sku ['sku']
endpoint tool: post_refunds ['order_id', 'amount']
endpoint tool: post_stock_by_sku_recount ['sku']
protocol revision: 2026-07-28
task tool: find_orders ['customer_id']
task tool: get_order_status ['order_id']
task tool: quote_refund ['order_id']
task tool: issue_refund ['quote_id']
task tool: check_stock ['sku']
post_refunds status: 201
post_refunds amount: 49.96
quote_refund amount: 23.98
quote_refund within limit: True

The endpoint tools mirror the API. get_orders requires no argument at all, so a model can list every customer's orders. post_refunds requires an order_id and an amount. And post_stock_by_sku_recount puts a slow warehouse job in front of a support model. When a model sends the whole order's total to post_refunds, the API accepts it with status 201 and records a refund of €49.96, for a ticket about one product. The API checks only that the amount isn't more than the order's total, so the model's arithmetic is the only check on the money.

The task tools move those decisions into the server. find_orders requires a customer_id, so a search covers one customer, though the model still picks which one. quote_refund takes the order and, optionally, one SKU, and the server works out the amount itself: €23.98 for the muffin tray's line. That amount is within the refund policy's limit, as the quote's within_limit field says. issue_refund takes no amount at all, only the quote's ID. The stock recount stays off this server; Stream progress on a long call puts it on a server of its own.

Splitting the refund in two also follows most of the specification's guidance for state across calls. The pinned revision has no protocol session, so a tool that needs state from an earlier call gets it as an explicit handle: one tool returns an ID, and the next takes it as an argument. The guidance asks that the creating tool's description state how long the handle lives, and that a call with an expired or unknown handle return a tool execution error that says so (tools, "Stateful tools"). In the shop's server, quote_refund returns a quote_id valid for 15 minutes, and its description says so.

What the server doesn't do yet matters as much. It trusts the customer_id and order IDs the caller sends, so a model, or a ticket written to mislead one, can list any customer's orders and quote any order. Whoever holds a quote_id can spend it. The guidance asks for a handle "with sufficient entropy (e.g., a UUIDv4)" on a server without authentication, and, on one with it, a check of the caller's authorization against the handle "on every call" (tools, "Stateful tools"). The shop's quote IDs come from Python's secrets module, so no one can work one out from the order, but they're only 40 bits and bound to no customer. Secure tools against misuse takes the acting user from the verified token's subject, never from an argument. Where customers sign in, that is the customer. At the support team's host it is a member of staff, and the customer comes from the ticket record the server looks up and checks (Keep the server from acting as a confused deputy).

Working rule: Start from the tasks in your tickets or logs, not from your routes, and give each task one tool. Move every decision the model shouldn't make into the server, such as an amount or a sequence of calls. Use a handle when one task needs the result of another, state its lifetime in the description of the tool that creates it, make it unguessable, and check on every call that it belongs to the caller. Expose an endpoint as it stands only when the task and the endpoint are the same, as check_stock and GET /stock/{sku} are.

この部分はまだ翻訳されていないため、英語で表示している。

Write descriptions the model reads

最終変更:版2026.11.11

The task tools from the previous section help only if the model picks the right one, and it picks from what the host shows it. The book's host loop, lib.host, shows the model each tool's name, description and input schema. The specification calls the description a "hint" that clients can use "to improve the LLM's understanding of available tools" (schema, Tool.description).

Most published descriptions are poor. One study of 856 tools on 103 servers found that 97.1% had at least one defect, and that 56% didn't say plainly what the tool is for (Hasan and others, 2026). In a controlled test with two tools that had identical interfaces, editing only one tool's description gave it more than 10 times the usage of the original with two of the models tested (Faghih and others, 2025). Longer isn't automatically better. In the first study, fully rewritten descriptions raised task success by a median 5.85 points, but added 67% more steps and made 1 case in 6 worse.

A description that helps says four things: what the tool does, when to use it rather than its neighbour, what its inputs look like, and what comes back. In the Python SDK a tool's description is its function's docstring, unless you pass description= to the decorator (tools). On Python 3.12.15, the book's runtime, the SDK passes the docstring through as written (mcp/server/mcpserver/tools/base.py), so a docstring that runs over several lines sends its line breaks and indentation to the model. The shop's server keeps its descriptions in one dictionary, DESCRIPTIONS, and passes each one as description=.

The example shows eight tickets and the shop's five tools to the model three times, with a different set of descriptions each time. Only the descriptions differ.

  • The vague set has one line per tool, of the kind an endpoint generator writes, such as "Refund quote."
  • The draft set is the shop's first draft, written as docstrings.
  • The revised set is the shop's second draft, written after reading the draft's results.

The eight were picked by hand from the shop's ticket queue, not sampled: two ask which orders a customer has, two where an order is, three about refunds, and one about stock. None carries injected instructions or a mistyped order ID. Before you run it, predict how many first calls the vague set and the draft each get right.

The model is the one every recording in this book uses: Qwen3-4B-Instruct-2507, run on the CPU with llama.cpp, as Let a model choose the tool set it up. The script recordings/description_choices.py made this recording, description-choices, sampling one reply per ticket and set at temperature 0.7 with one fixed seed. Scoring looks only at the first tool the model calls, not at its arguments. A ticket's right first tool is the one the shop's data tags it with, with one change: issue_refund needs a quote_id, so a refund request starts with quote_refund.

vague-description-wrong-tool.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 合格
"""Predict, then run: eight of the shop's tickets and the same five tools, shown to the model with three sets ofdescriptions: one-line ones, the shop's first draft, and its revision. Only the descriptions differ. The model'sreplies are a recording (examples/data/recorded/description-choices/), made with recordings/description_choices.py."""import asyncioimport jsonfrom mcp import Clientfrom lib import shop_toolsfrom lib.host import ReplayModel, choose_toolfrom lib.shop_data import load_shopTICKETS = ("T-0002", "T-0013", "T-0004", "T-0022", "T-0006", "T-0029", "T-0024", "T-0016")SETS = {"vague": shop_tools.VAGUE_DESCRIPTIONS, "draft": shop_tools.DRAFT_DESCRIPTIONS,        "revised": shop_tools.DESCRIPTIONS}model = ReplayModel("description-choices")  # the recorded replies, so no model runs heredef right_tool(ticket) -> str:    """The tool a correct host calls first. issue_refund takes a quote_id, so a refund starts with quote_refund."""    return "quote_refund" if ticket.expected_tool == "issue_refund" else ticket.expected_toolasync def main() -> None:    shop = load_shop()    async with Client(shop_tools.create_server()) as client:     # in-process: listing tools calls no API        listed = (await client.list_tools()).tools    right = dict.fromkeys(SETS, 0)    for ticket_id in TICKETS:        ticket = shop.ticket(ticket_id)        # the same tools each time, with only their descriptions swapped        choices = {label: choose_tool(model, ticket, shop_tools.with_descriptions(listed, descriptions))                   for label, descriptions in SETS.items()}        for label, choice in choices.items():            right[label] += choice.tool == right_tool(ticket)        if all(choice.tool == right_tool(ticket) for choice in choices.values()):            print(f"{ticket_id} all three:", right_tool(ticket))            continue        print(f"{ticket_id} needs:", right_tool(ticket))        for label, choice in choices.items():            print(f"{ticket_id} {label}:", choice.tool or "none")        if choices["revised"].tool == "quote_refund":            print(f"{ticket_id} revised sku:", choices["revised"].arguments.get("sku"))            print(f"{ticket_id} order's skus:", ", ".join(line.sku for line in shop.order(ticket.order_id).lines))    print("sampling temperature:", json.loads((model.folder / "manifest.json").read_text())["sampling"]["temperature"])    for label, count in right.items():        print(f"{label} right:", f"{count} of {len(TICKETS)}")asyncio.run(main())
出力python vague-description-wrong-tool.py
T-0002 all three: find_orders
T-0013 all three: find_orders
T-0004 all three: get_order_status
T-0022 all three: get_order_status
T-0006 needs: quote_refund
T-0006 vague: get_order_status
T-0006 draft: get_order_status
T-0006 revised: quote_refund
T-0006 revised sku: KG-1031
T-0006 order's skus: KG-1043
T-0029 needs: quote_refund
T-0029 vague: find_orders
T-0029 draft: get_order_status
T-0029 revised: quote_refund
T-0029 revised sku: KG-1022
T-0029 order's skus: KG-1019
T-0024 needs: quote_refund
T-0024 vague: get_order_status
T-0024 draft: get_order_status
T-0024 revised: quote_refund
T-0024 revised sku: KG-1022
T-0024 order's skus: KG-1050, KG-1051
T-0016 all three: check_stock
sampling temperature: 0.7
vague right: 5 of 8
draft right: 5 of 8
revised right: 8 of 8

The vague set chose the right first tool for 5 of 8 tickets, and the draft did the same, 5 of 8. Names and parameters alone carried the four order tickets and the stock ticket, so all three sets chose the same right tool for each. The draft's longer wording didn't help with the three refund tickets, where the choices differed. Ticket T-0006, about an order that "arrived with the enamelled saute pan cracked. what can you refund me", got get_order_status from the vague set and get_order_status from the draft.

The draft said what quote_refund does, but not that it makes looking the order up unnecessary. The revision says so in both tools. get_order_status sends refund questions to quote_refund, and quote_refund asks to be called first because "it checks the order itself". The revision changed more than that, though. It rewrote the opening of quote_refund's description, and, passed as description= instead of as a docstring, it dropped the draft's line breaks and indentation. With all three changes, the revised set chose the right first tool for 8 of 8 tickets. The run doesn't show which change mattered.

The revision fixed the choice of tool but not the arguments: none of the three refund calls would have worked. For T-0006 the model sent the SKU KG-1031, the example in the sku parameter's own description, and none of the three SKUs it sent was on its order. Report failures as tool results shows how the shop's server catches that mistake. T-0013's date was wrong with all three sets, as the next section shows.

Read these counts as one measurement. They come from one model at one seed, on eight tickets picked by hand, and another seed could change some choices. The revision was written after reading the results on the same eight tickets, so its score flatters it. Measure how often the right tool is chosen measures choices over the whole ticket queue, which is the test that decides.

Working rule: Write each description in two to four sentences: what the tool does, when to use it instead of the tool it's most often confused with, what its inputs look like, and what it returns. Pass it as description= rather than relying on a multi-line docstring, so the model reads exactly the text you wrote. Then record the model you ship choosing tools for real tickets, read the wrong choices, and change the descriptions those choices point to. Change one thing per recording when you need to know which change worked, and check the result on tickets you didn't use to write the change.

JSON Schema で入力に型を付ける

最終変更:版2026.11.11

前の節の説明文は、ツールが何を必要としているかをモデルに伝える。入力スキーマは、サーバーにそれを強制させる。すべてのツールは inputSchema を持つ。これは JSON Schema のオブジェクトであり、そのルートは "type": "object" を持つ。固定されたリビジョンでは、oneOf、if、then、else、$ref を含め、JSON Schema 2020-12 の任意のキーワードをこのスキーマに記述できる(変更履歴、スキーマ、Tool.inputSchema)。$schema フィールドを持たないスキーマは 2020-12 として解釈される。また、実装はネットワーク URI を指す $ref を自動的にたどっては「ならない(MUST NOT)」とされている(基本プロトコル)。したがって、既定ではスキーマによってクライアントに何かをダウンロードさせることはできない。

スキーマは二つの役割を果たす。一つは、有効な呼び出しの形をモデルに示すことである。もう一つは、ツールのコードが実行される前に、無効な呼び出しをサーバーが拒否できるようにすることである。仕様はサーバー側のこの役割を要件としており、サーバーはすべてのツール入力を検証「しなければならない(MUST)」とされている(ツールの「セキュリティ上の考慮事項」)。

Python SDK は関数の型ヒントからスキーマを構築し、pydantic の Annotated[..., Field(...)] がそこに制約を加える(ツール)。この店のサーバーは ID 型を一度だけ定義している。OrderId は pattern=r"^O-\d{4}$" を持つ文字列であり、CustomerId と Sku も同様である。find_orders は、status を 5 種類の注文ステータスからなる Literal として、placed_since を date として、limit を ge=1, le=50 の整数として受け取る。まず、これらのヒントから SDK が構築したスキーマを出力する。次に find_orders を三通りの方法で呼び出す。三つの不正な引数を一度に渡す場合、数値を文字列として送る場合、そして モデルが読む説明文を書くで記録されたモデルがチケット T-0013 について送った日付を渡す場合である。このチケットは、注文を「6 月 12 日以降」で求めていた。

reject-bad-arguments.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 合格
"""find_orders' typed inputs: the JSON Schema the SDK builds from them, one result that names three rejected arguments,a string the SDK converts without complaint, and a date that is valid but wrong. The point rests on the last two ordercounts: a date that passes validation can still return the wrong orders."""import asyncioimport jsonfrom mcp import Clientfrom lib import loopback, shop_api, shop_toolsasync def main() -> None:    with loopback.serve(shop_api.create_app()) as base_url:        async with Client(shop_tools.server_params(base_url)) as client:            tools = {tool.name: tool for tool in (await client.list_tools()).tools}            for name, prop in tools["find_orders"].input_schema["properties"].items():                rules = {k: v for k, v in prop.items() if k in ("pattern", "minimum", "maximum", "default")}                # an optional argument's schema is anyOf: its type or enum, and null                kinds = [p.get("enum") or p.get("format") or p["type"] for p in prop.get("anyOf", [prop])]                print(f"{name}:", json.dumps(kinds), json.dumps(rules))            bad = await client.call_tool("find_orders", {"customer_id": "42", "status": "lost", "limit": 500})            print("bad arguments is error:", bad.is_error)            assert bad.is_error            print(bad.content[0].text)            # "5" is a string; pydantic converts it to the integer 5 before the tool runs            loose = await client.call_tool("find_orders", {"customer_id": "C-0085", "limit": "5"})            print("string limit is error:", loose.is_error)            assert not loose.is_error            print("string limit orders:", len(loose.structured_content["orders"]))            # T-0013 asks for orders "since 12 Jun"; the recorded model sent 2023-06-12, a valid date            wrong_year = await client.call_tool("find_orders", {"customer_id": "C-0085", "placed_since": "2023-06-12"})            right_year = await client.call_tool("find_orders", {"customer_id": "C-0085", "placed_since": "2026-06-12"})            print("since 2023-06-12 orders:", len(wrong_year.structured_content["orders"]))            print("since 2026-06-12 orders:", len(right_year.structured_content["orders"]))asyncio.run(main())
出力python reject-bad-arguments.py
customer_id: ["string"] {"pattern": "^C-\\d{4}$"}
status: [["placed", "shipped", "delivered", "cancelled", "returned"], "null"] {"default": null}
placed_since: ["date", "null"] {"default": null}
limit: ["integer"] {"default": 10, "maximum": 50, "minimum": 1}
bad arguments is error: True
Error executing tool find_orders: 3 validation errors for find_ordersArguments
customer_id
  String should match pattern '^C-\d{4}$' [type=string_pattern_mismatch, input_value='42', input_type=str]
    For further information visit https://errors.pydantic.dev/2.14/v/string_pattern_mismatch
status
  Input should be 'placed', 'shipped', 'delivered', 'cancelled' or 'returned' [type=literal_error, input_value='lost', input_type=str]
    For further information visit https://errors.pydantic.dev/2.14/v/literal_error
limit
  Input should be less than or equal to 50 [type=less_than_equal, input_value=500, input_type=int]
    For further information visit https://errors.pydantic.dev/2.14/v/less_than_equal
string limit is error: False
string limit orders: 5
since 2023-06-12 orders: 5
since 2026-06-12 orders: 1

各ヒントはスキーマのキーワードになった。顧客 ID には pattern、ステータスには enum、日付には "format": "date"、件数の上限には minimum と maximum が対応する。三つの不正な引数を渡した呼び出しは、一つの失敗結果として返った。そのテキストには、失敗したすべての引数、破られた規則、送られた値が示されている。モデルは次の呼び出しで三つとも修正できる。

SDK は、ある点でスキーマよりも寛容である。スキーマでは limit は整数とされているが、"5" を渡した呼び出しは成功し、5 件の注文を返した。引数を検証する pydantic は、既定では数字の文字列を整数に変換する。この場合は問題がない。文字列と数値を区別したままにしなければならない場合は、そのフィールドを Field(strict=True) で宣言する。また pydantic は、スキーマで宣言されていない引数を、エラーを出さずに破棄する(mcp/server/mcpserver/utilities/func_metadata.py)。サーバーを confused deputy にしないはこの挙動を前提としている。

日付は、どのスキーマも捕捉できない誤りである。チケットの「6 月 12 日」には年がなく、モデルは 2023-06-12 を送った。これは、店のデータが終わる時点より 3 年前の、有効な日付である。この呼び出しは検証を通過し、5 件の注文、つまりその顧客のすべての注文を返した。店の該当年の 6 月 12 日以降に行われた 1 件ではなかった。スキーマが検査するのは形式である。意味は別の手段で与えなければならない。たとえば、ホストがチケットの日付をプロンプトに入れる方法や、年のない日付の読み方を説明文に書く方法がある。

仕様は、拒否された引数をどこに返すかについて一貫していない。ツールのページは、入力検証をツール実行エラーに含めており、これは結果として返る。スキーマリファレンスは、「無効なツール引数」を JSON-RPC エラー -32602 の下に挙げている(スキーマ、InvalidParamsError)。SDK はツールのページに従っており、本書も同じである。クライアントは実行エラーをモデルに渡す「べきである(SHOULD)」が、プロトコルエラーについては渡して「もよい(MAY)」とされているだけであり、仕様はそれを「回復に成功する可能性が低い」と述べている(ツールの「エラー処理」)。結果は、モデルが確実に読めると期待できる経路である。

実践ルール: すべての引数に、API が許す限り狭い型を付ける。ID にはパターン、固定値には enum、件数には範囲、日付には形式を使う。不正な呼び出しはコードが実行される前に SDK に拒否させ、すべての失敗を一度に返す。意味をスキーマに任せてはならない。有効な日付でも、誤った日付でありうるからである。スキーマで表現できないことはツールの内部で検査し、チケットでしばしば不完全になる値については、どう補うかを説明文に書く。

出力スキーマで構造化コンテンツを返す

最終変更:版2026.11.14

前の節で扱った入力にはスキーマがあり、結果にもスキーマを持たせることができる。ツールは outputSchema を宣言でき、その場合、結果は structuredContent を伴う。これは結果のデータを JSON として表したもので、プログラムがテキストを解析せずに読み取れる(tools、"Structured content")。ツールが出力スキーマを宣言した場合、サーバーはそれに適合する結果を返さなければならず("MUST")、クライアントはそれを検証すべきである("SHOULD")。構造化コンテンツを返すツールは、テキストしか読まないクライアントのために、同じ内容を JSON にシリアライズしてテキストブロックにも返すべきである("SHOULD")。同じ節には、structuredContent はサーバーが返す結果データであり、モデルの "structured outputs" とは無関係であるとの注記もある。

出力スキーマは、モデルよりもホスト側のコードの役に立つ。コードは、文中から "exceeds" を探す代わりに within_limit というフィールドで分岐でき、テストも文字列ではなくフィールドを検査できる。固定されたリビジョンでは、structuredContent は任意の JSON 値でよい(changelog)。リビジョン 2025-11-25 ではオブジェクトが必須であった(tools at 2025-11-25)。これについては Migrate a 2025-era server で扱う。

Python SDK は、関数の戻り値の型から出力スキーマを作る。プリミティブ型、None、リスト、ユニオンは {"result": ...} で包まれる。pydantic モデル、TypedDict、データクラス、dict[str, ...] は包まれない(structured output、mcp/server/mcpserver/utilities/func_metadata.py)。quote_refund は RefundQuote を返す。これは pydantic モデルで、見積もりの ID、注文、SKU、金額、ポリシー上限、within_limit、見積もりの有効期間(秒)を持つ。チケット T-0006 の注文 O-2289 を SKU なしで見積もると、見積もりは注文全体を対象とし、構造化された結果が得られる。次に、同じ金額を素の文字列として返すツールを一つだけ持つ第二のサーバーを用意し、ラッパーの働きを示す。

refund-quote-structured.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 合格
"""quote_refund returns a pydantic model, so the SDK publishes its output schema and returns structuredContent; a toolthat returns a bare string gets a {"result": ...} wrapper instead. The point rests on the bare structured content line,and the quote's within-limit flag and text block, which the code asserts."""import asyncioimport jsonfrom mcp import Clientfrom mcp.server.mcpserver import MCPServerfrom lib import loopback, shop_api, shop_toolsfrom lib.shop_data import load_shop, moneybare = MCPServer("bare-return")@bare.tool()def refund_amount(order_id: str) -> str:    """The refund for a whole order, as a decimal string."""    return money(load_shop().order(order_id).total_cents)async def main() -> None:    with loopback.serve(shop_api.create_app()) as base_url:        async with Client(shop_tools.server_params(base_url)) as client:            tools = {tool.name: tool for tool in (await client.list_tools()).tools}            print("output schema requires:", ", ".join(tools["quote_refund"].output_schema["required"]))            quote = await client.call_tool("quote_refund", {"order_id": "O-2289", "reason": "arrived cracked"})            shown = {**quote.structured_content, "quote_id": "(random)"}      # quote IDs differ on every run            print("structured content:", json.dumps(shown))            print("amount:", quote.structured_content["amount"])            print("within limit:", quote.structured_content["within_limit"])            assert quote.structured_content["within_limit"] is False            # the lifetime is in seconds; the prose gives it in minutes            print("quote lifetime minutes:", quote.structured_content["expires_in_seconds"] // 60)            # the text block a client that reads only text gets, parsed back to JSON            same_json = json.loads(quote.content[0].text) == quote.structured_content            print("text block is the same JSON:", same_json)            assert same_json    async with Client(bare) as client:                  # in-process: no wire needed to read a schema        tool = (await client.list_tools()).tools[0]        print("bare output schema:", json.dumps(tool.output_schema))        result = await client.call_tool("refund_amount", {"order_id": "O-2289"})        print("bare structured content:", json.dumps(result.structured_content))asyncio.run(main())
出力python refund-quote-structured.py
output schema requires: quote_id, order_id, sku, amount, policy_limit, within_limit, expires_in_seconds
structured content: {"quote_id": "(random)", "order_id": "O-2289", "sku": null, "amount": "180.00", "policy_limit": "150.00", "within_limit": false, "expires_in_seconds": 900}
amount: 180.00
within limit: False
quote lifetime minutes: 15
text block is the same JSON: True
bare output schema: {"properties": {"result": {"title": "Result", "type": "string"}}, "required": ["result"], "title": "refund_amountOutput", "type": "object"}
bare structured content: {"result": "180.00"}

見積もりの出力スキーマは quote_id, order_id, sku, amount, policy_limit, within_limit, expires_in_seconds を必須とし、構造化コンテンツにはそれらの各フィールドがある。金額 €180.00 はポリシーの上限を超えているため、within_limit は false である。このフラグが担当者の確認の起点になる様子は、結果ではなく入力要求を返すで扱う。テキストブロックには同じ JSON が入っており、コードがそれを確認している。

素の文字列を返すツールは、SDK が仕様に遅れている箇所を示す。固定されたリビジョンは文字列を構造化コンテンツとして許すが、SDK は依然としてオブジェクトでない値をすべて {"result": ...} で包み、それに合わせてオブジェクトのスキーマを公開する(mcp/server/mcpserver/utilities/func_metadata.py)。このツールの構造化コンテンツは、素の文字列ではなく {"result": "180.00"} である。文字列を期待して仕様どおりに書かれたホストは、代わりにオブジェクトを受け取る。すべてのツールからモデルを返せば、この問題は生じない。

構造化コンテンツは両側で検査される。SDK のクライアントは、成功した結果をすべて、tools/list から取得してキャッシュした出力スキーマに照らして検証する。構造化コンテンツが一致しない場合、または出力スキーマを持つツールが構造化コンテンツを返さなかった場合には RuntimeError を送出する(mcp/client/session.py、validate_tool_result)。SDK のサーバーも、送信前にツールの戻り値をそのツール自身のモデルに照らして検査する(mcp/server/mcpserver/utilities/func_metadata.py)。このため、不一致は変更があった側で失敗する。

実践ルール: すべてのツールに pydantic モデルを戻り値の型として与える。そうすれば SDK が出力スキーマを公開し、ラッパーなしで構造化コンテンツを返し、テキストブロックも自動で加える。ホスト側のコードが下す判断ごとに、within_limit のようなフィールドをモデルに置き、文中に埋もれさせない。素の文字列を返してよいのは、結果をどのコードも読まないツールだけである。

失敗をツール結果として報告する

最終変更:版2026.11.11

前の節で示した見積もりは、呼び出しが成功したときの結果である。呼び出しが失敗したとき、仕様は二つの経路のどちらかを与えている(toolsの "Error handling")。プロトコルエラーは JSON-RPC エラーであり、未知のツール、tools/callのスキーマに合わない要求、サーバーの障害に使われる。ツール実行エラーは isError を true に設定した通常の結果であり、API の失敗、無効な入力、業務ルール違反に使われる。本書の以降の部分でツールエラーと呼ぶ実行エラーについて、仕様は「言語モデルが自己修正に使える、実行可能なフィードバックを含む」と述べ、クライアントはそれらをモデルに渡す「SHOULD」とされている。

クライアントは実行エラーをモデルに渡すべきであり(SHOULD)、プロトコルエラーは渡してもよい(MAY)にとどまる。このため、どちらの経路を使うかによって、誰がその失敗を修正できるかが決まる。Python SDK では、ToolErrorを送出すると、指定したメッセージを持つ実行エラーが生成される。MCPErrorを送出すると、プロトコルエラーが生成される。それ以外の例外はクラッシュとして扱われる。このとき結果には "Error executing tool" とツール名だけが含まれ、例外はサーバーのログに残る(handling errors)。SDK のガイドは、この選択を一つの問いとして示している。より賢いモデルならこの失敗を避けられたか、という問いである。避けられたならToolErrorを送出し、避けられなかったならMCPErrorを送出する。

ショップのサーバーはこの基準に従っている。存在しない注文、返金できない注文、注文にない SKU、未知または期限切れの見積もりは、いずれもToolErrorであり、代わりに何をすべきかを述べたメッセージが付く。ショップの API からの 401 は、サーバーのキーが誤っていることを意味し、どのモデルにも修正できない。そのためサーバーは、JSON-RPC の内部エラーコードを付けてMCPErrorを送出する。API の停止など、それ以外のものはクラッシュのままとなる。意図的に失敗させる呼び出しは五つあり、コードが実行する順に並べると次のとおりである。

  1. モデルが読む説明を書くで改訂した説明に基づく、チケット T-0006 の記録済みの呼び出し。架空の SKU を含む。
  2. サーバーが発行していない見積もりを指定したissue_refund。
  3. 存在しないツール。
  4. 誤ったキーで起動したサーバーへの呼び出し。
  5. ショップの API が停止した後の呼び出し。
tool-error-versus-protocol-error.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 合格
"""Five failures and the path each takes: three tool execution errors the model reads (isError results), a crash themodel sees only as a generic message, and a protocol error (a JSON-RPC error) that only the host sees. The point restson which results are flagged as errors, and the code asserts that a missing tool is one of them."""import asynciofrom mcp import Client, MCPErrorfrom lib import loopback, shop_api, shop_toolsfrom lib.host import ReplayModel, choose_toolfrom lib.shop_data import load_shopasync def attempt(params, name: str, arguments: dict, label: str) -> object | None:    async with Client(params) as client:        try:            result = await client.call_tool(name, arguments)            print(f"{label} is error:", result.is_error)            print(f"{label} says:", result.content[0].text)            return result        except MCPError as error:            print(f"{label} JSON-RPC error code:", error.code)            print(f"{label} JSON-RPC error message:", error.message)            return Noneasync def main() -> None:    with loopback.serve(shop_api.create_app()) as base_url:        params = shop_tools.server_params(base_url)        async with Client(params) as client:          # T-0006's recorded choice, with the SKU the model made up            tools = (await client.list_tools()).tools        choice = choose_tool(ReplayModel("description-choices"), load_shop().ticket("T-0006"), tools)        await attempt(params, choice.tool, choice.arguments, "wrong SKU")        await attempt(params, "issue_refund", {"quote_id": "Q-0000000000"}, "unknown quote")        unknown = await attempt(params, "refund_order", {"order_id": "O-2289"}, "unknown tool")        assert unknown is not None and unknown.is_error  # a failed result, not a protocol error        # a key the shop's API rejects: the server answers with a protocol error, which the client raises        await attempt(shop_tools.server_params(base_url, api_key="wrong-key"), "get_order_status",                      {"order_id": "O-2289"}, "rejected key")    await attempt(params, "get_order_status", {"order_id": "O-2289"}, "API down")    # the API has stoppedasyncio.run(main())
出力python tool-error-versus-protocol-error.py
wrong SKU is error: True
wrong SKU says: Error executing tool quote_refund: Order O-2289 has no line for KG-1031. Its SKUs are KG-1043.
unknown quote is error: True
unknown quote says: Error executing tool issue_refund: There is no quote Q-0000000000. Call quote_refund for the order to get a quote_id.
unknown tool is error: True
unknown tool says: Unknown tool: refund_order
rejected key JSON-RPC error code: -32603
rejected key JSON-RPC error message: The shop's API rejected this server's key. The server needs reconfiguring.
API down is error: True
API down says: Error executing tool get_order_status

架空の SKU は実行エラーとして返され、そのテキストはモデルに欠けていた情報を与える。「Error executing tool quote_refund: Order O-2289 has no line for KG-1031. Its SKUs are KG-1043.」これを読んだモデルは、正しい SKU で再び呼び出すことができる。未知の見積もりのメッセージも同様に機能する。「Error executing tool issue_refund: There is no quote Q-0000000000. Call quote_refund for the order to get a quote_id.」

未知のツールの場合は、仕様からの逸脱が見られる。仕様の例では、未知のツールに対して JSON-RPC エラー -32602 を返すが、SDK のサーバーは代わりに実行エラーを返す(mcp/server/mcpserver/tools/tool_manager.py)。結果にはエラーの印が付き、そのテキストは「Unknown tool: refund_order」である。モデルにとっては、名前が誤っていたことが分かるため、こちらの方が有用な応答である。混乱したモデルを見つけるためにプロトコルエラーの数を数えているホストは、これらを検出できないため、実行エラーも数える必要がある。

誤ったキーの場合は、もう一方の経路をたどった。クライアントはMCPErrorを送出し、例はそれを JSON-RPC エラー -32603 として捕捉した。メッセージは「The shop's API rejected this server's key. The server needs reconfiguring.」である。ホストのコードはこれを受け取り、モデルはホストが渡した場合にだけこれを目にする。API が停止していたときは、モデルが受け取ったのは「Error executing tool get_order_status」だけであり、例外はサーバーのログに残った(handling errors)。

もう一つの誤りは、どちらの経路も通らないものである。エラーメッセージを通常の文字列として返すツールがそれにあたる。SDK は、返された文字列を isError を false にして送るため、モデルはそのエラーを成功した応答として読む(handling errors)。代わりに例外を送出する。

実践ルール: モデルが修正できる失敗にはすべてToolErrorを送出し、何が誤っていたか、代わりに何を送るべきかをメッセージに示す。有効な値が少数であれば、それも含める。MCPErrorは、設定の誤りなど、どのモデルにも修正できない失敗に限って送出し、予期しない例外は汎用的なままにして、内部の詳細がサーバーの中にとどまるようにする。エラーを単なる文字列として返してはならない。

この部分はまだ翻訳されていないため、英語で表示している。

Mark what a tool changes with annotations

最終変更:版2026.11.14

The errors in the previous section tell the model what went wrong after a call. A tool's annotations tell the host what a call will do before it's made, so the host can decide whether to ask for consent first. The specification wants a person able to say no to any tool call, as Let a model choose the tool quoted. A tool's annotations hold a title and four hints (schema, ToolAnnotations):

  • readOnlyHint: the tool doesn't change its environment. The default is false.
  • destructiveHint: a tool that changes something may destroy or overwrite data, rather than only add to it. The default is true.
  • idempotentHint: calling the tool again with the same arguments has no further effect. The default is false.
  • openWorldHint: the tool reaches entities outside a closed domain, such as the web. The default is true.

destructiveHint and idempotentHint mean something only when readOnlyHint is false. The defaults describe the worst case, so to a careful host a tool with no annotations is destructive, not idempotent, and reaches the open world. Annotations go into the Python SDK as ToolAnnotations(read_only_hint=..., destructive_hint=..., idempotent_hint=..., open_world_hint=...) to the tool() decorator (tools).

The shop's four reading tools carry read_only_hint=True and open_world_hint=False, because they only read the shop's own API. issue_refund is the one tool that changes something, and its hints are judgements. We set destructive_hint=False, because a refund adds a record and never overwrites one, and open_world_hint=False, because the tool talks only to the shop's API, which records the request for the shop's staff to pay. idempotent_hint=True is the hint that needs a guarantee behind it: the server returns the same refund for the same quote_id.

The code works out what a host should assume about each tool, filling in the default wherever a hint is missing, and applies a consent rule to the result. It includes the endpoint tool post_refunds, which has no annotations. Then it calls issue_refund twice with one quote, and POST /refunds twice with one amount.

annotate-the-refund-tool.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 合格
"""What each tool's annotations tell a host, with the specification's defaults filled in where a hint is missing, andwhether the server keeps issue_refund's idempotent promise when the same call arrives twice. The point rests on the tworefund pairs: issue_refund returns one refund both times, while two posts to the endpoint make two."""import asyncioimport httpx2from mcp import Clientfrom lib import loopback, shop_api, shop_tools# the specification's defaults, used for any hint a tool leaves outDEFAULTS = {"read_only_hint": False, "destructive_hint": True, "idempotent_hint": False, "open_world_hint": True}def assumed(annotations) -> dict:    """The hints a host should assume: each one the tool sets, and the specification's default for the rest."""    given = annotations.model_dump(exclude_none=True) if annotations else {}    hints = {hint: given.get(hint, default) for hint, default in DEFAULTS.items()}    if hints["read_only_hint"]:          # destructive and idempotent apply only to a tool that changes something        del hints["destructive_hint"], hints["idempotent_hint"]    return hintsasync def main() -> None:    with loopback.serve(shop_api.create_app()) as base_url:        async with Client(shop_tools.server_params(base_url)) as client:            tools = (await client.list_tools()).tools + shop_tools.endpoint_tools()[3:4]    # + post_refunds            for tool in tools:                hints = assumed(tool.annotations)                shown = ", ".join(h.removesuffix("_hint") for h, on in hints.items() if on) or "nothing"                print(f"{tool.name} assumes:", shown)                print(f"{tool.name} asks consent:", not hints["read_only_hint"])            quote = (await client.call_tool("quote_refund", {"order_id": "O-2415", "sku": "KG-1050"})).structured_content            first = await client.call_tool("issue_refund", {"quote_id": quote["quote_id"]})            again = await client.call_tool("issue_refund", {"quote_id": quote["quote_id"]})            print("issue_refund first refund:", first.structured_content["refund_id"])            print("issue_refund second refund:", again.structured_content["refund_id"])        # the amount the quote for KG-1050 gave, posted straight to the endpoint        twice = [httpx2.post(f"{base_url}/refunds", headers={"X-API-Key": shop_api.DEMO_API_KEY},                             json={"order_id": "O-2415", "amount": "23.98"}).json()["refund_id"] for _ in range(2)]        print("post_refunds first refund:", twice[0])        print("post_refunds second refund:", twice[1])asyncio.run(main())
出力python annotate-the-refund-tool.py
find_orders assumes: read_only
find_orders asks consent: False
get_order_status assumes: read_only
get_order_status asks consent: False
quote_refund assumes: read_only
quote_refund asks consent: False
issue_refund assumes: idempotent
issue_refund asks consent: True
check_stock assumes: read_only
check_stock asks consent: False
post_refunds assumes: destructive, open_world
post_refunds asks consent: True
issue_refund first refund: R-0111
issue_refund second refund: R-0111
post_refunds first refund: R-0112
post_refunds second refund: R-0113

Each of the four reading tools comes out as read_only, and issue_refund as idempotent: it isn't read-only, but it is neither destructive nor open-world. The unannotated post_refunds comes out as destructive, open_world, because that's what the defaults say. A host that asks for consent before any tool that isn't read-only asks before both refund tools and none of the others. The shop's host gets that rule in Ask for consent before side effects.

The two pairs of calls show why idempotent_hint=True is safe to claim for issue_refund and wouldn't be for the endpoint. Two calls of issue_refund with one quote returned R-0111 and R-0111: one refund, twice. Two identical posts to the API created R-0112 and R-0113: two refunds. The shop's API has no once-only check, so the server adds one. It stores the refund against its quote, under a lock, because the SDK runs synchronous tools on worker threads and two calls can arrive together.

アノテーションはヒントとして扱い、保証とは見なさない

プロトコルには、アノテーションがツールの実際の動作と一致しているかを検査する仕組みはない。仕様は、アノテーションが「ツールの動作を忠実に記述していることは保証されない」と述べ、信頼できるサーバーから提供されたものでない限り、クライアントはそれを信頼できないものとして扱わ「なければならない(MUST)」としている(schema、ToolAnnotations、tools)。返金ツールを読み取り専用と記したサーバーは、それを信じるホストの検査をすり抜けてしまう。Catch poisoned tool descriptionsでは、ツール定義が意図的に偽りを述べるサーバーを取り上げている。

サーバーの作者にとって、ヒントとはコードが守らなければならない約束である。この店の issue_refund が冪等であるのは、見積もりストアがそれを成り立たせているからであり、アノテーションがそう述べているからではない。再起動によってストアが失われた場合、再試行された呼び出しは二度目の返金ではなく「There is no quote」という結果を受け取ることになるが、これは依然として安全である。検査はサーバー側に置き、アノテーションはその検査内容の記述として扱う。

実践ルール: すべてのツールにアノテーションを付ける。ヒントを省くと、慎重なホストに最悪の場合を想定するよう告げることになるからである。ツールを冪等と記すのは、サーバーがそれを強制している場合に限る。返金や支払いなど、一度だけ行われなければならない処理は、サーバー側の検査の背後に置く。ホストとしては、信頼するサーバーのアノテーションをユーザーに何を提示するかの判断に用い、同意を省略する許可としては決して用いない(Ask for consent before side effects)。それ以外のサーバーのアノテーションは、すべて未検証の主張として扱う。

ツールの一覧を小さく保つ

最終変更:版2026.11.11

ホストは、前の各節のすべてのツールを、その説明と入力スキーマとともに、毎ターンモデルのプロンプトに入れる。モデルは選択を行う前に一覧全体を読む。ツールが増えるほどトークンの消費が増え、選択も難しくなる。MCP サーバーを用いたあるテストでは、リクエストに関連するツールだけを取得することで、選択の正確さが 13.62% から 43.13% へと 3 倍超に向上した(Gan and Sun, 2025)。エッジデバイスでは、小さなモデルに提示するツールを減らすと、関数呼び出しの成功率が上がり、実行時間が最大 70% 短縮された(Paramanayakam and others, 2025)。どちらも固有の条件で行われた単一の研究であるため、この店の数値としてではなく、効果の向きを示すものとして読むべきである。

このコストは、推測するよりも測定するほうが容易である。録画用スクリプトは、実行時に、録画に使うモデルのトークナイザーを用いて、各ツールがホストのプロンプトで占めるトークン数も数えた。このチェックは、改訂後のツール、モデルが読む説明を書くで扱った曖昧な説明のツール、およびエンドポイントのツールについて、そのトークン数を合計し、バイト数を測定する。トークン数を数えた後にツールが変更されている場合、チェックは実行を拒否する。

tool-list-size.py Python 3.12.15 · cryptography 50.0.2 · httpx2 2.16.2 · mcp 2.3.0 · mcp-types 2.3.0 · pydantic 2.14.3 · starlette 1.10.0 · uvicorn 0.54.0 合格
"""What the shop's tool list costs in the host's prompt: bytes, and tokens counted with the recording model's tokenizerwhen the recording was made (examples/data/recorded/description-choices/prompt_tokens.json). The point rests on therevised, vague and endpoint prompt token lines."""import asyncioimport hashlibimport jsonfrom mcp import Clientfrom lib import shop_toolsfrom lib.host import RECORDED, tool_specs# the token counts and line hashes the recording script wrotecounted = json.loads((RECORDED / "description-choices" / "prompt_tokens.json").read_text())def cost(label: str, tools) -> tuple[int, int]:    """Bytes and tokens of the tools as the host's prompt renders them, one JSON line per tool."""    lines = [json.dumps(spec, ensure_ascii=False) for spec in tool_specs(tools)]    # the hash of each line as the host renders it; a tool that changed since then fails here    for spec, line in zip(tool_specs(tools), lines):        if counted[label][spec["name"]]["sha256"] != hashlib.sha256(line.encode()).hexdigest():            raise LookupError(f"{spec['name']} changed since its tokens were counted: re-run the recording script")    tokens = sum(counted[label][spec["name"]]["tokens"] for spec in tool_specs(tools))    return sum(len(line.encode()) for line in lines), tokensasync def main() -> None:    async with Client(shop_tools.create_server()) as client:        result = await client.list_tools()    listed = result.tools    print("tools/list result bytes:", len(result.model_dump_json(by_alias=True, exclude_none=True).encode()))    vague = shop_tools.with_descriptions(listed, shop_tools.VAGUE_DESCRIPTIONS)    for label, tools in (("revised", listed), ("vague", vague), ("endpoint", shop_tools.endpoint_tools())):        size, tokens = cost(label, tools)        print(f"{label} prompt bytes:", size)        print(f"{label} prompt tokens:", tokens)    tokens_per_tool = cost("revised", listed)[1] / len(listed)  # cost returns (bytes, tokens): index 1 is tokens    print("revised tokens per tool:", round(tokens_per_tool))    print("20 such tools tokens:", round(20 * tokens_per_tool))       # arithmetic on the counts, not a count    print("prompt without tools tokens:", counted["prompt_without_tools"])    print("recording context tokens:", counted["context"])asyncio.run(main())
出力python tool-list-size.py
tools/list result bytes: 8049
revised prompt bytes: 3417
revised prompt tokens: 970
vague prompt bytes: 1945
vague prompt tokens: 620
endpoint prompt bytes: 1014
endpoint prompt tokens: 288
revised tokens per tool: 194
20 such tools tokens: 3880
prompt without tools tokens: 136
recording context tokens: 4096

コストの大半はスキーマにある。この店の改訂後の 5 つのツールは、プロンプトの中で 970 トークンを占める。ホストのそれ以外の指示は 136 トークンである。曖昧な説明では 620 トークンになるため、改訂後の説明は一覧のコストの約 3 分の 1 を占める。エンドポイントのツールは 288 トークンである。説明は 1 行だけで、スキーマにはパターンも列挙型も独自の説明もない。改訂後のスキーマは、JSON Schema で入力に型を付けるで不正な引数を検出したものと同じである。tools/list の完全な結果はさらに大きい。出力のバイト数が示すとおり、ホストのプロンプトには含まれない出力スキーマ、タイトル、アノテーションも含むためである。

1 ツールあたり約 194 トークンとすると、このようなツール 20 個は、モデルがチケットを読む前に約 3880 トークンを占める。これは録画の実行に使うコンテキスト 4096 トークンのほぼすべてに当たる。この数値は測定ではなく計算であり、実際のツールの大きさはさまざまである。一覧が短くなれば、2 つの説明が重なる可能性も下がる。これは、草稿で get_order_status と quote_refund に生じた問題であった(モデルが読む説明を書く)。

サーバーが一覧を短く保つには、1 種類の利用者に絞って提供する。この店のサーバーはサポートチケットを扱うため、在庫の再集計はその一覧にない。固定したリビジョンでは、サーバーは 1 つの接続のために一覧を絞り込むことはできない。ただし、一覧はリクエストが示す認可によって変わりうるものであり、順序は固定されている(一覧の結果をキャッシュする)。その節では結果に付くキャッシュのヒントを扱い、トークンが許可する範囲でツールを絞るでは、トークンによって変わる一覧を示す。

実践ルール: 各サーバーには 1 種類の利用者と、その利用者のタスクに必要な少数のツールだけを割り当て、一覧がホストのプロンプトで占めるコストを測定する。トークンは、スキーマと、モデルが混同する 2 つのツールを区別する一文に使い、スキーマと重複する説明文は削る。ホストが、モデルが適切に選択できる数より多くのツールを必要とする場合は、1 つのサーバーの一覧を接続に依存させるのではなく、ツールを複数のサーバーに分け、会話に必要なサーバーだけを接続する。

本番環境で起きる問題

最終変更:版2026.11.11

このショップのサーバーは、1台のマシン上で8件のチケットを処理する限りでは正しく動作する。しかし、チケットのキュー全体と実際のデプロイでは、ツール設計は次のような見分けやすい形で失敗する。

モデルが区別できない2つのツール。 モデルが読む説明を書くの説明文の草稿では、モデルは見積もりを出すべき注文を検索だけで済ませてしまった。本番では、対応するチケットの数に比べて呼び出し回数が極端に多い、または少ないツールや、1つで足りるのに2つのツールが続けて呼ばれる状況が兆候となる。ラベル付きのチケットに照らしてツールの選択回数を数え(正しいツールが選ばれる頻度を測る)、2つのツールを分ける文を修正する。

モデルが実際の値として送ってしまう例の値。 3件の返金チケットのうち1件で、モデルはskuパラメーターの説明にある例のSKUを、顧客が書いたものであるかのように送った。KG-1031は実在する製品であるため、そのSKUが注文に含まれているかを確かめる検査がなければ、ツールは誤った商品を見積もっていた。このショップの説明が実在の例のIDを残しているのは、記録をそれらのIDで行ったからにすぎない。兆候は、実際のトラフィックでは説明がつかないほど頻繁に、例の値が引数に現れることである。各引数をそれが属するレコードに結び付ける検査を維持し、使用中の範囲外のIDなど、実在し得ない例を選ぶ。

コードとずれていく出力スキーマ。 SDKのクライアントは、tools/listからキャッシュした出力スキーマに照らして各結果を検証し、両者が一致しなければRuntimeErrorを送出する(mcp/client/session.py)。フィールドを削除または変更したサーバーをリリースし、古い一覧をキャッシュしたクライアントがそれに接続すると、そのツールへのすべての呼び出しが失敗する。サーバーのリリース後、ホストにRuntimeError: Invalid structured contentが現れる。出力スキーマは契約として扱い、テストする(スキーマを契約として検査する)。

モデルが読めないクラッシュ。 ToolErrorまたはMCPError以外のすべての例外は、「Error executing tool」とだけ書かれてモデルに届く。会話の中に理由がないまま、同じ呼び出しを繰り返したり、あきらめたりするモデルに注意する。サーバーの標準エラー出力を読み、モデルが修正できる失敗をそれぞれToolErrorに変える。

プロセスとともに失われるハンドル。 このショップの見積もりはサーバーのメモリ上にある。再起動すると未確定の見積もりがすべて失われ、モデルは数分前に作った見積もりについて「There is no quote」と返される。1つのアドレスの背後に複数のレプリカがある場合は、失うものがさらに増える。あるレプリカで作った見積もりは、別のレプリカには知られていないからである。サーバーが複数のプロセスで動くようになったら、ハンドルは共有ストレージに保持する(スティッキーセッションなしでレプリカを動かす)。

サーバー間で衝突するツール名。 2つのサーバーに接続したホストでは、get_order_statusという名前のツールが2つ見えることがある。仕様は、ホストが曖昧さを解消すべきである(「SHOULD」)とし、たとえば各名前にサーバー識別子を接頭辞として付ける方法を挙げており(toolsの「Tool names」)、サーバーをまたいでツールに名前を付けるでその仕組みを作る。

ヘッダー内の個人データ。 x-mcp-headerを付けたパラメーターは、Streamable HTTPでは値がHTTPヘッダーにコピーされ、プロキシやログから見える状態になる。仕様は、個人データを含む機微なパラメーターにこの印を付けることを、サーバーは「SHOULD NOT」としている(tools)。したがって、顧客IDやメールアドレスには決して付けてはならない。このヘッダーについてはStreamable HTTPで提供するで扱う。

実践ルール: ショップのツールを本番に出す前に、出荷するモデルが実際のチケットのラベル付きサンプルでツールを選ぶ様子を記録し、モデルが修正できるすべての失敗が有用なメッセージ付きのToolErrorとして返ることを確認し、各出力スキーマを契約テストの対象にする。リリース後は、ツールの選択回数、引数に現れる例の値、ホストに現れるRuntimeErrorを監視する。

この章での決定事項

最終変更:版2026.11.11
  • エンドポイントごとにツールを用意するのではなく、タスク単位のツールを五つ用意する。 find_orders、get_order_status、quote_refund、issue_refund、check_stockであり、lib.shop_toolsに置く。在庫の再集計はサポート用サーバーに含めない。
  • 返金は見積もりと実行に分ける。 quote_refundは金額を計算し、15分間有効なquote_idを返す。issue_refundが受け取るのは、このハンドルだけである。
  • サーバーは呼び出し側のcustomer_idを信頼する。 また、quote_idはランダムな値だが短く、どの顧客にも結び付いていない。Secure tools against misuseでは、操作するユーザーを引数からではなく検証済みトークンから取得することで、この問題に対処する。
  • 同意の確認はまだ行わない。 ポリシーの上限の範囲内であれば、issue_refundは人に確認せずに実行される。ホストによる同意の確認は、Ask for consent before side effectsで扱う。
  • 説明文はdescription=として渡す。 説明文は一つの辞書にまとめてある。各説明文には、そのツールが何をするか、隣り合うツールではなくそのツールを使うべき場面、入力、結果を記す。説明文は、八件のチケットに対する一つのモデルの選択記録をもとに一度だけ改訂した。実行結果が評価するのは改訂全体であり、個々の文ではない。
  • すべての引数にAnnotated[..., Field(...)]で狭い型を付ける。 ID にはパターン、status には enum、limitには範囲、placed_sinceには日付を用いる。
  • すべてのツールは pydantic モデルを返す。 そのため SDK は出力スキーマを公開し、{"result": ...}のラッパーなしで構造化コンテンツを送る。
  • 拒否された引数は実行エラーとして返す。 仕様のツールのページと SDK がこの形を採っており、モデルはエラーを読んで呼び出しを修正できる。
  • モデルが修正できる問題にはToolErrorを使い、 メッセージには有効な値を含める。拒否された API キーにはMCPErrorを使う。それ以外は、汎用的なクラッシュのままにする。
  • すべてのツールにアノテーションを付ける。 読み取り用のツールは読み取り専用で、クローズドワールドである。issue_refundは追加的で、クローズドワールドで、冪等である。このヒントの裏には、サーバーによる一度限りのチェックがある。
  • 他のサーバーのアノテーションは信頼しない。 同意の要否は、アノテーションだけに依存させない。
  • 見積もりはサーバーのメモリ上に保持する。 これが成り立つのは、一つの stdio プロセスの間だけである。レプリカを使う場合は共有ストアが必要になる。

この版における本章

第2026.11.14版2026年11月19日時点で例が通過この章の7 例件のうち7件が合格

英語版の書籍(版2026.11.14)から翻訳した。

この節を引用する

形式

いずれの形式も、本訳書が従う英語版の書籍を出典として示す。

いずれの形式もこの版を明示している。そのリンクは現行版を開き、節の見出しには本文が最後に変更された日付が示される。アクセス日と取得日は、これを開いた日である。

このページの内容

全12章中の第3章: モデルが使えるツールを設計する

  1. Shape tools around tasks, not endpoints
  2. Write descriptions the model reads
  3. JSON Schema で入力に型を付ける
  4. 出力スキーマで構造化コンテンツを返す
  5. 失敗をツール結果として報告する
  6. Mark what a tool changes with annotations
  7. アノテーションはヒントとして扱い、保証とは見なさない
  8. ツールの一覧を小さく保つ
  9. 本番環境で起きる問題
  10. この章での決定事項

ページの先頭に戻るすべての章