Serve data as resources and prompts

閱讀約需 94 分鐘 分鐘,8 節 中共有 5 個範例。

版次 2026.11.14 範例於 2026年11 月 19 通過測試 70 個範例中有 70 個通過 變更內容

由 AI 翻譯。經人工以英文驗證。 我們如何製作書籍

譯自英文書,版次 2026.11.14。 閱讀原文

此部分尚未翻譯,因此以英文呈現。

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

最近一次變動於第 2026.11.14 版

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):

  • audience says who the content is for. The policies are for assistant, 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.
  • lastModified is an ISO 8601 time, here each policy's Updated: 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.

list-policy-resources.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 通過
"""Serves the shop's six policies as static resources, then lists them and reads the refund policy from a client.The point rests on the priority lines, where only the refund policy is 1.0, and on the two cache scope lines, which say public."""import asyncioimport sysfrom mcp import Client, StdioServerParametersfrom mcp.server.caching import CacheHintfrom mcp.server.mcpserver import MCPServerfrom mcp.server.mcpserver.resources import FileResourcefrom mcp.types import Annotationsfrom lib.policies import load_policiesHOUR_MS = 3_600_000server = MCPServer("shop-support", version="0.4.0", cache_hints={   # policies are the same for every caller    "resources/list": CacheHint(ttl_ms=HOUR_MS, scope="public"),    "resources/read": CacheHint(ttl_ms=HOUR_MS, scope="public")})for policy in load_policies():    server.add_resource(FileResource(        uri=f"shop://policies/{policy.slug}", name=f"{policy.slug}-policy", title=policy.title,        description=policy.summary, mime_type="text/markdown", path=policy.path,        # the refund policy is effectively required (1.0); the others matter only for some tickets (0.5)        annotations=Annotations(audience=["assistant"], priority=1.0 if policy.slug == "refund" else 0.5,                                # the file gives a day, not a time, so its update is taken as midnight UTC                                last_modified=f"{policy.updated}T00:00:00Z")))async def main() -> None:    params = StdioServerParameters(command=sys.executable, args=[__file__, "--serve"], env={})    async with Client(params) as client:        print("protocol revision:", client.protocol_version)        listed = await client.list_resources()        print("resources:", len(listed.resources))        for resource in listed.resources:            print(f"  {resource.uri}  {resource.title!r}  priority {resource.annotations.priority}")        print("list cache scope:", listed.cache_scope)        print("list ttl ms:", listed.ttl_ms)        read = await client.read_resource("shop://policies/refund")        contents = read.contents[0]                       # a read returns a list of contents; this file is its only item        print("mime type:", contents.mime_type)        print("first line:", contents.text.splitlines()[0])  # the file's first line is its title        print("read cache scope:", read.cache_scope)        print("read ttl ms:", read.ttl_ms)if __name__ == "__main__":    server.run() if "--serve" in sys.argv else asyncio.run(main())
輸出python list-policy-resources.py
protocol 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.

此部分尚未翻譯,因此以英文呈現。

Address records with resource templates

最近一次變動於第 2026.11.11 版

The six policies in the previous section suit a list, but the shop's orders don't. The data holds 501 orders whose IDs start with O-2 alone, and a resource for each would be useless to a host and expensive to serve. A resource template names many resources with one URI template, written in the syntax of RFC 6570 (RFC 6570). A client lists templates with resources/templates/list, fills in the variables, and reads the result with resources/read (resources).

In the Python SDK, the URI passed to @server.resource() picks the kind. Braces around a variable register a template, and the function's parameters must match the variables. A URI without braces registers a static resource (mcp/server/mcpserver/server.py, resource). The return value sets the contents: a str gives text, bytes give a blob, and anything else is converted to JSON.

A template also changes what a miss means. A read of a resource that doesn't exist fails, at the pinned revision, with the JSON-RPC error -32602, Invalid Params, and the URI goes in the error's data. The server "MUST NOT return an empty contents array" instead (resources). Revision 2025-11-25 used -32002 for the same case, and clients should still accept that code from older servers (changelog). In MCPServer, a function gets -32602 by raising ResourceNotFoundError. Any other ResourceError becomes -32603, and a resource, unlike a tool, has no isError result to fail with (handling errors).

The shop's order template is shop://orders/{order_id}, and its function wraps GET /orders/{order_id} on the shop's API, the endpoint that get_order_status wraps too. It raises ResourceNotFoundError when the API answers 404. An order belongs to one customer, so the read keeps the SDK's default cache hint, private with a lifetime of 0. The caching page names private as the scope for resources/read results "that depend on the authenticated user" (caching). Before the API sees anything, the function checks that the variable looks like an order ID, O- and four digits, and raises ResourceNotFoundError if it doesn't, so a malformed ID never reaches the API.

Four reads, one success and three kinds of miss: a real order, one that doesn't exist, one ID in the wrong format, and one URI whose variable tries to climb out of the order's path.

order-resource-template.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 通過
"""Reads orders through the template shop://orders/{order_id} and prints what each kind of miss returns.The point rests on the codes, which are all the same, and on the traversal's message, which the SDK wrote rather than the handler."""import asyncioimport jsonimport reimport sysfrom mcp import Client, MCPError, StdioServerParametersfrom mcp.server.mcpserver import MCPServerfrom mcp.server.mcpserver.exceptions import ResourceNotFoundErrorfrom lib import loopback, shop_api, shop_readsserver = MCPServer("shop-support", version="0.4.0")   # default cache hint: ttl 0, scope private@server.resource("shop://orders/{order_id}", title="One of the shop's orders", mime_type="application/json")async def order(order_id: str) -> dict:    """One order: its status, dates, lines and total, as the shop's API returns it."""    if not re.fullmatch(r"O-\d{4}", order_id):                      # check the format before the API sees it        raise ResourceNotFoundError(f"Order IDs look like O-1873, not {order_id!r}.")    if (found := await shop_reads.get_json(f"/orders/{order_id}")) is None:    # the API answered 404        raise ResourceNotFoundError(f"The shop has no order {order_id}.")    return foundasync def main() -> None:    with loopback.serve(shop_api.create_app()) as base_url:        params = StdioServerParameters(command=sys.executable, args=[__file__, "--serve"],                                       env=shop_api.server_env(base_url))        async with Client(params) as client:            template = (await client.list_resource_templates()).resource_templates[0]  # the server defines one template            print("template:", template.uri_template)            read = await client.read_resource("shop://orders/O-2476")            print("O-2476 status:", json.loads(read.contents[0].text)["status"])  # a read returns a list; the order is its only item            print("read cache scope:", read.cache_scope)            for case, uri in (("unknown order", "shop://orders/O-7144"),                              ("malformed", "shop://orders/2476"),                              # %2F is an encoded slash, so the URI has no path separator until the SDK decodes the variable                              ("traversal", "shop://orders/..%2F..%2Frefunds")):                try:                    await client.read_resource(uri)                except MCPError as err:                    print(f"{case} code:", err.error.code)                    print(f"{case} says:", err.error.message)                    print(f"{case} data uri:", err.error.data["uri"])  # the URI the server could not read, which the error carries                    assert err.error.code == -32602, case  # every miss gets the same code, the one the prose namesif __name__ == "__main__":    server.run() if "--serve" in sys.argv else asyncio.run(main())
輸出python order-resource-template.py
template: 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

The template is listed as shop://orders/{order_id}, and order O-2476 reads as shipped, with the cache scope private.

The three misses fail with the same code, -32602, but their messages come from different places. The unknown order, O-7144, gets the handler's own message, and its URI comes back in the error's data, shop://orders/O-7144. The ID 2476 gets the format check's message, Order IDs look like O-1873, not '2476'..

The traversal read fails too, but its message is the SDK's, Unknown resource: shop://orders/..%2F..%2Frefunds, not the handler's. The SDK decoded the variable to ../../refunds, found .. path segments in it, and refused the URI before the function ran. Without that refusal, the handler would have sent ../../refunds in its request path to the shop's API.

That refusal is ResourceSecurity, which by default rejects .. segments, absolute paths and NUL bytes in template variables, whatever encoding the URI used (mcp/server/mcpserver/resources/templates.py). The specification requires servers to validate every resource URI (resources), and the SDK's check backs that up without replacing it. It doesn't stop 2476, which passes ResourceSecurity, so only the handler's format check catches that one.

This template reads any order for whoever holds the server's API key, which suits the support team's host. The next section scopes reads to one customer.

Working rule: Use a resource template for records that share one shape and an ID. Return the API's own JSON, and raise ResourceNotFoundError for a miss, which gives the client -32602 with the URI. Keep the scope private for anything that belongs to a user. Leave the SDK's ResourceSecurity on, and validate the variable's format yourself too. Exempt a variable from the check only when it must carry a path, and then check the path yourself.

為使用者完成引數

最近一次變動於第 2026.11.11 版

當主機要向使用者顯示上一節的訂單範本時,需要使用者填入 order_id,但很少人記得訂單編號。引數完成(argument completion)讓主機在使用者輸入時,向伺服器請求建議。主機會送出 completion/complete,其中帶有一個參照,可以是附上範本 URI 的 ref/resource,也可以是附上提示名稱的 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)。如果處理函式以整家商店的訂單來完成訂單編號,任何人只要輸入 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。這次執行會輸入兩個前綴,並讀取兩筆呼叫者看不到的訂單。

complete-order-ids.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 通過
"""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.The 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."""import asyncioimport osimport sysfrom mcp import Client, MCPErrorfrom mcp.server.mcpserver import MCPServerfrom mcp.server.mcpserver.exceptions import ResourceNotFoundErrorfrom mcp.types import Completion, ResourceTemplateReferencefrom lib import loopback, shop_api, shop_readsserver = MCPServer("shop-support", version="0.4.0")@server.resource("shop://orders/{order_id}", title="One of your orders", mime_type="application/json")async def order(order_id: str) -> dict:    found = await shop_reads.get_order(order_id)                     # checks the ID's format before the API sees it    # the customer the server acts for, from the server's environment    if found is None or found["customer_id"] != os.environ["SHOP_CUSTOMER_ID"]:        raise ResourceNotFoundError(f"You have no order {order_id}.")   # the same answer either way    return found@server.completion()async def complete(ref, argument, context) -> Completion | None:    # this handler completes only the order template's order_id argument    if not isinstance(ref, ResourceTemplateReference) or argument.name != "order_id":        return None    # the API's newest-first page, at most 100 orders, which is also the protocol's cap of 100 values    page = await shop_reads.get_json("/orders", customer_id=os.environ["SHOP_CUSTOMER_ID"], limit=100)    # upper-cases what the user typed, so o-24 matches O-2476    matches = [o["order_id"] for o in page["orders"] if o["order_id"].startswith(argument.value.upper())]    cut_short = page["total"] > len(page["orders"])          # older orders the API didn't return may match too    # total is reported only when every match was counted    return Completion(values=matches, total=None if cut_short else len(matches), has_more=cut_short)async def main() -> None:    print("shop orders starting O-2:", shop_reads.orders_starting("O-2"))    print("most orders for one customer:", shop_reads.most_orders_per_customer())    with loopback.serve(shop_api.create_app()) as base_url:        # C-0127 is the customer the server acts for, passed in the server's environment        async with Client(shop_reads.server_params(__file__, base_url, SHOP_CUSTOMER_ID="C-0127")) as client:            for typed in ("O-2", "o-24"):                ref = ResourceTemplateReference(uri="shop://orders/{order_id}")                result = (await client.complete(ref, {"name": "order_id", "value": typed})).completion                print(f"{typed} offers:", ", ".join(result.values), f"({result.total} in all)")            for order_id in ("O-1767", "O-7144"):                 # another customer's order, and nobody's                try:                    await client.read_resource(f"shop://orders/{order_id}")                except MCPError as err:                    print(f"{order_id} answer:", err.error.code, err.error.message)if __name__ == "__main__":    server.run() if "--serve" in sys.argv else asyncio.run(main())
輸出python complete-order-ids.py
shop 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.。這兩個答案只有編號不同,所以呼叫者無從得知該訂單是否存在。

上限只對訂單超過 100 筆的顧客才有影響。商店資料中,單一顧客最多的訂單數是 100,因此對每位顧客而言,API 都會回傳其全部訂單,處理函式也會回報 total。若某位顧客有第 101 筆訂單,他得到的符合項目只會來自最新的 100 筆,不帶 total,且 has_more 為 true。這次執行無法呈現該情況,因為沒有顧客有那麼多訂單。

context.arguments 適用於需要多個引數的提示,例如先讓使用者選定顧客,再把訂單編號限縮到該顧客的提示。請把它視為使用者的輸入,絕不可當成授權依據,因為內容由呼叫伺服器的人決定。規格也要求伺服器對完成請求進行速率限制,並要求用戶端做防抖(debounce)處理,因為主機可能在每次按鍵時都送出一個請求(completion)。

實用原則: 只從呼叫者可以讀取的內容完成引數,而可讀取的範圍由伺服器所代表的對象決定,而不是由請求中的任何內容決定。自行依輸入的前綴過濾,並把清單控制在 100 個值以內,因為 SDK 不會代勞。只要你過濾的來源本身已被截斷,就設定 has_more;只有在你計算了每一筆符合項目時,才回報 total。對無法存取的紀錄,應給出與不存在的紀錄相同的找不到回應,讀取與完成皆然。

在資源變更時通知用戶端

最近一次變動於第 2026.11.11 版

當主機(host)把某個資源放到模型面前,例如來自訂單範本的一筆訂單,就必須得知該資源的變更,否則它會一直顯示過時的副本。在固定的規格版本中,用戶端以單一請求 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,並且「MUST NOT send notification types the client has not explicitly requested.」
  • notifications/resources/updated 訊息只帶有 URI,沒有其他內容。它表示該資源已變更,而不是資源現在的內容,因此用戶端要重新讀取。
  • 在 stdio 上,伺服器不會在重新連線之間保留任何訂閱狀態。串流中斷之後,用戶端要再次送出 subscriptions/listen,並重新擷取它所依賴的內容。

在 Python SDK 中,伺服器端程式碼以 await ctx.notify_resource_updated(uri) 發布變更。這會把更新交給訂閱匯流排(subscription bus),每條開啟中的串流都從它讀取(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 的盤點,之後關閉串流,再重新開啟。

stock-resource-changes.py Python 3.12.15 · anyio 4.16.0 · 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 通過
"""Watches two products with subscriptions/listen, records recounts while a stream is open and while it is closed, and re-reads after each.The point rests on the first event, which arrives, and on the re-listening line, which shows that nothing is replayed."""import asyncioimport sysimport anyiofrom mcp import Client, StdioServerParametersfrom mcp.server.mcpserver import Context, MCPServerfrom mcp.server.mcpserver.exceptions import ResourceNotFoundErrorfrom lib.shop_data import WAREHOUSES, load_shopfrom lib.shop_reads import stock_summaryserver = MCPServer("shop-support", version="0.4.0")counts = {(s.sku, s.warehouse): s.on_hand for s in load_shop().stock}   # stands in for the shop's stock system@server.resource("shop://stock/{sku}", title="On-hand stock for one product", mime_type="application/json")def stock(sku: str) -> dict:    if (sku, WAREHOUSES[0]) not in counts:              # a product exists if the first warehouse has a count for it        raise ResourceNotFoundError(f"The shop sells no product {sku}.")    return {warehouse: counts[sku, warehouse] for warehouse in WAREHOUSES}@server.tool()async def set_on_hand(sku: str, warehouse: str, counted: int, ctx: Context) -> str:    """Record a warehouse's recount of one product, replacing its on-hand count."""    counts[sku, warehouse] = counted    await ctx.notify_resource_updated(f"shop://stock/{sku}")  # the exact URI clients watch; another spelling never matches    return f"{sku} in {warehouse}: {counted}"async def main() -> None:    watched = ["shop://stock/KG-1018", "shop://stock/KG-9999"]           # KG-9999 doesn't exist    async with Client(StdioServerParameters(command=sys.executable, args=[__file__, "--serve"], env={})) as client:        async with client.listen(resource_subscriptions=watched) as changes:            print("honoured:", " and ".join(changes.honored.resource_subscriptions))            print("before:", await stock_summary(client, watched[0]))  # watched[0] is KG-1018            # KG-1026 isn't watched, so this recount sends nothing on the stream            await client.call_tool("set_on_hand", {"sku": "KG-1026", "warehouse": "north", "counted": 0})            # KG-1018 is watched, so its update reaches the open stream            await client.call_tool("set_on_hand", {"sku": "KG-1018", "warehouse": "south", "counted": 4})            print("first event:", (await anext(changes)).uri)            print("after:", await stock_summary(client, watched[0]))  # watched[0] is KG-1018        # recorded while no stream is open, so no stream can hear it        await client.call_tool("set_on_hand", {"sku": "KG-1018", "warehouse": "south", "counted": 3})        async with client.listen(resource_subscriptions=watched) as changes:            with anyio.move_on_after(1.0) as waited:                      # wait a second for anything replayed                await anext(changes)            print("events after re-listening:", 0 if waited.cancelled_caught else "at least 1")            print("re-read:", await stock_summary(client, watched[0]))  # watched[0] is KG-1018if __name__ == "__main__":    server.run() if "--serve" in sys.argv else asyncio.run(main())
輸出python stock-resource-changes.py
honoured: 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

最近一次變動於第 2026.11.14 版

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.

refund-review-prompt.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 通過
"""Packages a refund review as a prompt, with the refund policy embedded, the order quoted and the arguments checked first.The 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."""import asyncioimport jsonimport reimport sysfrom mcp import Client, MCPError, StdioServerParametersfrom mcp.server.mcpserver import MCPServerfrom mcp.types import INVALID_PARAMS, EmbeddedResource, TextResourceContentsfrom lib import loopback, shop_api, shop_readsfrom lib.policies import policyserver = MCPServer("shop-support", version="0.4.0")@server.prompt(title="Review a refund request")async def review_refund(order_id: str, amount: str) -> list[EmbeddedResource | str]:    """Check a customer's refund request against the refund policy before a person issues it."""    # up to five whole digits and exactly two decimals, so 24.99 and 343.49 pass    if not re.fullmatch(r"\d{1,5}\.\d{2}", amount):        raise MCPError(INVALID_PARAMS, f"Amounts look like 24.99, not {amount!r}.")    # the API is asked only for an ID in the right format, and None from it means no such order    if not re.fullmatch(r"O-\d{4}", order_id) or (order := await shop_reads.get_json(f"/orders/{order_id}")) is None:        raise MCPError(INVALID_PARAMS, f"No order {order_id!r}. Order IDs look like O-1873.")    return [EmbeddedResource(type="resource", resource=TextResourceContents(       # each item: one user message                uri="shop://policies/refund", mime_type="text/markdown", text=policy("refund").text)),            (f"Order {order_id}: {json.dumps(order)}\n\nThe customer asks for a refund of {amount}. "             "From the policy and the order only: does it qualify, how much may the shop refund, "             "and must a support lead confirm it?")]async def main() -> None:    good = {"order_id": "O-1145", "amount": "343.49"}  # the order, and the amount its customer asks for    tries = {"path as order_id": ("review_refund", {**good, "order_id": "../refunds"}),  # a path where an ID belongs             "missing amount": ("review_refund", {"order_id": "O-1145"}),             "unknown prompt": ("refund_review", good)}  # misspelled: the prompt is review_refund    with loopback.serve(shop_api.create_app()) as base_url:        env = shop_api.server_env(base_url)        async with Client(StdioServerParameters(command=sys.executable, args=[__file__, "--serve"], env=env)) as client:            for n, message in enumerate((await client.get_prompt("review_refund", good)).messages, 1):                print(f"message {n}:", message.role, message.content.type)            for case, (name, arguments) in tries.items():                try:                    await client.get_prompt(name, arguments)                except MCPError as err:                    print(f"{case}:", err.error.code, err.error.message)if __name__ == "__main__":    server.run() if "--serve" in sys.argv else asyncio.run(main())
輸出python refund-review-prompt.py
message 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.

在資源與工具之間做選擇

最近一次變動於第 2026.11.11 版

將每項能力放進正確的原語透過「由誰決定何時使用資料」這個問題,解決了大部分的選擇,但留下了一種情況尚未處理:資料同時屬於兩者。前面幾節發布的商店資料,與以任務而非端點來設計工具中各工具所回傳的資料屬於同一類:訂單來自 get_order_status,商品庫存來自 check_stock。以下談的是判斷,而非量測。

訂單範本讓主機端能在模型閱讀工單之前,先附上該工單所涉及的訂單。get_order_status 則讓模型改為查詢它在工單文字中發現的訂單。兩者應透過同一個 API 呼叫來讀取,如此才不會彼此不一致。

當工具找到主機端可能想保留的紀錄時,它可以回傳指向這些紀錄的資源連結,而不是完整內容,再由主機端讀取其所需的部分。規格並不保證這類連結會出現在 resources/list 的結果中(工具),因此伺服器可以連結到只有範本才能定址的紀錄。

實用原則: 當主機端會附加某筆紀錄、而模型會查詢該紀錄時,同時以資源和工具提供它,並由同一條程式碼路徑來支援兩者,使其不會彼此不一致。當工具找到主機端可能保留的紀錄時,回傳指向這些紀錄的資源連結,而不是其內容。

此部分尚未翻譯,因此以英文呈現。

What goes wrong in production

最近一次變動於第 2026.11.11 版

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 public for an hour, because they are the same for every caller. Orders keep the private default.
  • Orders are a resource template, shop://orders/{order_id}, over the same API endpoint as get_order_status, and a miss raises ResourceNotFoundError for -32602.
  • The SDK's ResourceSecurity stays 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_more when 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_hand tool publishes the update from the code path that changes the count.
  • Change notifications use subscriptions/listen, never resources/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_refund prompt embeds the refund policy, checks its arguments' formats first, and raises MCPError with INVALID_PARAMS itself.
  • 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。

引用本節

格式

各種格式皆引用英文原書,本譯本即依循該原書。

每種格式都會標示本版。其連結會開啟目前版次,節標題會說明該節內文最後一次變動的時間。存取日期與擷取日期即為你開啟此頁的當日。

本頁內容

第 4 章,共 12 章: Serve data as resources and prompts

  1. Expose the policies as resources
  2. Address records with resource templates
  3. 為使用者完成引數
  4. 在資源變更時通知用戶端
  5. Package a workflow as a prompt
  6. 在資源與工具之間做選擇
  7. What goes wrong in production
  8. Decisions this chapter made

返回頂端所有章節