MCP(模型上下文协议)

返回 AI Agent

Model Context Protocol:Anthropic 推出的开放标准,定义 AI 模型与外部工具/数据源之间的通信格式,让任意 LLM 客户端能以统一方式调用文件系统、数据库、API 等能力。


核心架构

┌─────────────────────────────────────────────────────┐
│                    MCP Client                       │
│         (Claude Desktop / IDE Plugin / Agent)      │
└───────────────────────┬─────────────────────────────┘
                        │  MCP Protocol(JSON-RPC 2.0)
           ┌────────────┼────────────┐
           ↓            ↓            ↓
     ┌──────────┐ ┌──────────┐ ┌──────────┐
     │ MCP      │ │ MCP      │ │ MCP      │
     │ Server   │ │ Server   │ │ Server   │
     │(文件系统)│ │(PostgreSQL│ │(GitHub)  │
     └──────────┘ └──────────┘ └──────────┘

三类能力

能力说明示例
Resources只读数据源,模型可订阅文件内容、数据库记录
Tools可执行操作,模型主动调用写文件、发 HTTP 请求
Prompts可复用的提示模板代码审查模板、翻译模板

传输方式

方式场景特点
stdio本地进程(CLI 工具、桌面应用)简单、低延迟、无网络
SSE(HTTP)远程服务、云端部署支持跨网络,适合多客户端

官方 MCP Server

# 文件系统(读写本地文件)
npx @modelcontextprotocol/server-filesystem /path/to/dir
 
# PostgreSQL(只读查询)
npx @modelcontextprotocol/server-postgres postgresql://user:pass@localhost/db
 
# GitHub(仓库操作)
npx @modelcontextprotocol/server-github
 
# Brave Search(网页搜索)
npx @modelcontextprotocol/server-brave-search

Claude Desktop 配置

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/docs"]
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/mydb"]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_xxx" }
    }
  }
}

配置文件位置:~/Library/Application Support/Claude/claude_desktop_config.json(macOS)


自定义 Python MCP Server

pip install mcp
import mcp.server.stdio
from mcp.server import Server
from mcp.types import Tool, TextContent
import redis
 
app = Server("redis-mcp")
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
 
@app.list_tools()
async def list_tools() -> list[Tool]:
    return [
        Tool(
            name="redis_get",
            description="从 Redis 获取指定 key 的值",
            inputSchema={
                "type": "object",
                "properties": {"key": {"type": "string", "description": "Redis key"}},
                "required": ["key"]
            }
        ),
        Tool(
            name="redis_set",
            description="向 Redis 写入 key-value",
            inputSchema={
                "type": "object",
                "properties": {
                    "key": {"type": "string"},
                    "value": {"type": "string"}
                },
                "required": ["key", "value"]
            }
        )
    ]
 
@app.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
    if name == "redis_get":
        val = r.get(arguments["key"])
        return [TextContent(type="text", text=val or "(key not found)")]
    elif name == "redis_set":
        r.set(arguments["key"], arguments["value"])
        return [TextContent(type="text", text="OK")]
 
if __name__ == "__main__":
    import asyncio
    asyncio.run(mcp.server.stdio.run(app))

运行:

python redis_mcp_server.py

在 Claude Desktop 中配置:

{
  "mcpServers": {
    "redis": {
      "command": "python",
      "args": ["/path/to/redis_mcp_server.py"]
    }
  }
}

MCP vs A2A

维度MCPA2A
提出方AnthropicGoogle
通信对象模型 ↔ 工具/数据源Agent ↔ Agent
协议层JSON-RPC 2.0(stdio/SSE)HTTP + JSON(Agent Card)
能力单元Resources / Tools / PromptsTask + Artifacts
状态管理无状态(工具调用)有状态(Task 生命周期)
典型场景给模型挂载文件系统、数据库主 Agent 委托子 Agent 完成子任务
互补关系工具层协作层

两者互补:MCP 解决”模型如何用工具”,A2A 解决”Agent 如何协作”。


相关文档

  • A2A — Agent 间协作协议
  • Skill — MCP 暴露的工具即技能
  • Memory — 记忆工具可通过 MCP 暴露给模型
  • RAG — 检索工具是常见的 MCP Tool