简介:本文将系统讲解如何使用Python实现基础模型上下文协议(MCP),涵盖协议核心概念、架构设计、关键操作实现及完整代码示例。通过构建支持发现、调用、获取功能的MCP服务器与客户端,帮助开发者理解协议运作机制,掌握AI模型与外部工具集成的标准化方法。
模型上下文协议(Model Context Protocol)是2024年提出的开放标准协议,旨在解决AI模型与外部工具/数据源集成时的标准化问题。其核心价值在于通过统一接口规范,实现不同语言模型与多样化工具的解耦连接,类似USB-C接口在硬件领域的标准化作用。
MCP采用经典客户端-服务器架构:
协议定义了三大基础操作:
tools/list和resources/list获取可用能力清单tools/call执行指定工具功能resources/read检索资源内容
# 基础依赖安装pip install jsonrpcserver jsonrpcclient uvicorn
from jsonrpcserver import method, dispatchfrom fastapi import FastAPIapp = FastAPI()# 工具集定义calculator_tools = {"add": lambda x, y: x + y,"multiply": lambda x, y: x * y}# Discovery端点实现@methoddef tools_list():return list(calculator_tools.keys())# Invoke端点实现@methoddef tools_call(tool_name, *args):if tool_name not in calculator_tools:raise ValueError("Tool not found")return calculator_tools[tool_name](*args)# JSON-RPC路由@app.post("/mcp")async def handle_rpc(request):response = await dispatch(request.body())return response
from jsonrpcclient import requestasync def discover_tools(base_url):response = await request(base_url, "tools_list")return response.data.resultasync def invoke_tool(base_url, tool_name, *args):response = await request(base_url,"tools_call",tool_name=tool_name,args=args)return response.data.result# 使用示例async def main():tools = await discover_tools("http://localhost:8000/mcp")print("Available tools:", tools)result = await invoke_tool("http://localhost:8000/mcp", "add", 5, 3)print("5 + 3 =", result)
{"method": "tools_list", "params": {}}{"result": ["add", "multiply"]}{"method": "tools_call", "params": {"tool_name": "add", "args": [2,3]}}{"result": 5}协议约定标准错误格式:
{"error": {"code": -32601,"message": "Method not found","data": "tools/unknown"}}
# 扩展工具集示例extended_tools = {"weather": lambda city: fetch_weather(city),"translate": lambda text, lang: translate_text(text, lang)}
# 资源检索实现knowledge_base = {"policy_2024": "公司2024年休假政策...","benefits": "员工福利体系说明..."}@methoddef resources_read(resource_id):return knowledge_base.get(resource_id, "Resource not found")
# 使用异步工具调用示例@methodasync def async_tool_call(tool_name, *args):loop = asyncio.get_event_loop()func = calculator_tools[tool_name]return await loop.run_in_executor(None, func, *args)
| 特性 | MCP协议 | 传统REST API | GraphQL |
|---|---|---|---|
| 接口标准化 | ✅ 强规范 | ❌ 自定义 | ⚠️ 部分标准 |
| 操作类型 | 3种基础操作 | 无限扩展 | 查询/变更 |
| 发现机制 | 内置支持 | 需额外实现 | Schema介绍 |
| 适用场景 | AI工具集成 | 通用Web服务 | 数据查询 |
MCP协议通过标准化接口设计,有效解决了AI模型与外部系统集成时的碎片化问题。本文实现的Python基础版本已覆盖核心功能,实际生产环境使用时还需考虑:
随着AI应用场景的扩展,MCP协议有望成为连接语言模型与数字世界的基础设施,类似HTTP协议在Web领域的地位。开发者可通过扩展本文实现,构建更复杂的工具生态系统,为智能应用开发提供标准化基础设施。