对话翻译App
20.8MB · 2026-04-06
MCP(Model Context Protocol,模型上下文协议)是由 Anthropic 于 2024 年底提出并开源的一种标准化协议,旨在让大语言模型(如 Claude、GPT、Llama 等)能够安全、高效、结构化地访问外部工具和数据源。
| 问题 | 传统方案 | MCP 方案 |
|---|---|---|
| 工具碎片化 | 每个工具需定制集成(如 LangChain 工具) | 统一接口,一次接入,多模型可用 |
| 上下文污染 | 工具结果以文本拼接,易混乱 | 结构化 JSON 响应,模型精准理解 |
| 安全性风险 | 直接暴露 API 密钥或系统命令 | 通过 MCP Server 隔离,权限可控 |
你想让 AI 帮你查天气 + 发邮件 + 查数据库。
[ LLM (Claude/GPT/Llama) ]
↓ (MCP over HTTP/WS)
[ MCP Client (内置在 AI 应用中) ]
↓
[ MCP Server (你的后端服务) ]
↓
[ 外部工具:数据库 / API / 文件系统 / 自定义函数 ]
| 组件 | 作用 | 示例 |
|---|---|---|
| MCP Server | 实现 MCP 协议的服务端 | 用 Python/Node.js 编写的微服务 |
| MCP Client | 模型侧的协议解析器 | Anthropic 官方提供,集成在 Claude 中 |
| Tool Definition | 工具的元数据描述 | JSON Schema 定义输入/输出 |
| Resource | 可被模型读取的数据源 | 如日历事件、文件列表 |
MCP 定义了三种核心操作:
send_email(), query_database(), create_jira_ticket()list_files(), get_calendar_events(), read_config()summarize_text, translate_to_chinese我们将创建一个简单的 MCP Server,提供两个功能:
pip install fastapi uvicorn pydantic
mcp_server.py# mcp_server.py
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import os
from datetime import datetime
import json
app = FastAPI()
# === MCP 协议核心:处理 LLM 的请求 ===
@app.post("/mcp")
async def handle_mcp_request(request: Request):
body = await request.json()
# 获取操作类型
method = body.get("method")
params = body.get("params", {})
if method == "initialize":
# 返回服务器支持的能力
return JSONResponse({
"jsonrpc": "2.0",
"id": body.get("id"),
"result": {
"protocolVersion": "2024-10-07",
"capabilities": {
"tools": {},
"resources": {}
}
}
})
elif method == "list_tools":
# 声明可用工具
return JSONResponse({
"jsonrpc": "2.0",
"id": body.get("id"),
"result": [
{
"name": "get_current_time",
"description": "获取服务器当前时间",
"inputSchema": {
"type": "object",
"properties": {},
"required": []
}
}
]
})
elif method == "call_tool":
tool_name = params.get("name")
if tool_name == "get_current_time":
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
return JSONResponse({
"jsonrpc": "2.0",
"id": body.get("id"),
"result": {
"content": [{"type": "text", "text": f"当前时间是: {current_time}"}],
"isError": False
}
})
elif method == "list_resources":
return JSONResponse({
"jsonrpc": "2.0",
"id": body.get("id"),
"result": [
{"uri": "file://project_files", "name": "项目文件列表"}
]
})
elif method == "read_resource":
uri = params.get("uri")
if uri == "file://project_files":
files = os.listdir(".")
file_list = "n".join(files)
return JSONResponse({
"jsonrpc": "2.0",
"id": body.get("id"),
"result": {
"contents": [{"type": "text", "text": file_list}]
}
})
# 未知方法
return JSONResponse({
"jsonrpc": "2.0",
"id": body.get("id"),
"error": {"code": -32601, "message": "Method not found"}
})
uvicorn mcp_server:app --host 0.0.0.0 --port 8000
现在你的 MCP Server 运行在
# client_example.py
from anthropic import Anthropic
import requests
client = Anthropic(api_key="your_api_key")
# 构造带 MCP 上下文的消息
response = client.messages.create(
model="claude-3-5-sonnet-20260201",
max_tokens=1024,
system="你是一个助手,可以使用工具获取信息。",
messages=[
{
"role": "user",
"content": "请告诉我现在的时间,并列出当前目录的文件。"
}
],
# 关键:附加 MCP 上下文(模拟 MCP Client 行为)
extra_headers={
"anthropic-beta": "mcp-2024-10-07"
},
# 实际生产中,此步骤由 MCP Client 自动完成
)
MCP 基于 JSON-RPC 2.0 协议,典型请求/响应如下:
{
"jsonrpc": "2.0",
"id": 1,
"method": "call_tool",
"params": {
"name": "get_current_time",
"arguments": {}
}
}
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"content": [
{
"type": "text",
"text": "当前时间是: 2026-02-08 10:30:45"
}
],
"isError": false
}
}
{
"jsonrpc": "2.0",
"id": 2,
"error": {
"code": -32602,
"message": "Invalid arguments"
}
}
# 在 FastAPI 中添加中间件
@app.middleware("http")
async def verify_api_key(request: Request, call_next):
key = request.headers.get("x-api-key")
if key != "your-secret-key":
return JSONResponse({"error": "Unauthorized"}, status_code=401)
return await call_next(request)
call_tool 的参数| 方案 | 优点 | 缺点 |
|---|---|---|
| MCP | 标准化、多模型兼容、安全隔离 | 生态较新,文档较少 |
| LangChain Tools | 生态成熟、插件丰富 | 绑定 LangChain,迁移成本高 |
| Function Calling (OpenAI) | 原生支持、简单易用 | 仅限 OpenAI 模型 |
| Custom API | 完全可控 | 需为每个模型重复开发 |
pip install mcp