什么是 MCP?
2025 年,Anthropic 提出了 MCP(Model Context Protocol),即大模型上下文协议。它主要为 AI 大模型和外部工具之间的交互提供了一个统一的处理协议。就像 USB-C 统一了物理接口一样,MCP 统一了大模型与工具的对接方式。
MCP 采用 C/S 架构,支持客户端调用远程 Server 提供的服务,同时也支持 stdio 流式传输模式,即在客户端本地启动 MCP 服务端。只需在配置文件中新增 MCP 服务端,就能利用其提供的各种工具,大大提高了大模型使用外部工具的便捷性。

MCP 是开源协议,旨在让所有 AI 厂商和工具都能集成到自己的客户端中,扩大可用面。只有用户越多,协议才能不断发展。
了解 Function Call
在 MCP 出现之前,开发 AI Agent 调用外部工具通常需要针对不同的 AI 大模型 SDK 编写不同的代码,最常用的是 OpenAI 提供的 Function Call 处理逻辑。
Function Call Demo
配置工具,AI 提供参数
调用 OpenAI 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 代码如下。我们将 tools 部分放入一个包含 dict 的 list,作为 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()
运行程序后,大模型会根据用户问题和提供的 tools 编写需要提供的参数。此时 content 会是空,不会输出直接内容,tool_calls 中会包含调用的工具和参数。
❯ uv run main.py
content:
tools: [ChatCompletionMessageToolCall(id='...', function=Function(arguments='{"city": "上海"}', name='get_weather'), type='function')]
...
对应如下 JSON 格式响应,包含了我们的参数:
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "...",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\n \"city\": \"上海\"\n}"
}
}
]
}
调用工具并让 AI 二次处理
随后,我们可以根据大模型返回的参数调用我们的函数,得到结果后再与大模型进行对话。此时需要维护对话上下文,首先需要将第一次请求 AI 返回的结果插入到上下文中("role": "assistant" 的 json 字符串),然后再插入工具调用的数据,格式如下:
{
"role": "tool",
"tool_call_id": "...",
"content": "{\"status\": \"success\", \"temp\": \"25\"}"
}
这样,AI 就能结合工具返回的实际数据生成最终回复。


