从开发者角度理解 MCP 协议

从开发者角度理解 MCP 协议

从开发者角度理解 MCP 协议 从开发者角度理解 MCP 协议 Modified March 19, 2025 Code block JavaScript Copy // 2.发送请求,包含函数定义 completion = client.chat.completions.create( model="gpt 4o", messages=[{"role": "user", "content": "What is the weather like in Paris today?"}], tools=tools ) // 3.检查是否调用函数 const message = response.choices[0].message // 输出结果 { "id": "call 12345xyz", "type": "function", "function": { "name": "get weather", "arguments": "{\"location\":\"Paris\", \"date\":\"2025 3 18\"}" } } 2. 使用模型响应调用 API Code block JavaScript Copy async function get weather(location, date) { const response = await fetch( ); const data = await response.json(); return data.current.temperature; } if (message.function call) { // 4. 获取函数调用详情 const functionName = message.function.name const args = JSON.parse(message.function.arguments) // 5. 执行实际功能 if (functionName === 'getWeather') { const weatherDate = await get weather(args.location,args.date) return { temperature: weatherDate.temperature, unit:weatherDate.unit, description:weatherDate.description } } } // 输出结果 { "temperature": 22, "unit": "celsius", "description": "Sunny" } 3. 将响应发送回模型进行汇总 Code block JavaScript Copy completion = client.chat.completions.create( model="gpt 4o", messages: [ {"role": "user", "content": "What is the weather like in Paris today?"}, {"role": "assistant", "content": null, "function call": {"name": "get weather", "arguments": "{\"location\":\"Paris\"}"}}, {"role": "function", "name": "get weather", "content": "{\"temperature\": "22", \"unit\": \"celsius\", \"description\": \"Sunny\"}"} ], functions:[ { "name": "get weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state" } }, "required": ["location"] } } ] ) // 输出结果 // The weather in Paris is currently sunny with a temperature of 22 degrees Celsius. 三、插件市场 All Tools 让全球的开发者主动帮助 OpenAI 写 Function call,允许第三方开发者来开发可调用的Function call Code block JavaScript Copy // 1. 创建manifest.json描述文件 { "schema version": "v1", "name for human": "TODO Manager", "name for model": "todo manager", "description for human": "Manages your TODOs!", "description for model": "An app for managing a user's TODOs", "api": { "url": "/openapi.json" }, "auth": { "type": "none" }, "logo url": "https://example.com/logo.png", "legal info url": "http://example.com", "contact email": "hello@example.com" } 限制:只能在OpenAI的ChatGPT Web使用,不能再其他地方复用。 Q:有没有一种标准协议,让所有AI应用能使用相同的方式访问工具呢? A:MCP MCP 模型上下文协议(Model Context Protocol) AI世界的“USB C”接口,链接所有AI应用与工具的桥梁。 MCP统一了交互标准,使一个协议兼容所有AI应用。 在Function Call的基础上拓展的出的三大功能: 1. 工具Tools:底层使用Function call实现,与OpenAI格式兼容。 2. 资源Resources:MCP独有,给AI提供参考信息,如文件内容、数据库记录、系统状态等。 3. 提示词Prompts:预设对话模板,如快捷指令、标准工作流、指导性提示等。 官方文档:https://modelcontextprotocol.io/ Code block JavaScript Copy // 列出工具的请求 { "jsonrpa": "1.0", "id": 1, "method": "tools/list" } // 调用工具的请求 { "jsonrpc": "1.0", "id": 1, "method": "tools/call", "params": { "name": "get weather", "arguments": {"location": "Paris"} } } // 工具执行结果响应 { "jsonrpc": "1.0", "id": 1, "result": { "content": [{ "type": "text", "text": "It's cloudy in Paris today, with a temperature of 10℃." }] } } MCP主要接口路径: • tools/list 获取可用工具列表 • tools/call 调用工具 • resources/list 获取可用资源列表 • resources/read 读取资源内容 • prompts/list 获取可用提示词列表 • prompts/get 获取提示词内容 • ... MCP转换步骤: • 客户端向MCP服务器请求工具列表 • 将MCP工具定义转换为Function call格式 • 发送Function Call定义给LLM • 接收LLM生成的Function call • 将Function call转为MCP工具调用 • 发送工具调用结果给LLM 手写MCP服务器示例: Code block JavaScript Copy const http = require("http"); http.createServer(() = { if(req.method === "POST") { let body = ''; req.on('data', chunk = {body += chunk.toString() }); req.on('end', () = { const request = JSON.parse(body); handelMcpRequest(request, res); }) } }).listen(3000); function handelMcpRequest(request, res) { const {id, method, params } = request; if (method === 'tools/list') { sendResponse(res,id, { tools:[{ name:"get weather", description: "Query the weather of the specified location", inputSchema:{ type:"object", properties: { city: { type: "string"} }, required: ["location"] } }] }) } else if (method === "tools/call") { sendResponse(res,id,{ content: [ { type:"text", text:"${params.arguments.location}clear weather" } ] }) } } function sendResponse(res, id, result) { res.writeHead(200, {'Content type': 'application/json'}) res.end(JSON.stringify({ jsonrpc:'2.0', id, result })) } TypeScript SDK示例: Code block JavaScript Copy import { Server } from "@modelcontextprotocol/sdk/server"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio"; import { ListToolsRequertSchema, CallToolRequestSchema } from "@modelcontextprotocol/sdk/types" // 创建服务器实例 const server = new Server({ name: "weather server", version: "1.0.0" }, { capavilities: { tools: {} prompt: {}, 2. 使用模型响应调用 API 3. 将响应发送回模型进行汇总 三、插件市场 All Tools 让全球的开发者主动帮助 OpenAI 写 Function call,允许第三方开发者来开发可调用的Function call 限制:只能在OpenAI的ChatGPT Web使用,不能再其他地方复用。 Q:有没有一种标准协议,让所有AI应用能使用相同的方式访问工具呢? A:MCP MCP 模型上下文协议(Model Context Protocol) AI世界的“USB C”接口,链接所有AI应用与工具的桥梁。 MCP统一了交互标准,使一个协议兼容所有AI应用。 在Function Call的基础上拓展的出的三大功能: 1. 工具Tools:底层使用Function call实现,与OpenAI格式兼容。 2. 资源Resources:MCP独有,给AI提供参考信息,如文件内容、数据库记录、系统状态等。 3. 提示词Prompts:预设对话模板,如快捷指令、标准工作流、指导性提示等。 官方文档:https://modelcontextprotocol.io/ MCP主要接口路径: • tools/list 获取可用工具列表 • tools/call 调用工具 • resources/list 获取可用资源列表 • resources/read 读取资源内容 • prompts/list 获取可用提示词列表 • prompts/get 获取提示词内容 • ... MCP转换步骤: • 客户端向MCP服务器请求工具列表 • 将MCP工具定义转换为Function call格式 • 发送Function Call定义给LLM • 接收LLM生成的Function call • 将Function call转为MCP工具调用 • 发送工具调用结果给LLM 手写MCP服务器示例: TypeScript SDK示例: ⌨️ 作者:x 作者:x 从基础的聊天API开始使用 Q:如何实现连续对话? A:将每次与AI完整聊天记录,添加到一个数组(例:conversationHistory)中,在下次请求时将conversationHistory传入messages中。 ps:还有更多方法,如总结前面的历史信息放入messages等等... 消息类型: 1. role:“developer”(原“system”) a. 设定AI的行为和角色、定义回答的风格和限制等 b. 用户通常看不到此消息 c. 模型会始终遵循这些指令且优先于用户消息 a. 设定AI的行为和角色、定义回答的风格和限制等 b. 用户通常看不到此消息 c. 模型会始终遵循这些指令且优先于用户消息 2. role:“user” a. 用户发送的问题或指令 b. 通常显示在用户对话框内 c. 包含用户的问题、陈述、请求等 a. 用户发送的问题或指令 b. 通常显示在用户对话框内 c. 包含用户的问题、陈述、请求等 3. role:“assistant” a. 由模型生成的消息 b. 根据历史上下文生成 c. 展示给用户的内容 a. 由模型生成的消息 b. 根据历史上下文生成 c. 展示给用户的内容 但我们知道,AI的回答源于他训练的数据,当用户问到与“实时性”相关的问题时,AI就傻眼了。 于是就有了第一代解决方案:用提示词实现工具调用! 用提示词实现工具调用 通过提示词,让AI输出一个结构化的JSON数据,去外部调用相关的API,拿到最后的数据结果,再交给AI总结回复。 缺点:AI输出的结果不可靠,可能出现错误的JSON格式,或符号错误等。 这个问题OpenAI也意识到了,于是... OpenAI解决方案 一、插件计划 从2023年3月份,OpenAI宣布插件计划开始,到5月份上线,其中包括OpenAI的三个插件:联网、代码、画图。 二、Function calling 函数调用 经过对模型的微调,既可以检测何时需要调用函数(取决于用户的输入)也可以使用符合函数签名的 JSON 进行响应。函数调用使开发人员能够更可靠地从模型中获取结构化数据。 在接口层面你就可以声明有哪些工具可以调用 1. 使用函数和用户输入调用模型

在 小宇宙note 阅读完整内容