知识库 · AI 智能体
从开发者角度理解 MCP 协议
从开发者视角详解MCP协议前身:从传统Chat API、提示词工具调用,到OpenAI插件计划和Function Calling的演进过程,重点分析各方案的实现方式、优缺点及实际代码示例。
作者:x
从基础的聊天API开始使用
// 手动调用api —— 传统的API调用方式
async function main(userMessage) {
const res = await fetch('https://api.openai.com/v1/chat/completions'),
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${api_key}`
},
body: JSON.stringify({
model:'gpt-4o',
messages: [
{
"role": "user",
"content": "Hello!"
}
]
})
}
}
// SDK方式
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
async function main() {
const completion = await openai.chat.completions.create({
messages: [
{ role: "user", content: "Hello!" }
],
model: "gpt-4o",
});
return completion.choices[0];
}
Q:如何实现连续对话?
A:将每次与AI完整聊天记录,添加到一个数组(例:conversationHistory)中,在下次请求时将conversationHistory传入messages中。
ps:还有更多方法,如总结前面的历史信息放入messages等等...
消息类型:
-
role:“developer”(原“system”)
-
设定AI的行为和角色、定义回答的风格和限制等
-
用户通常看不到此消息
-
模型会始终遵循这些指令且优先于用户消息
-
role:“user”
-
用户发送的问题或指令
-
通常显示在用户对话框内
-
包含用户的问题、陈述、请求等
-
role:“assistant”
-
由模型生成的消息
-
根据历史上下文生成
-
展示给用户的内容
但我们知道,AI的回答源于他训练的数据,当用户问到与“实时性”相关的问题时,AI就傻眼了。
于是就有了第一代解决方案:用提示词实现工具调用!
用提示词实现工具调用
通过提示词,让AI输出一个结构化的JSON数据,去外部调用相关的API,拿到最后的数据结果,再交给AI总结回复。
当用户向你询问天气信息时,请将用户的需求输出为以下JSON格式:
{
"function": "getWeather",
"params": {
"city": "location",
"date": "2025-03-18"
}
}
缺点:AI输出的结果不可靠,可能出现错误的JSON格式,或符号错误等。
这个问题OpenAI也意识到了,于是...
OpenAI解决方案
一、插件计划
从2023年3月份,OpenAI宣布插件计划开始,到5月份上线,其中包括OpenAI的三个插件:联网、代码、画图。
二、Function calling 函数调用
经过对模型的微调,既可以检测何时需要调用函数(取决于用户的输入)也可以使用符合函数签名的 JSON 进行响应。函数调用使开发人员能够更可靠地从模型中获取结构化数据。
在接口层面你就可以声明有哪些工具可以调用
- 使用函数和用户输入调用模型
// 1.定义可用的函数
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current temperature for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City and country e.g. Bogotá, Colombia"
}
},
"required": [
"location"
],
"additionalProperties": False
},
"strict": True
}
}]
// 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\"}"
}
}
- 使用模型响应调用 API
async function get_weather(location, date) {
const response = await fetch(`https:/weatherapi.com?location=${location}&date=${date}`);
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" }
- 将响应发送回模型进行汇总
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
// 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的基础上拓展的出的三大功能:
-
工具Tools:底层使用Function call实现,与OpenAI格式兼容。
-
资源Resources:MCP独有,给AI提供参考信息,如文件内容、数据库记录、系统状态等。
-
提示词Prompts:预设对话模板,如快捷指令、标准工作流、指导性提示等。
官方文档:https://modelcontextprotocol.io/
// 列出工具的请求
{
"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服务器示例:
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示例:
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: {},
resources: {}
}
})
const transport = new StdioServerTransport();
await server.connect(transport);
// 具体内容查看官方文档