0. 什么是 MCP

MCP 是一个开放协议,他定义了向 LLM 提供上下文的的方式,通过一种标准化的方式将外部工具或数据源接入到大模型。

image.png

作为服务端开发者,主要关心如何开发 MCP Server 将自己的业务服务接入到大模型。

MCP 服务主要提供一下三种功能:

  1. 资源 Resource:客户端可以读取的数据,可以是文本、文件、uri 等等。
  2. 工具 Tools:LLM 可以调用的函数。LLM 可以通过工具获取外部世界的信息甚至操控外部世界。
  3. 提示词 Prompt:帮助用户完成特定功能预先设置好的提示词,用户可以通过“/”触发选择。

我们主要关注工具的实现

1. 交互协议

MCP 客户端与服务器之间的所有消息必须遵循 JSON-RPC 2.0规范

{
  jsonrpc: "2.0";
  id: string | number;
  method: string;
  params?: {
    [key: string]: unknown;
  };
}

1.1 初始化

初始化阶段是客户端和服务端首次通信

客户端需要向服务端提供:支持的协议版本,客户端信息

服务端的响应提供:服务端支持的功能,协商后的版本号,服务端的信息

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "initialize",
  "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "roots": {
        "listChanged": true
      },
      "sampling": {},
      "elicitation": {}
    },
    "clientInfo": {
      "name": "ExampleClient",
      "title": "Example Client Display Name",
      "version": "1.0.0"
    }
  }
}

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "logging": {},
      "prompts": {
        "listChanged": true
      },
      "resources": {
        "subscribe": true,
        "listChanged": true
      },
      "tools": {
        "listChanged": true
      }
    },
    "serverInfo": {
      "name": "ExampleServer",
      "title": "Example Server Display Name",
      "version": "1.0.0"
    },
    "instructions": "Optional instructions for the client"
  }
}