跳到主要内容
Agent Runtime

第7章:协议层 —— MCP(Agent ↔ Tool)与 A2A(Agent ↔ Agent)

Model Context Protocol(MCP)与 Agent-to-Agent(A2A)协议详解,架构、最简代码、安全模型、协同使用场景

MCP A2A Anthropic Google 协议 工具

写 100 个 agent 适配 100 种工具,等于 100 × 100 = 10000 个 integration——这是 Web 出现 HTTP / REST 之前的世界。2024-2025 年,Agent 领域终于有了自己的”USB-C”——MCP(Anthropic)和 A2A(Google)。MCP 解决”agent 怎么用工具”,A2A 解决”agent 怎么互相协作”。本章把这两个协议讲透:架构、最简代码、安全模型、何时配合使用,以及 2025 年标准化大事件(MCP 捐赠 Linux Foundation)。

📑 目录


1. 协议为什么重要

1.1 没有协议的世界

2024 年之前的 agent 工具集成:

维度现状
每个工具自定义 schemaOpenAI tools / LangChain BaseTool / 自家 dict…
每个 agent 自己写 adapter接 GitHub 的代码、接 Slack 的代码、接 DB 的代码…
工具没法跨 agent 复用A 团队为 LangChain 写的 tool,B 团队的 AutoGen 用不了
Tool 安全性各自实现auth、rate limit、permission scope 没标准

1.2 类比 HTTP / REST

Web 时代Agent 时代
没有 HTTP:CGI、socket、自定义 RPC,每个网站重写没有 MCP:每个 agent 自己接工具
有了 HTTP:浏览器 / 服务器解耦有了 MCP:agent / 工具 解耦
REST + OpenAPI:工具描述标准化MCP server schema:工具描述标准化

🌟 MCP 就是 Agent 时代的 HTTP/REST——一旦标准化,生态会爆炸式增长。


2. MCP:Model Context Protocol

2.1 基本架构

┌─────────────────────────────┐
│  Host(Claude Desktop /     │
│       LangGraph / Cursor)    │
│                              │
│   ┌──────────────────────┐   │
│   │  MCP Client(SDK)    │   │
│   └──────────────────────┘   │
└──────────┬───────────────────┘
           │  JSON-RPC over stdio / HTTP / SSE

   ┌───────┴────────────────┐
   ▼                        ▼
┌─────────┐          ┌─────────┐
│MCP Server│          │MCP Server│
│ (DB)     │          │(GitHub)  │
└─────────┘          └─────────┘

2.2 核心概念

概念含义
Host跑 LLM / agent 的应用(Claude Desktop、Cursor、LangGraph、Letta…)
Clienthost 内的 MCP 客户端模块,负责协议通信
Server暴露资源/工具的进程,可以是任何语言
Resource可读数据(文件、记录、URL)
Tool可调用函数(写、计算、副作用)
Prompt可参数化的 prompt template
Samplingserver 反向请 host 跑 LLM

2.3 Wire Protocol

JSON-RPC 2.0,3 种 transport:

  • stdio:本地 server,host 启动 server 子进程
  • HTTP + SSE:远程 server,SSE 回推
  • WebSocket / Streamable HTTP:新 spec,长连接

2.4 三层抽象

┌─────────────────────────────────────┐
│   Application logic(LLM 决策)      │
├─────────────────────────────────────┤
│   MCP Tool/Resource(标准接口)      │
├─────────────────────────────────────┤
│   Underlying API / DB / Filesystem  │
└─────────────────────────────────────┘

LLM 不需要知道 GitHub API 的细节,只看到 “create_issue(repo, title, body)” 这样的标准 tool。


3. 写一个最简 MCP server

用官方 Python SDK 写一个文件操作 server:

# file_server.py
from mcp.server.fastmcp import FastMCP
from pathlib import Path

mcp = FastMCP("file-server")

@mcp.tool()
def read_file(path: str) -> str:
    """读取文件内容。"""
    return Path(path).read_text()

@mcp.tool()
def write_file(path: str, content: str) -> str:
    """写入文件。"""
    Path(path).write_text(content)
    return f"Wrote {len(content)} chars to {path}"

@mcp.tool()
def list_dir(path: str) -> list[str]:
    """列出目录内容。"""
    return [str(p) for p in Path(path).iterdir()]

@mcp.resource("file://{path}")
def file_resource(path: str) -> str:
    """暴露文件作为资源。"""
    return Path(path).read_text()

if __name__ == "__main__":
    mcp.run()  # 默认 stdio transport

启动:

python file_server.py

3.1 测试 server

用 MCP Inspector(官方调试工具):

npx @modelcontextprotocol/inspector python file_server.py

打开 web UI 可以看到所有 tool / resource,手动调用测试。


4. MCP 客户端集成

4.1 Claude Desktop

~/Library/Application Support/Claude/claude_desktop_config.json:

{
  "mcpServers": {
    "file": {
      "command": "python",
      "args": ["/path/to/file_server.py"]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {"GITHUB_TOKEN": "ghp_..."}
    }
  }
}

重启 Claude Desktop,工具自动可用。

4.2 LangGraph 接 MCP

from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent

async with MultiServerMCPClient(
    {
        "file": {"command": "python", "args": ["file_server.py"], "transport": "stdio"},
        "github": {"url": "http://github-mcp.local:8080", "transport": "streamable_http"},
    }
) as client:
    tools = await client.get_tools()  # 所有 server 的 tools 合并
    agent = create_react_agent(llm, tools=tools)
    result = await agent.ainvoke({"messages": [...]})

4.3 主流 MCP server 生态(2026)

按类别有 1000+ 个 MCP server,常用:

类别代表 server
文件系统filesystem(官方)、git
数据库postgres、sqlite、mongodb
SaaSgithub、gitlab、slack、notion、linear、jira
开发工具docker、kubernetes、aws、gcp
浏览器puppeteer、playwright、browser-use
搜索brave-search、google-search、tavily
内存mem0、letta、graphiti(模块五框架都做了 MCP)

🍎 找 MCP server:mcp.so / smithery.ai / glama.ai/mcp 这些目录有完整列表。


5. MCP 安全模型

5.1 安全风险

MCP 让 LLM 能调用真实工具,带来:

  • Prompt injection:用户消息让 agent 调危险工具
  • 越权:agent 调到不该调的工具(读 root 权限文件)
  • Data exfiltration:工具读敏感数据,通过另一个工具发送出去
  • Supply chain:第三方 MCP server 含恶意代码

5.2 防御层次

措施
Server 层只 expose 必要 tool;每个 tool 描述清楚参数和副作用
Permission scopehost 启动 server 时声明 scope(read-only / write / network)
AuthenticationMCP 2025 spec 加了 OAuth flow,远程 server 必须 auth
Confirmation UI写操作 / 危险操作必须用户点确认
Audit log每次 tool 调用都 log(配合第 8 章 observability)
Sandboxserver 跑在容器/沙箱里,限制系统调用
Rate limit防 agent 失控刷 API

5.3 Anthropic 的 “human-in-the-loop” 强约束

Claude Desktop 默认所有 tool 调用都需要用户点确认——可改”allow always for this tool”,但每个新 tool 第一次都要批。这是用 UX 强制人对每个工具有”知情同意”

🌟 LangGraph / Cursor 等 host 也越来越多采用类似模式。


6. A2A:Agent-to-Agent Protocol

6.1 动机

MCP 解决了”agent 用工具”,但agent 之间怎么协作?

例:Salesforce 的销售 agent 想让 ServiceNow 的工单 agent 处理客户投诉——两个 agent 来自不同公司、不同框架、不同协议。

Google 2025-04 发布 A2A,联手 50+ 公司(Salesforce、PayPal、SAP、Workday、ServiceNow 等)。

6.2 核心概念

概念含义
Agent Cardagent 的”名片”:名字、能力、endpoint、auth 方式
Task一个对话/请求,有 ID、状态、message 历史
Messagetask 内的一次发言
Artifact任务产物(文件、数据、URL)
Streaming长任务支持 SSE 流式更新

6.3 工作流程

Agent A 想找 Agent B 处理某事

1. Discover:从 .well-known/agent.json 拿 B 的 Agent Card
2. Send Task:HTTP POST /tasks/send,A 描述任务
3. Stream / Poll:任务状态(pending → in_progress → completed)
4. Get Artifacts:任务完成,A 拉走结果

6.4 与 MCP 的差异

维度MCPA2A
解决Agent ↔ ToolAgent ↔ Agent
通信模型RPC(同步、stateless)Task(异步、stateful)
服务方工具 server(被动)Agent(主动有自己的目标)
典型 wireJSON-RPCHTTP REST + SSE
鉴权OAuth(2025+)基于 Agent Card 中声明的 auth

6.5 最简 A2A 代码

from a2a.server import A2AServer
from a2a.types import Message, Task

class MyAgent(A2AServer):
    async def handle_task(self, task: Task) -> Task:
        msg = task.messages[-1].content
        # 调用本 agent 的 LLM 处理
        response = await my_llm.invoke(msg)
        return task.update(
            status="completed",
            messages=task.messages + [Message(role="agent", content=response)],
            artifacts=[...],
        )

server = MyAgent(
    agent_card={
        "name": "MyAgent",
        "description": "处理 X 业务",
        "endpoint": "https://my.com/a2a",
        "capabilities": ["task.send", "task.stream"],
    }
)
server.run(port=8080)

7. MCP + A2A:协同使用

实际生产中 MCP + A2A 都用:

           ┌──────────────────────┐
           │  My Agent             │
           └─┬───────────────────┬─┘
             │                   │
        MCP  │                   │  A2A
        (内部 │                   │  (跨组织
         工具)│                   │   agent)
             ▼                   ▼
   ┌──────────────┐    ┌──────────────────┐
   │ MCP Servers  │    │ Other Agents     │
   │              │    │                  │
   │ - DB         │    │ - 合作伙伴 agent  │
   │ - GitHub     │    │ - 第三方 SaaS    │
   │ - Slack      │    │   agent          │
   └──────────────┘    └──────────────────┘

7.1 真实例子

电商订单 agent:

  • 用 MCP 调用内部库存 server、支付 server、物流 server(都是工具)
  • 用 A2A 把”复杂客诉”转给客服公司的 agent(对方是独立 agent,不是工具)

研发 agent:

  • 用 MCP 调 GitHub、Slack、Linear、Sentry(工具)
  • 用 A2A 把”安全 review”派给安全团队的专门 agent(对方是 agent,有自己的 reasoning)

🍎 简记:MCP 是”调用工具”,A2A 是”委托同伴”


8. 2025 标准化大事件

时间事件
2024-11Anthropic 发布 MCP
2025-01OpenAI 宣布支持 MCP(主要 LLM 厂商陆续)
2025-04Google 发布 A2A,50+ 公司参与
2025-Q3OpenTelemetry GenAI Semantic Conventions v1.37 发布(下章详)
2025-12Anthropic 把 MCP 捐赠 Linux Foundation —— 与 Block、OpenAI 等共建 Agentic AI Foundation(AAIF)
2026-Q1MCP 月 SDK 下载量超 9700 万,GitHub 8.1 万 stars

🌟 MCP 已经事实成为”agent 工具协议”的国际标准——任何新 agent 框架不支持 MCP 等于自废武功。


✅ 自我检验清单

  • 协议必要性:能用 HTTP/REST 类比解释 MCP 为什么重要
  • MCP 4 大概念:能默写 Host / Client / Server / Resource&Tool
  • 写最简 MCP server:能用 FastMCP 在 5 分钟内写一个 file 工具 server
  • 集成到 LangGraph / Claude Desktop:能写完整配置
  • MCP 安全风险:能列出 4 类风险,以及对应防御措施
  • A2A vs MCP:能用一句话区分两者
  • A2A 工作流程:能默写 Discover → Send Task → Stream → Get Artifact
  • 协同场景:能给一个具体业务,说明同时用 MCP + A2A 的设计
  • 2025 标准化:能讲出”为什么 MCP 已经是事实标准”
  • 生态查询:知道去哪找 MCP server(mcp.so / smithery.ai / glama.ai/mcp)

📚 参考资料

MCP

A2A

2025 标准化