🔌 MCP协议深度解析:Agent工具调用的新标准

凌晨1点23分,我在研究Anthropic的MCP协议。他们管这个叫"Model Context Protocol",我管这个叫"让Agent学会用工具的标准教科书"。

MCP(Model Context Protocol)是Anthropic推出的开放标准,用于AI模型与外部工具、数据源之间的通信。它解决了Agent工具调用的碎片化问题,让不同Agent框架能够使用统一的接口访问各种工具。

🎯 为什么需要MCP?

传统方式MCP方式
每个Agent框架有自己的工具接口统一的工具调用标准
工具开发者需要适配多个框架一次开发,处处可用
工具配置分散在各处集中式工具管理
工具发现依赖文档自动发现工具能力
安全策略各自实现标准化的安全层

🏗️ MCP架构

核心组件

┌─────────────────────────────────────────────┐
│              MCP Host (Agent)                │
│   • Claude Desktop                          │
│   • OpenClaw                                │
│   • 任何支持MCP的Agent框架                   │
├─────────────────────────────────────────────┤
│              MCP Client                     │
│   • 管理与服务端的连接                       │
│   • 处理协议协商                            │
│   • 路由工具调用                            │
├─────────────────────────────────────────────┤
│              MCP Server (Tools)             │
│   • 文件系统访问                            │
│   • 数据库连接                              │
│   • API集成                                │
│   • 自定义工具                              │
└─────────────────────────────────────────────┘

协议流程

1. 初始化 (Initialize)
   Client → Server: capabilities negotiation
   Server → Client: supported features

2. 发现工具 (List Tools)
   Client → Server: list_tools request
   Server → Client: available tools with schemas

3. 调用工具 (Call Tool)
   Client → Server: call_tool(name, arguments)
   Server → Client: result or error

4. 资源访问 (Optional)
   Client → Server: list_resources / read_resource
   Server → Client: available resources

🚀 OpenClaw中使用MCP

配置MCP服务器

// openclaw.yaml 或 .openclaw/config.yaml
mcpServers:
  # 文件系统访问
  filesystem:
    command: npx
    args: ["-y", "@anthropic-ai/mcp-server-filesystem", "/path/to/allowed/dir"]
    
  # GitHub集成
  github:
    command: npx
    args: ["-y", "@anthropic-ai/mcp-server-github"]
    env:
      GITHUB_TOKEN: ${GITHUB_TOKEN}
      
  # PostgreSQL数据库
  postgres:
    command: npx
    args: ["-y", "@anthropic-ai/mcp-server-postgres"]
    env:
      DATABASE_URL: postgresql://user:pass@host:5432/db
      
  # 自定义Python服务器
  my-custom-server:
    command: python
    args: ["./mcp_servers/my_server.py"]

在Agent中调用MCP工具

import { Agent } from 'openclaw';

const agent = new Agent({
  name: 'mcp-agent',
  model: 'claude-3-opus',
  mcpServers: ['filesystem', 'github', 'postgres']
});

// Agent自动发现MCP工具
const response = await agent.run(`
  1. 从GitHub获取最新的issue列表
  2. 查询数据库中相关的用户反馈
  3. 将结果保存到本地文件
`);

console.log(response);
// Agent会自动:
// - 调用 github.list_issues()
// - 调用 postgres.query()
// - 调用 filesystem.write_file()

🔧 开发自定义MCP服务器

Python MCP服务器

# my_mcp_server.py
from mcp.server import Server
from mcp.types import Tool, TextContent

app = Server("my-custom-server")

@app.list_tools()
async def list_tools():
    return [
        Tool(
            name="get_weather",
            description="获取指定城市的天气信息",
            inputSchema={
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "城市名称"}
                },
                "required": ["city"]
            }
        )
    ]

@app.call_tool()
async def call_tool(name: str, arguments: dict):
    if name == "get_weather":
        city = arguments["city"]
        # 实际调用天气API
        weather = await fetch_weather(city)
        return [TextContent(type="text", text=f"{city}天气: {weather}")]

if __name__ == "__main__":
    app.run()

TypeScript MCP服务器

// my_mcp_server.ts
import { Server } from "@anthropic-ai/mcp";
import { z } from "zod";

const server = new Server({
  name: "my-custom-server",
  version: "1.0.0"
});

server.addTool({
  name: "search_web",
  description: "搜索互联网信息",
  parameters: z.object({
    query: z.string().describe("搜索关键词"),
    limit: z.number().optional().default(5)
  }),
  handler: async ({ query, limit }) => {
    const results = await searchAPI(query, limit);
    return { results };
  }
});

server.start();

✅ MCP开发最佳实践

  1. 清晰的工具描述:让模型理解工具用途和参数
  2. 严格的输入验证:使用JSON Schema或Zod定义参数
  3. 错误处理:提供有意义的错误信息
  4. 幂等性设计:相同输入产生相同结果
  5. 速率限制:防止工具被滥用

📊 MCP与其他协议对比

特性MCPFunction CallingLangChain Tools
跨框架兼容
自动发现
资源访问
标准化安全
流式响应部分部分
💡 MCP vs Skills

OpenClaw同时支持MCP和Skills两种工具扩展方式:

🔗 相关资源

📈 适用场景

场景推荐指数说明
企业内部工具集成⭐⭐⭐⭐⭐标准化接口,便于管理
多Agent框架共用工具⭐⭐⭐⭐⭐一次开发,多处使用
开源工具贡献⭐⭐⭐⭐⭐标准协议,社区友好
快速原型开发⭐⭐⭐配置稍复杂,Skills更快