AIHero
    03 / 06模型上下文协议教程 · 阅读约 3 分钟

    使用 MCP 提示词

    使用提示词模板释放 MCP Server 的能力,非常适合增强 LLM 工作流,并通过自定义命令提高效率。

    Matt Pocock
    Matt Pocock
    源代码下一课
    本页目录

    到目前为止,我们一直在讨论如何向 MCP Server 添加工具。

    但网上很少有人讨论另一项能力:可以通过 MCP Server 向用户提供提示词。

    这使你可以把 MCP 用作 提示词目录 ——也就是一组可供用户随时调用、快速完成目标的提示词。

    下面展示 我最喜欢的提示词模板之一 ,我在创作本文时就使用了它。

    代码

    先从样板代码开始:Server 和 Transport:

    import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
    import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
    const server = new McpServer({
    name: "Prompt Directory",
    version: "1.0.0",
    });
    // ...more code in here
    const transport = new StdioServerTransport();
    await server.connect(transport);

    这个 Server 将包含一个 cleanTranscription 提示词。我大多数文章都通过口述录制,这个提示词能帮助我清理转录中的错误。

    滚动式代码讲解

    1

    首先添加一个 prompt 到 Server。它的语法与 tool非常相似。不过这里不使用 server.tool,而是调用 server.prompt:

    2

    接下来添加一段描述,说明这个工具的实际作用。

    3

    这个工具会接收需要清理的文件路径,因此使用 zod 定义该参数:

    4

    最后添加回调函数,返回提示词的值。返回结果位于 messages 数组中,其中 role 为 user ,并包含一段文本内容。

    server.prompt("cleanTranscription");

    这意味着我们已经向 MCP Server 添加了一个名为 clean transcription 的提示词模板。

    提示词

    如果你感兴趣,下面就是我使用的提示词:

    const getPrompt = (path: string) =>
    `
    Clean up the transcript in the file at ${path}
    Do not edit the words,
    only the formatting and any incorrect transcriptions.
    Turn long-form numbers to short-form:
    One hundred and twenty-three -> 123
    Three hundred thousand, four hundred and twenty-two -> 300,422
    Add punctuation where necessary.
    Wrap any references to code in backticks.
    Include links as-is - do not modify links.
    Common terms:
    LLM-as-a-judge
    ReAct
    Reflexion
    RAG
    Vercel
    `;

    其中大约包含 200 个常见术语,为保持简洁,这里没有全部列出。

    演示

    可以在 Claude Code 中采用与 前面相同的方式.

    连接后,提示词模板会作为一个可在 Claude 内部运行的命令加载。输入以下内容即可访问: /cleanTranscription ,从 Claude Code 界面连接到这个 Server。提示词会通过自动补全显示:

    /cleanTranscription visible from Claude Code

    运行命令后,系统会提示我们填写 path 参数:

    Claude Code asking for the path variable

    随后便会针对该文件运行提示词。

    总结

    这是一个把 MCP Server 用作提示词目录的简单示例。你可以向用户提供一组提示词,让他们用这些提示词引导自己的 LLM 行为。

    它既是非常强大的个人效率工具,也可以为 MCP Client 的常用工作流提供命令。

    登录以保存进度。