1. 什么是 MCP?
2025 年,Anthropic 提出了 MCP(Model Context Protocol)协议。简单来说,这是大模型上下文协议,旨在为 AI 大模型和外部工具之间的交互提供一个统一的处理标准。就像 USB-C 接口统一了物理连接方式一样,MCP 试图统一大模型调用工具的对接规范。
MCP 采用 C/S(客户端/服务端)架构,支持在客户端设备上调用远程 Server 提供的服务,同时也支持 stdio 流式传输模式,这意味着你可以在本地启动 MCP 服务端。只需在配置文件中新增 MCP 服务端,就能让大模型便捷地使用各种外部工具。

作为开源协议,MCP 鼓励所有 AI 厂商和工具将其集成到客户端中。生态越丰富,协议的生命力就越强。
2. 了解 Function Call
在 MCP 普及之前,AI Agent 开发若要调用外部工具,往往需要针对不同的大模型 SDK 编写适配代码。其中最为经典的是 OpenAI 提供的 Function Call 处理逻辑。
2.1. Function Call Demo
2.1.1. 配置工具,AI 提供参数
调用 Chat Completions 接口时,可以通过 tools 参数传入外部工具定义。这包含了工具的作用、所需参数及其释义。其中 tool_choice 字段设为 auto 代表让大模型自动选择是否调用工具,设为 none 则禁止调用。
{
"tool_choice": "auto",
"messages": [
{
"role": "system",
"content": "你是一个天气查询助手"
},
{
"role": "user",
"content": "帮我查询上海的天气"
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "城市名"
}
},
"required": ["city"]
}
}
}
]
}
对应的 Python OpenAI 代码如下。我们将工具列表放入 create 函数的 tools 参数中,并设置 tool_choice="auto"。这里以硅基流动的 Qwen2.5 模型为例演示,运行前请替换正确的 API Key。
import openai
import json
def main():
client = openai.OpenAI(
api_key="xxxxx",
base_url="https://api.siliconflow.cn/v1"
)
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "城市名"
}
},
"required": ["city"]
}
}
}]
res = client.chat.completions.create(
model="Qwen/Qwen2.5-32B-Instruct",
messages=[
{"role": "system", "content": "你是一个天气查询助手"},
{"role": "user", "content": "帮我查询上海的天气"}
],
tools=tools,
tool_choice="auto"
)
print("content:", res.choices[0].message.content)
print("tools:", res.choices[0].message.tool_calls)
print("message:", res.choices[0].message.to_dict())
if __name__ == "__main__":
main()
运行后,大模型会根据用户问题和提供的工具生成参数。此时 content 通常为空,而 tool_calls 会包含调用的工具名称及参数。
❯ uv run main.py
content:
tools: [ChatCompletionMessageToolCall(id='...', function=Function(arguments='{"city": "上海"}', name='get_weather'), type='function')]
message: {'content': '', 'role': 'assistant', 'tool_calls': [...]}
响应 JSON 格式如下,清晰展示了参数结构:
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "...",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\n \"city\": \"上海\"\n}"
}
}
]
}
2.1.2. 调用工具并让 AI 二次处理
拿到参数后,我们需要执行实际函数并将结果返回给大模型进行二次处理。这一步的关键是维护对话上下文:首先插入第一次请求的 Assistant 消息,然后追加一条 role: "tool" 的消息,内容即为函数执行结果。
{
"role": "tool",
"tool_call_id": "01964be6e485603d6a2a0acbbc7eba91",
"content": "{'temperature': 25, 'city': '上海'}"
}
将这条消息加入上下文再次发送给模型,它就能结合真实数据给出最终回答。这种流程虽然有效,但每个模型的实现细节可能不同,导致 Agent 开发时需要针对特定 SDK 做适配。而 MCP 的出现,正是为了标准化这一过程。


