一、MCP 开发环境准备
-
基础要求
- 编程语言:Python/Node.js/Go(推荐Python,生态支持最完善)
- 工具依赖:
mcp-sdk
(官方SDK,pip install mcp-client
)- JSON-RPC 2.0兼容框架(如FastAPI、Flask for Python)
-
快速验证环境
# 安装Python测试环境 pip install mcp-client fastapi uvicorn
二、5分钟搭建第一个MCP Server
示例:创建一个天气查询服务
-
定义工具描述符(
weather_tool.json
){"name": "get_weather","description": "查询指定城市天气","parameters": {"type": "object","properties": {"city": {"type": "string", "description": "城市名称"}},"required": ["city"]} }
-
实现Server逻辑(Python示例)
from fastapi import FastAPI from mcp_server import McpServerapp = FastAPI() server = McpServer(app)@server.tool("get_weather") async def query_weather(city: str):# 模拟天气API调用return {"city": city, "temp": "25°C", "condition": "晴天"}if __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=8000)
-
启动并测试
curl -X POST http://localhost:8000/mcp \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"get_weather","params":{"city":"北京"},"id":1}'
三、连接AI模型实战(以Claude为例)
-
配置MCP Host
# claude_config.yaml tools:- type: mcpurl: http://localhost:8000/mcptools_file: "./weather_tool.json"
-
用户交互示例
用户:今天北京天气怎么样? Claude:<调用get_weather工具> 北京当前天气:25°C,晴天