MCP快速入门实战案例

一、MCP 开发环境准备

  1. 基础要求

    • 编程语言:Python/Node.js/Go(推荐Python,生态支持最完善)
    • 工具依赖:
      • mcp-sdk(官方SDK,pip install mcp-client
      • JSON-RPC 2.0兼容框架(如FastAPI、Flask for Python)
  2. 快速验证环境

    # 安装Python测试环境
    pip install mcp-client fastapi uvicorn
    

二、5分钟搭建第一个MCP Server

示例:创建一个天气查询服务
  1. 定义工具描述符weather_tool.json

    {
      "name": "get_weather",
      "description": "查询指定城市天气",
      "parameters": {
        "type": "object",
        "properties": {
          "city": {"type": "string", "description": "城市名称"}
        },
        "required": ["city"]
      }
    }
    
  2. 实现Server逻辑(Python示例)

    from fastapi import FastAPI
    from mcp_server import McpServer
    
    app = 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 uvicorn
        uvicorn.run(app, host="0.0.0.0", port=8000)
    
  3. 启动并测试

    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为例)

  1. 配置MCP Host

    # claude_config.yaml
    tools:
      - type: mcp
        url: http://localhost:8000/mcp
        tools_file: "./weather_tool.json"
    
  2. 用户交互示例

    用户:今天北京天气怎么样?
    Claude:<调用get_weather工具> 北京当前天气:25°C,晴天
    

你可能感兴趣的:(IT前沿视界,MCP,AI,AIGC,AIGENT)