MCP协议详解:AI的标准化USB接口
AI · 技术

MCP协议详解:AI的标准化USB接口

模块 08:MCP 协议

AI Agent 的「标准化接口」—— Model Context Protocol,统一 LLM 与外部世界的通信

1. 什么是 MCP

MCP(Model Context Protocol)是 Anthropic 在 2024 年底发布的开放标准,为 LLM 应用提供统一的工具和数据源接入协议。

没有 MCP 之前:
  每个 LLM 应用 × 每个工具 = N×M 个自定义集成
  OpenAI 需要自己的 Function Calling
  Claude 需要自己的 Tool Use
  每个工具需要为每个 LLM 写适配器

有了 MCP:
  所有 LLM 应用 ← MCP Client ← MCP Server ← 各种工具/数据源
  一套标准,处处通用

类比理解: MCP 就像 USB 接口标准。以前每个设备都需要专用接口,现在统一用 USB,即插即用。


2. MCP 架构

┌─────────────────────────────────────────────┐
│                Host(宿主)                   │
│  Claude Desktop / IDE / 自定义应用             │
│  ┌─────────────────────────────────────────┐ │
│  │            MCP Client                   │ │
│  │  管理与 Server 的连接和通信              │ │
│  └───────────────┬─────────────────────────┘ │
└──────────────────┼───────────────────────────┘
                   │ MCP 协议
     ┌─────────────┼─────────────┐
     ▼             ▼             ▼
┌─────────┐  ┌─────────┐  ┌─────────┐
│ Server A │  │ Server B │  │ Server C │
│ 文件系统  │  │ 数据库   │  │ Web API  │
└─────────┘  └─────────┘  └─────────┘

核心角色

角色 职责 示例
Host 宿主应用,管理 Client 生命周期 Claude Desktop、VS Code
Client 与 Server 建立连接,转发请求 内嵌在 Host 中
Server 提供工具、资源和提示模板 文件系统、数据库、API

3. MCP 核心能力

3.1 Tools(工具)

Server 向 LLM 暴露可调用的函数:

# Python MCP Server - 定义工具
from mcp.server import Server
from mcp.types import Tool, TextContent

server = Server("my-tools")

@server.tool()
async def query_database(sql: str) -> str:
    """执行 SQL 查询并返回结果"""
    results = await db.execute(sql)
    return json.dumps(results)

@server.tool()
async def send_email(to: str, subject: str, body: str) -> str:
    """发送邮件"""
    await email_client.send(to=to, subject=subject, body=body)
    return f"邮件已发送至 {to}"
// TypeScript MCP Server - 定义工具
server.setRequestHandler("tools/list", async () => ({
  tools: [
    {
      name: "query_database",
      description: "执行 SQL 查询",
      inputSchema: {
        type: "object",
        properties: {
          sql: { type: "string", description: "SQL 查询语句" }
        },
        required: ["sql"]
      }
    }
  ]
}));

server.setRequestHandler("tools/call", async (request) => {
  const { name, arguments: args } = request.params;
  if (name === "query_database") {
    const results = await db.execute(args.sql);
    return { content: [{ type: "text", text: JSON.stringify(results) }] };
  }
});

3.2 Resources(资源)

Server 向 LLM 暴露可读取的数据源:

@server.resource("file://documents/{path}")
async def read_document(path: str) -> str:
    """读取文档内容"""
    with open(f"documents/{path}") as f:
        return f.read()

@server.resource("db://users/{user_id}")
async def get_user(user_id: str) -> str:
    """获取用户信息"""
    user = await db.get_user(user_id)
    return json.dumps(user)

3.3 Prompts(提示模板)

Server 提供预定义的提示模板:

@server.prompt()
async def code_review(code: str, language: str) -> str:
    """代码审查提示模板"""
    return f"""请审查以下 {language} 代码,关注:
1. 潜在的 bug
2. 性能问题
3. 安全漏洞
4. 代码风格

{code}


请以结构化的方式输出审查结果。"""

3.4 Sampling(采样)

Server 请求 LLM 进行推理(需要 Host 授权):

@server.tool()
async def analyze_with_llm(text: str) -> str:
    """使用 LLM 分析文本"""
    # 请求 Host 的 LLM 进行分析
    result = await server.request_sampling(
        messages=[{"role": "user", "content": f"分析以下文本的情感:{text}"}],
        max_tokens=100
    )
    return result.content

4. 传输协议

4.1 stdio(标准输入输出)

# Server 通过 stdin/stdout 通信
import mcp.server.stdio

async def main():
    async with mcp.server.stdio.stdio_server() as (read, write):
        await server.run(read, write, server.create_initialization_options())

# 启动命令:python server.py
// Client 配置
{
  "command": "python",
  "args": ["server.py"]
}

适用场景: 本地工具、CLI 集成

4.2 SSE(Server-Sent Events)

# Server 通过 HTTP SSE 通信
from mcp.server.sse import SseServerTransport
from starlette.applications import Starlette
from starlette.routing import Route

sse = SseServerTransport("/messages")

async def handle_sse(request):
    async with sse.connect_sse(request.scope, request.receive, request._send) as streams:
        await server.run(streams[0], streams[1], server.create_initialization_options())

app = Starlette(routes=[
    Route("/sse", endpoint=handle_sse),
    Route("/messages", endpoint=sse.handle_post_message, methods=["POST"]),
])

适用场景: 远程服务、Web 集成

4.3 Streamable HTTP(新标准)

# 最新的传输方式,支持流式 HTTP
from mcp.server.streamable_http import StreamableHTTPServerTransport

适用场景: 生产环境、云部署


5. MCP Server 开发实战

5.1 文件系统 Server

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

server = Server("filesystem")

@server.tool()
async def read_file(path: str) -> str:
    """读取文件内容"""
    if not os.path.exists(path):
        return f"Error: 文件不存在 - {path}"
    with open(path) as f:
        return f.read()

@server.tool()
async def write_file(path: str, content: str) -> str:
    """写入文件"""
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, 'w') as f:
        f.write(content)
    return f"文件已写入: {path}"

@server.tool()
async def list_directory(path: str = ".") -> str:
    """列出目录内容"""
    entries = []
    for entry in os.listdir(path):
        full_path = os.path.join(path, entry)
        entry_type = "目录" if os.path.isdir(full_path) else "文件"
        size = os.path.getsize(full_path) if os.path.isfile(full_path) else "-"
        entries.append(f"[{entry_type}] {entry} ({size} bytes)")
    return "\n".join(entries)

@server.resource("file://{path}")
async def get_file_resource(path: str) -> str:
    """文件资源"""
    with open(path) as f:
        return f.read()

5.2 数据库 Server

import sqlite3
from mcp.server import Server

server = Server("database")
db = sqlite3.connect("app.db")

@server.tool()
async def execute_query(sql: str) -> str:
    """执行 SQL 查询"""
    # 安全检查
    sql_upper = sql.strip().upper()
    if not sql_upper.startswith("SELECT"):
        return "Error: 只允许 SELECT 查询"

    try:
        cursor = db.execute(sql)
        columns = [desc[0] for desc in cursor.description]
        rows = cursor.fetchall()

        # 格式化为表格
        result = " | ".join(columns) + "\n"
        result += "-" * 40 + "\n"
        for row in rows:
            result += " | ".join(str(v) for v in row) + "\n"

        return result
    except Exception as e:
        return f"Error: {str(e)}"

@server.tool()
async def list_tables() -> str:
    """列出所有表"""
    cursor = db.execute("SELECT name FROM sqlite_master WHERE type='table'")
    return "\n".join(row[0] for row in cursor.fetchall())

@server.tool()
async def describe_table(table_name: str) -> str:
    """查看表结构"""
    cursor = db.execute(f"PRAGMA table_info({table_name})")
    columns = cursor.fetchall()
    return "\n".join(
        f"{col[1]} ({col[2]}) {'NOT NULL' if col[3] else 'NULL'}"
        for col in columns
    )

5.3 GitHub Server

import httpx
from mcp.server import Server

server = Server("github")

GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN")
headers = {"Authorization": f"token {GITHUB_TOKEN}"}

@server.tool()
async def get_repo_info(owner: str, repo: str) -> str:
    """获取仓库信息"""
    async with httpx.AsyncClient() as client:
        resp = await client.get(
            f"https://api.github.com/repos/{owner}/{repo}",
            headers=headers
        )
        data = resp.json()
        return json.dumps({
            "name": data["name"],
            "description": data["description"],
            "stars": data["stargazers_count"],
            "language": data["language"],
            "updated_at": data["updated_at"]
        }, indent=2)

@server.tool()
async def list_issues(owner: str, repo: str, state: str = "open") -> str:
    """列出 Issues"""
    async with httpx.AsyncClient() as client:
        resp = await client.get(
            f"https://api.github.com/repos/{owner}/{repo}/issues",
            headers=headers,
            params={"state": state, "per_page": 10}
        )
        issues = resp.json()
        return "\n".join(
            f"#{i['number']} {i['title']} ({i['state']})"
            for i in issues
        )

6. MCP Client 使用

6.1 Claude Desktop 配置

// ~/Library/Application Support/Claude/claude_desktop_config.json
{
  "mcpServers": {
    "filesystem": {
      "command": "python",
      "args": ["/path/to/filesystem_server.py"],
      "env": {
        "ALLOWED_PATHS": "/Users/me/documents"
      }
    },
    "database": {
      "command": "python",
      "args": ["/path/to/database_server.py"],
      "env": {
        "DB_PATH": "/path/to/data.db"
      }
    }
  }
}

6.2 Python Client

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def run_client():
    server_params = StdioServerParameters(
        command="python",
        args=["server.py"]
    )

    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            # 初始化
            await session.initialize()

            # 列出可用工具
            tools = await session.list_tools()
            print("可用工具:", [t.name for t in tools.tools])

            # 调用工具
            result = await session.call_tool(
                "query_database",
                arguments={"sql": "SELECT * FROM users LIMIT 5"}
            )
            print("结果:", result.content[0].text)

            # 读取资源
            resource = await session.read_resource("file://documents/readme.md")
            print("文档:", resource.contents[0].text)

7. MCP 安全考虑

安全原则:
1. 最小权限:Server 只暴露必要的工具和资源
2. 输入验证:严格验证所有参数
3. 路径限制:文件系统 Server 限制可访问路径
4. SQL 注入防护:数据库 Server 只允许安全查询
5. 速率限制:防止工具被滥用
6. 审计日志:记录所有工具调用
7. Human-in-the-loop:敏感操作需要用户确认

8. MCP 生态

工具/服务 说明
MCP Inspector 调试工具
MCP Servers 仓库 官方示例 Server
Smithery MCP Server 注册中心
mcp.run 托管 MCP Server 服务

9. 延伸阅读


小码提示: MCP 是 Agent 工具生态的未来标准。建议先用 Python SDK 写一个简单的 Server(如文件系统),跑通后再开发业务相关的 Server。理解 Tools、Resources、Prompts 三个核心概念是关键。