Agent开发
入门
MCP 协议入门:构建 AI 工具调用标准接口
2026-08
14 分钟阅读
#MCP协议
#工具调用
#标准接口
#Agent开发
#协议设计
什么是 MCP
MCP(Model Context Protocol)是 Anthropic 于 2024 年底推出的开放协议,旨在标准化 AI 模型与外部工具/数据源之间的通信。它定义了统一的接口规范,让任何 AI 模型都能通过标准方式访问工具、资源和提示模板。2026 年,MCP 已成为 AI Agent 开发的事实标准。
MCP 核心概念
| 概念 | 说明 | 示例 |
|---|
| Server | 提供工具/资源的服务端 | GitHub Server、Filesystem Server |
| Client | 使用工具的 AI 宿主 | Claude Desktop、自定义 Agent |
| Tool | 可调用的函数能力 | search_code、create_issue |
| Resource | 可读取的数据源 | 文件内容、数据库记录 |
| Prompt | 预定义的提示词模板 | 代码审查模板 |
构建一个 MCP Server
# weather_server.py
from mcp.server import Server, NotificationOptions
from mcp.server.models import InitializationCapabilities
import mcp.server.stdio
import mcp.types as types
import json
app = Server("weather-server")
@app.list_tools()
async def handle_list_tools() -> list[types.Tool]:
return [
types.Tool(
name="get-weather",
description="获取指定城市的天气信息",
inputSchema={
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称"}
},
"required": ["city"]
}
),
types.Tool(
name="get-forecast",
description="获取未来天气预报",
inputSchema={
"type": "object",
"properties": {
"city": {"type": "string"},
"days": {"type": "integer", "minimum": 1, "maximum": 7}
},
"required": ["city"]
}
)
]
@app.call_tool()
async def handle_call_tool(name: str, arguments: dict) -> list[types.TextContent]:
if name == "get-weather":
city = arguments["city"]
# 调用真实天气 API
weather = f"{city}今天晴天,25°C"
return [types.TextContent(type="text", text=weather)]
elif name == "get-forecast":
city = arguments["city"]
days = arguments.get("days", 3)
forecast = f"{city}未来{days}天以晴为主"
return [types.TextContent(type="text", text=forecast)]
raise ValueError(f"Unknown tool: {name}")
async def main():
async with mcp.server.stdio.stdio_server() as (read, write):
await app.run(read, write, InitializationCapabilities())
if __name__ == "__main__":
import asyncio
asyncio.run(main())
DeepSeek + MCP 集成
# deepseek_mcp_client.py
from openai import OpenAI
import subprocess
import json
import os
class DeepSeekMCPClient:
def __init__(self, server_script):
self.client = OpenAI(
api_key=os.getenv('DEEPSEEK_API_KEY'),
base_url='https://api.deepseek.com'
)
self.server = server_script
self.tools = self._load_tools()
def _load_tools(self):
"""从 MCP Server 加载工具列表"""
# 实际应通过 MCP 协议通信,这里简化为预定义
return [{
"type": "function",
"function": {
"name": "get-weather",
"description": "获取城市天气",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"}
},
"required": ["city"]
}
}
}]
def chat_with_tools(self, user_message):
messages = [{"role": "user", "content": user_message}]
response = self.client.chat.completions.create(
model='deepseek-v4-flash',
messages=messages,
tools=self.tools,
tool_choice='auto'
)
msg = response.choices[0].message
if msg.tool_calls:
for tc in msg.tool_calls:
result = self._execute_tool(tc.function.name, json.loads(tc.function.arguments))
messages.append({"role": "tool", "tool_call_id": tc.id, "content": result})
final = self.client.chat.completions.create(
model='deepseek-v4-flash',
messages=messages
)
return final.choices[0].message.content
return msg.content
def _execute_tool(self, name, args):
# 调用 MCP Server 执行工具
result = subprocess.run(
['python', self.server, name, json.dumps(args)],
capture_output=True, text=True
)
return result.stdout
# 使用
client = DeepSeekMCPClient('weather_server.py')
result = client.chat_with_tools("北京今天天气怎么样?")
print(result)
配置 Claude Desktop MCP
// ~/Library/Application Support/Claude/claude_desktop_config.json (macOS)
// %APPDATA%\Claude\claude_desktop_config.json (Windows)
{
"mcpServers": {
"deepseek-tools": {
"command": "python",
"args": ["/path/to/weather_server.py"]
}
}
}
常用 MCP Server 推荐
| Server | 安装命令 | 功能 |
|---|
| filesystem | npx -y @modelcontextprotocol/server-filesystem /path | 文件读写 |
| github | npx -y @modelcontextprotocol/server-github | GitHub 操作 |
| postgres | npx -y @modelcontextprotocol/server-postgres | 数据库查询 |
| brave-search | npx -y @modelcontextprotocol/server-brave-search | 网页搜索 |
| memory | npx -y @modelcontextprotocol/server-memory | 知识记忆 |
MCP vs Function Calling 对比
| MCP | Function Calling |
|---|
| 标准化 | ✅ 开放协议,跨平台 | 厂商特定实现 |
| 复用性 | 一次构建,多模型通用 | 需按模型适配 |
| 生态 | 30+ 官方 Server | 需自行开发 |
| 复杂度 | 需要独立 Server 进程 | 内嵌在应用代码中 |
建议:对外提供通用工具时使用 MCP,应用内私有工具使用 Function Calling。