Serve data as resources and prompts
阅读约需 86分钟 分钟,8节中含5个示例。
这部分尚未翻译,因此以英文显示。
By the end of this chapter you can publish the shop's policies and records as Model Context Protocol resources, address many records with one resource template, complete an argument while a user types it, tell a client when a resource changes, and package a refund review as a prompt the user can pick. The chapter's claims, and the code behind them, hold for mcp 2.3.0, the Python SDK, at revision 2026-07-28 of the specification.
The shop sells kitchen and garden goods, and most of what its support team's host needs to answer a ticket is something to read, not something to do. Separate the host, the client and the server gave the shop's server, shop-support, one capability of each kind: the tool get_order_status, the refund policy as a resource, and a short review_refund prompt. One document and one prompt don't cover it. Every refund answer must follow the refund policy, a ticket is about one order, and a stock question is about one product's count. If each of those is a tool, the model has to decide to fetch it, and it may not.
For this, a Model Context Protocol (MCP) server has two other primitives, which differ from tools in who decides when they're used (Put each capability in the right primitive). A resource is data the server publishes under a URI, and the host decides whether to put it in front of a model. A prompt is a message template the server offers, and the user picks it. This chapter builds both out for the shop.
The server keeps the name shop-support throughout. Each example defines only the part its section teaches, and runs itself as chapter 2's server examples do: with no arguments, the file starts a client that launches the same file with --serve over stdio.
这部分尚未翻译,因此以英文显示。
Expose the policies as resources
shop-support already publishes one of the rules an answer must follow, the refund policy, which Resources are data the application chooses showed how to serve, and the shop has five more. Each one suits a resource: data that a server publishes under a URI, with a name, an optional title and description, a mimeType, and contents that are either text or a base64 blob (resources). A client lists a server's resources with resources/list and reads one with resources/read.
Resources are application-driven: the host decides how they're used. The specification's resources page says a host might show a picker, search the resources, or include some automatically, based on heuristics or the model's own selection. The protocol gives the model no way to read a resource; the host decides, though it may let the model choose. A resource's URI follows RFC 3986, and a server may use a scheme of its own. The specification keeps https:// for resources a client can fetch without the server, directly from the web.
The six are the shop's policies, short rules written for this book on refunds, returns, shipping, stock, data handling and escalation. They are Markdown files in examples/data/shop/policies/, licensed CC BY 4.0 with the book's text and listed in the data card, examples/data/shop/README.md. lib.policies reads each one's title, Updated: date and one-sentence summary, so the server can describe every policy without opening the files on each request.
The server publishes each policy as a static resource at shop://policies/{slug}. The refund policy keeps the URI shop://policies/refund and the name refund-policy that chapter 2 gave it. The SDK's FileResource reads the file again on every resources/read, so an edited policy reaches the next read without a restart (mcp/server/mcpserver/resources/types.py). A resource's annotations are three hints the host may use or ignore (resources):
audiencesays who the content is for. The policies are forassistant, the model.priority, from 0.0 to 1.0, says how important the content is, and 1 means "effectively required". We give the refund policy 1.0 and the others 0.5. That is a judgement: every refund answer must follow the refund policy, while the other five matter only for some tickets.lastModifiedis an ISO 8601 time, here each policy'sUpdated:date.
At the pinned revision, resources/list and resources/read results carry two cache hints. ttlMs says how long a result stays fresh, and cacheScope says whether a cache may share it across callers (caching). The SDK's default is a ttlMs of 0 with the private scope (mcp/server/caching.py). The policies are the same for every caller and change rarely, so this server marks both methods public for an hour. Listing and reading the policies shows both hints.
1"""Serves the shop's six policies as static resources, then lists them and reads the refund policy from a client.2The point rests on the priority lines, where only the refund policy is 1.0, and on the two cache scope lines, which say public."""3import asyncio4import sys56from mcp import Client, StdioServerParameters7from mcp.server.caching import CacheHint8from mcp.server.mcpserver import MCPServer9from mcp.server.mcpserver.resources import FileResource10from mcp.types import Annotations1112from lib.policies import load_policies1314HOUR_MS = 3_600_00015server = MCPServer("shop-support", version="0.4.0", cache_hints={ # policies are the same for every caller16 "resources/list": CacheHint(ttl_ms=HOUR_MS, scope="public"),17 "resources/read": CacheHint(ttl_ms=HOUR_MS, scope="public")})1819for policy in load_policies():20 server.add_resource(FileResource(21 uri=f"shop://policies/{policy.slug}", name=f"{policy.slug}-policy", title=policy.title,22 description=policy.summary, mime_type="text/markdown", path=policy.path,23 # the refund policy is effectively required (1.0); the others matter only for some tickets (0.5)24 annotations=Annotations(audience=["assistant"], priority=1.0 if policy.slug == "refund" else 0.5,25 # the file gives a day, not a time, so its update is taken as midnight UTC26 last_modified=f"{policy.updated}T00:00:00Z")))272829async def main() -> None:30 params = StdioServerParameters(command=sys.executable, args=[__file__, "--serve"], env={})31 async with Client(params) as client:32 print("protocol revision:", client.protocol_version)33 listed = await client.list_resources()34 print("resources:", len(listed.resources))35 for resource in listed.resources:36 print(f" {resource.uri} {resource.title!r} priority {resource.annotations.priority}")37 print("list cache scope:", listed.cache_scope)38 print("list ttl ms:", listed.ttl_ms)39 read = await client.read_resource("shop://policies/refund")40 contents = read.contents[0] # a read returns a list of contents; this file is its only item41 print("mime type:", contents.mime_type)42 print("first line:", contents.text.splitlines()[0]) # the file's first line is its title43 print("read cache scope:", read.cache_scope)44 print("read ttl ms:", read.ttl_ms)454647if __name__ == "__main__":48 server.run() if "--serve" in sys.argv else asyncio.run(main())
python list-policy-resources.pyprotocol revision: 2026-07-28
resources: 6
shop://policies/data-handling 'Data-handling policy' priority 0.5
shop://policies/escalation 'Escalation policy' priority 0.5
shop://policies/refund 'Refund policy' priority 1.0
shop://policies/returns 'Returns policy' priority 0.5
shop://policies/shipping 'Shipping policy' priority 0.5
shop://policies/stock 'Stock policy' priority 0.5
list cache scope: public
list ttl ms: 3600000
mime type: text/markdown
first line: # Refund policy
read cache scope: public
read ttl ms: 3600000
The client sees 6 resources, sorted by slug, and only the refund policy has priority 1.0. The list carries the scope public and a lifetime of 3600000 milliseconds, so a client may reuse it for an hour and share it between users. Cache list results shows what a client does with the hints.
Reading shop://policies/refund returned the file itself, as text/markdown text that begins with the line # Refund policy. The read carries the same scope, public, because the server marks both methods public.
That exchange never put the refund policy in front of a model. The server published it, and the host alone decides when to include it. Put resources in the model's context builds the host loop that does so for every refund ticket.
Working rule: Publish the documents a host should be able to put in front of a model as static resources, under a scheme that names your system, with a MIME type and a description the host can show. Use https:// only for resources the client can fetch without your server. Mark a result public only when every caller gets the same one, and give high priority only to the one or two documents every answer depends on, not to all of them.
用资源模板定位记录
上一节中的六条策略适合列表,但商店的订单不适合。数据中仅以 O-2 开头的订单 ID 就有 501 个,为每个订单各建一个资源,对宿主毫无用处,服务成本也很高。资源模板(resource template)用一个 URI 模板指代许多资源,写法遵循 RFC 6570 的语法(RFC 6570)。客户端用 resources/templates/list 列出模板,填入变量,再用 resources/read 读取结果(resources)。
在 Python SDK 中,传给 @server.resource() 的 URI 决定资源的种类。变量两侧带花括号的 URI 注册为模板,此时函数的参数必须与变量一致。不带花括号的 URI 注册为静态资源(mcp/server/mcpserver/server.py,resource)。返回值决定内容:str 生成文本,bytes 生成二进制数据块,其他任何值都会被转换为 JSON。
模板还改变了未命中的含义。在所固定的修订版本中,读取不存在的资源会失败,并返回 JSON-RPC 错误 -32602(Invalid Params),URI 放在错误的 data 中。服务器"MUST NOT return an empty contents array",即不得改为返回空数组(resources)。修订版本 2025-11-25 对同一情形使用 -32002,客户端仍应接受旧版服务器返回的这个代码(changelog)。在 MCPServer 中,函数通过抛出 ResourceNotFoundError 得到 -32602。抛出任何其他 ResourceError 都会变成 -32603,而且与工具不同,资源没有可用来表示失败的 isError 结果(handling errors)。
商店的订单模板是 shop://orders/{order_id},其函数封装了商店 API 上的 GET /orders/{order_id},get_order_status 封装的也是这个端点。当 API 返回 404 时,函数抛出 ResourceNotFoundError。订单属于某一位客户,因此这次读取保留 SDK 默认的缓存提示,即范围为 private、生存期为 0。缓存页面将 private 列为 resources/read 结果中"依赖于已认证用户"的范围(caching)。在 API 收到任何内容之前,函数先检查变量是否像订单 ID,即 O- 加四位数字,若不是则抛出 ResourceNotFoundError,因此格式错误的 ID 永远不会到达 API。
四次读取,一次成功,三种未命中:一个真实存在的订单,一个不存在的订单,一个格式错误的 ID,以及一个其变量试图跳出订单路径的 URI。
1"""Reads orders through the template shop://orders/{order_id} and prints what each kind of miss returns.2The point rests on the codes, which are all the same, and on the traversal's message, which the SDK wrote rather than the handler."""3import asyncio4import json5import re6import sys78from mcp import Client, MCPError, StdioServerParameters9from mcp.server.mcpserver import MCPServer10from mcp.server.mcpserver.exceptions import ResourceNotFoundError1112from lib import loopback, shop_api, shop_reads1314server = MCPServer("shop-support", version="0.4.0") # default cache hint: ttl 0, scope private151617@server.resource("shop://orders/{order_id}", title="One of the shop's orders", mime_type="application/json")18async def order(order_id: str) -> dict:19 """One order: its status, dates, lines and total, as the shop's API returns it."""20 if not re.fullmatch(r"O-\d{4}", order_id): # check the format before the API sees it21 raise ResourceNotFoundError(f"Order IDs look like O-1873, not {order_id!r}.")22 if (found := await shop_reads.get_json(f"/orders/{order_id}")) is None: # the API answered 40423 raise ResourceNotFoundError(f"The shop has no order {order_id}.")24 return found252627async def main() -> None:28 with loopback.serve(shop_api.create_app()) as base_url:29 params = StdioServerParameters(command=sys.executable, args=[__file__, "--serve"],30 env=shop_api.server_env(base_url))31 async with Client(params) as client:32 template = (await client.list_resource_templates()).resource_templates[0] # the server defines one template33 print("template:", template.uri_template)34 read = await client.read_resource("shop://orders/O-2476")35 print("O-2476 status:", json.loads(read.contents[0].text)["status"]) # a read returns a list; the order is its only item36 print("read cache scope:", read.cache_scope)37 for case, uri in (("unknown order", "shop://orders/O-7144"),38 ("malformed", "shop://orders/2476"),39 # %2F is an encoded slash, so the URI has no path separator until the SDK decodes the variable40 ("traversal", "shop://orders/..%2F..%2Frefunds")):41 try:42 await client.read_resource(uri)43 except MCPError as err:44 print(f"{case} code:", err.error.code)45 print(f"{case} says:", err.error.message)46 print(f"{case} data uri:", err.error.data["uri"]) # the URI the server could not read, which the error carries47 assert err.error.code == -32602, case # every miss gets the same code, the one the prose names484950if __name__ == "__main__":51 server.run() if "--serve" in sys.argv else asyncio.run(main())
python order-resource-template.pytemplate: shop://orders/{order_id}
O-2476 status: shipped
read cache scope: private
unknown order code: -32602
unknown order says: The shop has no order O-7144.
unknown order data uri: shop://orders/O-7144
malformed code: -32602
malformed says: Order IDs look like O-1873, not '2476'.
malformed data uri: shop://orders/2476
traversal code: -32602
traversal says: Unknown resource: shop://orders/..%2F..%2Frefunds
traversal data uri: shop://orders/..%2F..%2Frefunds
模板被列为 shop://orders/{order_id},订单 O-2476 读取为 shipped,缓存范围为 private。
三次未命中都以同一个代码 -32602 失败,但它们的消息来源不同。不存在的订单 O-7144 得到处理函数自己的消息,其 URI 在错误的 data 中返回,即 shop://orders/O-7144。ID 2476 得到格式检查的消息,即 Order IDs look like O-1873, not '2476'.。
路径穿越的读取同样失败,但它的消息来自 SDK,即 Unknown resource: shop://orders/..%2F..%2Frefunds,而不是处理函数。SDK 把变量解码为 ../../refunds,发现其中含有 .. 路径段,于是在函数运行之前就拒绝了该 URI。若没有这次拒绝,处理函数会把 ../../refunds 放进请求路径,发送给商店的 API。
这次拒绝由 ResourceSecurity 完成。它默认拒绝模板变量中的 .. 段、绝对路径和 NUL 字节,无论 URI 使用了何种编码(mcp/server/mcpserver/resources/templates.py)。规范要求服务器验证每一个资源 URI(resources),SDK 的检查是对此的补充,而不能取代它。它拦不住 2476,因为该值能通过 ResourceSecurity,所以只有处理函数的格式检查能拦下它。
这个模板为持有服务器 API 密钥的任何人读取任意订单,适合客服团队的宿主。下一节把读取范围限定到单个客户。
工作准则: 对形状相同、带有 ID 的记录使用资源模板。返回 API 自己的 JSON,未命中时抛出 ResourceNotFoundError,这会让客户端得到 -32602 及 URI。凡是属于某个用户的内容,都保持 private 范围。保持 SDK 的 ResourceSecurity 开启,并且自己也要验证变量的格式。只有当变量必须携带路径时,才让它免于该检查,而且此时要自己检查路径。
为用户补全参数
如果宿主要把上一节的订单模板展示给用户,就需要用户填写 order_id,而很少有人记得订单 ID。参数补全(argument completion)让宿主可以在用户输入时向服务器请求建议。宿主发送 completion/complete,其中带有一个引用:要么是 ref/resource,附模板的 URI;要么是 ref/prompt,附提示的名称;此外还有参数名及其已输入的部分值。宿主还可以附上 context.arguments,即用户已为其他参数选定的值。结果中包含 values(最多 100 个),以及可选的 total 和 hasMore。提供补全的服务器需要声明 completions 能力(completion)。
在 Python SDK 中,一个 @server.completion() 处理器为服务器上的所有模板和提示提供服务。它接收引用、参数和上下文,返回 Completion 或 None。注册该处理器即声明了这项能力。SDK 不会过滤它返回的内容,因此放进 values 的内容就是界面所显示的内容(completions)。SDK 也不强制执行 100 项的上限。Completion 类型规定不得超过 100 项,但并没有任何检查(mcp_types/_types.py),所以处理器必须自行截断列表。
补全同时也是一种查询,而查询可能泄露信息。规范要求服务器对敏感的建议进行访问控制,以防补全披露不该披露的信息(completion)。如果处理器依据整个商店的订单来补全订单 ID,那么任何人输入 O-2,都能得知商店里存在哪些订单。
因此,处理器只补全服务器所代表的那位客户的订单。在 stdio 方式下,宿主在服务器的环境中指明这位客户,方式与它传入商店 API 密钥相同。这里 SHOP_CUSTOMER_ID 为 C-0127,即下了订单 O-2476 的客户。在 HTTP 方式下,用 OAuth 授权客户端一文用访问令牌所声明的内容取代该环境变量。支持团队宿主的令牌指向一名工作人员,所以客户要从服务器查到的工单中得出(只有在客户自己登录的场景下,令牌的主体才是客户;参见避免服务器沦为混淆代理)。
处理器向商店 API 请求该客户的订单,并保留以用户已输入内容开头的订单。API 最多返回一位客户的 100 个订单,按从新到旧排列(examples/lib/shop_api.py),所以结果永远不会超过协议的上限。处理器也保持这一顺序:对于支持工单,最新的订单可能性最大,而且规范要求建议“按相关度排序”(completion)。
API 的响应还带有该客户的订单总数。当这个总数大于 API 实际返回的数量时,更早的订单也可能匹配,所以处理器省略 total 并设置 has_more。否则,它把匹配数量作为 total 报告。订单模板对读取应用同样的范围限制:读取他人的订单,得到的未找到答复与读取不存在的订单相同。一个共享模块 lib.shop_reads 包含两个处理器都使用的异步辅助函数,用来调用商店 API。这次运行输入了两个前缀,并读取了两个调用者看不到的订单。
1"""Completes order IDs for shop://orders/{order_id} from the orders of the one customer the server acts for, and answers another customer's order as if it didn't exist.2The point rests on the offers, which hold only the caller's orders, and on the two answers at the end, which differ only in the ID."""3import asyncio4import os5import sys67from mcp import Client, MCPError8from mcp.server.mcpserver import MCPServer9from mcp.server.mcpserver.exceptions import ResourceNotFoundError10from mcp.types import Completion, ResourceTemplateReference1112from lib import loopback, shop_api, shop_reads13server = MCPServer("shop-support", version="0.4.0")141516@server.resource("shop://orders/{order_id}", title="One of your orders", mime_type="application/json")17async def order(order_id: str) -> dict:18 found = await shop_reads.get_order(order_id) # checks the ID's format before the API sees it19 # the customer the server acts for, from the server's environment20 if found is None or found["customer_id"] != os.environ["SHOP_CUSTOMER_ID"]:21 raise ResourceNotFoundError(f"You have no order {order_id}.") # the same answer either way22 return found232425@server.completion()26async def complete(ref, argument, context) -> Completion | None:27 # this handler completes only the order template's order_id argument28 if not isinstance(ref, ResourceTemplateReference) or argument.name != "order_id":29 return None30 # the API's newest-first page, at most 100 orders, which is also the protocol's cap of 100 values31 page = await shop_reads.get_json("/orders", customer_id=os.environ["SHOP_CUSTOMER_ID"], limit=100)32 # upper-cases what the user typed, so o-24 matches O-247633 matches = [o["order_id"] for o in page["orders"] if o["order_id"].startswith(argument.value.upper())]34 cut_short = page["total"] > len(page["orders"]) # older orders the API didn't return may match too35 # total is reported only when every match was counted36 return Completion(values=matches, total=None if cut_short else len(matches), has_more=cut_short)373839async def main() -> None:40 print("shop orders starting O-2:", shop_reads.orders_starting("O-2"))41 print("most orders for one customer:", shop_reads.most_orders_per_customer())42 with loopback.serve(shop_api.create_app()) as base_url:43 # C-0127 is the customer the server acts for, passed in the server's environment44 async with Client(shop_reads.server_params(__file__, base_url, SHOP_CUSTOMER_ID="C-0127")) as client:45 for typed in ("O-2", "o-24"):46 ref = ResourceTemplateReference(uri="shop://orders/{order_id}")47 result = (await client.complete(ref, {"name": "order_id", "value": typed})).completion48 print(f"{typed} offers:", ", ".join(result.values), f"({result.total} in all)")49 for order_id in ("O-1767", "O-7144"): # another customer's order, and nobody's50 try:51 await client.read_resource(f"shop://orders/{order_id}")52 except MCPError as err:53 print(f"{order_id} answer:", err.error.code, err.error.message)545556if __name__ == "__main__":57 server.run() if "--serve" in sys.argv else asyncio.run(main())
python complete-order-ids.pyshop orders starting O-2: 501
most orders for one customer: 100
O-2 offers: O-2476, O-2230 (2 in all)
o-24 offers: O-2476 (1 in all)
O-1767 answer: -32602 You have no order O-1767.
O-7144 answer: -32602 You have no order O-7144.
补全只向每位调用者提供其自己的订单。就整个商店而言,O-2 会匹配 501 个订单,超出一次答复所允许的上限,但客户 C-0127 输入 O-2 时,得到的是 O-2476, O-2230 (2 in all),没有别的。以小写输入 o-24 得到 O-2476 (1 in all),因为处理器先把用户输入的内容转为大写。
读取另一位客户的订单 O-1767,返回 -32602 You have no order O-1767.;读取不存在的订单 O-7144,返回 -32602 You have no order O-7144.。这两个答复只有 ID 不同,所以调用者无法判断订单是否存在。
上限只对订单超过 100 个的客户有意义。商店数据中单个客户的订单最多为 100,因此对每位客户,API 都返回其全部订单,处理器会报告 total。若某位客户有第 101 个订单,则只会从最新的 100 个订单中提供匹配项,不带 total,且 has_more 为真。这次运行无法展示这种情形,因为没有客户有那么多订单。
context.arguments 的用武之地,是接受多个参数的提示,例如先由用户选定一位客户,再把订单 ID 限定在该客户之内。要把它当作用户的输入,绝不能当作授权,因为调用服务器的人可以决定它的内容。规范还要求服务器对补全请求限速,并要求客户端对请求去抖,因为宿主可能每次击键都发送一个请求(completion)。
工作准则: 只根据调用者有权读取的内容来补全参数,而这一范围由服务器所代表的对象决定,不由请求中的任何内容决定。自行按已输入的前缀过滤,并把列表保持在 100 个值以内,因为 SDK 不会这样做。只要你过滤的来源本身被截断,就设置 has_more;只有数清了全部匹配项,才报告 total。对无权访问的记录,给出与不存在的记录相同的未找到答复,读取和补全都一样。
资源变化时通知客户端
宿主若已把某个资源(例如来自订单模板的订单)交给模型,就必须得知该资源的变化,否则它会一直展示过时的副本。在固定的修订版本中,客户端用一个请求来申请变更通知,即 subscriptions/listen。它的过滤器可以指定要监视的资源 URI(resourceSubscriptions),也可以申请列表变更通知(resourcesListChanged、toolsListChanged、promptsListChanged),而响应是一条长期存在的通知流(subscriptions)。
subscriptions/listen 取代了 2025 年各修订版本中的三项内容:resources/subscribe、resources/unsubscribe 以及 HTTP GET 流(changelog)。SDK 的 Client.subscribe_resource 已被弃用,并且只能与 2025 年代的服务器通信(mcp/client/client.py)。如何从中迁移,见梳理旧服务器的依赖项。
这条流有固定的形态(subscriptions):
- 服务器首先发送
notifications/subscriptions/acknowledged,指明它将接受的过滤器子集。 - 随后,它给每条通知都标上
io.modelcontextprotocol/subscriptionId,即 listen 请求的 JSON-RPC ID,并且“不得发送客户端未明确请求的通知类型”。 notifications/resources/updated消息只携带 URI,不含其他内容。它只说明该资源发生了变化,而不说明资源现在的内容,因此客户端要再次读取。- 在 stdio 上,服务器不会在重新连接之间保留订阅状态。流中断后,客户端要再次发送
subscriptions/listen,并重新获取它所依赖的内容。
在 Python SDK 中,服务器代码通过 await ctx.notify_resource_updated(uri) 发布变更。这会把更新交给一条订阅总线,所有已打开的流都从该总线读取(mcp/server/mcpserver/context.py)。在客户端,async with client.listen(resource_subscriptions=[...]) as changes 发送请求并等待确认。随后 changes.honored 保存服务器同意的内容,遍历 changes 即可得到事件。服务器正常关闭会结束循环,而突然中断则会引发 SubscriptionLost(mcp/client/client.py,listen)。任何内容都不会重放,SDK 也指出,中断的流不可恢复(mcp/server/subscriptions.py)。库存示例展示了这会带来什么代价。
商店的库存政策规定,负数表示应当重新盘点,而 KG-1018 在 south 仓库中的数量为负。为了在单个进程内展示变化,该示例把库存数量保存在服务器的内存中,以代替商店的库存系统。它把每种商品的库存数量发布为 shop://stock/{sku},并增加了一个工具 set_on_hand,仓库的宿主在重新盘点后会调用它。该工具替换一个数量,并为该商品的 URI 发布一条更新。客户端监视 KG-1018 和 KG-9999,后者并不存在。它先记录另一种商品的一次重新盘点,再记录 KG-1018 的一次,随后关闭这条流并重新打开。
1"""Watches two products with subscriptions/listen, records recounts while a stream is open and while it is closed, and re-reads after each.2The point rests on the first event, which arrives, and on the re-listening line, which shows that nothing is replayed."""3import asyncio4import sys56import anyio7from mcp import Client, StdioServerParameters8from mcp.server.mcpserver import Context, MCPServer9from mcp.server.mcpserver.exceptions import ResourceNotFoundError1011from lib.shop_data import WAREHOUSES, load_shop12from lib.shop_reads import stock_summary1314server = MCPServer("shop-support", version="0.4.0")15counts = {(s.sku, s.warehouse): s.on_hand for s in load_shop().stock} # stands in for the shop's stock system161718@server.resource("shop://stock/{sku}", title="On-hand stock for one product", mime_type="application/json")19def stock(sku: str) -> dict:20 if (sku, WAREHOUSES[0]) not in counts: # a product exists if the first warehouse has a count for it21 raise ResourceNotFoundError(f"The shop sells no product {sku}.")22 return {warehouse: counts[sku, warehouse] for warehouse in WAREHOUSES}232425@server.tool()26async def set_on_hand(sku: str, warehouse: str, counted: int, ctx: Context) -> str:27 """Record a warehouse's recount of one product, replacing its on-hand count."""28 counts[sku, warehouse] = counted29 await ctx.notify_resource_updated(f"shop://stock/{sku}") # the exact URI clients watch; another spelling never matches30 return f"{sku} in {warehouse}: {counted}"313233async def main() -> None:34 watched = ["shop://stock/KG-1018", "shop://stock/KG-9999"] # KG-9999 doesn't exist35 async with Client(StdioServerParameters(command=sys.executable, args=[__file__, "--serve"], env={})) as client:36 async with client.listen(resource_subscriptions=watched) as changes:37 print("honoured:", " and ".join(changes.honored.resource_subscriptions))38 print("before:", await stock_summary(client, watched[0])) # watched[0] is KG-101839 # KG-1026 isn't watched, so this recount sends nothing on the stream40 await client.call_tool("set_on_hand", {"sku": "KG-1026", "warehouse": "north", "counted": 0})41 # KG-1018 is watched, so its update reaches the open stream42 await client.call_tool("set_on_hand", {"sku": "KG-1018", "warehouse": "south", "counted": 4})43 print("first event:", (await anext(changes)).uri)44 print("after:", await stock_summary(client, watched[0])) # watched[0] is KG-101845 # recorded while no stream is open, so no stream can hear it46 await client.call_tool("set_on_hand", {"sku": "KG-1018", "warehouse": "south", "counted": 3})47 async with client.listen(resource_subscriptions=watched) as changes:48 with anyio.move_on_after(1.0) as waited: # wait a second for anything replayed49 await anext(changes)50 print("events after re-listening:", 0 if waited.cancelled_caught else "at least 1")51 print("re-read:", await stock_summary(client, watched[0])) # watched[0] is KG-1018525354if __name__ == "__main__":55 server.run() if "--serve" in sys.argv else asyncio.run(main())
python stock-resource-changes.pyhonoured: shop://stock/KG-1018 and shop://stock/KG-9999
before: north 2, south -6
first event: shop://stock/KG-1018
after: north 2, south 4
events after re-listening: 0
re-read: north 2, south 3
SDK 会接受客户端请求的每一个 URI,即使该 URI 并不存在。在这里,确认同时接受了两者,即 shop://stock/KG-1018 and shop://stock/KG-9999,包括商店并不销售的那种商品,而且 SDK 不会检查调用方是否有权读取其中任何一个(mcp/server/subscriptions.py)。生产环境中会出什么问题会再谈这一点。
流处于打开状态时发生的变更,会以事件的形式到达客户端,客户端随后重新读取。KG-1026 的重新盘点没有在这条流上发送任何内容,因为没有人要求监视它,而第一个事件指明的是 shop://stock/KG-1018。KG-1018 在重新盘点前读到 north 2, south -6,之后读到 north 2, south 4。
无人监听时发生的变更,其通知就永远丢失了。客户端关闭了流,随后的第二次重新盘点把 south 的数量设为 3。在重新打开的流上,等待一秒后收到 0 个事件,只有重新读取一次,即 north 2, south 3,才能看到这一变化。
内存中的总线只能到达其所在进程内的流。若服务器有两个副本,一个副本上的变更永远不会到达另一个副本上的流,因此各副本需要一条共享总线(subscriptions)。不使用粘性会话运行多个副本就以这种方式运行商店的服务器。
工作准则: 只监视宿主已交给模型或用户的资源,并把每个事件当作再次读取的提示,而不是新的值。每次打开流时,包括第一次和每次中断之后,都要重新读取你所依赖的全部内容,因为任何内容都不会重放。要为客户端读取的确切 URI 发布更新,并且从执行该变更的代码路径中发布。
这部分尚未翻译,因此以英文显示。
Package a workflow as a prompt
The resources in the previous sections give a host the shop's data. Some of the support team's work, though, is a fixed procedure that a person starts, such as reviewing a refund before anyone issues it. A prompt packages such a procedure as a named message template that the server offers and the user picks, for example as a slash command. The user decides when it's used, and the server writes it, as Prompts are templates the user chooses quoted.
A prompt has a name, an optional title and description, and arguments, each with a name, a description and whether it's required. A client lists prompts with prompts/list and fills one in with prompts/get, which returns messages. Each message has the role user or assistant and one content block: text, an image, audio, a resource link, or an embedded resource that carries a resource's contents inside the message. There is no system role, so a prompt is not a system prompt, and the host keeps its own. The same page says implementations "MUST carefully validate all prompt inputs and outputs to prevent injection attacks or unauthorized access to resources."
With the Python SDK, @server.prompt() takes the prompt's name from the function, its arguments from the parameters and its description from the docstring. The function returns the messages, and a bare string or content block becomes one user message (mcp/server/mcpserver/prompts/base.py). An MCPError the function raises reaches the client unchanged. But for an unknown prompt or a missing required argument, the SDK raises a plain ValueError (mcp/server/mcpserver/server.py, get_prompt), though the specification assigns -32602 to both (schema).
The support team reviews each refund request against the refund policy, which says that a refund above €150.00 needs a support lead to confirm it. Chapter 2's review_refund took only an order_id, and its one message told the model which tool and resource to fetch. Here the prompt gains a second argument, amount, and carries what the review needs itself. Before it calls anything, it checks that both arguments look like the shop's formats. Then it looks the order up through the shop's API and returns two user messages. The first embeds the refund policy under its URI, shop://policies/refund, so the host needn't read it separately. The second quotes the order and asks the review's three questions.
Filling the prompt in for order O-1145, whose customer asks for €343.49, shows the messages a model would receive. Three bad calls follow: a path where an order ID belongs, a missing argument and a misspelled prompt name.
1"""Packages a refund review as a prompt, with the refund policy embedded, the order quoted and the arguments checked first.2The point rests on the two messages, and on the three failures: a bad path gets Invalid Params, while a missing amount and a misspelled name both get an internal error."""3import asyncio4import json5import re6import sys78from mcp import Client, MCPError, StdioServerParameters9from mcp.server.mcpserver import MCPServer10from mcp.types import INVALID_PARAMS, EmbeddedResource, TextResourceContents1112from lib import loopback, shop_api, shop_reads13from lib.policies import policy1415server = MCPServer("shop-support", version="0.4.0")161718@server.prompt(title="Review a refund request")19async def review_refund(order_id: str, amount: str) -> list[EmbeddedResource | str]:20 """Check a customer's refund request against the refund policy before a person issues it."""21 # up to five whole digits and exactly two decimals, so 24.99 and 343.49 pass22 if not re.fullmatch(r"\d{1,5}\.\d{2}", amount):23 raise MCPError(INVALID_PARAMS, f"Amounts look like 24.99, not {amount!r}.")24 # the API is asked only for an ID in the right format, and None from it means no such order25 if not re.fullmatch(r"O-\d{4}", order_id) or (order := await shop_reads.get_json(f"/orders/{order_id}")) is None:26 raise MCPError(INVALID_PARAMS, f"No order {order_id!r}. Order IDs look like O-1873.")27 return [EmbeddedResource(type="resource", resource=TextResourceContents( # each item: one user message28 uri="shop://policies/refund", mime_type="text/markdown", text=policy("refund").text)),29 (f"Order {order_id}: {json.dumps(order)}\n\nThe customer asks for a refund of {amount}. "30 "From the policy and the order only: does it qualify, how much may the shop refund, "31 "and must a support lead confirm it?")]323334async def main() -> None:35 good = {"order_id": "O-1145", "amount": "343.49"} # the order, and the amount its customer asks for36 tries = {"path as order_id": ("review_refund", {**good, "order_id": "../refunds"}), # a path where an ID belongs37 "missing amount": ("review_refund", {"order_id": "O-1145"}),38 "unknown prompt": ("refund_review", good)} # misspelled: the prompt is review_refund39 with loopback.serve(shop_api.create_app()) as base_url:40 env = shop_api.server_env(base_url)41 async with Client(StdioServerParameters(command=sys.executable, args=[__file__, "--serve"], env=env)) as client:42 for n, message in enumerate((await client.get_prompt("review_refund", good)).messages, 1):43 print(f"message {n}:", message.role, message.content.type)44 for case, (name, arguments) in tries.items():45 try:46 await client.get_prompt(name, arguments)47 except MCPError as err:48 print(f"{case}:", err.error.code, err.error.message)495051if __name__ == "__main__":52 server.run() if "--serve" in sys.argv else asyncio.run(main())
python refund-review-prompt.pymessage 1: user resource
message 2: user text
path as order_id: -32602 No order '../refunds'. Order IDs look like O-1873.
missing amount: -32603 Internal server error
unknown prompt: -32603 Internal server error
The filled-in prompt is two messages. The first, user resource, embeds the refund policy itself, and the second, user text, carries the order and the questions. Nothing here calls a model. These messages are what a host sends a model when a person picks the prompt, and Run the host loop makes that turn.
The failures show where the SDK and the specification part. The path, ../refunds, never reached the shop's API, because the format check raised MCPError with INVALID_PARAMS, and the client got -32602 No order '../refunds'. Order IDs look like O-1873.. The two failures the SDK handles itself came back differently. A missing amount gave -32603 Internal server error, and the misspelled name gave -32603 Internal server error. Both carry the internal-error code rather than the -32602 the specification assigns, and the SDK's own message is hidden behind a generic one. So a host can't tell either mistake from a crash in the server.
Prompt arguments also become text that a model reads. A customer's words pasted into a free-text argument would reach the model inside a user message, which is one reason this prompt takes only an order ID and a decimal amount. Treat ticket text as untrusted data covers that path in general.
Working rule: Offer a prompt for a procedure a person starts by name, and keep its arguments to values with a format you can check. Embed the resources the procedure depends on, so the host needn't fetch them. Validate every argument before you use it, and raise MCPError with INVALID_PARAMS for a bad one, because the SDK's own checks answer with an internal error.
在资源与工具之间做选择
将每项能力放入合适的原语通过判断“由谁决定何时使用数据”解决了大部分选择问题,但还留下了一种情形:数据两者兼是。前面的各节发布的商店数据,与围绕任务而非端点来设计工具中各工具返回的数据属于同一类:订单来自 get_order_status,商品库存来自 check_stock。下面的内容属于判断,而非测量。
订单模板让宿主能在模型阅读工单之前,先附上工单所涉及的订单。get_order_status 则让模型转而查询它在工单文本中发现的订单。让两者都通过同一个 API 调用读取数据,这样它们就不会不一致。
当工具找到宿主可能想要保留的记录时,它可以返回指向这些记录的资源链接,而不是记录的完整内容,由宿主读取所需的那些。规范并不保证这类链接会出现在 resources/list 的结果中(工具),因此服务器可以链接到只能通过模板寻址的记录。
**工作准则:**当宿主会附加某条记录、而模型会查询它时,应将该记录同时作为资源和工具提供,并让两者共用同一条代码路径,使它们不会不一致。当工具找到宿主可能保留的记录时,返回指向这些记录的资源链接,而不是记录的内容。
这部分尚未翻译,因此以英文显示。
What goes wrong in production
The shop's resources and prompts work on one machine with one caller. In production, with many callers, caches, replicas and hosts the shop didn't write, they fail in a handful of ways, and each has a symptom you can catch early.
A per-user read gets a public cache scope. A cache "MUST NOT" be shared across authorization contexts, and public tells it the result may be (caching). MCPServer can't set the hint on each function, so cache_hints sets one hint per method, and a server that serves public policies and private orders gives the same hint on every resources/read (mcp/server/mcpserver/server.py, _handle_read_resource). Keep resources/read private on a server that serves anything per user, or give the policies a server of their own. The sign is a user who sees an order that isn't theirs, which no test with one user finds. And ttlMs is not a polling interval: clients "SHOULD NOT" poll on it.
Lists differ between connections. resources/list and prompts/list must not vary per connection, as Cache list results said of the tool list. A list may vary by the authorization on the request, and it may change over time if the server sends a list-changed notification (resources, prompts). A server that adds a resource after a tool call breaks every client's cache. It shows up as a list that changes after a tool call, or changes with no list-changed notification.
A client watches what it can't read. The SDK honours every URI a client asks to watch, as the stock example showed with a product the shop doesn't sell. A client watching another customer's order would learn that the order exists, and when it changed. Put middleware on subscriptions/listen that rejects URIs the caller may not read (subscriptions). Watch for an acknowledgment that echoes URIs the caller could never read.
An update never matches. MCPServer compares URIs as exact strings (subscriptions), so a client watching shop://stock/kg-1018 never hears about shop://stock/KG-1018. The specification also allows an update to name a sub-resource of the watched URI (schema), and MCPServer never matches one. The giveaway is a client that refreshes only when it reconnects. Publish the exact URI your templates produce, and normalize IDs before you build a URI.
A dropped stream goes unnoticed. Nothing is replayed, so a host that loses its stream and never re-listens shows stale data indefinitely. One that re-listens without re-reading misses every change made while it was away, as the stock example showed (mcp/server/subscriptions.py). Catch SubscriptionLost, re-listen, then re-read.
Completion becomes an enumeration endpoint. A handler that completes from every record, or trusts context.arguments for access, lets anyone list what exists, one keystroke at a time. A host that sends a request per keystroke also multiplies the load (completion). Scope suggestions to the caller, cap them, rate-limit per caller, and watch completion request rates as you would login attempts.
Prompt errors look like crashes. The SDK answers an unknown prompt or a missing argument with -32603, as the prompt example showed, so a host's logs mix users' mistakes with server faults. Raise MCPError with INVALID_PARAMS for every argument you reject, and alert on the internal errors that remain.
Working rule: Test resources and prompts with two callers before they reach production. Neither may see, complete or watch the other's records, and neither should see a list change without a list-changed notification. Check that every resources/read of a user's data carries the private scope, and that a host recovers from a dropped stream by re-listening and re-reading.
这部分尚未翻译,因此以英文显示。
Decisions this chapter made
- The shop's policies are six static resources at
shop://policies/{slug}, served from Markdown files written for the book, with the refund policy at priority 1.0 as a judgement. - The policies' list and reads are
publicfor an hour, because they are the same for every caller. Orders keep theprivatedefault. - Orders are a resource template,
shop://orders/{order_id}, over the same API endpoint asget_order_status, and a miss raisesResourceNotFoundErrorfor -32602. - The SDK's
ResourceSecuritystays on, and handlers still check the format of what they're given. - Completion offers only the caller's own orders, newest first and bounded by the API's limit of 100, with
has_morewhen the API held more back. Another customer's order reads as not found. - Who the server acts for comes from the environment over stdio. Over HTTP, the token's subject says who is calling: for the support host, a member of staff, with the customer taken from the ticket record (Authorize clients with OAuth, Keep the server from acting as a confused deputy).
- The stock example keeps counts in the server's memory, standing in for the shop's stock system, and the
set_on_handtool publishes the update from the code path that changes the count. - Change notifications use
subscriptions/listen, neverresources/subscribe, and the client re-reads on every event and every new stream. - No model call in this chapter. The prompt's messages are the input to a model turn that the book's host loop makes later.
- The
review_refundprompt embeds the refund policy, checks its arguments' formats first, and raisesMCPErrorwithINVALID_PARAMSitself. - Data the host attaches is a resource, and data the model looks up is a tool. A record can be both, served from one code path.
本章,在本版次中
版次 2026.11.14示例于 2026年11月19日 通过本章 5个示例 个示例中有 5 个通过
译自英文版图书,版次 2026.11.14。