晴天技术
AI7 min read

MCP 协议详解:AI 工具调用的开放标准

MCP 协议详解:AI 工具调用的开放标准

MCPAI协议工具调用Claude

MCP(Model Context Protocol)是 Anthropic 推出的开放协议,让 AI 能调用外部工具和数据源。

什么是 MCP?

MCP 是一个标准协议,让 AI 模型能够:

  • 调用外部工具(API、数据库、文件系统)
  • 访问外部数据源
  • 与各种服务集成

为什么需要 MCP?

没有 MCP 之前:

  • 每个 AI 工具需要单独集成
  • 工具开发者需要为每个 AI 平台适配
  • 用户需要手动配置

有了 MCP:

  • 统一的工具接口标准
  • 工具开发者只需实现一次
  • 用户即插即用

MCP 架构

┌─────────────┐     MCP      ┌─────────────┐
│   AI 模型   │ ←──────────→ │  MCP 服务器  │
│  (Client)   │              │  (Tools)    │
└─────────────┘              └─────────────┘
     │                            │
     │                            ├─ 文件系统
     │                            ├─ 数据库
     │                            ├─ API 服务
     │                            └─ 其他工具

支持 MCP 的工具

工具支持程度说明
Claude Desktop✅ 完整官方支持
Claude Code✅ 完整CLI 支持
Cursor✅ 支持IDE 集成
Windsurf✅ 支持IDE 集成
Continue✅ 支持VS Code 插件

MCP 核心概念

1. Tools(工具)

AI 可以调用的函数:

{
  "name": "read_file",
  "description": "读取文件内容",
  "inputSchema": {
    "type": "object",
    "properties": {
      "path": {
        "type": "string",
        "description": "文件路径"
      }
    },
    "required": ["path"]
  }
}

2. Resources(资源)

AI 可以访问的数据:

{
  "uri": "file:///path/to/file",
  "name": "配置文件",
  "description": "应用配置文件",
  "mimeType": "application/json"
}

3. Prompts(提示)

预定义的提示模板:

{
  "name": "code_review",
  "description": "代码审查",
  "arguments": [
    {
      "name": "code",
      "description": "要审查的代码",
      "required": true
    }
  ]
}

创建 MCP 服务器

Python 实现

from mcp.server import Server
from mcp.types import Tool, TextContent

server = Server("my-tools")

@server.tool()
async def read_file(path: str) -> str:
    """读取文件内容"""
    with open(path) as f:
        return f.read()

@server.tool()
async def write_file(path: str, content: str) -> str:
    """写入文件"""
    with open(path, 'w') as f:
        f.write(content)
    return "写入成功"

@server.tool()
async def run_sql(query: str) -> str:
    """执行 SQL 查询"""
    # 连接数据库执行查询
    return results

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

TypeScript 实现

import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

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

server.setRequestHandler("tools/call", async (request) => {
  const { name, arguments: args } = request.params;

  if (name === "read_file") {
    const content = await readFile(args.path);
    return { content: [{ type: "text", text: content }] };
  }
});

const transport = new StdioServerTransport();
await server.connect(transport);

常用 MCP 服务器

1. 文件系统服务器

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"]
    }
  }
}

2. GitHub 服务器

{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "your-token"
      }
    }
  }
}

3. PostgreSQL 服务器

{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/mydb"]
    }
  }
}

4. Puppeteer(浏览器)

{
  "mcpServers": {
    "puppeteer": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-puppeteer"]
    }
  }
}

在 Claude Desktop 中配置

编辑 ~/Library/Application Support/Claude/claude_desktop_config.json

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/totalo/workspace"]
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/mydb"]
    }
  }
}

在 Claude Code 中配置

# 添加 MCP 服务器
claude mcp add filesystem npx -y @modelcontextprotocol/server-filesystem /path/to/dir

# 查看已配置的服务器
claude mcp list

# 删除服务器
claude mcp remove filesystem

自定义 MCP 服务器实战

数据库查询服务器

from mcp.server import Server
import pymysql

server = Server("db-tools")

def get_connection():
    return pymysql.connect(
        host='localhost',
        user='root',
        password='password',
        database='mydb'
    )

@server.tool()
async def query_database(sql: str) -> str:
    """执行 SQL 查询并返回结果"""
    conn = get_connection()
    try:
        with conn.cursor() as cursor:
            cursor.execute(sql)
            results = cursor.fetchall()
            return str(results)
    finally:
        conn.close()

@server.tool()
async def list_tables() -> str:
    """列出所有表"""
    conn = get_connection()
    try:
        with conn.cursor() as cursor:
            cursor.execute("SHOW TABLES")
            return str(cursor.fetchall())
    finally:
        conn.close()

@server.tool()
async def describe_table(table_name: str) -> str:
    """查看表结构"""
    conn = get_connection()
    try:
        with conn.cursor() as cursor:
            cursor.execute(f"DESCRIBE {table_name}")
            return str(cursor.fetchall())
    finally:
        conn.close()

API 网关服务器

from mcp.server import Server
import httpx

server = Server("api-gateway")

@server.tool()
async def call_api(method: str, url: str, body: str = None) -> str:
    """调用外部 API"""
    async with httpx.AsyncClient() as client:
        if method.upper() == "GET":
            response = await client.get(url)
        elif method.upper() == "POST":
            response = await client.post(url, json=body)
        return response.text

@server.tool()
async def get_weather(city: str) -> str:
    """获取天气信息"""
    url = f"https://api.weather.com/v1/{city}"
    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        return response.text

MCP 的优势

对开发者

  • 一次实现,到处可用:工具只需实现一次
  • 标准接口:不需要为每个 AI 平台适配
  • 易于分发:npm/pip 包即可分发

对用户

  • 即插即用:配置简单
  • 工具丰富:社区贡献的工具
  • 安全可控:权限管理

MCP vs Function Calling

维度MCPFunction Calling
标准化✅ 开放标准各厂商不同
工具发现✅ 自动手动定义
跨平台
复杂度中等

未来展望

  1. 工具生态爆发:更多 MCP 服务器
  2. 平台支持扩展:更多 AI 工具支持 MCP
  3. 企业级特性:权限、审计、监控
  4. 标准化推进:成为行业标准

总结

MCP 是 AI 工具调用的未来标准:

  • 统一接口:一次实现,到处可用
  • 生态丰富:社区贡献的工具
  • 易于集成:配置即用
  • 安全可控:权限管理

对开发者来说,现在是学习和实现 MCP 服务器的好时机。