MCP 资源详解:URI、模板、读取、订阅与错误

MCP 资源详解:URI、模板、读取、订阅与错误

资源是服务器按 URI 公开的一份数据,宿主应用可以把它放到模型面前:文件、数据库 schema、一条记录、一份日志。它的路径是:能力声明、列表、模板、读取、订阅、失败。下面按 2026-07-28 修订版走完这条路径,并逐个修订版说明自 2024-11-05 以来改了什么。

动作这一侧见 MCP 工具详解。怎样把服务器设计得让模型好用,见 MCP 服务器最佳实践。规范的约束文本见官方 资源页。

一、资源、工具还是提示

规范给每种原语指定了不同的控制方。控制方决定由谁触发,也就决定了你该做哪一种。

你想要做成由谁触发原因
把数据交给应用,作为上下文(文件内容、schema、一条记录)资源宿主应用:资源是应用驱动的,规范不规定界面形态宿主可以列出、搜索、让用户挑选,或按启发式自动带入
让模型自己执行动作或取数工具模型:工具是模型控制的模型自己决定何时调用 tools/call
提供用户挑选的可复用消息模板,例如斜杠命令提示用户:提示是用户控制的由用户显式选择
从工具结果指向一份更大的数据返回 resource_link 的工具模型调用工具,客户端之后可以读取该 URI工具结果里的资源链接不保证出现在 resources/list 中

如果模型需要在对话中自己去找数据,只有资源是不够的,因为带入什么由宿主决定。这种场景请公开一个工具,资源留给宿主应用选择附带的数据。

二、一次资源读取的路径

步骤消息要点章节
1能力声明支持资源的服务器必须声明 resources 能力。listChanged 与 subscribe 可选且相互独立;{ "resources": {} } 合法四
2resources/list支持分页与缓存。结果集可以为空、可以随时间变化,但不得因连接而异三、四
3resources/templates/list以 RFC 6570 URI 模板表示参数化资源;支持分页与缓存三、四
4resources/read带 uri。在 Streamable HTTP 上,URI 还会放进 Mcp-Name 头四、六
5结果contents:文本或 base64 二进制条目,各带自己的 uri;或 input_required 结果四、五
6订阅想要更新的客户端以 resourceSubscriptions 打开 subscriptions/listen;服务器发送 notifications/resources/updated,客户端重新读取四
7列表变更声明了 listChanged 时,服务器发送 notifications/resources/list_changed,客户端重新列出四

三、定义在五个修订版中的变化

任何修订版里,资源只有 uri 与 name、模板只有 uriTemplate 与 name 是必填的,其余字段都是后来加的。下表由各修订版 schema.json 的 definitions / $defs 生成,— 表示该修订版没有定义这个字段。本表及后面的表格用年月标注列:2024-11 即 2024-11-05,2025-03 即 2025-03-26,2025-06 即 2025-06-18,2025-11 即 2025-11-25,2026-07 即 2026-07-28。

字段2024-112025-032025-062025-112026-07
Resource.uri必填必填必填必填必填
Resource.name必填必填必填必填必填
Resource.title——可选可选可选
Resource.description可选可选可选可选可选
Resource.mimeType可选可选可选可选可选
Resource.size可选可选可选可选可选
Resource.icons———可选可选
Resource.annotations可选可选可选可选可选
Resource._meta——可选可选可选
ResourceTemplate.uriTemplate必填必填必填必填必填
ResourceTemplate.name必填必填必填必填必填
ResourceTemplate.title——可选可选可选
ResourceTemplate.description可选可选可选可选可选
ResourceTemplate.mimeType可选可选可选可选可选
ResourceTemplate.icons———可选可选
ResourceTemplate.annotations可选可选可选可选可选
ResourceTemplate._meta——可选可选可选
Annotations.audience—可选可选可选可选
Annotations.priority—可选可选可选可选
Annotations.lastModified——可选可选可选
  • title 与 _meta 出现在 2025-06-18,icons 出现在 2025-11-25。size(base64 之前的原始字节数)从一开始就有。Annotations 出现在 2025-03-26,带 audience 和 priority;lastModified 在 2025-06-18 加入。
  • URI。 每个资源由一个 URI(RFC 3986)标识,2026-07-28 的 schema 里声明了 format: uri。规范点名了 https://(只在客户端能自行从网上取到资源、不必经过服务器时使用)、file://(行为像文件系统的资源,不要求真有物理文件系统)和 git://。自定义 scheme 必须符合 RFC 3986。除非校验器强制 format,schema 接受任意字符串作 URI;第十节的脚本会检查列出的 URI 是否带 scheme。
  • 注解。 audience 取 "user"、"assistant" 或二者,priority 从 0.0(可有可无)到 1.0(实际上必需),lastModified 是 ISO 8601 时间戳。它们是供过滤、排序和展示用的提示。
  • 内容。 读取返回文本(text)或二进制(blob,base64)条目,每条带 uri 和可选的 mimeType。schema 把 text 与 blob 写成两个可选分支,并不禁止同时带两者的条目(第五节)。

四、列表、读取与订阅

第一张表列出几个关键消息的字段。resources/read params 自 2025-11-25 起是具名定义,之前是内联对象;这一组里不列 _meta,因为旧的内联定义没有它(第五节的矩阵覆盖了 2026-07-28 对它的要求)。

字段2024-112025-032025-062025-112026-07
ListResourcesResult.resources必填必填必填必填必填
ListResourcesResult.nextCursor可选可选可选可选可选
ListResourcesResult.ttlMs————必填
ListResourcesResult.cacheScope————必填
ListResourcesResult.resultType————必填
ListResourcesResult._meta可选可选可选可选可选
ListResourceTemplatesResult.resourceTemplates必填必填必填必填必填
ListResourceTemplatesResult.nextCursor可选可选可选可选可选
ListResourceTemplatesResult.ttlMs————必填
ListResourceTemplatesResult.cacheScope————必填
ListResourceTemplatesResult.resultType————必填
ListResourceTemplatesResult._meta可选可选可选可选可选
resources/read params.uri必填必填必填必填必填
resources/read params.inputResponses————可选
resources/read params.requestState————可选
ReadResourceResult.contents必填必填必填必填必填
ReadResourceResult.ttlMs————必填
ReadResourceResult.cacheScope————必填
ReadResourceResult.resultType————必填
ReadResourceResult._meta可选可选可选可选可选

第二张表显示各消息存在于哪些修订版。2026-07-28 用一条流取代了订阅 RPC:

项目2024-112025-032025-062025-112026-07
resources/subscribe 请求✓✓✓✓—
resources/unsubscribe 请求✓✓✓✓—
notifications/resources/updated✓✓✓✓✓
notifications/resources/list_changed✓✓✓✓✓
subscriptions/listen 请求————✓
notifications/subscriptions/acknowledged————✓
resourceSubscriptions 过滤器————✓
resource_link 内容块——✓✓✓

实践中的含义:

  • resultType、ttlMs、cacheScope 必填。 2026-07-28 里三个结果都要有它们。服务器必须在 resources/list、resources/templates/list、resources/read 的 resultType: "complete" 结果里带缓存提示,ttlMs 要 >= 0;ttlMs: 0 表示立即过期。"public" 适合对所有用户相同的列表和模板;"private" 适合依赖已认证用户的 resources/read 结果,或按用户过滤的列表;缓存不得在不同授权上下文之间共享私有响应。
  • 列表不依赖连接。 声明了 resources 的服务器必须用“当前对该请求方可用的资源集合”回答 resources/list。这个集合可以随时间变化,可以随请求携带的授权而不同,但不得因连接而异,也不得因同一连接上的其他请求而变。
  • 一次读取,多段内容。 服务器可以对一次 resources/read 返回多段内容,例如读取目录资源时返回其中的多个文件。它也可以返回 InputRequiredResult;客户端携带 inputResponses(以及服务器给出的 requestState)重试。
  • 模板。 resources/templates/list 返回 RFC 6570 URI 模板,例如 file:///{path}。模板参数可以通过补全 API自动补全。
  • 订阅。 客户端发送 subscriptions/listen,在 notifications.resourceSubscriptions 里列出 URI。服务器先确认,再在同一条流上为这些 URI 发送 notifications/resources/updated。通知只带 uri 和 io.modelcontextprotocol/subscriptionId(它等于 listen 请求的 JSON-RPC id);客户端要重新读取资源才能拿到新内容。每种通知类型都是显式开启的:服务器不得发送客户端没有请求的类型。resources/subscribe 与 resources/unsubscribe 已不存在。subscribe 能力表示服务器是否支持针对具体资源的更新通知。
  • 列表变更。 声明了 listChanged 的服务器应当发送 notifications/resources/list_changed;客户端在同一个 subscriptions/listen 过滤器里用 resourcesListChanged: true 开启它。服务器可以只给 ttlMs 而不声明 listChanged,此时客户端完全依赖 TTL。
  • 结束一条流。 由客户端关闭流。服务器自己结束订阅时,应当先发送一个成功的 subscriptions/listen 结果;没有它的断开属于意外断开,客户端可以据此重连。见订阅。

五、同一条消息,五份 schema

对某个修订版有效的消息,在其他修订版里还有效吗?每一行都对五份 schema.json 校验。✓ 表示有效,✗ 表示被拒绝,— 表示该修订版没有定义这一行所涉及的东西,校验无从说起。

消息2024-112025-032025-062025-112026-07
不带 ttlMs、cacheScope、resultType 的 ListResourcesResult✓✓✓✓✗
不带 ttlMs、cacheScope、resultType 的 ReadResourceResult✓✓✓✓✗
不带 params._meta 的 resources/read 请求✓✓✓✓✗
contents 为空数组的 ReadResourceResult✓✓✓✓✓
条目同时带 text 和 blob 的 ReadResourceResult✓✓✓✓✓
resources/read 返回 input_required 结果✗✗✗✗✓
带 icons 的 Resource———✓✓
resources/subscribe 请求✓✓✓✓—

各行的构造方式:第 1 至 7 行都从 2026-07-28 的官方示例出发。第 1 至 3 行删去所列字段,第 4 行把 contents 清空,第 5 行给文本条目加上 blob,第 6 行是官方 input_required 示例按 resources/read 响应校验,第 7 行加上 icons 数组。第 8 行是手写的 resources/subscribe 请求。所有未改动的示例都能通过 2026-07-28 schema 的校验:21 个定义下的 22 个资源相关示例,无一无效。

  • 第 1 至 3 行。 2026-07-28 要求 resultType、带 cacheScope 的 ttlMs 以及请求的 _meta。为 2025-11-25 及更早版本写的代码,补上它们之前通不过校验。
  • 第 4、5 行在所有版本里都有效,却依然是错的。 资源不存在时返回空的 contents 数组,只有规范正文禁止,schema 并不拒绝;同时带 text 和 blob 的条目也一样。schema 校验抓不到这两种问题,第十节的脚本能抓到。
  • 第 6 行。 在 2026-07-28 之前,input_required 结果不是合法的读取结果:它没有 contents。
  • 第 8 行。 resources/subscribe 到 2025-11-25 为止是合法请求,在 2026-07-28 中不存在。
  • 这种方法的局限。 JSON Schema 校验只检查形状。某一列没有 ✗,不代表各版本的行为兼容。

有些变化只存在于资源页的正文里。下表逐个修订版的页面检查,看引入该规则的句子是否出现:

规范文本是否写到2024-112025-032025-062025-112026-07
资源不存在必须返回 -32602————✓
资源不存在返回 -32002✓✓✓✓—
资源不存在时不得返回空的 contents 数组————✓
resources/list 不得因连接而异————✓
一次 resources/read 可返回多段内容————✓
resources/read 可返回 InputRequiredResult————✓
resources/subscribe 发起订阅✓✓✓✓—
subscriptions/listen 送达更新————✓
自定义 URI scheme 遵循 RFC 3986——✓✓✓
file:// 的文件路径必须净化————✓

“资源不存在”这一行最容易让客户端出问题:到 2025-11-25 为止规范写的是 -32002,2026-07-28 写的是 -32602(第七节)。

六、经 Streamable HTTP 读取:Mcp-Name 头

在 Streamable HTTP 上,resources/read 请求必须带两个头:Mcp-Method: resources/read,以及值为 params.uri 的 Mcp-Name。处理请求正文的服务器必须把解码后的头与正文比对,不一致就以 HTTP 400 和 JSON-RPC 错误 -32020(HeaderMismatchError)拒绝。缺少该头同样按此拒绝。

URI 往往不是纯 ASCII,所以这个头有转义写法。如果取值无法安全地表示为纯 ASCII 头值(含非 ASCII、控制字符、首尾空白),或者它本身长得像转义标记,客户端必须发送 =?base64? + UTF-8 字节的 Base64 + ?=,服务器先解码再比对。URI notes://café 这样发出:

POST /mcp HTTP/1.1
Mcp-Method: resources/read
Mcp-Name: =?base64?bm90ZXM6Ly9jYWbDqQ==?=
{"jsonrpc": "2.0", "id": 1, "method": "resources/read",
 "params": {"uri": "notes://café", "_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28", "...": "..."}}}

像 config://app/settings 这样的普通 URI 原样发送。两个典型错误:客户端直接发非 ASCII 原值(头不合法),以及服务器不解码就把头与正文比对(于是所有非 ASCII URI 都回 -32020)。脚本会探测这两种情况(header-mismatch、header-base64)。

七、错误:该返回什么、会收到什么

情形收到的内容怎么处理
资源或模板取值不存在JSON-RPC 错误 -32602(InvalidParamsError),data.uri 带上 URI。规范示例的消息是 Resource not found客户端:刷新列表,别再重试。服务器:必须返回它,绝不能返回空的 contents
2025-11-25 及更早的服务器表达同一件事-32002客户端应当也接受 -32002;2026-07-28 的服务器用 -32602
缺 uri,或 URI 不可用-32602:缺 uri 时 SDK 回 Invalid request parameters,URI 不可用时回 Unknown resource修客户端;原样重试不可能成功。服务器必须校验所有资源 URI
模板取值试图逃出根目录(../、绝对路径)SDK 在处理函数运行前就回 -32602 Unknown resource。规范:提供 file:// 资源时,服务器必须净化文件路径以防目录遍历自己测试;任何一次成功都按漏洞处理
资源背后的后端失败(数据库不可用、配额用尽)-32603(InternalError)。规范:服务器遇到内部错误应当返回它退避重试;不要把密钥写进消息
请求头与 uri 不一致(Mcp-Method、Mcp-Name)或缺失HTTP 400 加 -32020(HeaderMismatchError)客户端或网关的问题;修正请求头,非 ASCII URI 用 Base64 编码
协议版本未知,或缺少所需的客户端能力HTTP 400 加 -32022 或 -32021(形状与工具相同)见 MCP 工具详解
方法不存在,例如对 2026-07-28 的服务器调用 resources/subscribeHTTP 404 加 -32601(MethodNotFoundError)改用 subscriptions/listen
服务器要先拿到更多输入才能读取不是错误:resultType: "input_required" 的结果回答这些请求,带上 inputResponses、requestState 和新的 JSON-RPC id 重试

资源错误都是协议错误:与工具结果不同,读取结果没有 isError 字段(第四节)。

八、官方 Python SDK 2.3.0 的返回

参考服务器每种形态各定义一个资源:带注解的文本资源、二进制资源和三个模板。它使用官方 SDK(pip install mcp==2.3.0)。touch 工具只是为了让订阅的运行能“改变”一个资源:

resources_ref_server.py
"""Official Python SDK (mcp==2.3.0) resources server at http://127.0.0.1:8230/mcp, no auth.

Resources: a text resource with annotations, a binary resource, three templates (a closed set of notes, files under
`sample-docs/` served through `safe_join`, a status that fails on purpose) and the tool `touch`, which announces a
resource update. The templates keep the SDK's default `ResourceSecurity` policy: traversal, absolute paths and
NUL bytes in a template value are rejected before the handler runs.
"""
import base64
from pathlib import Path

from mcp.server.mcpserver import Context, MCPServer
from mcp.server.mcpserver.exceptions import ResourceError, ResourceNotFoundError
from mcp.shared.path_security import safe_join
from mcp.types import Annotations

ROOT = Path(__file__).resolve().parent / "sample-docs"
NOTES = {"standup": "Standup at 09:30.", "release": "Release freeze on Friday."}
# A 1x1 transparent PNG.
PIXEL = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==")

server = MCPServer("resources-ref")


@server.resource("config://app/settings", name="settings", title="Application settings",
                 description="Current settings as JSON", mime_type="application/json",
                 annotations=Annotations(audience=["user"], priority=0.8))
def settings() -> str:
    return '{"theme": "dark", "retries": 3}'


@server.resource("image://logo", name="logo", mime_type="image/png")
def logo() -> bytes:
    return PIXEL


@server.resource("notes://{topic}", name="notes", description="A note by topic")
def note(topic: str) -> str:
    if topic not in NOTES:
        raise ResourceNotFoundError("no note %r" % topic)
    return NOTES[topic]


@server.resource("docs://files/{+path}", name="docs", description="Files under sample-docs")
def doc(path: str) -> str:
    try:
        return safe_join(ROOT, path).read_text(encoding="utf-8")
    except (FileNotFoundError, IsADirectoryError):
        raise ResourceNotFoundError("no file %r" % path) from None


@server.resource("status://{kind}", name="status", description="Service status; busy and crash fail on purpose")
def status(kind: str) -> str:
    if kind == "ok":
        return "all systems normal"
    if kind == "busy":
        raise ResourceError("upstream quota exhausted, retry later")  # an anticipated failure
    if kind == "crash":
        raise RuntimeError("db password is hunter2")  # a crash: the SDK withholds this text from the client
    raise ResourceNotFoundError("no status %r" % kind)


@server.tool()
async def touch(uri: str, ctx: Context) -> str:
    """Announce that a resource changed, so `subscriptions/listen` streams deliver an update."""
    await ctx.notify_resource_updated(uri)
    return "announced " + uri


if __name__ == "__main__":
    server.run("streamable-http", port=8230)

用 2026-07-28 的请求格式经 Streamable HTTP 发了二十次请求。每个响应都对 2026-07-28 schema.json 里它对应的定义校验,错误还要对其错误码的定义校验,流中的每一帧对相应的通知校验(二十次全部有效,每行记录末尾写明了定义名):

运行请求SDK 的返回对照规范
listresources/listttlMs: 0、cacheScope: "private"、resultType: "complete",2 个资源(模板单独列出)有效。SDK 用最保守的值填满必填提示
templatesresources/templates/list同样的提示,3 个模板有效
read-textsettings 资源一段文本内容,application/json有效
read-blobimage://logo一段 blob 内容,image/png,70 字节原始数据的 base64有效
read-templatenotes://standup模板产生的一段文本内容有效
read-filedocs://files/README.md经 {+path} 模板读到的文件文本有效
unknown-uri一个没有注册的静态 URIHTTP 400,-32602,Unknown resource: config://nope符合“资源不存在”的规则
unknown-topicnotes://nopeHTTP 400,-32602,处理函数给出的消息符合:处理函数抛出了 ResourceNotFoundError
missing-filedocs://files/missing.mdHTTP 400,-32602符合:处理函数把 FileNotFoundError 转成了 ResourceNotFoundError
traversal路径以 ../ 开头的 docs://files/ URIHTTP 400,-32602,Unknown resource安全:模板没有匹配,处理函数根本没运行
absolute-pathdocs://files//etc/passwd同上同上
bad-urinot a uri同上不可用的 URI 按“资源不存在”回答
non-ascii-urinotes://café,请求头用 Base64 标记发送-32602,消息为 no note 'café'处理函数拿到的是解码后的值:请求头被接受了
status-busystatus://busy,处理函数抛出 ResourceErrorHTTP 200,-32603,处理函数给出的消息有效的 InternalError。这条消息会到达客户端:只写可以展示的文字
status-crashstatus://crash,处理函数抛出 RuntimeError("db password is hunter2")HTTP 200,-32603,Error creating resource from template status://crash有效。SDK 扣下原始文字,在服务器上记录 traceback
header-mismatchMcp-Name 设成另一个 URI 的读取HTTP 400,-32020符合 Streamable HTTP 的规则
missing-uri不带 uri 的 resources/readHTTP 400,-32602,Invalid request parameters符合
subscribe-oldresources/subscribeHTTP 404,-32601该方法在 2026-07-28 中已不存在(第四节)
listen-ackresourceSubscriptions 里带一个 URI 的 subscriptions/listen一帧:确认通知,以请求 id 作为 subscriptionId有效:符合确认通知的 schema
listen-update同一条流;touch 先宣布 config://other,再宣布已订阅的 URI先是确认,然后只有一条针对已订阅 URI 的更新通知有效;没有请求的 URI 不会送达,符合规范要求
二十次运行的原始记录
list             HTTP 200 result   ttlMs=0 cacheScope=private resultType=complete resources=2 | ListResourcesResultResponse valid
templates        HTTP 200 result   ttlMs=0 cacheScope=private resultType=complete templates=3 | ListResourceTemplatesResultResponse valid
read-text        HTTP 200 result   ttlMs=0 cacheScope=private resultType=complete contents: application/json text '{"theme": "dark", "retries": 3}' | ReadResourceResultResponse valid
read-blob        HTTP 200 result   ttlMs=0 cacheScope=private resultType=complete contents: image/png blob 70 bytes | ReadResourceResultResponse valid
read-template    HTTP 200 result   ttlMs=0 cacheScope=private resultType=complete contents: text/plain text 'Standup at 09:30.' | ReadResourceResultResponse valid
read-file        HTTP 200 result   ttlMs=0 cacheScope=private resultType=complete contents: text/plain text '# Sample docs\n\nServed through the `docs:' | ReadResourceResultResponse valid
unknown-uri      HTTP 400 error    code -32602 'Unknown resource: config://nope' | JSONRPCErrorResponse+InvalidParamsError valid
unknown-topic    HTTP 400 error    code -32602 "no note 'nope'" | JSONRPCErrorResponse+InvalidParamsError valid
missing-file     HTTP 400 error    code -32602 "no file 'missing.md'" | JSONRPCErrorResponse+InvalidParamsError valid
traversal        HTTP 400 error    code -32602 'Unknown resource: docs://files/../resources_ref_server.py' | JSONRPCErrorResponse+InvalidParamsError valid
absolute-path    HTTP 400 error    code -32602 'Unknown resource: docs://files//etc/passwd' | JSONRPCErrorResponse+InvalidParamsError valid
bad-uri          HTTP 400 error    code -32602 'Unknown resource: not a uri' | JSONRPCErrorResponse+InvalidParamsError valid
non-ascii-uri    HTTP 400 error    code -32602 "no note 'café'" | JSONRPCErrorResponse+InvalidParamsError valid
status-busy      HTTP 200 error    code -32603 'upstream quota exhausted, retry later' | JSONRPCErrorResponse+InternalError valid
status-crash     HTTP 200 error    code -32603 'Error creating resource from template status://crash' | JSONRPCErrorResponse+InternalError valid
header-mismatch  HTTP 400 error    code -32020 "mcp-name header does not match the request body's 'uri' parameter" | JSONRPCErrorResponse+HeaderMismatchError valid
missing-uri      HTTP 400 error    code -32602 'Invalid request parameters' | JSONRPCErrorResponse+InvalidParamsError valid
subscribe-old    HTTP 404 error    code -32601 'Method not found' | JSONRPCErrorResponse+MethodNotFoundError valid
listen-ack       HTTP 200 stream   ack(resourceSubscriptions=1) | SubscriptionsAcknowledgedNotification valid
listen-update    HTTP 200 stream   ack(resourceSubscriptions=1) -> updated(config://app/settings) | ResourceUpdatedNotification+SubscriptionsAcknowledgedNotification valid

这些运行说明了 SDK 的几件事:

  • 资源不存在就是 ResourceNotFoundError。 在处理函数里抛出它,得到 2026-07-28 规范要求的 -32602。如果处理函数对缺失的笔记抛出普通异常,就会走 status-crash 那条崩溃路径:返回 -32603 加一条通用消息,客户端会把它当作服务器故障,还可能重试。
  • ResourceError 与崩溃都以 -32603 结束。 ResourceError 用于你预料到的失败,它的消息会到达客户端;其他任何异常都算崩溃:客户端只看到 URI,traceback 留在服务器日志里。
  • 模板默认是安全的。 含 ..、是绝对路径或含 NUL 字节的模板取值,在处理函数运行前就被拒绝。读文件时仍要像示例那样用 safe_join 解析,绝不要拼接字符串来构造路径。
  • 更新是发后即忘。 SDK 先确认,给每一帧打上请求 id,只送达被请求的内容。它的文档写明投递没有重放:流断开后,客户端要重新 listen 并重新读取。
  • 缓存提示偏保守。 ttlMs: 0 加 "private" 永远有效,但等于关闭缓存。数据允许时请设置真实的值。

九、失败模式与恢复

现象原因怎么发现怎么恢复
客户端把“资源不存在”当成服务器故障,或一直重试服务器回了 -32603(出现了意外异常),而不是 -32602读取一个不可能存在的 URI;运行脚本(not-found-code)抛出 SDK 的 ResourceNotFoundError,或自己返回 -32602
客户端分不清“空”和“不存在”服务器对不存在的资源返回 contents: []。规范:不得这样,空数组有歧义not-found-code、template-not-found返回 -32602 错误
客户端不认识旧版服务器的“资源不存在”2026-07-28 起错误码从 -32002 改为 -32602;到 2025-11-25 为止的服务器仍发 -32002对两代服务器各读取一个不存在的 URI客户端两个码都接受;2026-07-28 的服务器返回 -32602
通过模板能读到根目录之外的文件处理函数拼接路径而不检查traversal-rejected用 safe_join 或等价方式解析,保留 SDK 默认的 ResourceSecurity,读取前先检查访问权限
每个非 ASCII URI 都回 -32020服务器不解码 Base64 标记就把 Mcp-Name 与正文比对,或客户端直接发了非 ASCII 原值header-base64先解码再比对;客户端负责编码
经网关的请求以 -32020 或 400 失败网关丢弃或改写了 Mcp-Method、Mcp-Nameheader-mismatch;对比两端的请求头原样转发标准请求头
客户端一直显示过期内容它没有订阅:没声明 subscribe,或 subscriptions/listen 没带 resourceSubscriptions,或流断了没人重新 listen检查能力声明;观察流里是否收到确认声明 subscribe,带上 URI 去 listen,断开后重新 listen 并重新读取资源,因为通知里只有 URI
旧客户端的 resources/subscribe 失败2026-07-28 里没有这个方法HTTP 404,-32601改用 subscriptions/listen
两个客户端拿到不同的列表列表依赖连接状态。不得如此,只有授权可以改变它用相同凭证在两条连接上调用 resources/list 并比对只根据请求的授权计算列表
一个用户的内容被缓存发给了另一个用户依赖用户的读取结果被标成 cacheScope: "public",或缓存忽略了授权用两个令牌对比 cacheScope 与内容依赖用户的结果用 "private"
客户端无法渲染二进制资源blob 不是合法 base64,或缺少 mimeTyperead-blob-base64、read-mime用标准 base64 编码原始字节,并写明 MIME 类型
客户端的错误消息里出现了密钥处理函数把后端消息放进了 ResourceError逐个触发失败并阅读消息只用可展示的文字抛出 ResourceError;其余交给 SDK 扣下,把原因记在日志里
模板对任何取值都有回答处理函数对每个输入都返回内容,无法区分“不存在”template-not-found(WARN)对照实际存在的数据校验取值,并抛出 ResourceNotFoundError

十、检查你自己的资源端点

lint_resources.py 连接一个 Streamable HTTP 端点。它列出资源与模板,读取最多五个已列出的资源,并发出几个健康服务器不应满足的探测读取:不存在的 URI、不存在的模板取值、路径遍历、不匹配的 Mcp-Name、非 ASCII URI。探测都是普通读取,不会改动任何东西;但不要把它指向读取会有副作用的端点。它只需要 Python 标准库。

lint_resources.py
#!/usr/bin/env python3
"""Lint the resources of an MCP server against spec 2026-07-28 over Streamable HTTP.

Usage: lint_resources.py URL [--token T] [--max-reads N]
URL: the Streamable HTTP endpoint. The linter lists resources and templates, reads up to N listed resources
(default 5) and sends a few probe reads that no healthy server may satisfy: a missing URI, a missing template
value, path traversal, a mismatching `Mcp-Name` header and a non-ASCII URI. The probes are plain reads and change
nothing; do not point them at an endpoint where reading has side effects.
Levels: FAIL = a MUST of the spec is violated, WARN = a SHOULD or a recommendation is not followed.
Exit code: 0 no FAIL, 1 at least one FAIL, 2 the endpoint cannot be read.
"""
import argparse
import base64
import binascii
import http.client
import json
import re
import sys
from urllib.parse import urlsplit

VERSION = "2026-07-28"
SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")
VARIABLE_RE = re.compile(r"\{[+#./;?&]?[^}]+\}")
MISSING_URI = "lint-probe://missing/resource"
MISSING_VALUE = "x-lint-missing"
TRAVERSAL_VALUES = ["../x-lint-traversal", "%2e%2e/x-lint-traversal", "/etc/passwd"]
counts = {"PASS": 0, "WARN": 0, "FAIL": 0}


def report(name, ok, detail, level="FAIL"):
    status = "PASS" if ok else level
    counts[status] += 1
    print("%s %s: %s" % (status, name, detail))


def mcp_name(value):
    """Mcp-Name header value: plain ASCII as is, anything else in the Base64 sentinel format."""
    plain = value.isascii() and value.isprintable() and value == value.strip() \
        and not (value.startswith("=?base64?") and value.endswith("?="))
    return value if plain else "=?base64?%s?=" % base64.b64encode(value.encode()).decode()


def request(url, method, params=None, token=None, name=None):
    """Build one 2026-07-28 request: (parsed URL, body, headers).

    `Mcp-Name` is `params.name` or `params.uri`; pass `name` to send another value."""
    meta = {"io.modelcontextprotocol/protocolVersion": VERSION,
            "io.modelcontextprotocol/clientInfo": {"name": "lint-resources", "version": "0"},
            "io.modelcontextprotocol/clientCapabilities": {}}
    headers = {"Accept": "application/json, text/event-stream", "Content-Type": "application/json",
               "MCP-Protocol-Version": VERSION, "Mcp-Method": method}
    source = name if name is not None else (params or {}).get("name", (params or {}).get("uri"))
    if isinstance(source, str):
        headers["Mcp-Name"] = mcp_name(source)
    if token:
        headers["Authorization"] = "Bearer " + token
    body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": {**(params or {}), "_meta": meta}})
    return urlsplit(url), body, headers


def rpc(url, method, params=None, token=None, name=None):
    """POST one request and return (HTTP status, JSON-RPC message or None)."""
    parts, body, headers = request(url, method, params, token, name)
    cls = http.client.HTTPSConnection if parts.scheme == "https" else http.client.HTTPConnection
    conn = cls(parts.netloc, timeout=15)
    conn.request("POST", parts.path or "/", body, headers)
    resp = conn.getresponse()
    raw = resp.read().decode("utf-8", "replace")
    conn.close()
    try:
        return resp.status, json.loads(raw)
    except ValueError:
        for line in reversed(raw.splitlines()):  # SSE: the last data line holding a response
            if line.startswith("data:"):
                try:
                    return resp.status, json.loads(line[5:].strip())
                except ValueError:
                    continue
    return resp.status, None


def list_all(url, method, key, token):
    """Return (items, first result) of a paginated list method."""
    items, cursor, first = [], None, None
    for _ in range(50):
        status, msg = rpc(url, method, {"cursor": cursor} if cursor else None, token)
        result = (msg or {}).get("result")
        if status != 200 or not isinstance(result, dict) or not isinstance(result.get(key), list):
            raise ValueError("%s failed: HTTP %s, %s" % (method, status, json.dumps(msg)[:200]))
        items += result[key]
        first = first or result
        cursor = result.get("nextCursor")
        if not cursor:
            return items, first
    raise ValueError("%s still paginating after 50 pages" % method)


def envelope_problems(result):
    """Results of 2026-07-28 MUST carry resultType and the caching hints, with ttlMs >= 0."""
    ttl, scope = result.get("ttlMs"), result.get("cacheScope")
    problems = []
    if not isinstance(result.get("resultType"), str):
        problems.append("resultType is missing")
    if not isinstance(ttl, int) or isinstance(ttl, bool) or ttl < 0:
        problems.append("ttlMs is %r, want an integer >= 0" % ttl)
    if scope not in ("public", "private"):
        problems.append("cacheScope is %r, want 'public' or 'private'" % scope)
    return problems


def envelope_check(result):
    """(ok, detail) of the envelope of a list result."""
    problems = envelope_problems(result)
    return not problems, "; ".join(problems) if problems else "resultType=%s ttlMs=%d cacheScope=%s" % (
        result["resultType"], result["ttlMs"], result["cacheScope"])


def lint_capability(url, token):
    status, msg = rpc(url, "server/discover", None, token)
    result = (msg or {}).get("result")
    caps = result.get("capabilities") if isinstance(result, dict) else None
    declared = isinstance(caps, dict) and isinstance(caps.get("resources"), dict)
    report("capability-declared", declared, "the `resources` capability is %s (server/discover, HTTP %s)"
           % ("declared" if declared else "missing", status))
    if declared:
        print("INFO resources capability: listChanged=%s subscribe=%s" % (
            caps["resources"].get("listChanged", False), caps["resources"].get("subscribe", False)))


def lint_listed(resources, templates):
    named = [r for r in resources if isinstance(r, dict) and isinstance(r.get("uri"), str)
             and SCHEME_RE.match(r["uri"]) and isinstance(r.get("name"), str)]
    report("resource-fields", len(named) == len(resources),
           "%d of %d resources have a name and an absolute URI with a scheme" % (len(named), len(resources)))
    uris = [r["uri"] for r in named]
    dup = sorted({u for u in uris if uris.count(u) > 1})
    report("uri-unique", not dup, "duplicates: %s" % dup if dup else "no duplicate URIs", "WARN")
    plain = [r["uri"] for r in named if not isinstance(r.get("mimeType"), str)]
    report("resource-mime", not plain, "no mimeType: %s" % plain if plain
           else "every listed resource states a mimeType", "WARN")
    good = [t for t in templates if isinstance(t, dict) and isinstance(t.get("name"), str)
            and isinstance(t.get("uriTemplate"), str) and VARIABLE_RE.search(t["uriTemplate"])]
    report("template-fields", len(good) == len(templates),
           "%d of %d templates have a name and a uriTemplate with a {variable}" % (len(good), len(templates)))


def decode_blob(blob):
    try:
        base64.b64decode(blob, validate=True)
        return True
    except (binascii.Error, ValueError, TypeError):
        return False


def lint_reads(url, uris, token):
    """Read each URI and check envelope, contents, blob encoding and mimeType."""
    envelope, content, blob, mime, answered = [], [], [], [], 0
    for uri in uris:
        status, msg = rpc(url, "resources/read", {"uri": uri}, token)
        result = (msg or {}).get("result") if isinstance(msg, dict) else None
        if not isinstance(result, dict):
            content.append("%s: HTTP %s without a result" % (uri, status))
            continue
        answered += 1
        if envelope_problems(result):
            envelope.append(uri)
        items = result.get("contents")
        if not isinstance(items, list) or not items:
            content.append("%s: contents is empty or not an array" % uri)
            continue
        for item in items:
            kinds = [k for k in ("text", "blob") if isinstance(item, dict) and isinstance(item.get(k), str)]
            if not isinstance(item, dict) or not isinstance(item.get("uri"), str) or len(kinds) != 1:
                content.append("%s: an item needs a uri and exactly one of text or blob" % uri)
                continue
            if "blob" in item and not decode_blob(item["blob"]):
                blob.append(uri)
            if not isinstance(item.get("mimeType"), str):
                mime.append(uri)
    report("read-envelope", not envelope, "resultType, ttlMs or cacheScope is wrong for %s" % envelope if envelope
           else "%d reads carry resultType, ttlMs and cacheScope" % answered)
    report("read-contents", not content, "; ".join(content) if content
           else "%d reads return non-empty contents, each item with a uri and exactly one of text or blob" % answered)
    report("read-blob-base64", not blob, "blob is not valid base64: %s" % blob if blob
           else "every blob is valid base64")
    report("read-mime", not mime, "no mimeType on contents of %s" % mime if mime
           else "every content item states a mimeType", "WARN")


def probe_not_found(url, uri, token, answered="FAIL"):
    """Read something that cannot exist. Return (PASS|WARN|FAIL, detail): -32602 is required, the legacy -32002
    only a WARN, an empty contents array is a FAIL, contents for a made-up URI get the level `answered`."""
    status, msg = rpc(url, "resources/read", {"uri": uri}, token)
    if not isinstance(msg, dict):
        return "FAIL", "HTTP %s without a JSON-RPC message for %s" % (status, uri)
    error = msg.get("error")
    if isinstance(error, dict):
        code = error.get("code")
        return ("PASS" if code == -32602 else "WARN" if code == -32002 else "FAIL",
                "%s answered with code %s (HTTP %s)" % (uri, code, status))
    if (msg.get("result") or {}).get("contents") == []:
        return "FAIL", "%s answered with an empty contents array, which hides the missing resource" % uri
    return answered, "%s was answered with contents, so the server cannot tell what is missing" % uri


def worst(outcomes):
    """The most severe (level, detail) of several outcomes; the details of that level are joined."""
    level = max((o[0] for o in outcomes), key=("PASS", "WARN", "FAIL").index)
    return level, "; ".join(o[1] for o in outcomes if o[0] == level)


def fill(template, value):
    return VARIABLE_RE.sub(value, template)


def lint_probes(url, templates, token):
    level, detail = probe_not_found(url, MISSING_URI, token)
    report("not-found-code", level == "PASS", detail, level)
    templates = [t["uriTemplate"] for t in templates if isinstance(t, dict) and isinstance(t.get("uriTemplate"), str)]
    templates = templates[:5]
    if templates:
        level, detail = worst([probe_not_found(url, fill(t, MISSING_VALUE), token, "WARN") for t in templates])
        report("template-not-found", level == "PASS", detail if level != "PASS"
               else "%d template probes answered with -32602" % len(templates), level)
    leaked = []
    for template in templates:
        for value in TRAVERSAL_VALUES:
            uri = fill(template, value)
            status, msg = rpc(url, "resources/read", {"uri": uri}, token)
            if isinstance(msg, dict) and (msg.get("result") or {}).get("contents"):
                leaked.append(uri)
    if templates:
        report("traversal-rejected", not leaked, "read succeeded for %s" % leaked if leaked
               else "%d traversal probes were rejected" % (len(templates) * len(TRAVERSAL_VALUES)))
    else:
        print("INFO no templates, the template and traversal probes are skipped")
    status, msg = rpc(url, "resources/read", {"uri": MISSING_URI}, token, name="lint-probe://other")
    code = ((msg or {}).get("error") or {}).get("code") if isinstance(msg, dict) else None
    report("header-mismatch", status == 400 and code == -32020,
           "a mismatching Mcp-Name was answered with HTTP %s, code %s (want 400, -32020)" % (status, code))
    status, msg = rpc(url, "resources/read", {"uri": "lint-probe://caf\u00e9"}, token)
    code = ((msg or {}).get("error") or {}).get("code") if isinstance(msg, dict) else None
    report("header-base64", code != -32020, "a non-ASCII URI sent as a Base64 sentinel was answered with code %s"
           % code)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("url")
    ap.add_argument("--token", help="bearer token for the endpoint")
    ap.add_argument("--max-reads", type=int, default=5, help="how many listed resources to read")
    args = ap.parse_args()
    if not args.url.startswith(("http://", "https://")):
        ap.error("URL must start with http:// or https://")
    try:
        resources, listing = list_all(args.url, "resources/list", "resources", args.token)
        templates, template_listing = list_all(args.url, "resources/templates/list", "resourceTemplates", args.token)
        print("INFO %d resources, %d templates" % (len(resources), len(templates)))
        lint_capability(args.url, args.token)
        report("list-envelope", *envelope_check(listing))
        report("templates-envelope", *envelope_check(template_listing))
        lint_listed(resources, templates)
        uris = [r["uri"] for r in resources if isinstance(r, dict) and isinstance(r.get("uri"), str)]
        if uris:
            lint_reads(args.url, uris[:args.max_reads], args.token)
        else:
            print("INFO no listed resources, the read checks are skipped")
        lint_probes(args.url, templates, args.token)
    except (OSError, ValueError, http.client.HTTPException) as exc:
        print("ERROR %s" % exc)
        return 2
    print("%d pass, %d warn, %d fail" % (counts["PASS"], counts["WARN"], counts["FAIL"]))
    return 1 if counts["FAIL"] else 0


if __name__ == "__main__":
    sys.exit(main())
python3 lint_resources.py http://127.0.0.1:8230/mcp
python3 lint_resources.py https://example.com/mcp --token "$TOKEN" --max-reads 10

FAIL 表示违反了“必须”;WARN 表示没做到“应当”或推荐做法。退出码 0 表示没有 FAIL,1 表示至少一个 FAIL,2 表示端点读取失败。

检查级别规则
capability-declaredFAILserver/discover 声明了 resources 能力
list-envelopeFAILresources/list 结果带 resultType、整数 ttlMs >= 0,以及取值为 public 或 private 的 cacheScope
templates-envelopeFAILresources/templates/list 同上
resource-fieldsFAIL每个已列出的资源都有字符串 name 和带 scheme 的 uri
uri-uniqueWARN列出的 URI 互不重复
resource-mimeWARN已列出的资源写明了 mimeType
template-fieldsFAIL每个模板都有 name,以及含 {变量} 的 uriTemplate
read-envelopeFAIL每个读取结果都带 resultType、ttlMs 和 cacheScope
read-contentsFAILcontents 是非空数组;每个条目有 uri,且 text 与 blob 恰有一个
read-blob-base64FAIL每个 blob 都是合法 base64
read-mimeWARN每个内容条目写明了 mimeType
not-found-codeFAIL编造的 URI 回 -32602;-32002 只是 WARN,空的 contents 或任何内容都是 FAIL
template-not-foundFAIL编造的模板取值回 -32602;-32002 或对编造取值返回内容是 WARN,空的 contents 是 FAIL
traversal-rejectedFAIL模板取值里的 ../、%2e%2e/ 和绝对路径从不返回内容(服务器没有列出模板时跳过)
header-mismatchFAILMcp-Name 与 uri 不同的读取,以 HTTP 400 和 -32020 回答
header-base64FAIL以 Base64 标记发送的非 ASCII URI 不会被 -32020 拒绝

对第八节 SDK 服务器的记录输出:

INFO 2 resources, 3 templates
PASS capability-declared: the `resources` capability is declared (server/discover, HTTP 200)
INFO resources capability: listChanged=True subscribe=True
PASS list-envelope: resultType=complete ttlMs=0 cacheScope=private
PASS templates-envelope: resultType=complete ttlMs=0 cacheScope=private
PASS resource-fields: 2 of 2 resources have a name and an absolute URI with a scheme
PASS uri-unique: no duplicate URIs
PASS resource-mime: every listed resource states a mimeType
PASS template-fields: 3 of 3 templates have a name and a uriTemplate with a {variable}
PASS read-envelope: 2 reads carry resultType, ttlMs and cacheScope
PASS read-contents: 2 reads return non-empty contents, each item with a uri and exactly one of text or blob
PASS read-blob-base64: every blob is valid base64
PASS read-mime: every content item states a mimeType
PASS not-found-code: lint-probe://missing/resource answered with code -32602 (HTTP 400)
PASS template-not-found: 3 template probes answered with -32602
PASS traversal-rejected: 9 traversal probes were rejected
PASS header-mismatch: a mismatching Mcp-Name was answered with HTTP 400, code -32020 (want 400, -32020)
PASS header-base64: a non-ASCII URI sent as a Base64 sentinel was answered with code -32602
16 pass, 0 warn, 0 fail

脚本还对一个每次只破坏一条规则的桩端点运行过。每个缺陷都由表中的某项检查指出:对不存在的资源返回空 contents、旧的 -32002、2025-11-25 形态的结果、同时带 text 和 blob 的条目、损坏的 blob、缺少名称或 scheme、接受 ../ 的模板、忽略或无法解码 Mcp-Name 的服务器,以及没有声明能力的服务器。

十一、发布资源之前

  • resources/list 对每条连接都相同(只允许随授权变化),带 ttlMs 与 cacheScope,过滤后的列表用 "private"。
  • 每个 URI 都带 scheme;自定义 scheme 符合 RFC 3986;只有客户端能直接取到时才用 https://。
  • 资源或模板取值不存在时返回 -32602,绝不返回空的 contents;客户端同时接受旧的 -32002。
  • 文本用 text,二进制用 base64 blob,每个条目都有 uri 与 mimeType。
  • 模板取值经过校验;路径相对于某个根目录解析;遍历与绝对路径被拒绝。
  • 到达客户端的错误不含密钥;崩溃记在服务器日志里。
  • 服务器读取 Mcp-Name,解码 Base64 标记,并以 -32020 拒绝不一致。
  • 数据会变化的话,声明 subscribe 与 listChanged,并告诉客户端收到 notifications/resources/updated 后重新读取;设置真实的 ttlMs。
  • 脚本在你的端点上通过;更换 SDK、网关或所服务的修订版之后重新运行。

版本与验证说明

表格由官方 schema.json 生成,官方示例逐个对 schema 校验,运行时行为来自对官方 Python SDK 2.3.0(mcp==2.3.0)的实际运行。规范文字与 schema 都取自官方仓库的同一个固定提交(dae694f6,含 2026-07-28 修订版及之前四个修订版)。表格用 jsonschema 4.26.0 生成并核对:schema 声明 draft-07 的修订版用 draft-07 校验器,其余用 2020-12 校验器。SDK 的运行使用 mcp==2.3.0、Python 3.14(macOS)。官方文本或 SDK 变化后需要重跑。

来源