Serve data as resources and prompts

읽는 데 약 60분분 걸린다, 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를 채우게 해야 하는데, 주문 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에 담긴 것이 그대로 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가 고객인 경우는 고객이 직접 로그인하는 곳뿐이다. 혼동된 대리인으로 서버가 행동하지 않게 하기를 참고한다).

핸들러는 가게의 API에 그 고객의 주문을 요청하고, 사용자가 입력한 문자열로 시작하는 주문만 남긴다. API는 고객의 주문을 최신순으로 최대 100개까지 반환하므로(examples/lib/shop_api.py), 응답이 프로토콜의 상한을 넘을 수 없다. 핸들러는 이 순서도 그대로 유지한다. 지원 티켓에서는 최신 주문일 가능성이 가장 높고, 명세도 제안을 "관련도순으로 정렬"하라고 요구하기 때문이다(completion).

API 응답에는 고객의 전체 주문 수도 들어 있다. 이 총수가 API가 반환한 주문 수보다 크면 더 오래된 주문 중에도 일치하는 것이 있을 수 있으므로, 핸들러는 total을 생략하고 has_more을 설정한다. 그렇지 않으면 일치한 개수를 total로 보고한다. 주문 템플릿은 읽기에도 같은 범위를 적용한다. 다른 고객의 주문은 존재하지 않는 주문과 똑같은 not-found 응답을 받는다. 공유 모듈 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.가 반환된다. 두 응답은 ID만 다르므로 호출자는 주문이 존재하는지 알 수 없다.

상한이 문제가 되는 것은 주문이 100개를 넘는 고객뿐이다. 가게의 데이터에서 한 고객이 가진 주문 수의 최댓값은 100이므로, 모든 고객에 대해 API가 주문을 전부 반환하고 핸들러는 total을 보고한다. 주문이 101개째인 고객은 최신 100개에서 찾은 일치 항목만 제안받으며, total은 없고 has_more은 true가 된다. 그렇게 많은 주문을 가진 고객이 없으므로 이 실행으로는 그 경우를 보일 수 없다.

context.arguments가 제 역할을 하는 경우는 인수를 둘 이상 받는 프롬프트, 예를 들어 사용자가 먼저 고른 고객으로 주문 ID를 좁히는 프롬프트다. 서버를 호출하는 쪽이 그 내용을 정하므로, 이를 사용자의 입력으로 다루고 인가로는 절대 취급하지 않는다. 명세는 또한 호스트가 키 입력마다 요청을 보낼 수 있으므로 서버는 완성 요청에 속도 제한을 두고 클라이언트는 디바운스하도록 요구한다(completion).

작업 규칙: 호출자가 읽을 수 있는 것만으로 인수를 완성하되, 그 범위는 요청 안의 어떤 내용도 아닌 서버가 누구를 대신해 행동하는지로 정한다. 입력된 접두사에 따른 필터링은 SDK가 하지 않으므로 직접 하고, 목록도 100개 이내로 유지한다. 걸러 낸 원본 자체가 잘렸다면 항상 has_more을 설정하고, 일치하는 항목을 모두 센 경우에만 total을 보고한다. 접근할 수 없는 레코드에는 없는 레코드와 같은 not-found 응답을 주며, 읽기와 완성 모두 그렇게 한다.

리소스가 바뀌면 클라이언트에 알리기

마지막으로 변경된 판: 2026.11.11판

주문 템플릿에서 만든 주문처럼, 호스트가 모델 앞에 내놓은 리소스는 변경 사항을 전달받아야 한다. 그렇지 않으면 호스트는 오래된 사본을 계속 보여 준다. 고정된 리비전에서 클라이언트는 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를 보내, 필터 가운데 받아들일 부분 집합을 알린다.
  • 그다음 모든 알림에 listen 요청의 JSON-RPC ID인 io.modelcontextprotocol/subscriptionId를 붙이며, "클라이언트가 명시적으로 요청하지 않은 알림 유형은 보내서는 안 된다(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 창고의 수량이 음수다. 예제는 한 프로세스 안에서 변경을 보이기 위해 수량을 서버 메모리에 두며, 이는 가게의 재고 시스템을 대신한다. 각 제품의 수량을 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를 존재하지 않는 것이라도 모두 받아들인다. 여기서 확인 응답은 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으로 바꾸었다. 다시 연 스트림에서 1초를 기다렸을 때 이벤트는 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.

이 장에서 내린 결정

  • 상점의 정책은 여섯 개의 정적 리소스이다. 리소스는 shop://policies/{slug}에 있고, 이 책을 위해 작성한 Markdown 파일로 제공한다. 환불 정책의 우선순위는 판단에 따라 1.0으로 두었다.
  • 정책의 목록과 읽기는 한 시간 동안 public이다. 호출자와 관계없이 내용이 같기 때문이다. 주문은 기본값인 private을 유지한다.
  • 주문은 리소스 템플릿이다. shop://orders/{order_id}는 get_order_status와 같은 API 엔드포인트를 사용하며, 해당 주문이 없으면 -32602에 해당하는 ResourceNotFoundError를 발생시킨다.
  • SDK의 ResourceSecurity은 켜 둔다. 핸들러는 전달받은 값의 형식도 계속 검사한다.
  • 자동 완성은 호출자 본인의 주문만 제안한다. 최신 주문부터 보여 주며 API의 한도인 100개로 제한하고, API가 더 많은 결과를 남겨 둔 경우에는 has_more를 함께 돌려준다. 다른 고객의 주문은 찾을 수 없는 것으로 읽힌다.
  • 서버가 누구를 대신해 동작하는지는 stdio에서는 환경에서 정해진다. HTTP에서는 토큰의 subject가 호출자를 나타낸다. 지원 호스트에서는 호출자가 직원이며, 고객은 티켓 기록에서 가져온다(OAuth로 클라이언트 인가하기, 서버가 혼동된 대리인이 되지 않게 하기).
  • 재고 예제는 서버의 메모리에 수량을 보관한다. 이는 상점의 재고 시스템을 대신하며, set_on_hand 도구는 수량을 바꾸는 코드 경로에서 갱신을 게시한다.
  • 변경 알림에는 subscriptions/listen를 사용하고 resources/subscribe는 사용하지 않는다. 클라이언트는 모든 이벤트와 새 스트림마다 다시 읽는다.
  • 이 장에는 모델 호출이 없다. 프롬프트의 메시지는 이 책의 호스트 루프가 나중에 수행하는 모델 턴의 입력이다.
  • review_refund 프롬프트는 환불 정책을 포함한다. 먼저 인수의 형식을 검사하고, MCPError를 INVALID_PARAMS와 함께 직접 발생시킨다.
  • 호스트가 첨부하는 데이터는 리소스이고, 모델이 조회하는 데이터는 도구이다. 하나의 기록이 둘 다일 수 있으며, 이 경우 하나의 코드 경로에서 제공한다.

이 판의 이 장

2026.11.14판예제 통과 2026년 11월 19이 장에서 5개 예제개 중 5개가 통과한다

영어판 2026.11.14판을 번역한 것이다.

이 절 인용

형식

각 형식은 이 번역이 따르는 영문 원서를 출처로 표기한다.

모든 형식은 이 판을 명시한다. 링크는 현재 판을 열며, 여기서 절의 제목은 본문이 마지막으로 바뀐 시점을 알려 준다. 접근 날짜와 검색 날짜는 이 자료를 여는 날짜다.

이 페이지의 내용

12장 중 4장: 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. 이 장에서 내린 결정

맨 위로 돌아가기전체 장