加载中
加载中

MCP 服务器中的提示(prompts)让您可以定义预构建、高质量的指令,客户端可以直接使用,而无需从零开始编写自己的提示。可以将它们视为精心设计的模板,能够提供比用户自己想出的内容更好的结果。

为什么使用提示?

假设您希望 Claude 将文档重新格式化为 markdown。用户可能只需输入"将 report.pdf 转换为 markdown"就能得到不错的结果。但如果他们使用了您专门为文档格式化设计的、经过充分测试的专用提示,他们很可能会得到更好的输出。

用户提示"将 report.pdf 转换为 markdown"旁边是一个长提示,将 Claude 设定为文档转换专家。

关键的洞察在于:虽然用户可以自己完成这些任务,但当他们使用由 MCP 服务器作者精心设计和测试过的提示时,会获得更优质的结果。

提示的工作原理

提示定义了一组客户端可以直接使用的用户和助手消息。当客户端请求一个提示时,您的服务器会返回一个消息列表,这些消息可以直接发送给 Claude。

用户提示"将 report.pdf 转换为 markdown"旁边是一个长服务器提示,给出了角色、Markdown 规则和示例输出。

基本结构如下所示:

python
@mcp.prompt(
    name="format",
    description="Rewrites the contents of a document in Markdown format",
)
def format_document(
    doc_id: str = Field(description="Id of the document to format"),
) -> list[base.Message]:
    # 返回消息列表

构建格式化命令

下面是一个实际的例子。我们将创建一个格式化命令,让用户输入 /format doc_id 将任意文档重新格式化为 markdown 语法。

该提示的实现包含了给 Claude 的详细指令:

python
def format_document(
    doc_id: str = Field(description="Id of the document to format"),
) -> list[base.Message]:
    prompt = f"""
Your goal is to reformat a document to be written with markdown syntax.

The id of the document you need to reformat is:

{doc_id}


Add in headers, bullet points, tables, etc as necessary. Feel free to add in structure.
Use the 'edit_document' tool to edit the document. After the document has been reformatted...
"""
    
    return [
        base.UserMessage(prompt)
    ]

测试您的提示

您可以使用 MCP Inspector 测试提示。导航到 Prompts 选项卡,选择您的提示,并提供任何所需的参数。

MCP Inspector 中显示"format"提示,doc_id 设置为"outlook.pdf",以及 Get Prompt 返回的用户消息。

检查器会准确显示将发送给 Claude 的消息内容,包括任何参数是如何插入到提示文本中的。

主要优势

  • 质量控制 - 您可以在用户看到之前测试和完善提示
  • 一致性 - 用户每次都能获得可靠的结果
  • 专业化 - 提示可以针对您服务器的特定领域进行定制
  • 可复用性 - 多个客户端可以使用相同的精心设计的提示

实现细节

不要忘记导入消息类型所需的基础模块:

python
from mcp.server.fastmcp import FastMCP
from mcp.server.fastmcp.prompts import base

提示应当是高质量、经过充分测试的,并且与您的 MCP 服务器的整体用途相关。在我们的文档管理示例中,格式化提示非常合理,因为该服务器专门处理文档操作。