MCP 提示详解:参数、消息、补全与错误

MCP 提示详解:参数、消息、补全与错误

提示是服务器提供、由用户来挑选的可复用消息模板,例如斜杠命令菜单里的一项。它的路径是:能力声明、列表、参数、获取、补全、变更通知、失败。下面按 2026-07-28 修订版走完这条路径,并逐个修订版说明自 2024-11-05 以来改了什么。

宿主应用附带的数据见 MCP 资源详解,模型执行的动作见 MCP 工具详解。怎样把服务器设计得让模型好用,见 MCP 服务器最佳实践。规范的约束文本见官方 提示页。

一、提示、工具还是资源

规范给每种原语指定了不同的控制方。控制方决定由谁触发,也就决定了你该做哪一种。对提示,规范说得很明确:“用户控制”指的是由谁决定何时使用这个提示,而不是谁来写它的内容;内容由服务器定义。

你想要做成由谁触发原因
提供用户显式挑选的可复用起始消息(斜杠命令、菜单项)提示用户:提示是用户控制的由用户选择,消息由服务器填好
把指令与一个文件或一条记录捆成一条由用户选择的消息消息里带嵌入 resource 或 resource_link 的提示用户挑选提示,服务器决定嵌入什么用户的一次选择把指令和数据一起带来
把数据交给应用,作为上下文资源宿主应用:资源是应用驱动的宿主可以列出、搜索,或按启发式带入
让模型自己执行动作或取数工具模型:工具是模型控制的模型自己决定何时调用 tools/call
希望模型自己决定使用某个模板工具模型模型无法选择提示,选择的是用户。请把这个能力公开成工具

提示的参数永远是字符串(第三节)。输入有结构时,要么编码进字符串,要么把这个能力做成工具,工具的 inputSchema 才能描述结构。

二、一个提示的路径

步骤消息要点章节
1能力支持提示的服务器必须声明 prompts 能力。listChanged 表示它是否会通知变更四
2prompts/list支持分页与缓存。集合可以为空、可以随时间变化,但不得因连接而异三、四
3completion/complete可选。需要 completions 能力。引用是 {"type": "ref/prompt", "name": ...},每次最多 100 个值四
4prompts/get参数是字符串;结果是一组消息。也可以回复 InputRequiredResult四、五
5使用客户端把消息放进对话。这是宿主的工作,不是协议消息四
6subscriptions/listen带 promptsListChanged: true 时,集合变化后服务器应当发送 notifications/prompts/list_changed。通知不带列表:重新列出四

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

— 表示该修订版没有定义这个字段。各列是五个修订版(年月;完整日期是 2024-11-05、2025-03-26、2025-06-18、2025-11-25 与 2026-07-28)。

字段2024-112025-032025-062025-112026-07
Prompt.name必填必填必填必填必填
Prompt.title——可选可选可选
Prompt.description可选可选可选可选可选
Prompt.arguments可选可选可选可选可选
Prompt.icons———可选可选
Prompt._meta——可选可选可选
PromptArgument.name必填必填必填必填必填
PromptArgument.title——可选可选可选
PromptArgument.description可选可选可选可选可选
PromptArgument.required可选可选可选可选可选
PromptMessage.role必填必填必填必填必填
PromptMessage.content必填必填必填必填必填
字段2024-112025-032025-062025-112026-07
ListPromptsResult.prompts必填必填必填必填必填
ListPromptsResult.nextCursor可选可选可选可选可选
ListPromptsResult.ttlMs————必填
ListPromptsResult.cacheScope————必填
ListPromptsResult.resultType————必填
ListPromptsResult._meta可选可选可选可选可选
prompts/get params.name必填必填必填必填必填
prompts/get params.arguments可选可选可选可选可选
prompts/get params.inputResponses————可选
prompts/get params.requestState————可选
GetPromptResult.description可选可选可选可选可选
GetPromptResult.messages必填必填必填必填必填
GetPromptResult.resultType————必填
GetPromptResult._meta可选可选可选可选可选
PromptReference.type必填必填必填必填必填
PromptReference.name必填必填必填必填必填
PromptReference.title——可选可选可选

提示消息可以带哪些内容块,由 PromptMessage.content 解析得出:

内容块2024-112025-032025-062025-112026-07
text✓✓✓✓✓
image✓✓✓✓✓
audio—✓✓✓✓
resource_link——✓✓✓
resource✓✓✓✓✓

这些表说明了几件事:

  • 只有 name 是必填的,提示与参数都一样。title 自 2025-06 起有,icons 自 2025-11 起有。参数没写 required 就是可选。
  • 2026-07 改了列表结果。 ListPromptsResult 现在要求 ttlMs、cacheScope 和 resultType。GetPromptResult 只要求 resultType:缓存规则列出了 prompts/list 而没有 prompts/get,所以渲染出的提示不带缓存提示。
  • prompts/get 在 2026-07 增加了 inputResponses 与 requestState,用于多轮往返流程(第四节)。
  • 内容块变多了。 audio 自 2025-03 起被接受,resource_link 自 2025-06 起。2026-07 的提示页是第一次用文字描述资源链接(第五节的规则表),所以发送它们的服务器对 2025-06 及之后的 schema 是正确的,但按旧页面写的客户端可能没有预期到。
  • 角色只有 user 与 assistant,五个修订版都一样,没有 system 角色(第五节)。

四、列表、获取与变更通知

  • 能力。 支持提示的服务器必须在发现结果里声明,例如 { "capabilities": { "prompts": { "listChanged": true } } }。listChanged 可选。
  • 列表。 prompts/list 返回对发起请求的客户端可用的提示。集合可以为空、可以随时间变化、可以取决于请求上的授权,但不得因连接而异,也不得作为其他请求的副作用而变化。它是分页的:沿着 nextCursor 取下去。结果带 ttlMs(>= 0 的整数;0 表示立即过期)和 cacheScope。只有对所有用户都相同的列表才用 "public";缓存不得跨授权上下文共享。
  • 参数。 每个已列出的提示可以有 arguments:一组 name,以及可选的 title、description、required。在 prompts/get 里,客户端把 arguments 作为字符串值的对象发送。规范要求服务器应当在处理前校验提示参数,实现必须仔细校验所有提示的输入与输出(第五节规则表的最后一行)。
  • 消息。 结果里是 messages,每条有 role 和一个 content 块。文本是 text。图片和音频带 base64 的 data 与 mimeType(都是必须)。resource_link 指向一个资源但不嵌入它。嵌入的 resource 带 uri,以及 text 或 blob。客户端自己能读取该 URI 时用链接,提示必须自带数据时用嵌入资源。
  • 需要更多输入。 服务器可以用 InputRequiredResult 回复 prompts/get。客户端带着 inputResponses,以及服务器发来的 requestState(如果有)重试。见官方多轮往返请求页。
  • 补全。 声明了 completions 能力的服务器可以补全提示参数:客户端发送 completion/complete,带 ref: {"type": "ref/prompt", "name": ...}、参数名和已输入的值。最多返回 100 个值,context.arguments 带着已经选好的参数。见补全。
  • 变更通知。 声明了 listChanged 的服务器应当向以 promptsListChanged: true 打开 subscriptions/listen 的客户端发送 notifications/prompts/list_changed。客户端重新列出。

五、同一条消息,五份 schema

对某个修订版有效的消息,在其他修订版里还有效吗?每一行都对五份 schema.json 逐个校验。✓ 表示有效,✗ 表示被拒绝,— 表示该修订版没有定义这一行所指的东西,校验也就说明不了什么。

消息2024-112025-032025-062025-112026-07
不带 ttlMs、cacheScope、resultType 的 ListPromptsResult✓✓✓✓✗
不带 resultType 的 GetPromptResult✓✓✓✓✗
不带 ttlMs 和 cacheScope 的 GetPromptResult✓✓✓✓✓
带 audio 内容块的消息✗✓✓✓✓
带 resource_link 内容块的消息✗✗✓✓✓
角色为 system 的消息✗✗✗✗✗
messages 为空数组的 GetPromptResult✓✓✓✓✓
不带 params._meta 的 prompts/get 请求✓✓✓✓✗
参数值为数字的 prompts/get 请求✗✗✗✗✗
prompts/get 返回 input_required 结果✗✗✗✗✓
带 icons 的 Prompt———✓✓

各条消息与规则在哪个修订版里存在:

项目2024-112025-032025-062025-112026-07
notifications/prompts/list_changed✓✓✓✓✓
带 PromptReference 的 completion/complete✓✓✓✓✓
subscriptions/listen 请求————✓
promptsListChanged 过滤器————✓
prompts/get 的 inputResponses————✓
规范文本是否写到2024-112025-032025-062025-112026-07
服务端声明 prompts 能力✓✓✓✓✓
提示名无效返回 -32602✓✓✓✓✓
缺少必填参数返回 -32602✓✓✓✓✓
prompts/list 不得因连接而异————✓
列表可因请求携带的授权而异————✓
prompts/get 可返回 InputRequiredResult————✓
列表变更经 subscriptions/listen(promptsListChanged)送达————✓
音频数据必须是 base64 编码—✓✓✓✓
提示消息可包含资源链接————✓
实现必须校验所有提示的输入和输出✓✓✓✓✓

怎么读这个矩阵:

  • 2025-11-25 形态的结果会被 2026-07-28 拒绝:缺 resultType、ttlMs、cacheScope 的列表,以及缺 resultType 的获取结果(第 1、2 行)。没有缓存提示的获取结果是有效的(第 3 行)。
  • system 永远无效。 要移植系统提示,把它作为 user 消息发送。数字类型的参数同样永远无效,由客户端转成字符串。
  • 空的 messages 数组通过所有 schema。 规范没有禁止它,客户端应当把它当作“没有可插入的内容”,而不是错误。
  • 没有 params._meta 的 prompts/get 只被 2026-07-28 拒绝。 现在每个请求都带协议版本与客户端信息。
  • 规范文字落后于 schema:schema 自 2025-06 起允许资源链接,提示页自 2026-07 起才描述它们(规则表)。

最新修订版的官方示例已对各自的定义校验:12 个定义下的 14 个提示相关示例,无一无效。

六、经 Streamable HTTP 获取提示:Mcp-Name 头

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

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

POST /mcp HTTP/1.1
Mcp-Method: prompts/get
Mcp-Name: =?base64?csOpc3Vtw6k=?=

code_review 这样的普通名称原样发送。典型的两个 bug 是:客户端发送了原始的非 ASCII 值;服务器没有解码就拿头去比对正文。脚本会探测这两种情况(header-mismatch、header-base64)。

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

对提示,规范说服务器应当返回标准 JSON-RPC 错误:无效的提示名与缺少必需参数用 -32602(Invalid params),内部错误用 -32603。这是“应当”而不是“必须”,所以脚本对另一个错误码只给 WARN,对仍然渲染出结果的情形给 FAIL。

情形收到的内容怎么处理
提示名不存在规范:-32602。SDK 2.3.0 回复 -32603 Internal server error,HTTP 200(第八节)客户端:刷新列表并停止重试;对不在列表里的名称收到 -32603,就当作不存在。服务端:技术栈允许时返回 -32602
缺少必需参数规范:-32602。SDK 2.3.0 回复 -32603,HTTP 200同上。绝不要把参数当作空值或 None 来渲染提示
参数值不是字符串-32602 与 Invalid request parameters,HTTP 400(SDK)修客户端:把值转成字符串
你自己的校验失败(某个参数值不可接受)抛出 SDK 的 MCPError,错误码 INVALID_PARAMS:-32602 加上你的消息,HTTP 400写一条可以安全展示的消息:它会到达客户端
模板函数崩溃-32603 Internal server error,HTTP 200;SDK 不发出异常文本看服务器日志;退避重试是合理的
请求里缺少 name-32602 Invalid request parameters,HTTP 400修客户端
头与 name 不一致,或缺失HTTP 400 与 -32020(HeaderMismatchError)客户端或网关的 bug;修好头,非 ASCII 名称用 Base64 编码
服务器渲染之前需要更多输入不是错误:resultType: "input_required" 的结果回答这些请求,带着 inputResponses 与 requestState 重试

提示错误是协议错误:与工具结果不同,提示结果没有 isError 字段。

八、官方 Python SDK 2.3.0 的返回

参考服务器每种消息形态各定义一个提示:带可选参数的纯文本、三条消息的对话、来自封闭文件集的嵌入资源、资源链接、图片,以及一个故意崩溃的提示。它使用官方 SDK(pip install mcp==2.3.0)。add_prompt 工具只是为了让流的运行能让列表发生变化:

prompts_ref_server.py
"""Official Python SDK (mcp==2.3.0) prompts server at http://127.0.0.1:8231/mcp, no auth.

Prompts: a plain-text template with an optional argument, a multi-message conversation, a prompt that embeds a
file from `sample-docs/` (a closed set, anything else is an invalid-params error), a prompt that links to a
resource, a prompt that returns an image, and one that fails on purpose. The `focus` argument of `code_review`
has a completion handler. The tool `add_prompt` registers one more prompt at run time and announces the change
to `subscriptions/listen` streams.
"""
from pathlib import Path

from mcp.server.mcpserver import Context, MCPServer
from mcp.server.mcpserver.prompts.base import AssistantMessage, Message, UserMessage
from mcp.server.mcpserver.utilities.types import Image
from mcp.shared.exceptions import MCPError
from mcp.types import (Completion, EmbeddedResource, INVALID_PARAMS, ResourceLink, TextResourceContents)

ROOT = Path(__file__).resolve().parent / "sample-docs"
FILES = ["CHANGELOG.md", "checklist.md"]
FOCUS = ["correctness", "performance", "security", "style"]
# A 1x1 transparent PNG.
PIXEL = bytes.fromhex("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d49444154789c636460f80f"
                      "0001870180eb47ba920000000049454e44ae426082")

server = MCPServer("prompts-ref")


@server.prompt(title="Code review", description="Ask for a review of a piece of code")
def code_review(code: str, focus: str = "correctness") -> str:
    return "Please review this code, focusing on %s:\n\n%s" % (focus, code)


@server.prompt(title="Debug an error", description="Start a debugging conversation about an error message")
def debug_error(error: str) -> list[Message]:
    return [UserMessage("I am seeing this error:"), UserMessage(error),
            AssistantMessage("What is the smallest input that reproduces it?")]


@server.prompt(title="Review a file", description="Embed one of the sample files and ask for a review")
def review_file(name: str) -> list[Message]:
    if name not in FILES:
        raise MCPError(code=INVALID_PARAMS, message="unknown file %r, want one of %s" % (name, FILES))
    text = (ROOT / name).read_text(encoding="utf-8")
    embedded = EmbeddedResource(type="resource", resource=TextResourceContents(
        uri="file:///sample-docs/" + name, mime_type="text/markdown", text=text))
    return [UserMessage("Review this file for mistakes:"), UserMessage(embedded)]


@server.prompt(title="Release notes", description="Point the model at the release notes resource")
def release_notes() -> list[Message]:
    link = ResourceLink(type="resource_link", name="release", uri="notes://release", mime_type="text/plain")
    return [UserMessage("Summarize the release notes behind this link:"), UserMessage(link)]


@server.prompt(title="Explain the logo", description="Attach the logo as an image")
def explain_logo() -> list[Message]:
    return [UserMessage("What does this logo show?"), UserMessage(Image(data=PIXEL, format="png"))]


@server.prompt(title="Broken", description="Fails on purpose; a crash must not leak its text to the client")
def broken(secret: str = "x") -> str:
    raise RuntimeError("db password is hunter2")


@server.completion()
async def complete(ref, argument, context):
    if getattr(ref, "type", None) == "ref/prompt" and ref.name == "code_review" and argument.name == "focus":
        return Completion(values=[v for v in FOCUS if v.startswith(argument.value)], total=None, has_more=None)
    return None


@server.tool()
async def add_prompt(name: str, ctx: Context) -> str:
    """Register one more prompt named NAME and announce it to `subscriptions/listen` streams."""
    server.add_prompt(server._prompt_manager.get_prompt("code_review").model_copy(update={"name": name}))
    await ctx.notify_prompts_changed()
    return "added " + name


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

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

运行请求SDK 的返回对照规范
listprompts/listttlMs: 0、cacheScope: "private"、resultType: "complete",6 个提示有效。SDK 把必需的提示填成最保守的值
get-textcode_review,带必需的 code一条 user 文本消息,参数已填入有效
get-optionalcode_review,带 code 和 focus一条用到 focus 的 user 文本消息有效
get-conversationdebug_error三条文本消息:user、user、assistant有效:一个提示可以含多条消息和两种角色
get-embeddedreview_file,文件 checklist.md一条文本消息和一个嵌入的 resource,带 uri、mimeType 和 text有效
get-linkrelease_notes一条文本消息和一个 resource_link有效
get-imageexplain_logo一条文本消息和一个 image 块,image/png有效
unknown-prompt一个没有注册的名称HTTP 200、-32603、Internal server error合法的 InternalError,但规范说 -32602(应当):脚本给 WARN
missing-argumentcode_review,不带 codeHTTP 200、-32603、Internal server error同上
extra-argumentcode_review,带一个未知参数 bogusHTTP 200、-32603合法的错误。规范没有谈多余的参数;SDK 会拒绝它们
number-argumentcode 以数字 5 发送HTTP 400、-32602、Invalid request parameters一致:参数值在每个修订版里都是字符串
bad-filereview_file,文件 ../xHTTP 400、-32602、unknown file '../x' 加上允许的名称一致:处理函数抛出了 INVALID_PARAMS 的 MCPError,它的消息会到达客户端
crashbroken,处理函数抛出 RuntimeError("db password is hunter2")HTTP 200、-32603、Internal server error有效。异常文本不会发给客户端
header-mismatchMcp-Name 设成另一个名称HTTP 400、-32020、mcp-name header does not match符合 Streamable HTTP 的规则
missing-name不带 name 的 prompts/getHTTP 400、-32602、Invalid request parameters一致
complete-focus对 code_review.focus 做 completion/complete,值为 pvalues: ["performance"]有效
complete-unknown对不存在的提示做补全values: [],没有错误有效:SDK 把未知的引用当作没有可补全的内容
listen-acksubscriptions/listen,带 promptsListChanged: true一帧:确认,以请求 id 作为 subscriptionId 标记对确认通知的 schema 有效
listen-changed同一条流;add_prompt 注册一个提示先是确认,随后一条列表变更通知有效
list-after再次 prompts/list7 个提示有效:通知不带列表,客户端必须重新列出
二十次运行的原始记录
list             HTTP 200 result   ttlMs=0 cacheScope=private resultType=complete prompts=6 | ListPromptsResultResponse valid
get-text         HTTP 200 result   resultType=complete messages: user text 'Please review this code, focus' | GetPromptResultResponse valid
get-optional     HTTP 200 result   resultType=complete messages: user text 'Please review this code, focus' | GetPromptResultResponse valid
get-conversation HTTP 200 result   resultType=complete messages: user text 'I am seeing this error:'; user text 'boom'; assistant text 'What is the smallest input tha' | GetPromptResultResponse valid
get-embedded     HTTP 200 result   resultType=complete messages: user text 'Review this file for mistakes:'; user resource file:///sample-docs/checklist.md | GetPromptResultResponse valid
get-link         HTTP 200 result   resultType=complete messages: user text 'Summarize the release notes be'; user resource_link notes://release | GetPromptResultResponse valid
get-image        HTTP 200 result   resultType=complete messages: user text 'What does this logo show?'; user image image/png | GetPromptResultResponse valid
unknown-prompt   HTTP 200 error    code -32603 'Internal server error' | JSONRPCErrorResponse+InternalError valid
missing-argument HTTP 200 error    code -32603 'Internal server error' | JSONRPCErrorResponse+InternalError valid
extra-argument   HTTP 200 error    code -32603 'Internal server error' | JSONRPCErrorResponse+InternalError valid
number-argument  HTTP 400 error    code -32602 'Invalid request parameters' | JSONRPCErrorResponse+InvalidParamsError valid
bad-file         HTTP 400 error    code -32602 "unknown file '../x', want one of ['CHANGELOG.md', 'checklist.md']" | JSONRPCErrorResponse+InvalidParamsError valid
crash            HTTP 200 error    code -32603 'Internal server error' | JSONRPCErrorResponse+InternalError valid
header-mismatch  HTTP 400 error    code -32020 "mcp-name header does not match the request body's 'name' parameter" | JSONRPCErrorResponse+HeaderMismatchError valid
missing-name     HTTP 400 error    code -32602 'Invalid request parameters' | JSONRPCErrorResponse+InvalidParamsError valid
complete-focus   HTTP 200 result   resultType=complete values=['performance'] | CompleteResultResponse valid
complete-unknown HTTP 200 result   resultType=complete values=[] | CompleteResultResponse valid
listen-ack       HTTP 200 stream   ack(promptsListChanged=True) | SubscriptionsAcknowledgedNotification valid
listen-changed   HTTP 200 stream   ack(promptsListChanged=True) -> list_changed | PromptListChangedNotification+SubscriptionsAcknowledgedNotification valid
list-after       HTTP 200 result   ttlMs=0 cacheScope=private resultType=complete prompts=7 | ListPromptsResultResponse valid

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

  • 未知提示与缺少参数是 -32603,不是 -32602。 SDK 在你的函数运行之前检查名称与必需参数,抛出的是普通异常,服务器把它变成通用的内部错误,HTTP 200。规范说 -32602(应当)。这个 SDK 的客户端只能靠列表来区分“不存在”和“服务器故障”。
  • 你自己的 MCPError 会保留错误码。 在函数里抛出 MCPError(code=INVALID_PARAMS, ...) 得到 -32602、HTTP 400 和你的消息。用它校验参数值,并保证文字可以安全展示。
  • 崩溃是通用的。 模板函数里抛出的异常文本,客户端永远看不到;原因留在服务器日志里。
  • 参数来自函数签名。 没有默认值的形参列为 required: true,有默认值的是 required: false。值必须是字符串;其他类型在你的代码运行前就是 -32602。
  • 富消息可用。 返回的消息列表保留各自的角色;SDK 的 Image 辅助类变成 image 块;EmbeddedResource 或 ResourceLink 原样通过。
  • 变更通知很小。 SDK 先确认这条流,再发送 notifications/prompts/list_changed。通知不带列表,所以客户端要重新列出(list-after)。

九、失败模式与恢复

现象原因怎么发现怎么恢复
客户端对不存在的提示反复重试,或者显示为服务器故障服务器对未知名称返回 -32603(SDK 的做法)而不是 -32602unknown-prompt(WARN)客户端:对不在列表里的名称收到 -32603,就当作不存在。服务端:技术栈允许时返回 -32602
提示用空值或 None 的参数渲染出来服务器没有检查必需参数missing-argument(有结果返回时是 FAIL)渲染前校验,并回复 -32602
客户端丢弃或拒绝某条消息角色是 system(或不是 user、assistant 的任何值)get-messages把系统文本作为 user 消息发送
图片或音频块无法显示data 不是有效 base64,或缺少 mimeTypeget-content用标准 base64 编码,并写明 MIME 类型
嵌入的资源无法使用text 与 blob 同时有、都没有,或 blob 无效get-contenttext 与 blob 恰好一个,加上 uri
2026-07-28 的客户端拒绝列表结果缺 resultType、ttlMs 或 cacheScope(2025-11-25 的形态)list-envelope补上这三个字段;ttlMs: 0 加 "private" 永远有效
渲染出的提示被拒绝结果缺 resultTypeget-envelope补上 resultType: "complete"
两个客户端看到不同的提示列表列表取决于连接状态。这是不得的;只有授权可以改变它list-stable(WARN,启发式),或在两条连接上列出并对比只按请求的授权来计算列表;这样的列表标 "private"
某个用户的提示从缓存里被发给另一个用户取决于用户的列表被标成 cacheScope: "public",或缓存忽略了授权用两个令牌对比 cacheScope 与列表取决于用户的列表用 "private"
客户端菜单里是过期的提示没有声明 listChanged,或没有人带 promptsListChanged: true 监听,或流断开了检查能力;观察流里有没有确认声明 listChanged,监听,收到通知或重连后重新列出
每个非 ASCII 的提示名都回 -32020服务器没有解码 Base64 标记就拿 Mcp-Name 比对正文,或客户端发了原始值header-base64先解码再比对;客户端负责编码
经过网关的请求以 -32020 或 400 失败网关丢掉或改写了 Mcp-Method 或 Mcp-Nameheader-mismatch;对比两端的头原样转发标准头
补全卡住界面或被截断服务器返回的值超过 100 个completion-values最多返回 100 个并设置 hasMore
密钥出现在客户端的错误消息里处理函数把后端的消息放进了 MCPError触发每种失败并阅读消息只用可以安全展示的文字抛出 MCPError;让崩溃保持通用

十、检查你自己的提示端点

lint_prompts.py 连接一个 Streamable HTTP 端点。它列出提示,渲染其中最多五个,并发出几个健康服务器不应满足的探测:未知的提示名、缺少必需参数、不匹配的 Mcp-Name、非 ASCII 的提示名。必需参数用文本 lint-sample 填充;传 --arg PROMPT.ARGUMENT=VALUE 可以给出真实的值,被拒绝的样例值报为 INFO,不算缺陷。渲染提示和请求补全在健康的服务器上不会改动任何东西;不要把脚本指向它们有副作用的端点。它只需要 Python 3 标准库:

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

Usage: lint_prompts.py URL [--token T] [--max-gets N] [--arg PROMPT.ARGUMENT=VALUE ...]
URL: the Streamable HTTP endpoint. The linter lists the prompts, renders up to N of them (default 5) and sends a
few probes that no healthy server may satisfy: an unknown prompt name, a missing required argument, a mismatching
`Mcp-Name` header and a non-ASCII prompt name. Required arguments of a listed prompt are filled with the text
`lint-sample` unless `--arg` gives a real value; a rejected sample value is reported as INFO, not as a defect.
Rendering a prompt and a completion request change nothing in a healthy server; do not point the linter at an
endpoint where they have 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 sys
from urllib.parse import urlsplit

VERSION = "2026-07-28"
SAMPLE = "lint-sample"
MISSING_PROMPT = "lint-probe-missing-prompt"
ROLES = ("user", "assistant")
NAMED_METHODS = ("prompts/get", "tools/call")  # methods whose Mcp-Name header carries params.name
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`; pass `name` to
    send another value."""
    meta = {"io.modelcontextprotocol/protocolVersion": VERSION,
            "io.modelcontextprotocol/clientInfo": {"name": "lint-prompts", "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")
    if isinstance(source, str) and method in NAMED_METHODS:
        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, token):
    """Return (prompts, first result) of the paginated `prompts/list`."""
    items, cursor, first = [], None, None
    for _ in range(50):
        status, msg = rpc(url, "prompts/list", {"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("prompts"), list):
            raise ValueError("prompts/list failed: HTTP %s, %s" % (status, json.dumps(msg)[:200]))
        items += result["prompts"]
        first = first or result
        cursor = result.get("nextCursor")
        if not cursor:
            return items, first
    raise ValueError("prompts/list still paginating after 50 pages")


def envelope_problems(result, caching):
    """Every 2026-07-28 result MUST carry resultType; list results also carry ttlMs >= 0 and cacheScope."""
    problems = []
    if not isinstance(result.get("resultType"), str):
        problems.append("resultType is missing")
    if caching:
        ttl, scope = result.get("ttlMs"), result.get("cacheScope")
        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 decode_blob(blob):
    try:
        base64.b64decode(blob, validate=True)
        return True
    except (binascii.Error, ValueError, TypeError):
        return False


def content_problem(block):
    """None when a message content block has the shape of its `type`, else the problem as text."""
    if not isinstance(block, dict):
        return "content is not an object"
    kind = block.get("type")
    if kind == "text":
        return None if isinstance(block.get("text"), str) else "text block without a text string"
    if kind in ("image", "audio"):
        ok = isinstance(block.get("mimeType"), str) and isinstance(block.get("data"), str) \
            and decode_blob(block["data"])
        return None if ok else "%s block needs a mimeType and base64 data" % kind
    if kind == "resource_link":
        ok = isinstance(block.get("uri"), str) and isinstance(block.get("name"), str)
        return None if ok else "resource_link block needs a uri and a name"
    if kind == "resource":
        res = block.get("resource")
        kinds = [k for k in ("text", "blob") if isinstance(res, dict) and isinstance(res.get(k), str)]
        if not isinstance(res, dict) or not isinstance(res.get("uri"), str) or len(kinds) != 1:
            return "embedded resource needs a uri and exactly one of text or blob"
        return None if "blob" not in res or decode_blob(res["blob"]) else "embedded blob is not valid base64"
    return "unknown content type %r" % kind


def lint_capability(url, token):
    """Check the `prompts` capability and return the capabilities object ({} when unreadable)."""
    status, msg = rpc(url, "server/discover", None, token)
    result = (msg or {}).get("result")
    caps = result.get("capabilities") if isinstance(result, dict) else None
    caps = caps if isinstance(caps, dict) else {}
    declared = isinstance(caps.get("prompts"), dict)
    report("capability-declared", declared, "the `prompts` capability is %s (server/discover, HTTP %s)"
           % ("declared" if declared else "missing", status))
    if declared:
        print("INFO prompts capability: listChanged=%s; completions %s" % (
            caps["prompts"].get("listChanged", False), "declared" if "completions" in caps else "not declared"))
    return caps


def lint_listed(prompts):
    named = [p for p in prompts if isinstance(p, dict) and isinstance(p.get("name"), str) and p["name"]]
    report("prompt-fields", len(named) == len(prompts), "%d of %d prompts have a name" % (len(named), len(prompts)))
    names = [p["name"] for p in named]
    dup = sorted({n for n in names if names.count(n) > 1})
    report("name-unique", not dup, "duplicates: %s" % dup if dup else "no duplicate prompt names")
    bad, usable = [], []
    for p in named:
        args = p.get("arguments", [])
        ok = isinstance(args, list) and all(isinstance(a, dict) and isinstance(a.get("name"), str)
                                            and isinstance(a.get("required", False), bool) for a in args)
        (usable if ok else bad).append(p if ok else p["name"])
    report("argument-fields", not bad, "malformed arguments in %s" % bad if bad
           else "every argument has a name and a boolean `required` when present")
    twice = [p["name"] for p in named if isinstance(p.get("arguments"), list)
             and len({a.get("name") for a in p["arguments"] if isinstance(a, dict)}) < len(p["arguments"])]
    report("argument-unique", not twice, "repeated argument names in %s" % twice if twice
           else "no prompt repeats an argument name", "WARN")
    bare = [p["name"] for p in named if not isinstance(p.get("description"), str) or not p["description"]]
    report("prompt-description", not bare, "no description: %s" % bare if bare
           else "every listed prompt has a description", "WARN")
    return usable


def sample_arguments(prompt, overrides):
    """(arguments, sampled): arguments for `prompts/get`, and whether a required one is a made-up sample."""
    args, sampled = {}, False
    for arg in prompt.get("arguments", []):
        if arg.get("required"):
            key = "%s.%s" % (prompt["name"], arg["name"])
            sampled = sampled or key not in overrides
            args[arg["name"]] = overrides.get(key, SAMPLE)
    return args, sampled


def lint_gets(url, prompts, overrides, token, limit):
    """Render each prompt and check the envelope, the messages and every content block."""
    envelope, messages, content, failed, skipped, rendered = [], [], [], [], [], 0
    for prompt in prompts[:limit]:
        args, sampled = sample_arguments(prompt, overrides)
        status, msg = rpc(url, "prompts/get", {"name": prompt["name"], "arguments": args} if args
                          else {"name": prompt["name"]}, token)
        result = msg.get("result") if isinstance(msg, dict) else None
        if not isinstance(result, dict):
            code = ((msg or {}).get("error") or {}).get("code") if isinstance(msg, dict) else None
            (skipped if sampled else failed).append("%s (HTTP %s, code %s)" % (prompt["name"], status, code))
            continue
        rendered += 1
        if envelope_problems(result, False):
            envelope.append(prompt["name"])
        items = result.get("messages")
        if not isinstance(items, list):
            messages.append("%s: messages is not an array" % prompt["name"])
            continue
        for item in items:
            if not isinstance(item, dict) or item.get("role") not in ROLES:
                messages.append("%s: role %r, want one of %s" % (prompt["name"], (item or {}).get("role")
                                                                 if isinstance(item, dict) else item, list(ROLES)))
                continue
            problem = content_problem(item.get("content"))
            if problem:
                content.append("%s: %s" % (prompt["name"], problem))
    report("get-envelope", not envelope, "resultType is missing for %s" % envelope if envelope
           else "%d rendered prompts carry resultType" % rendered)
    report("get-messages", not messages, "; ".join(messages) if messages
           else "messages is an array and every message has the role user or assistant")
    report("get-content", not content, "; ".join(content) if content
           else "every content block has the shape of its type (text, image, audio, resource_link, resource)")
    report("get-succeeds", not failed, "prompts/get failed for %s" % "; ".join(failed) if failed
           else "every prompt that needs no sample value rendered", "WARN")
    if skipped:
        print("INFO sample values were rejected for %s; pass --arg PROMPT.ARGUMENT=VALUE to judge them"
              % "; ".join(skipped))


def probe_error(url, params, token, what):
    """Send a request no healthy server may satisfy. Return (PASS|WARN|FAIL, detail): -32602 passes, another
    error code is a WARN (the spec says SHOULD), a rendered result is a FAIL."""
    status, msg = rpc(url, "prompts/get", params, token)
    if not isinstance(msg, dict):
        return "FAIL", "HTTP %s without a JSON-RPC message for %s" % (status, what)
    error = msg.get("error")
    if isinstance(error, dict):
        code = error.get("code")
        return ("PASS" if code == -32602 else "WARN", "%s answered with code %s (HTTP %s)" % (what, code, status))
    return "FAIL", "%s was answered with a result, so the server rendered something that cannot exist" % what


def lint_probes(url, prompts, token):
    level, detail = probe_error(url, {"name": MISSING_PROMPT}, token, "an unknown prompt")
    report("unknown-prompt", level == "PASS", detail, level)
    needy = next((p for p in prompts if any(a.get("required") for a in p.get("arguments", []))), None)
    if needy:
        level, detail = probe_error(url, {"name": needy["name"]}, token, "%s without its required arguments"
                                    % needy["name"])
        report("missing-argument", level == "PASS", detail, level)
    else:
        print("INFO no listed prompt has a required argument, the missing-argument probe is skipped")
    status, msg = rpc(url, "prompts/get", {"name": MISSING_PROMPT}, 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, "prompts/get", {"name": "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 prompt name sent as a Base64 sentinel was answered with "
           "code %s" % code)


def lint_completion(url, prompts, caps, token):
    """Ask for completions of the first argument of the first prompt that has one."""
    target = next(((p, a) for p in prompts for a in p.get("arguments", []) if isinstance(a, dict)), None)
    if "completions" not in caps or not target:
        print("INFO completions are not declared or no prompt has an argument, the completion probe is skipped")
        return
    prompt, arg = target
    status, msg = rpc(url, "completion/complete", {"ref": {"type": "ref/prompt", "name": prompt["name"]},
                                                   "argument": {"name": arg["name"], "value": ""}}, token)
    values = (((msg or {}).get("result") or {}).get("completion") or {}).get("values") if isinstance(msg, dict) \
        else None
    ok = isinstance(values, list) and len(values) <= 100 and all(isinstance(v, str) for v in values)
    report("completion-values", ok, "%s.%s answered with %d string values (HTTP %s)" % (
        prompt["name"], arg["name"], len(values), status) if ok else
        "completion for %s.%s is not an array of at most 100 strings (HTTP %s)" % (prompt["name"], arg["name"],
                                                                                    status))


def parse_overrides(items, ap):
    overrides = {}
    for item in items:
        key, sep, value = item.partition("=")
        if not sep or "." not in key:
            ap.error("--arg wants PROMPT.ARGUMENT=VALUE, got %r" % item)
        overrides[key] = value
    return overrides


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("url")
    ap.add_argument("--token", help="bearer token for the endpoint")
    ap.add_argument("--max-gets", type=int, default=5, help="how many listed prompts to render")
    ap.add_argument("--arg", action="append", default=[], metavar="PROMPT.ARGUMENT=VALUE",
                    help="a real value for a required argument (repeatable)")
    args = ap.parse_args()
    if not args.url.startswith(("http://", "https://")):
        ap.error("URL must start with http:// or https://")
    overrides = parse_overrides(args.arg, ap)
    try:
        prompts, listing = list_all(args.url, args.token)
        print("INFO %d prompts" % len(prompts))
        caps = lint_capability(args.url, args.token)
        problems = envelope_problems(listing, True)
        report("list-envelope", not problems, "; ".join(problems) if problems else
               "resultType=%s ttlMs=%d cacheScope=%s" % (listing["resultType"], listing["ttlMs"],
                                                         listing["cacheScope"]))
        named = lint_listed(prompts)
        if named:
            lint_gets(args.url, named, overrides, args.token, args.max_gets)
        else:
            print("INFO no listed prompts, the render checks are skipped")
        lint_probes(args.url, named, args.token)
        lint_completion(args.url, named, caps, args.token)
        again, _ = list_all(args.url, args.token)
        before = sorted(str(p.get("name")) for p in prompts if isinstance(p, dict))
        after = sorted(str(p.get("name")) for p in again if isinstance(p, dict))
        report("list-stable", before == after, "the set of prompts differs between two lists taken one after "
               "the other (legitimate only if it changed in between)" if before != after
               else "two consecutive lists return the same prompts", "WARN")
    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_prompts.py http://127.0.0.1:8231/mcp --arg review_file.name=checklist.md
python3 lint_prompts.py https://example.com/mcp --token "$TOKEN" --max-gets 10

FAIL 表示违反了“必须”;WARN 表示没做到“应当”或推荐做法。退出码 0 表示没有 FAIL,1 表示至少一个 FAIL,2 表示端点读取失败,其中包括列表分页超过 50 页仍未结束。

检查级别规则
capability-declaredFAILserver/discover 声明了 prompts 能力
list-envelopeFAILprompts/list 的结果带 resultType、>= 0 的整数 ttlMs,以及取值为 public 或 private 的 cacheScope
prompt-fieldsFAIL每个已列出的提示都有非空字符串 name
name-uniqueFAIL提示名唯一
argument-fieldsFAIL每个参数都有字符串 name,有 required 时它是布尔值
argument-uniqueWARN一个提示不重复同一个参数名
prompt-descriptionWARN每个已列出的提示都有描述
get-envelopeFAIL每个渲染结果都带 resultType
get-messagesFAILmessages 是数组,每条消息的角色是 user 或 assistant
get-contentFAIL每个内容块都符合其类型的形状:text 有字符串,image 与 audio 有 mimeType 和 base64 的 data,resource_link 有 uri 与 name,resource 有 uri,以及恰好一个 text 或 blob(有效 base64)
get-succeedsWARN不需要样例值的提示能无错误地渲染
unknown-promptFAIL未知名称回复 -32602;另一个错误码是 WARN,渲染出结果是 FAIL
missing-argumentFAIL缺少必需参数的提示回复 -32602;另一个错误码是 WARN,渲染出结果是 FAIL(没有提示带必需参数时跳过)
header-mismatchFAILMcp-Name 与 name 不同的 prompts/get 回复 HTTP 400 与 -32020
header-base64FAIL以 Base64 标记发送的非 ASCII 提示名不会以 -32020 被拒绝
completion-valuesFAIL声明了 completions 时,对第一个提示的第一个参数做补全,结果是最多 100 个字符串的数组(否则跳过)
list-stableWARN连续两次列表返回相同的提示。服务器在两次之间合法地改变列表是可能的

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

INFO 6 prompts
PASS capability-declared: the `prompts` capability is declared (server/discover, HTTP 200)
INFO prompts capability: listChanged=True; completions declared
PASS list-envelope: resultType=complete ttlMs=0 cacheScope=private
PASS prompt-fields: 6 of 6 prompts have a name
PASS name-unique: no duplicate prompt names
PASS argument-fields: every argument has a name and a boolean `required` when present
PASS argument-unique: no prompt repeats an argument name
PASS prompt-description: every listed prompt has a description
PASS get-envelope: 5 rendered prompts carry resultType
PASS get-messages: messages is an array and every message has the role user or assistant
PASS get-content: every content block has the shape of its type (text, image, audio, resource_link, resource)
PASS get-succeeds: every prompt that needs no sample value rendered
WARN unknown-prompt: an unknown prompt answered with code -32603 (HTTP 200)
WARN missing-argument: code_review without its required arguments answered with code -32603 (HTTP 200)
PASS header-mismatch: a mismatching Mcp-Name was answered with HTTP 400, code -32020 (want 400, -32020)
PASS header-base64: a non-ASCII prompt name sent as a Base64 sentinel was answered with code -32603
PASS completion-values: code_review.code answered with 0 string values (HTTP 200)
PASS list-stable: two consecutive lists return the same prompts
15 pass, 2 warn, 0 fail

脚本还对一个每次只破坏一条规则的桩端点运行过。每个缺陷都由表中的某项检查指出:没有 prompts 能力、2025-11-25 形态的结果、没有名称或名称重复的提示、没有名称的参数或重复的参数、没有描述的提示、角色 system、没有文本的 text 块与没有数据的 image 块、不是 base64 的 blob、本该被拒绝却被渲染的未知提示或缺少的参数、-32603 而不是 -32602、无法用样例值渲染的提示、从不比对或不解码的头、两次调用之间增长的列表、nextCursor 永远不结束的列表(退出码 2)、含 101 个值的补全、不是 JSON 的响应体,以及空列表(规范允许,脚本报告时不算缺陷)。没有缺陷的桩端点通过且没有警告。

十一、发布提示之前

  • 声明了 prompts 能力;只有确实会通知变更时才声明 listChanged。
  • prompts/list 对每条连接都相同(只允许随授权变化),带 ttlMs 与 cacheScope,取决于用户的列表用 "private"。
  • 每个提示都有唯一的 name、title 与 description;每个参数都有 name,需要时写 required。
  • 参数是字符串;必需参数在渲染前检查,缺少时回 -32602,绝不用空值代替。
  • 消息只用 user 和 assistant 两种角色;图片与音频是带 mimeType 的 base64;嵌入的资源有 uri,以及恰好一个 text 或 blob。
  • 到达客户端的错误不含密钥;崩溃记在服务器日志里。
  • 服务器读取 Mcp-Name,解码 Base64 标记,并以 -32020 拒绝不一致。
  • 提供补全的话,最多返回 100 个值。
  • 脚本在你的端点上通过;更换 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 变化后需要重跑。

来源