设计模型可以使用的工具

阅读约需 89分钟 分钟,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 目前只有一个工具: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.

编写供模型阅读的描述

最近一次修改见于版次 2026.11.11

上一节的任务工具只有在模型选对工具时才有用,而模型是根据宿主展示给它的内容来选择的。本书的宿主循环 lib.host 会向模型展示每个工具的名称、描述和输入模式。规范把描述称为一种“提示”,客户端可以用它来“提高大语言模型对可用工具的理解”(schema,Tool.description)。

已发布的描述大多质量不佳。一项针对 103 个服务器上 856 个工具的研究发现,97.1% 的工具至少存在一处缺陷,56% 的工具没有明确说明自己的用途(Hasan and others, 2026)。在一项对照测试中,两个工具的接口完全相同,只修改其中一个工具的描述,在所测的两个模型上,该工具的使用次数就达到原来的 10 倍以上(Faghih and others, 2025)。更长并不一定更好。在第一项研究中,完全重写的描述使任务成功率的中位数提高了 5.85 个百分点,但步骤增加了 67%,并且在 6 个案例中有 1 个变得更差。

有帮助的描述要说明四件事:工具做什么,什么时候应使用它而不是与它相近的工具,输入是什么样子,以及返回什么。在 Python SDK 中,工具的描述就是其函数的文档字符串,除非向装饰器(decorator)传入 description=(tools)。在本书所用的运行环境 Python 3.12.15 上,SDK 会原样传递文档字符串(mcp/server/mcpserver/tools/base.py),因此跨越多行的文档字符串会把其中的换行和缩进一并发送给模型。商店的服务器把所有描述放在一个字典 DESCRIPTIONS 中,并把每一条作为 description= 传入。

该示例向模型展示八张工单和商店的五个工具,共进行三次,每次使用一组不同的描述。只有描述不同。

  • 模糊组每个工具只有一行,是端点生成器会写出的那种,例如“退款报价。”
  • 初稿组是商店的第一稿,写成文档字符串。
  • 修订组是商店的第二稿,在阅读初稿的结果之后写成。

这八张工单是从商店的工单队列中手工挑选的,并非抽样:两张询问客户有哪些订单,两张询问订单在哪里,三张与退款有关,一张与库存有关。其中没有注入的指令,也没有输错的订单 ID。运行之前,请先预测模糊组和初稿各有多少张工单的第一次调用是正确的。

所用模型是本书所有录制都使用的那一个:Qwen3-4B-Instruct-2507,在 CPU 上通过 llama.cpp 运行,设置方式见让模型选择工具。脚本 recordings/description_choices.py 生成了这次录制 description-choices,每张工单采样一个回复,温度设为 0.7,并使用一个固定的种子。评分只看模型调用的第一个工具,不看其参数。一张工单的正确首个工具是商店数据为它标注的那个,但有一处改动:issue_refund 需要 quote_id,因此退款请求要从 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

模糊组为 5 of 8 张工单选对了第一个工具,初稿的结果相同,为 5 of 8。仅凭名称和参数,四张订单工单和库存工单就都能选对,所以三组对每张工单选择的正确工具都相同。初稿更长的措辞对三张退款工单没有帮助,这三张工单上各组的选择不同。工单 T-0006 讲的是一份订单“到货时珐琅炒锅裂了。你们能退我多少钱”,模糊组给出 get_order_status,初稿给出 get_order_status。

初稿说明了 quote_refund 的作用,却没有说明它使查询订单变得不必要。修订在两个工具中都写明了这一点。get_order_status 把退款问题转给 quote_refund,而 quote_refund 要求先被调用,因为“它会自己检查订单”。不过,修订改动的不止这些。它重写了 quote_refund 的描述开头,并且改为以 description= 传入而不是写成文档字符串,从而去掉了初稿的换行和缩进。做了这三处改动后,修订组为 8 of 8 张工单选对了第一个工具。这次运行并未表明是哪一处改动起了作用。

修订纠正了工具的选择,却没有纠正参数:三次退款调用都不会成功。对于 T-0006,模型发送的 SKU 是 KG-1031,这是 sku 参数自身描述中的示例,而它发送的三个 SKU 都不在该订单中。把失败作为工具结果报告介绍了商店的服务器如何捕获这类错误。T-0013 的日期在三组描述下都是错的,下一节会说明原因。

请把这些计数当作一次测量。它们来自一个模型、一个种子,以及手工挑选的八张工单,换一个种子可能会改变部分选择。修订是在阅读同样这八张工单的结果之后写成的,所以它的得分偏高。衡量正确工具被选中的频率在整个工单队列上测量选择,那才是起决定作用的测试。

工作准则: 每条描述写两到四句话:工具做什么,什么时候应使用它而不是最容易与它混淆的工具,输入是什么样子,以及返回什么。请以 description= 传入,而不要依赖多行文档字符串,这样模型读到的就恰好是你写下的文字。然后,录制你要发布的模型为真实工单选择工具的过程,阅读错误的选择,并修改这些选择所指向的描述。需要知道哪一处改动起了作用时,每次录制只改一处,并在撰写该改动时没有用到的工单上检验结果。

用 JSON Schema 为输入定型

最近一次修改见于版次 2026.11.11

上一节中的描述告诉模型工具需要什么,而输入模式则让服务器强制执行这些要求。每个工具都有一个 inputSchema,它是根节点带有 "type": "object" 的 JSON Schema 对象。在固定的修订版本中,其中可以出现任何 JSON Schema 2020-12 关键字(变更日志),包括 oneOf、if、then、else 和 $ref(模式,Tool.inputSchema)。没有 $schema 字段的模式按 2020-12 解读;对于指向网络 URI 的 $ref,实现“MUST NOT”自动跟随(基础协议),因此默认情况下,模式无法让客户端下载任何内容。

模式承担两项工作。它向模型展示有效调用的形状,也让服务器在工具的任何代码运行之前拒绝无效调用。规范把服务器这一半的职责定为一项要求:服务器“MUST”验证所有工具输入(工具,“Security considerations”)。

Python SDK 根据函数的类型提示构建模式,而 pydantic 的 Annotated[..., Field(...)] 为这些提示添加约束(工具)。商店的服务器只定义一次各 ID 类型。OrderId 是带有 pattern=r"^O-\d{4}$" 的字符串,CustomerId 和 Sku 的做法与之相同。find_orders 的 status 是五种订单状态的 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",limit 的取值范围对应 minimum 和 maximum。带有三个错误参数的调用返回了一个失败结果,其文本列出了每个失败的参数、违反的规则以及发送的值。模型可以在下一次调用中一并纠正这三处错误。

SDK 在一点上比模式更宽松。模式规定 limit 是整数,但发送 "5" 的调用却成功了,并返回了 5 个订单。负责验证参数的 Pydantic 默认会把数字字符串转换为整数。这在此处无害。如果字符串与数字必须保持区分,请用 Field(strict=True) 声明该字段。Pydantic 还会不报错地丢弃模式中未声明的任何参数(mcp/server/mcpserver/utilities/func_metadata.py),防止服务器沦为被欺骗的代理一节依赖这一行为。

日期是任何模式都无法发现的错误。工单中的“12 Jun”没有年份,而模型发送了 2023-06-12,这是一个有效日期,比商店数据的结束时间早三年。该调用通过了验证,并返回了 5 个订单,即该客户的全部订单,而不是商店当年 6 月 12 日以来下的 1 个订单。模式检查的是形式,含义必须另有来源,例如由宿主把工单的日期放进提示,或者由描述说明如何解读没有年份的日期。

对于被拒绝的参数应当放在何处,规范并不一致。其工具页面把输入验证列入工具执行错误,这类错误以结果的形式返回。其模式参考则把“invalid tool arguments”列在 JSON-RPC 错误 -32602 之下(模式,InvalidParamsError)。SDK 遵循工具页面,本书也是如此。客户端“SHOULD”把执行错误传给模型,但对协议错误只是“MAY”传递,规范称协议错误“less likely to result in successful recovery”(工具,“Error handling”)。结果是模型可以指望读到的路径。

工作准则: 在 API 允许的范围内,把每个参数的类型定得尽量窄:ID 用模式,固定取值用枚举,数量用边界,日期用格式。让 SDK 在你的代码运行之前拒绝错误调用,并一次返回所有失败。不要指望模式承载含义,因为有效的日期仍可能是错误的日期。在工具内部检查模式无法表达的内容,并在描述中说明如何填写工单中常常不完整的取值。

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

Return structured content with an output schema

最近一次修改见于版次 2026.11.14

The inputs from the previous section have a schema, and results can have one too. A tool may declare an outputSchema, and its result then carries structuredContent: the result's data as JSON that a program can read without parsing text (tools, "Structured content"). When a tool declares an output schema, the server "MUST" return results that conform to it, and clients "SHOULD" validate them. A tool that returns structured content "SHOULD" also return it serialized as JSON in a text block, for clients that read only text. The same section notes that structuredContent is the server's result data, unrelated to a model's "structured outputs".

The output schema serves the host's code more than the model. Code can branch on a field called within_limit instead of searching a sentence for "exceeds", and a test can check a field instead of a string. structuredContent may be any JSON value at the pinned revision (changelog). Revision 2025-11-25 required an object (tools at 2025-11-25), which Migrate a 2025-era server covers.

The Python SDK builds the output schema from the function's return type. Primitive types, None, lists and unions are wrapped in {"result": ...}. Pydantic models, TypedDicts, dataclasses and dict[str, ...] aren't (structured output; mcp/server/mcpserver/utilities/func_metadata.py). quote_refund returns RefundQuote, a pydantic model with the quote's ID, the order, the SKU, the amount, the policy limit, within_limit and the quote's lifetime in seconds. Quoting order O-2289 for ticket T-0006 with no SKU, so the quote covers the whole order, shows the structured result. A second server then has one tool that returns the same amount as a bare string, to show the wrapper.

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"}

The quote's output schema requires quote_id, order_id, sku, amount, policy_limit, within_limit, expires_in_seconds, and the structured content has each of those fields. Its amount, €180.00, is more than the policy's limit, so within_limit is false, and Return an input request instead of a result is where that flag starts a person's confirmation. The text block holds the same JSON, as the code checks.

The bare tool shows where the SDK lags the specification. The pinned revision allows a string as structured content, but the SDK still wraps any value that isn't an object in {"result": ...}, and publishes an object schema to match (mcp/server/mcpserver/utilities/func_metadata.py). The bare tool's structured content is {"result": "180.00"}, not the bare string. A host written to the specification that expects a string gets an object instead. Return a model from every tool and the question never comes up.

Both sides check structured content. The SDK's client validates every successful result against the output schema it cached from tools/list. It raises a RuntimeError when the structured content doesn't match, or when a tool with an output schema returns none (mcp/client/session.py, validate_tool_result). The SDK's server also checks a tool's return value against the tool's own model before sending it (mcp/server/mcpserver/utilities/func_metadata.py), so a mismatch fails on whichever side changed.

Working rule: Give every tool a pydantic model as its return type, so the SDK publishes an output schema, returns structured content with no wrapper, and adds the text block for you. Put a field in the model for each decision the host's code makes, such as within_limit, rather than leaving it in a sentence. Return a bare string only from a tool whose result no code reads.

将失败作为工具结果报告

最近一次修改见于版次 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.

把注解视为提示,而非保证

协议并不会核对注解与工具的实际行为是否一致。规范指出,注解“不保证能如实描述工具行为”,并要求客户端“必须”将注解视为不可信,除非它们来自受信任的服务器(schema,ToolAnnotations;tools)。如果某个服务器把退款工具标为只读,那么任何轻信该标记的宿主都会放行它。识别被投毒的工具描述展示了一个故意在工具定义中说谎的服务器。

对服务器的作者来说,提示是代码必须兑现的承诺。商店的 issue_refund 之所以是幂等的,是因为报价存储保证了这一点,而不是因为注解这样声明。假如重启导致存储丢失,重试的调用会得到“不存在该报价”,而不是第二次退款,这样仍然是安全的。检查应保留在服务器中,注解只是对这项检查的描述。

工作准则: 为每个工具添加注解,因为省略提示会让谨慎的宿主按最坏情况处理。只有在服务器确实强制保证幂等时,才将工具标为幂等;退款、支付以及其他只能发生一次的操作,都应由服务器上的检查来把关。作为宿主,应使用受信任服务器的注解来决定向用户展示什么,绝不能把它当作跳过用户同意的许可(在产生副作用前征求同意),并将其他所有服务器的注解视为未经验证的声明。

保持工具列表精简

最近一次修改见于版次 2026.11.11

宿主在每一轮都会把前面几节中的每个工具连同其描述和输入模式放进模型的提示词,模型在选择之前会读完整个列表。工具越多,消耗的词元越多,选择也越困难。在一项针对 MCP 服务器的测试中,只检索与请求相关的工具,使选择准确率提高了两倍多,从 13.62% 升至 43.13%(Gan 和 Sun,2025)。在边缘设备上,给小模型提供更少的工具,提高了它们的函数调用成功率,并将执行时间最多缩短了 70%(Paramanayakam 等,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

成本大部分在模式上。商店中修订后的五个工具在提示词中占 970 个词元,而宿主其余指令占 136 个。使用含糊的描述时,它们占 620 个,因此修订后的描述约占列表成本的三分之一。端点工具占 288 个:描述只有一行,模式中没有 pattern、枚举,也没有各自的描述。修订后的模式,就是在用 JSON Schema 约束输入中拦下错误参数的那些模式。完整的 tools/list 结果还要更大,因为它还包含输出模式、标题和注解,而宿主的提示词不包含这些内容,输出中的字节数也说明了这一点。

按每个工具约 194 个词元计算,20 个这样的工具在模型读到工单之前就要占用约 3880 个词元:几乎是录制所用的 4096 词元上下文的全部。这个数字是算术推算,不是测量结果,实际工具的大小各不相同。列表更短,也会降低两条描述相互重叠的可能性,而草稿中 get_order_status 与 quote_refund 的问题正是如此(见编写供模型阅读的描述)。

服务器要让列表保持精简,办法是只服务于一类受众。商店的服务器服务于支持工单,所以库存盘点工具不在其中。在固定的修订版本下,服务器无法为某个连接裁剪列表,不过列表可以随请求所携带的授权而不同,并且按固定顺序返回(缓存列表结果)。该节介绍结果上的缓存提示,按令牌允许的范围限定工具则展示了随令牌而变化的列表。

工作准则: 让每个服务器只服务一类受众,只提供该受众的任务所需的少量工具,并测量列表在你的宿主提示词中的开销。把词元花在模式上,以及用来区分模型容易混淆的两个工具的那句话上,删去重复模式内容的描述文字。当宿主需要的工具超过其模型能够良好选择的数量时,把工具拆分到多个服务器上,只连接某次对话所需的服务器,而不要让一个服务器的列表取决于连接。

生产环境中会出什么问题

最近一次修改见于版次 2026.11.11

这家商店的服务器在一台机器上处理八张工单时运行正常。但面对整个工单队列和真实部署,工具设计会以几种常见的方式出错。

模型无法区分的两个工具。 编写供模型阅读的描述中的描述草稿,让模型去查询本应直接报价的订单。在生产环境中,这种问题的迹象是:某个工具被调用的次数远多于或远少于它所服务的工单数,或者本来一个工具就够用,却先后调用了两个工具。请对照已标注的工单统计工具选择情况(衡量正确工具的选择频率),并修改用来区分这两个工具的那句话。

模型当作真实值发送的示例值。 在三张退款工单中,有一张的情况是:模型把 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”。若多个副本共用一个地址,损失更大,因为在一个副本上生成的报价,下一个副本并不知道。一旦服务器以多个进程运行,就应把句柄保存在共享存储中(在没有粘性会话的情况下运行多个副本)。

跨服务器冲突的工具名称。 连接了两台服务器的宿主,可能会看到两个都叫 get_order_status 的工具。规范规定宿主“SHOULD”消除歧义,例如为每个名称加上服务器标识符作为前缀(tools,“Tool names”),而跨服务器命名工具一节就实现了这一做法。

请求头中的个人数据。 在 Streamable HTTP 上,被标记为 x-mcp-header 的参数,其值会被复制到 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虽然随机,却很短,也不与任何客户绑定。保护工具免遭滥用的处理办法是从已验证的令牌中获取执行操作的用户,而不是从参数中获取。
  • **目前还没有征得同意的环节。**在策略限额之内,issue_refund无需询问任何人即可运行;宿主的同意机制将在产生副作用之前征求同意中介绍。
  • **描述以description=的形式传入,**全部来自同一个字典。每条描述说明工具的作用、何时应使用它而不是相邻的工具、它的输入以及它的结果。描述曾修订一次,依据是某个模型在八张工单上的选择记录;这次运行将改进归功于修订的整体,而不是其中任何一句话。
  • **每个参数都用Annotated[..., Field(...)]做了严格的类型限定:**ID 使用正则模式,状态使用枚举,limit使用取值范围,placed_since使用日期。
  • **每个工具都返回一个 pydantic 模型,**因此 SDK 会发布输出模式,并发送不带{"result": ...}包装的结构化内容。
  • **被拒绝的参数以执行错误的形式返回,**这与规范的工具页面和 SDK 的做法一致,模型因此可以读取错误并修正其调用。
  • **模型能够修正的问题使用ToolError,**并在消息中给出有效取值;被拒绝的 API 密钥使用MCPError;其余情况一律仍按通用崩溃处理。
  • **每个工具都带有注解。**读取类工具是只读的,并且是封闭世界的。issue_refund是增量式、封闭世界且幂等的,提示背后有服务器的一次性检查作为支撑。
  • **来自其他服务器的注解不可信,**同意与否绝不单独取决于这些注解。
  • **报价保存在服务器的内存中,**这对单个 stdio 进程成立。多个副本则需要共享存储。

本章,在本版次中

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

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

引用本节

格式

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

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

本页内容

第 3 章,共 12 章: 设计模型可以使用的工具

  1. Shape tools around tasks, not endpoints
  2. 编写供模型阅读的描述
  3. 用 JSON Schema 为输入定型
  4. Return structured content with an output schema
  5. 将失败作为工具结果报告
  6. Mark what a tool changes with annotations
  7. 把注解视为提示,而非保证
  8. 保持工具列表精简
  9. 生产环境中会出什么问题
  10. 本章的决定

返回顶部全部章节