Skip to content

A2A(Agent2Agent)协议全面学习指南

📚 系统梳理 + 易理解 + 强记忆

A2A 是 Google 于 2025 年 4 月发布的首个标准智能体交互协议,被称为「AI 智能体的通用语言」


目录


一、核心基础

1.1 A2A 协议定义

A2A(Agent2Agent Protocol) 是 Google 于 2025 年 4 月 10 日在 Google Cloud Next 2025 大会上发布的开源智能体交互协议

一句话定义:A2A 是让不同 AI 智能体(Agent)之间能够相互发现、通信、协作的标准化协议。

┌─────────────────────────────────────────────────────────────────┐
│                    A2A 协议核心定位                              │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│    ┌─────────┐         A2A 协议          ┌─────────┐            │
│    │ Agent A │ ◄─────────────────────► │ Agent B │            │
│    │ (框架X) │      标准化通信           │ (框架Y) │            │
│    └─────────┘                          └─────────┘            │
│         │                                    │                  │
│         │              A2A 协议              │                  │
│         └──────────────────────────────────►│                  │
│                         │                    │                  │
│                    ┌─────────┐               │                  │
│                    │ Agent C │ ◄────────────┘                  │
│                    │ (框架Z) │                                  │
│                    └─────────┘                                  │
│                                                                  │
│  **重点**:跨框架、跨供应商、跨平台的智能体间通信                   │
└─────────────────────────────────────────────────────────────────┘

1.2 设计初衷与背景

痛点A2A 解决方案
智能体孤岛不同框架的 Agent 无法通信 → 提供统一协议标准
重复造轮子每次集成都需自定义接口 → 一次实现,处处可用
协作复杂多 Agent 协同难以实现 → 原生支持任务编排
生态割裂各厂商封闭生态 → 开源开放,50+ 企业支持

设计原则(官方定义):

  1. 拥抱智能体能力:支持自然语言协商、任务代理、多模态交互
  2. 基于现有标准:使用 HTTP、JSON-RPC、SSE 等成熟技术
  3. 默认安全:内置企业级认证授权机制
  4. 支持长任务:原生处理耗时任务,支持实时进度反馈
  5. 模态无关:支持文本、文件、表单、流式数据等多种内容类型

1.3 核心定位:A2A vs MCP

⚠️ 易混淆点:A2A 和 MCP 不是竞争关系,而是互补关系

┌─────────────────────────────────────────────────────────────────┐
│                    协议定位对比                                   │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  MCP (Model Context Protocol)                                    │
│  ┌─────────┐                      ┌─────────────────────────┐   │
│  │   LLM   │ ◄─── MCP 协议 ────► │  工具/资源/数据源        │   │
│  └─────────┘                      │  (Tool, Resource, API)  │   │
│                                   └─────────────────────────┘   │
│  定位:LLM 与外部工具的连接(人→工具)                            │
│                                                                  │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  A2A (Agent2Agent Protocol)                                      │
│  ┌─────────┐                      ┌─────────┐                   │
│  │ Agent A │ ◄─── A2A 协议 ────► │ Agent B │                   │
│  └─────────┘                      └─────────┘                   │
│  定位:智能体之间的协作(Agent→Agent)                            │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘
对比维度MCPA2A
发布方Anthropic (2024.11)Google (2025.04)
核心定位LLM ↔ 工具/资源Agent ↔ Agent
通信对象模型与外部系统智能体与智能体
主要能力工具调用、资源获取任务编排、能力协商
任务模型同步为主支持长时异步任务
发现机制Agent Card 能力发现
关系垂直连接(深度)水平连接(广度)

⭐ 重点理解

  • MCP:让 Agent 能「使用工具」(类似给机器人装上手臂)
  • A2A:让 Agent 能「协作对话」(类似让机器人之间交流)

1.4 与其他协议的对比

协议定位通信模式适用场景
A2AAgent 间通信任务驱动、异步多智能体协作
MCPLLM-工具连接请求-响应工具调用
Function Calling模型调用函数同步调用单次工具调用
gRPC通用 RPC请求-响应/流微服务通信
MQTT消息队列发布-订阅IoT、消息推送
HTTP RESTWeb API请求-响应Web 服务

1.5 适用场景与不适用场景

✅ 适用场景

场景说明
多智能体协作系统多个专业 Agent 协同完成复杂任务
跨平台 Agent 集成不同框架/供应商的 Agent 需要通信
企业级 AI 工作流需要任务编排、状态管理的业务流程
AI 助手联邦多个 AI 助手共享能力、分工协作
长时任务处理需要异步执行、进度反馈的任务

❌ 不适用场景

场景原因替代方案
简单工具调用杀鸡用牛刀Function Calling
LLM 直连外部数据不是 A2A 设计目标MCP
实时流媒体传输非核心优化方向WebRTC、gRPC
IoT 设备通信协议过重MQTT、CoAP
单体应用内部通信无需标准化直接函数调用

二、技术规范

2.1 核心架构

核心组件说明

组件职责类比
A2A Client发起请求的一方(可以是另一个 Agent)客户
A2A Server接收请求、执行任务的 Agent服务商
Agent Card描述 Agent 能力的元数据文件名片/简历
Task工作的基本单位,有完整生命周期工单
MessageClient 与 Server 之间的通信内容对话消息
Artifact任务执行产生的输出物工作成果

2.2 核心概念详解

2.2.1 Agent Card(智能体名片)

⭐ 重点:Agent Card 是 A2A 的发现机制核心,类似「AI 的数字简历」

硬性要求:必须部署在 /.well-known/agent.json 路径

json
{
  "name": "智能文档助手",
  "description": "专业的文档处理和分析智能体",
  "url": "https://doc-agent.example.com/a2a",
  "version": "1.0.0",
  
  "capabilities": {
    "streaming": true,
    "pushNotifications": true,
    "stateTransitionHistory": true
  },
  
  "authentication": {
    "schemes": ["Bearer"],
    "credentials": "oauth2"
  },
  
  "defaultInputModes": ["text/plain", "application/json"],
  "defaultOutputModes": ["text/plain", "application/json", "application/pdf"],
  
  "skills": [
    {
      "id": "document_analysis",
      "name": "文档分析",
      "description": "分析文档内容、提取关键信息",
      "inputModes": ["application/pdf", "text/plain"],
      "outputModes": ["application/json"]
    },
    {
      "id": "document_translation",
      "name": "文档翻译",
      "description": "将文档翻译成目标语言",
      "inputModes": ["text/plain"],
      "outputModes": ["text/plain"]
    }
  ]
}

字段说明

字段必选说明
nameAgent 名称
descriptionAgent 功能描述
urlA2A 服务端点 URL
version版本号
capabilities支持的能力标志
authentication认证方式
skills技能列表(核心!)
defaultInputModes默认输入格式
defaultOutputModes默认输出格式

2.2.2 Task(任务)

⭐ 重点:Task 是 A2A 的工作基本单位,有完整的生命周期

任务状态流转

任务状态说明

状态说明是否终态
submitted已提交,等待处理
working正在处理中
input_required需要客户端提供更多输入
completed任务成功完成
failed任务执行失败
canceled任务被取消

Task 数据结构

json
{
  "id": "task-uuid-12345",
  "sessionId": "session-uuid-67890",
  "status": {
    "state": "working",
    "message": {
      "role": "agent",
      "parts": [
        {
          "type": "text",
          "text": "正在分析文档..."
        }
      ]
    },
    "timestamp": "2025-04-10T10:30:00Z"
  },
  "artifacts": [],
  "history": []
}

2.2.3 Message(消息)

Message 是 Client 和 Agent 之间的通信单元:

json
{
  "role": "user",  // "user" 或 "agent"
  "parts": [
    {
      "type": "text",
      "text": "请帮我分析这份文档"
    },
    {
      "type": "file",
      "file": {
        "name": "report.pdf",
        "mimeType": "application/pdf",
        "bytes": "base64编码内容..."
      }
    }
  ]
}

2.2.4 Part(内容单元)

Part 类型说明示例
TextPart文本内容普通文字、Markdown
FilePart文件内容(内联或 URI)PDF、图片、音视频
DataPart结构化数据JSON 表单、配置
json
// TextPart
{ "type": "text", "text": "这是文本内容" }

// FilePart (内联)
{ 
  "type": "file", 
  "file": { 
    "name": "image.png", 
    "mimeType": "image/png", 
    "bytes": "base64..." 
  } 
}

// FilePart (URI)
{ 
  "type": "file", 
  "file": { 
    "name": "video.mp4", 
    "mimeType": "video/mp4", 
    "uri": "https://example.com/video.mp4" 
  } 
}

// DataPart
{ 
  "type": "data", 
  "data": { 
    "formField1": "value1", 
    "formField2": 123 
  } 
}

2.2.5 Artifact(工件/产出物)

Agent 执行任务后产生的输出:

json
{
  "name": "分析报告",
  "description": "文档分析结果",
  "parts": [
    {
      "type": "text",
      "text": "## 分析摘要\n..."
    },
    {
      "type": "file",
      "file": {
        "name": "analysis.json",
        "mimeType": "application/json",
        "bytes": "eyJyZXN1bHQiOi..."
      }
    }
  ],
  "index": 0,
  "append": false,
  "lastChunk": true
}

2.3 通信模型

2.3.1 通信流程

2.3.2 请求/响应格式(JSON-RPC 2.0)

请求格式

json
{
  "jsonrpc": "2.0",
  "id": "req-001",
  "method": "tasks/send",
  "params": {
    "id": "task-uuid-12345",
    "message": {
      "role": "user",
      "parts": [
        { "type": "text", "text": "分析这个文档" }
      ]
    }
  }
}

响应格式(成功)

json
{
  "jsonrpc": "2.0",
  "id": "req-001",
  "result": {
    "id": "task-uuid-12345",
    "sessionId": "session-uuid-67890",
    "status": {
      "state": "working",
      "timestamp": "2025-04-10T10:30:00Z"
    }
  }
}

响应格式(错误)

json
{
  "jsonrpc": "2.0",
  "id": "req-001",
  "error": {
    "code": -32600,
    "message": "Invalid Request",
    "data": { "details": "Missing required field: message" }
  }
}

2.4 核心方法(Methods)

方法说明请求方向
tasks/send发送任务消息(同步)Client → Server
tasks/sendSubscribe发送任务并订阅更新(流式)Client → Server
tasks/get获取任务状态Client → Server
tasks/cancel取消任务Client → Server
tasks/pushNotification/set设置推送通知Client → Server
tasks/pushNotification/get获取推送配置Client → Server
tasks/resubscribe重新订阅任务更新Client → Server

方法详解

python
# tasks/send - 发送任务(最常用)
{
    "method": "tasks/send",
    "params": {
        "id": "task-123",           # 任务ID(可选,不填则自动生成)
        "sessionId": "session-456", # 会话ID(可选,用于关联多轮对话)
        "message": {                # 消息内容
            "role": "user",
            "parts": [...]
        },
        "acceptedOutputModes": ["text/plain", "application/json"],  # 可接受的输出格式
        "pushNotification": {       # 推送配置(可选)
            "url": "https://my-app.com/webhook",
            "authentication": {...}
        }
    }
}

# tasks/sendSubscribe - 流式任务(SSE)
# 请求格式同 tasks/send,响应为 SSE 流

2.5 传输方式

传输方式说明使用场景
HTTP POST标准请求-响应短任务、同步调用
HTTP + SSE服务器推送事件长任务、流式输出
Webhook推送通知异步回调、状态更新

HTTP 端点要求

POST {agent_url}           # JSON-RPC 请求端点
GET  {agent_url}/sse       # SSE 订阅端点(用于 sendSubscribe)
GET  /.well-known/agent.json  # Agent Card 发现端点

2.6 认证与安全机制

硬性要求:企业级部署必须配置认证!

支持的认证方式

认证方式说明配置示例
API Key简单密钥认证Authorization: Bearer xxx
OAuth 2.0标准 OAuth 流程支持多种 Grant Type
mTLS双向 TLS 证书企业内网推荐
自定义自定义认证头根据业务需求

Agent Card 中的认证配置

json
{
  "authentication": {
    "schemes": ["Bearer", "OAuth2"],
    "credentials": "oauth2",
    "oauth2": {
      "authorizationUrl": "https://auth.example.com/authorize",
      "tokenUrl": "https://auth.example.com/token",
      "scopes": {
        "read": "读取权限",
        "write": "写入权限"
      }
    }
  }
}

2.7 错误处理规范

标准错误码(基于 JSON-RPC 2.0):

错误码名称说明
-32700Parse ErrorJSON 解析错误
-32600Invalid Request无效请求
-32601Method Not Found方法不存在
-32602Invalid Params参数错误
-32603Internal Error内部错误

A2A 扩展错误码

错误码名称说明
-32001Task Not Found任务不存在
-32002Task Canceled任务已取消
-32003Authentication Failed认证失败
-32004Permission Denied权限不足
-32005Rate Limited请求限流

三、核心能力

3.1 智能体发现(Agent Discovery)

⭐ 重点:通过 Agent Card 实现即插即用的能力发现

发现流程代码示例

python
import httpx

async def discover_agent(base_url: str):
    """发现并解析 Agent 能力"""
    agent_card_url = f"{base_url}/.well-known/agent.json"
    
    async with httpx.AsyncClient() as client:
        response = await client.get(agent_card_url)
        agent_card = response.json()
    
    print(f"Agent: {agent_card['name']}")
    print(f"描述: {agent_card['description']}")
    print(f"技能列表:")
    for skill in agent_card.get('skills', []):
        print(f"  - {skill['name']}: {skill['description']}")
    
    return agent_card

3.2 任务编排(Task Orchestration)

A2A 原生支持复杂任务的编排和协调:

┌─────────────────────────────────────────────────────────────────┐
│                    多 Agent 任务编排示例                          │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  ┌───────────────┐                                              │
│  │   用户请求     │ "帮我写一篇技术博客并翻译成英文"              │
│  └───────┬───────┘                                              │
│          │                                                       │
│          ▼                                                       │
│  ┌───────────────┐      A2A       ┌───────────────┐             │
│  │ 编排 Agent    │ ─────────────► │ 写作 Agent    │             │
│  │ (Orchestrator)│                │               │             │
│  └───────┬───────┘                └───────┬───────┘             │
│          │                                │                      │
│          │                                │ 返回中文文章         │
│          │                                ▼                      │
│          │         A2A            ┌───────────────┐             │
│          └──────────────────────► │ 翻译 Agent    │             │
│                                   │               │             │
│                                   └───────┬───────┘             │
│                                           │                      │
│                                           │ 返回英文翻译         │
│                                           ▼                      │
│                                   ┌───────────────┐             │
│                                   │   最终结果     │             │
│                                   └───────────────┘             │
└─────────────────────────────────────────────────────────────────┘

3.3 多智能体协同

协同模式

模式说明适用场景
串行协作Agent A → Agent B → Agent C流水线任务
并行协作Agent A ⇉ Agent B, C, D分解子任务
竞争协作多 Agent 竞标同一任务最优选择
投票协作多 Agent 共同决策质量保证

3.4 消息路由

A2A 支持灵活的消息路由机制:

json
{
  "method": "tasks/send",
  "params": {
    "id": "task-123",
    "message": {
      "role": "user",
      "parts": [{ "type": "text", "text": "处理请求" }]
    },
    "routing": {
      "preferredAgent": "agent-uuid-456",  // 优先路由
      "fallbackAgents": ["agent-uuid-789"], // 备选路由
      "loadBalancing": "round-robin"        // 负载均衡
    }
  }
}

3.5 关键特性总结

特性说明对比优势
跨平台支持任何框架、任何语言vs 私有协议
低耦合Agent 之间松散耦合vs 紧耦合集成
可扩展自定义 Skill、Part 类型vs 固定能力
多模态支持文本、文件、流媒体vs 纯文本
长任务原生异步、进度反馈vs 同步阻塞
安全性内置认证、授权机制vs 无安全考虑

四、应用实践

4.1 典型落地场景

场景一:多智能体协作系统

┌─────────────────────────────────────────────────────────────────┐
│                    企业智能助手联邦                              │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  用户: "帮我处理本月的报销单,并生成财务报表"                      │
│                                                                  │
│  ┌─────────────┐    A2A    ┌─────────────┐                      │
│  │ 入口 Agent  │ ────────► │ 文档 Agent  │  提取报销单信息       │
│  └─────────────┘           └──────┬──────┘                      │
│         │                         │                              │
│         │                         ▼                              │
│         │          A2A     ┌─────────────┐                      │
│         └────────────────► │ 财务 Agent  │  生成财务报表        │
│                            └──────┬──────┘                      │
│                                   │                              │
│                                   ▼                              │
│                            ┌─────────────┐                      │
│                            │ 审批 Agent  │  自动提交审批        │
│                            └─────────────┘                      │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

场景二:AI 工作流

python
# 示例:代码审查工作流
async def code_review_workflow(code_diff: str):
    # 1. 静态分析 Agent
    static_result = await call_agent(
        agent_url="https://static-analyzer.example.com",
        skill="code_analysis",
        input=code_diff
    )
    
    # 2. 安全扫描 Agent(并行)
    security_result = await call_agent(
        agent_url="https://security-scanner.example.com",
        skill="vulnerability_scan",
        input=code_diff
    )
    
    # 3. 代码审查 Agent
    review_result = await call_agent(
        agent_url="https://code-reviewer.example.com",
        skill="review",
        input={
            "code": code_diff,
            "static_analysis": static_result,
            "security_scan": security_result
        }
    )
    
    return review_result

场景三:分布式智能体平台

┌─────────────────────────────────────────────────────────────────┐
│                    分布式 Agent 平台架构                          │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │                    Agent Registry                        │    │
│  │                  (Agent Card 注册中心)                    │    │
│  └────────────────────────┬────────────────────────────────┘    │
│                           │                                      │
│         ┌─────────────────┼─────────────────┐                   │
│         │                 │                 │                    │
│         ▼                 ▼                 ▼                    │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐             │
│  │ Agent Pod 1 │  │ Agent Pod 2 │  │ Agent Pod N │             │
│  │ (K8s 部署)  │  │ (K8s 部署)  │  │ (K8s 部署)  │             │
│  └─────────────┘  └─────────────┘  └─────────────┘             │
│         │                 │                 │                    │
│         └─────────────────┴─────────────────┘                   │
│                           │                                      │
│                           ▼                                      │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │                    A2A Gateway                           │    │
│  │            (负载均衡、认证、路由、监控)                    │    │
│  └─────────────────────────────────────────────────────────┘    │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

4.2 主流适配框架/工具

框架/工具支持程度说明
LangChain✅ 官方支持首批支持企业之一
AutoGPT✅ 社区支持多智能体协作
CrewAI✅ 原生支持团队协作框架
Google ADK✅ 官方 SDKAgent Development Kit
Vertex AI✅ 深度集成Google Cloud 产品
Salesforce✅ 企业支持Einstein Agent
SAP✅ 企业支持Joule Agent

4.3 快速上手实践

Step 1:创建 Agent Card

json
// /.well-known/agent.json
{
  "name": "我的第一个 A2A Agent",
  "description": "一个简单的 Echo Agent,用于学习 A2A",
  "url": "http://localhost:8000/a2a",
  "version": "1.0.0",
  "capabilities": {
    "streaming": false,
    "pushNotifications": false
  },
  "skills": [
    {
      "id": "echo",
      "name": "Echo 回显",
      "description": "将输入内容原样返回",
      "inputModes": ["text/plain"],
      "outputModes": ["text/plain"]
    }
  ]
}

Step 2:实现 A2A Server(Python)

python
# a2a_server.py
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import uuid

app = FastAPI()

# 存储任务
tasks = {}

@app.get("/.well-known/agent.json")
async def get_agent_card():
    """返回 Agent Card"""
    return {
        "name": "Echo Agent",
        "description": "简单的回显 Agent",
        "url": "http://localhost:8000/a2a",
        "version": "1.0.0",
        "capabilities": {"streaming": False},
        "skills": [{
            "id": "echo",
            "name": "Echo",
            "description": "回显输入内容",
            "inputModes": ["text/plain"],
            "outputModes": ["text/plain"]
        }]
    }

@app.post("/a2a")
async def handle_a2a(request: Request):
    """处理 A2A JSON-RPC 请求"""
    body = await request.json()
    
    method = body.get("method")
    params = body.get("params", {})
    request_id = body.get("id")
    
    if method == "tasks/send":
        return handle_task_send(params, request_id)
    elif method == "tasks/get":
        return handle_task_get(params, request_id)
    elif method == "tasks/cancel":
        return handle_task_cancel(params, request_id)
    else:
        return JSONResponse({
            "jsonrpc": "2.0",
            "id": request_id,
            "error": {
                "code": -32601,
                "message": f"Method not found: {method}"
            }
        })

def handle_task_send(params: dict, request_id: str):
    """处理 tasks/send 请求"""
    task_id = params.get("id") or str(uuid.uuid4())
    message = params.get("message", {})
    
    # 提取输入文本
    input_text = ""
    for part in message.get("parts", []):
        if part.get("type") == "text":
            input_text += part.get("text", "")
    
    # 创建任务并立即完成(Echo 逻辑)
    task = {
        "id": task_id,
        "sessionId": params.get("sessionId") or str(uuid.uuid4()),
        "status": {
            "state": "completed",
            "message": {
                "role": "agent",
                "parts": [{"type": "text", "text": f"Echo: {input_text}"}]
            }
        },
        "artifacts": [{
            "name": "echo_result",
            "parts": [{"type": "text", "text": input_text}]
        }]
    }
    
    tasks[task_id] = task
    
    return JSONResponse({
        "jsonrpc": "2.0",
        "id": request_id,
        "result": task
    })

def handle_task_get(params: dict, request_id: str):
    """处理 tasks/get 请求"""
    task_id = params.get("id")
    task = tasks.get(task_id)
    
    if not task:
        return JSONResponse({
            "jsonrpc": "2.0",
            "id": request_id,
            "error": {
                "code": -32001,
                "message": "Task not found"
            }
        })
    
    return JSONResponse({
        "jsonrpc": "2.0",
        "id": request_id,
        "result": task
    })

def handle_task_cancel(params: dict, request_id: str):
    """处理 tasks/cancel 请求"""
    task_id = params.get("id")
    task = tasks.get(task_id)
    
    if task:
        task["status"]["state"] = "canceled"
    
    return JSONResponse({
        "jsonrpc": "2.0",
        "id": request_id,
        "result": task or {"id": task_id, "status": {"state": "canceled"}}
    })

# 运行:uvicorn a2a_server:app --host 0.0.0.0 --port 8000

Step 3:实现 A2A Client

python
# a2a_client.py
import httpx
import asyncio

async def discover_agent(base_url: str) -> dict:
    """发现 Agent 能力"""
    async with httpx.AsyncClient() as client:
        response = await client.get(f"{base_url}/.well-known/agent.json")
        return response.json()

async def send_task(agent_url: str, message: str) -> dict:
    """发送任务"""
    payload = {
        "jsonrpc": "2.0",
        "id": "req-001",
        "method": "tasks/send",
        "params": {
            "message": {
                "role": "user",
                "parts": [{"type": "text", "text": message}]
            }
        }
    }
    
    async with httpx.AsyncClient() as client:
        response = await client.post(agent_url, json=payload)
        return response.json()

async def main():
    base_url = "http://localhost:8000"
    
    # 1. 发现 Agent
    print("=== 发现 Agent ===")
    agent_card = await discover_agent(base_url)
    print(f"Agent: {agent_card['name']}")
    print(f"Skills: {[s['name'] for s in agent_card['skills']]}")
    
    # 2. 发送任务
    print("\n=== 发送任务 ===")
    result = await send_task(
        f"{base_url}/a2a",
        "Hello, A2A!"
    )
    print(f"Result: {result}")

if __name__ == "__main__":
    asyncio.run(main())

Step 4:运行测试

bash
# 终端 1:启动 Server
pip install fastapi uvicorn httpx
uvicorn a2a_server:app --host 0.0.0.0 --port 8000

# 终端 2:运行 Client
python a2a_client.py

预期输出

=== 发现 Agent ===
Agent: Echo Agent
Skills: ['Echo']

=== 发送任务 ===
Result: {
  "jsonrpc": "2.0",
  "id": "req-001",
  "result": {
    "id": "xxx-xxx-xxx",
    "status": {"state": "completed", ...},
    "artifacts": [{"name": "echo_result", ...}]
  }
}

五、进阶拓展

5.1 版本迭代与更新

版本发布时间主要更新
1.0.02025.04首次发布,核心协议定义
1.x规划中增强流式支持、多模态优化

关注官方更新

  • GitHub: google/a2a-protocol(假设仓库名)
  • 文档: https://a2a-protocol.dev(假设官网)

5.2 性能优化技巧

优化点方法效果
连接复用HTTP/2 多路复用减少连接开销
批量请求合并多个小任务降低网络延迟
流式响应使用 SSE 订阅提升响应体验
缓存 Agent Card本地缓存 + TTL减少发现开销
异步处理使用 Webhook 回调释放客户端资源

示例:连接池配置

python
import httpx

# 创建带连接池的客户端
client = httpx.AsyncClient(
    http2=True,  # 启用 HTTP/2
    limits=httpx.Limits(
        max_keepalive_connections=20,
        max_connections=100
    ),
    timeout=httpx.Timeout(30.0, connect=10.0)
)

5.3 私有化部署要点

5.3.1 部署架构

┌─────────────────────────────────────────────────────────────────┐
│                    私有化部署架构                                │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │                    负载均衡器 (Nginx/Kong)               │    │
│  └────────────────────────────┬────────────────────────────┘    │
│                               │                                  │
│         ┌─────────────────────┼─────────────────────┐           │
│         │                     │                     │            │
│         ▼                     ▼                     ▼            │
│  ┌─────────────┐      ┌─────────────┐      ┌─────────────┐      │
│  │ Agent Pod 1 │      │ Agent Pod 2 │      │ Agent Pod 3 │      │
│  └─────────────┘      └─────────────┘      └─────────────┘      │
│                                                                  │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │                    共享存储层                            │    │
│  │         (Redis 缓存 + PostgreSQL 持久化)                 │    │
│  └─────────────────────────────────────────────────────────┘    │
│                                                                  │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │                    监控告警 (Prometheus + Grafana)       │    │
│  └─────────────────────────────────────────────────────────┘    │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

5.3.2 关键配置

Nginx 代理配置

nginx
upstream a2a_agents {
    least_conn;
    server agent1:8000;
    server agent2:8000;
    server agent3:8000;
}

server {
    listen 443 ssl http2;
    server_name a2a.example.com;
    
    # Agent Card 发现
    location /.well-known/agent.json {
        proxy_pass http://a2a_agents;
        proxy_cache agent_card_cache;
        proxy_cache_valid 200 5m;
    }
    
    # A2A 端点
    location /a2a {
        proxy_pass http://a2a_agents;
        proxy_http_version 1.1;
        proxy_set_header Connection '';
        proxy_buffering off;  # SSE 支持
    }
}

5.3.3 安全加固

措施说明
mTLS双向 TLS 认证
网络隔离VPC 内网部署
访问控制RBAC 权限管理
审计日志记录所有 A2A 调用
速率限制防止滥用

5.4 生态与周边工具链

┌─────────────────────────────────────────────────────────────────┐
│                    A2A 生态工具链                                │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  开发工具                                                        │
│  ├── Google Agent Development Kit (ADK)                         │
│  ├── A2A SDK (Python/TypeScript/Go)                             │
│  └── A2A CLI (命令行工具)                                        │
│                                                                  │
│  测试工具                                                        │
│  ├── A2A Inspector (可视化调试)                                  │
│  ├── Mock Agent Server                                          │
│  └── 集成测试框架                                                │
│                                                                  │
│  运维工具                                                        │
│  ├── Agent Registry (注册中心)                                   │
│  ├── A2A Gateway (网关)                                         │
│  └── 监控面板 (Grafana Dashboard)                                │
│                                                                  │
│  集成框架                                                        │
│  ├── LangChain A2A Adapter                                      │
│  ├── CrewAI A2A Plugin                                          │
│  └── Vertex AI Agent Builder                                    │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

核心知识点速记清单

📋 30 秒速记

A2A = Agent 之间的标准化通信协议(Google 出品)

核心组件:
  - Agent Card = AI 的数字名片 (/.well-known/agent.json)
  - Task = 工作基本单位(6 种状态)
  - Message = 通信内容(包含多个 Part)
  - Artifact = 任务产出物

关键方法:
  - tasks/send = 发送任务
  - tasks/sendSubscribe = 流式任务
  - tasks/get = 查询状态
  - tasks/cancel = 取消任务

vs MCP:
  - MCP = LLM ↔ 工具(垂直连接)
  - A2A = Agent ↔ Agent(水平连接)
  - 两者互补,不是竞争!

📋 一图速记

┌─────────────────────────────────────────────────────────────────┐
│                    A2A 协议知识地图                              │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  [发现] Agent Card ──► [通信] JSON-RPC ──► [执行] Task          │
│     │                      │                   │                │
│     ▼                      ▼                   ▼                │
│  /.well-known/       tasks/send           状态流转              │
│  agent.json          tasks/subscribe      submitted→working     │
│                      tasks/get            →completed/failed     │
│                      tasks/cancel                               │
│                                                                  │
│  [安全] 认证机制     [传输] HTTP/SSE      [产出] Artifact       │
│  Bearer/OAuth2       同步/流式            文本/文件/数据         │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

📋 公式速记

A2A 完整流程 = 发现(Agent Card) + 通信(JSON-RPC) + 执行(Task) + 产出(Artifact)

协议选择公式:
  - 需要调用工具? → MCP
  - 需要 Agent 协作? → A2A
  - 简单函数调用? → Function Calling
  - 两者都需要? → MCP + A2A

常见误区避坑指南

❌ 误区一:A2A 和 MCP 是竞争关系

正解:两者是互补关系

┌─────────────────────────────────────────────────────────────────┐
│                    正确理解                                      │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │                      完整 AI 系统                        │    │
│  │                                                          │    │
│  │  ┌───────┐         ┌───────┐         ┌───────┐          │    │
│  │  │Agent A│◄──A2A──►│Agent B│◄──A2A──►│Agent C│          │    │
│  │  └───┬───┘         └───┬───┘         └───┬───┘          │    │
│  │      │                 │                 │               │    │
│  │      MCP               MCP               MCP             │    │
│  │      │                 │                 │               │    │
│  │  ┌───▼───┐         ┌───▼───┐         ┌───▼───┐          │    │
│  │  │ 工具1 │         │ 工具2 │         │ 工具3 │          │    │
│  │  └───────┘         └───────┘         └───────┘          │    │
│  │                                                          │    │
│  └─────────────────────────────────────────────────────────┘    │
│                                                                  │
│  A2A 负责 Agent 间协作,MCP 负责 Agent 使用工具                  │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

❌ 误区二:A2A 只能用于 Google 产品

正解:A2A 是开源开放协议,任何框架都可以实现!

已支持的企业/框架(首批 50+):

  • Salesforce、SAP、ServiceNow
  • LangChain、MongoDB、PayPal
  • Atlassian、Box、Cohere
  • ...

❌ 误区三:简单任务也要用 A2A

正解:A2A 适合跨 Agent 协作场景,简单任务使用 Function Calling 即可。

场景推荐方案
单 Agent 调用计算器Function Calling
单 Agent 查数据库MCP
多 Agent 协作完成报告A2A
Agent 联邦共同决策A2A

❌ 误区四:Agent Card 可以随便放

正解:Agent Card 必须放在 /.well-known/agent.json 路径!

✅ https://my-agent.com/.well-known/agent.json
❌ https://my-agent.com/agent.json
❌ https://my-agent.com/api/agent-card

❌ 误区五:忽略任务状态管理

正解:A2A 的 Task 有完整生命周期,必须正确处理状态转换!

python
# ❌ 错误:忽略 input_required 状态
if task.status.state == "completed":
    return task.artifacts

# ✅ 正确:处理所有状态
match task.status.state:
    case "completed":
        return task.artifacts
    case "failed":
        raise TaskFailedError(task.status.message)
    case "input_required":
        # 处理需要更多输入的情况
        additional_input = await get_user_input()
        return await send_additional_input(task.id, additional_input)
    case "working":
        # 等待或轮询
        await asyncio.sleep(1)
        return await poll_task_status(task.id)

❌ 误区六:不配置认证就上生产

正解:生产环境必须配置认证机制!

json
// ❌ 危险:无认证
{
  "name": "My Agent",
  "url": "https://my-agent.com/a2a"
}

// ✅ 安全:配置认证
{
  "name": "My Agent",
  "url": "https://my-agent.com/a2a",
  "authentication": {
    "schemes": ["Bearer"],
    "credentials": "oauth2"
  }
}

学习检查清单

完成本文档学习后,你应该能够:

  • [ ] 清晰定义 A2A 协议及其核心价值
  • [ ] 区分 A2A 和 MCP 的定位与适用场景
  • [ ] 编写标准的 Agent Card
  • [ ] 理解 Task 的 6 种状态及其转换
  • [ ] 使用 JSON-RPC 格式发送 A2A 请求
  • [ ] 实现简单的 A2A Server 和 Client
  • [ ] 配置认证和安全机制
  • [ ] 处理常见错误和异常情况
  • [ ] 设计多 Agent 协作架构

📝 文档版本:v1.0
最后更新:2026-02-09
协议版本:A2A 1.0.0 (2025.04)
适用人群:AI 应用开发者、架构师