MCP Server

MCP是一套 标准协议, 它规定了 应用程序 之间 如何通信 如何通信: 基本规范 1. 初始化 initia…

MCP是一套 标准协议, 它规定了 应用程序 之间 如何通信

如何通信:

  • 通信方式
    • stdio: 推荐,高效、简洁、本地
    • http: 可远程
      • StreamHTTP
      • SSE
  • 通信格式: 基于JSON-RPC的进一步规范

基本规范

1. 初始化 initialize

两个应用程序要开始通信,首先需要初始化

request

{
 "jsonrpc": "2.0",
 "id": 1,
 "method": "initialize", // 固定为 initialize
 "params": {
   "protocolVersion": "2024-11-05",
   "capabilities": {
     "roots": {
       "listChanged": true
    },
     "sampling": {},
     "elicitation": {}
  },
   "clientInfo": { // 告知服务器客户端的信息
     "name": "ExampleClient",
     "title": "Example Client Display Name",
     "version": "1.0.0"
  }
}
}

response

{
 "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"
}
}

2. 发现工具 tools/list

服务器有哪些工具函数可以供客户端调用

request

{
 "jsonrpc": "2.0",
 "id": 1,
 "method": "tools/list",
}

response

{
 "jsonrpc": "2.0",
 "id": 1,
 "result": {
   "tools": [
    {
       "name": "get_weather",
       "title": "Weather Information Provider",
       "description": "Get current weather information for a location",
       "inputSchema": {
         "type": "object",
         "properties": {
           "location": {
             "type": "string",
             "description": "City name or zip code"
          },
        },
         "required": ["location"]
      }
    }
  ]
}
}

3. 工具调用 tools/call

request

{
 "jsonrpc": "2.0",
 "id": 2,
 "method": "tools/call", // 调用工具
 "params": {
   "name": "get_weather", // 工具名,对应工具发现中的name
   "arguments": { // 工具参数,需要和工具发现中的结构一致
     "location": "New York"
  }
}
}

response

{
 "jsonrpc": "2.0",
 "id": 2,
 "result": {
   "content": [{ // 函数结果需要放到content字段中,如果有多个,使用数组
     // 函数结果的类型
     // 支持的类型: https://modelcontextprotocol.io/specification/2025-06-18/server/tools#tool-result
     "type": "text",
     "text": "72°F"
  }]
}
}

文档https://modelcontextprotocol.io/specification/2025-06-18/server/tools#listing-tools

Previous Post

Next Post

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

About the Author

每个人都有自己得时区,在自己得时区里,一切都是准时的。

BlockSpare — News, Magazine and Blog Addons for (Gutenberg) Block Editor