Skip to content

协议对比与选择

MCP vs A2A 对比分析及选型指南

4. 协议对比与选择

4.1 功能对比

功能MCPA2A
工具调用✅ 核心功能❌ 不直接支持
资源访问✅ Resources❌ 通过 Message 间接
Agent 发现❌ 无✅ Agent Card
任务管理❌ 无✅ Task 生命周期
流式响应❌ 有限支持✅ SSE 原生支持
多模态✅ 支持✅ 支持
长任务❌ 设计为同步✅ 异步、推送通知
身份认证基础✅ OAuth 2.0, W3C DID

4.2 选择指南

选择 MCP 当:
├── 需要让 AI 访问工具和数据源
├── 构建单 Agent 应用
├── 需要读取文件、调用 API
└── 需要快速集成已有服务

选择 A2A 当:
├── 需要多个 Agent 协作
├── Agent 来自不同供应商/框架
├── 需要处理长时间运行的任务
└── 需要企业级安全和审计

两者结合当:
├── 构建复杂的多 Agent 系统
├── Agent 既需要工具也需要协作
└── 企业级 AI 工作流

4.3 集成架构

┌─────────────────────────────────────────────────────────────────────────┐
│                     企业 AI 系统架构示例                                  │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                          │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │                         API Gateway                              │    │
│  │                    (认证、限流、日志)                              │    │
│  └───────────────────────────┬─────────────────────────────────────┘    │
│                              │                                           │
│                              ▼                                           │
│  ┌─────────────────────────────────────────────────────────────────┐    │
│  │                    Orchestrator Agent                            │    │
│  │              (任务规划、Agent 调度、结果汇总)                       │    │
│  └───────────────────────────┬─────────────────────────────────────┘    │
│                              │                                           │
│              ┌───────────────┼───────────────┐                          │
│              │ A2A           │ A2A           │ A2A                       │
│              ▼               ▼               ▼                          │
│  ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐        │
│  │  Specialist      │ │  Specialist      │ │  Specialist      │        │
│  │  Agent A         │ │  Agent B         │ │  Agent C         │        │
│  │  (数据分析)       │ │  (文档生成)       │ │  (邮件发送)       │        │
│  └────────┬─────────┘ └────────┬─────────┘ └────────┬─────────┘        │
│           │ MCP                 │ MCP                │ MCP              │
│           ▼                     ▼                    ▼                  │
│  ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐        │
│  │  MCP Servers     │ │  MCP Servers     │ │  MCP Servers     │        │
│  │  - Database      │ │  - Google Docs   │ │  - SMTP          │        │
│  │  - Analytics API │ │  - Templates     │ │  - Calendar      │        │
│  └──────────────────┘ └──────────────────┘ └──────────────────┘        │
│                                                                          │
└─────────────────────────────────────────────────────────────────────────┘

5. 安全考量

5.1 MCP 安全

typescript
// 1. Server 能力限制
const server = new Server({
  name: "secure-server",
  version: "1.0.0"
}, {
  capabilities: {
    // 只开放必要的能力
    tools: {},
    // resources: {},  // 不暴露资源
    // prompts: {},    // 不暴露提示
  }
});

// 2. 路径白名单
const ALLOWED_PATHS = [
  '/safe/directory',
  '/another/safe/path'
];

function isPathAllowed(path: string): boolean {
  const resolved = path.resolve(path);
  return ALLOWED_PATHS.some(allowed => 
    resolved.startsWith(path.resolve(allowed))
  );
}

// 3. 敏感数据过滤
function sanitizeOutput(data: any): any {
  const sensitiveKeys = ['password', 'token', 'secret', 'apiKey'];
  
  if (typeof data === 'object') {
    for (const key of Object.keys(data)) {
      if (sensitiveKeys.some(s => key.toLowerCase().includes(s))) {
        data[key] = '[REDACTED]';
      } else if (typeof data[key] === 'object') {
        data[key] = sanitizeOutput(data[key]);
      }
    }
  }
  
  return data;
}

5.2 A2A 安全

typescript
// 1. OAuth 2.0 认证
app.use('/a2a', async (req, res, next) => {
  const authHeader = req.headers.authorization;
  
  if (!authHeader?.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Missing authentication' });
  }
  
  const token = authHeader.slice(7);
  
  try {
    const payload = await verifyToken(token);
    req.user = payload;
    next();
  } catch {
    return res.status(401).json({ error: 'Invalid token' });
  }
});

// 2. 任务权限检查
function canAccessTask(user: User, taskId: string): boolean {
  const task = tasks.get(taskId);
  
  // 检查用户是否有权限访问此任务
  return task?.metadata?.ownerId === user.id ||
         user.roles.includes('admin');
}

// 3. 请求验证
import { z } from 'zod';

const TaskSendSchema = z.object({
  id: z.string().uuid().optional(),
  message: z.object({
    role: z.enum(['user', 'agent']),
    parts: z.array(z.union([
      z.object({ type: z.literal('text'), text: z.string().max(100000) }),
      z.object({ type: z.literal('file'), file: z.object({
        name: z.string(),
        mimeType: z.string(),
        uri: z.string().url().optional(),
        bytes: z.string().optional()
      })})
    ]))
  })
});

// 4. 审计日志
function auditLog(action: string, details: any) {
  const entry = {
    timestamp: new Date().toISOString(),
    action,
    userId: details.userId,
    taskId: details.taskId,
    ip: details.ip,
    // 不记录敏感内容
  };
  
  auditLogger.info(entry);
}

6. 生态系统

6.1 MCP 生态

官方 Servers

Server功能安装
@modelcontextprotocol/server-filesystem文件系统访问npx -y @modelcontextprotocol/server-filesystem /path
@modelcontextprotocol/server-githubGitHub APInpx -y @modelcontextprotocol/server-github
@modelcontextprotocol/server-postgresPostgreSQL 数据库npx -y @modelcontextprotocol/server-postgres
@modelcontextprotocol/server-sqliteSQLite 数据库npx -y @modelcontextprotocol/server-sqlite
@modelcontextprotocol/server-puppeteer浏览器自动化npx -y @modelcontextprotocol/server-puppeteer

社区 Servers

  • Notion, Slack, Discord 集成
  • AWS, GCP, Azure 云服务
  • Jira, Linear 项目管理
  • Figma 设计工具

6.2 A2A 生态

支持的框架

  • LangChain / LangGraph
  • CrewAI
  • Google ADK (Agent Development Kit)
  • Microsoft AutoGen

企业合作伙伴

  • Salesforce, SAP, ServiceNow
  • Atlassian, Box, MongoDB
  • Accenture, Deloitte, PwC

7. 关键要点

MCP 要点

  1. 三大能力: Resources(资源)、Tools(工具)、Prompts(提示)
  2. Client-Server 架构: Host 托管应用,Client 处理协议,Server 提供能力
  3. JSON-RPC 2.0: 标准化的请求-响应格式
  4. 安全第一: 路径验证、权限控制、审计日志

A2A 要点

  1. Agent Card: Agent 的能力名片,支持发现与对接
  2. Task 生命周期: submitted → working → completed/failed
  3. SSE 流式更新: 实时状态推送和部分结果
  4. 企业级安全: OAuth 2.0、W3C DID 身份认证

选择建议

场景推荐协议
AI 访问文件/数据库MCP
AI 调用外部 APIMCP
多 Agent 协作A2A
跨组织 Agent 互操作A2A
完整企业 AI 系统MCP + A2A

8. 参考资源

官方文档

SDK

深度文章

前端面试知识库