データをリソースとプロンプトとして提供する
読了まで約70 分分、8 節 節の 5 例 例。
この章を終えると、店のポリシーとレコードを Model Context Protocol のリソースとして公開し、1つのリソーステンプレートで多数のレコードを指定し、ユーザーが入力している間に引数を補完し、リソースが変更されたときにクライアントへ通知し、返金審査をユーザーが選べるプロンプトとしてまとめられるようになる。この章の主張とその裏付けとなるコードは、mcp 2.3.0(Python SDK)について、仕様のリビジョン 2026-07-28 で成り立つ。
店は台所用品と園芸用品を販売しており、サポートチームのホストがチケットに答えるために必要なものの大半は、実行する対象ではなく読む対象である。ホスト、クライアント、サーバーを分離するでは、店のサーバー shop-support に、それぞれの種類の機能を1つずつ持たせた。ツール get_order_status、リソースとしての返金ポリシー、短い review_refund プロンプトである。ただし、1つの文書と1つのプロンプトでは足りない。返金に関する回答はどれも返金ポリシーに従わなければならず、チケットは1件の注文に関するものであり、在庫の質問は1つの商品の在庫数に関するものである。これらをすべてツールにすると、モデルがそれを取得するかどうかを自分で判断しなければならず、取得しない可能性がある。
そのため、Model Context Protocol(MCP)のサーバーには、ツールとは別に2つのプリミティブがある。これらはツールと、いつ使うかを誰が決めるかという点で異なる(各機能を適切なプリミティブに置く)。リソース は、サーバーが URI のもとで公開するデータであり、それをモデルに見せるかどうかはホストが決める。プロンプト は、サーバーが提供するメッセージのテンプレートであり、ユーザーがそれを選ぶ。この章では、店のためにこの両方を作り上げる。
サーバーの名前は、この章を通して shop-support のままとする。各例は、その節が教える部分だけを定義し、第2章のサーバーの例と同様に自分自身を実行する。引数なしで実行すると、そのファイルはクライアントを起動し、そのクライアントが同じファイルを --serve 付きで 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.
この部分はまだ翻訳されていないため、英語で表示している。
Address records with resource templates
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.
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
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.
ユーザーのために引数を補完する
前の節の注文テンプレートを人に見せるホストは、ユーザーに order_id を入力してもらう必要があるが、注文 ID を覚えている人は少ない。引数の補完(argument completion)を使うと、ホストはユーザーの入力中にサーバーへ候補を問い合わせることができる。ホストは completion/complete を送る。その際、参照として、テンプレートの URI を持つ ref/resource、またはプロンプトの名前を持つ ref/prompt のいずれかを指定し、さらに引数の名前と入力途中の値を添える。ホストは context.arguments を加えてもよい。これは、他の引数についてユーザーがすでに選んだ値である。結果には values が最大 100 件含まれ、任意で total と hasMore が付く。補完を提供するサーバーは completions ケイパビリティを宣言する(completion)。
Python SDK では、1 つの @server.completion() ハンドラーがサーバー上のすべてのテンプレートとプロンプトを受け持つ。このハンドラーは参照、引数、コンテキストを受け取り、Completion または None を返す。ハンドラーを登録すると、ケイパビリティが宣言される。SDK は返された内容をフィルタリングしないので、values に入れたものがそのまま UI に表示される(completions)。100 件の上限も SDK は強制しない。Completion 型は 100 件を超えてはならないと述べているが、それを検査する処理はない(mcp_types/_types.py)。したがって、ハンドラー自身がリストの件数を制限しなければならない。
補完は一種の検索でもあり、検索は情報を漏らしうる。仕様は、機微な候補についてサーバーがアクセスを制御することを求めており、これによって補完が開示すべきでない情報を開示することを防ぐ(completion)。店全体の注文 ID から補完するハンドラーは、O-2 と入力した人に、店のどの注文が存在するかを教えてしまう。
そこで、ハンドラーはサーバーが代理を務める顧客の注文だけを補完する。stdio の場合、ホストは店の API キーを渡すのと同じ方法で、サーバーの環境にその顧客を指定する。ここでは SHOP_CUSTOMER_ID が C-0127 であり、注文 O-2476 を行った顧客である。HTTP の場合は、OAuth でクライアントを認可するがこの環境変数を、アクセストークンが示す内容に置き換える。サポート用ホストのトークンはスタッフを指すので、顧客はサーバーが調べるチケットから決まる(トークンの subject が顧客になるのは、顧客自身がサインインする場合だけである。サーバーを confused deputy にしないを参照)。
ハンドラーは、その顧客の注文を店の API に問い合わせ、ユーザーが入力した文字列で始まるものを残す。API が返す注文は 1 顧客につき最大 100 件で、新しい順である(examples/lib/shop_api.py)。そのため、答えがプロトコルの上限を超えることはない。ハンドラーはこの順序も保つ。サポートチケットでは新しい注文が最も候補になりやすく、仕様も候補を「関連度順にソート」するよう求めているからである(completion)。
API のレスポンスには、顧客の注文総数も含まれる。この総数が API の返した件数より多いときは、古い注文も一致する可能性があるので、ハンドラーは total を省き、has_more を設定する。そうでなければ、一致した件数を total として報告する。注文テンプレートも、読み取りに同じ範囲の制限を適用する。他の顧客の注文には、存在しない注文と同じ「見つからない」という答えが返る。共有モジュール lib.shop_reads には、両方のハンドラーが店の API を呼ぶために使う非同期ヘルパーがある。実行では、2 つの接頭辞を入力し、呼び出し元に見えない 2 つの注文を読み取る。
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 件の注文に一致し、1 回の答えに許される数を超える。しかし顧客 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. が返る。2 つの答えは ID の部分しか違わないので、呼び出し元は注文が存在するかどうかを知ることができない。
上限が問題になるのは、注文が 100 件を超える顧客だけである。店のデータで 1 顧客の注文数が最も多いのは 100 なので、どの顧客についても API はその顧客の注文をすべて返し、ハンドラーは total を報告する。101 件目の注文を持つ顧客には、最新の 100 件からの一致だけが提示され、total は付かず、has_more は true になる。これほど多くの注文を持つ顧客はいないので、実行ではこのケースを示せない。
context.arguments が役に立つのは、複数の引数を取るプロンプトである。たとえば、ユーザーが最初に選んだ顧客に注文 ID を絞り込むプロンプトがそうだ。これはユーザーの入力として扱い、認可として扱ってはならない。サーバーを呼び出す側が、その内容を自由に決められるからである。仕様はさらに、ホストがキー入力ごとにリクエストを送る場合があるため、サーバーには補完リクエストのレート制限を、クライアントにはそのデバウンスを求めている(completion)。
実践ルール: 補完は、呼び出し元が読み取ってよいものからだけ行う。それはサーバーが誰の代理を務めるかで決め、リクエストの内容では決めない。入力された接頭辞によるフィルタリングは自分で行い、リストは 100 件以内に収める。SDK はそれを行わないからである。フィルタリングした元のデータ自体が途中で打ち切られていた場合は、必ず has_more を設定し、total を報告するのは、一致をすべて数えたときだけにする。アクセスできないレコードには、存在しないレコードと同じ「見つからない」という答えを返す。これは読み取りでも補完でも同じである。
リソースが変更されたときにクライアントへ知らせる
ホストが、注文テンプレートから作った注文のようなリソースをモデルの前に提示している場合、ホストは変更を知らなければならない。知らなければ、古いコピーを表示し続けることになる。固定したリビジョンでは、クライアントは1つのリクエスト subscriptions/listen で変更通知を要求する。そのフィルタには、監視するリソース URI (resourceSubscriptions) を指定でき、リストの変更 (resourcesListChanged、toolsListChanged、promptsListChanged) も要求できる。レスポンスは通知の長寿命のストリームである (subscriptions)。
subscriptions/listen は、2025年のリビジョンにあった3つのものを置き換える。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)」。 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 倉庫で数量が負になっている。1つのプロセス内で変更を示すため、この例では数量をサーバーのメモリに保持し、店の在庫システムの代わりとする。各商品の数量は shop://stock/{sku} として公開され、ツール set_on_hand が追加される。これは、倉庫のホストが再カウントの後に呼び出すものである。このツールは1つの数量を置き換え、その商品の 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 と読み取れる。
誰も購読していない間に行われた変更の通知は、永久に失われる。クライアントがストリームを閉じ、2回目の再カウントで south の数量が3に設定された。再び開いたストリームで1秒待ったところ、イベントは 0 件だった。変更が分かるのは、新たに読み込む north 2, south 3 だけである。
メモリ内のバスは、自身のプロセス内のストリームにしか届かない。サーバーのレプリカが2つあると、一方での変更はもう一方のストリームには届かない。したがってレプリカには共有バスが必要である (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の結果に現れることは保証されていない(tools)。そのため、サーバーは、テンプレートでしかアドレス指定できないレコードにもリンクを張ることができる。
実践ルール: ホストがレコードを添付し、モデルがそれを参照する場合は、そのレコードをリソースとしてもツールとしても提供し、両方を一つのコードパスから提供して、内容が食い違わないようにする。ツールが、ホストが保持するかもしれないレコードを見つけた場合は、その内容ではなく、レコードへのリソースリンクを返す。
この部分はまだ翻訳されていないため、英語で表示している。
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)から翻訳した。