MCP

MCP 多 Agent 架构设计:构建协作式 AI Agent 系统

深入探讨基于 Model Context Protocol 的多 Agent 架构设计模式,包括任务分解、协作通信和状态管理的最佳实践。

单个 AI Agent 的能力终究有限。当面对复杂任务时,我们需要多个 Agent 协作——每个 Agent 专注于特定领域,通过协调完成单个 Agent 无法胜任的工作。Model Context Protocol 为构建这样的多 Agent 系统提供了理想的基础设施。

为什么需要多 Agent 系统

考虑一个真实的业务场景:用户要求 AI 系统”分析竞争对手的产品并生成报告”。这个任务涉及多个步骤:

  1. 搜索和收集竞品信息
  2. 分析产品特性和定价
  3. 整理市场份额数据
  4. 撰写分析报告
  5. 生成可视化图表

如果用单个 Agent 处理所有步骤,上下文会迅速膨胀,推理质量下降。更合理的做法是让多个专门的 Agent 各司其职。

多 Agent 的优势

专业化分工——每个 Agent 专注于特定领域,可以配置最合适的工具和提示词。

上下文隔离——每个 Agent 只需要维护自己任务相关的上下文,避免信息过载。

并行处理——独立的子任务可以由不同 Agent 并行执行,提高整体效率。

容错能力——单个 Agent 的失败不会导致整个系统崩溃。

基于 MCP 的多 Agent 架构

MCP 的 Client-Server 天然适合多 Agent 架构。我们可以将每个 Agent 视为一个 MCP Client,连接到不同的 MCP Server 获取所需能力。

┌─────────────────────────────────────────────┐
│              编排层 (Orchestrator)            │
│                                             │
│  ┌─────────┐  ┌─────────┐  ┌─────────┐     │
│  │ Agent A │  │ Agent B │  │ Agent C │     │
│  │ 研究员  │  │ 分析师  │  │ 写作者  │     │
│  └────┬────┘  └────┬────┘  └────┬────┘     │
│       │            │            │           │
└───────┼────────────┼────────────┼───────────┘
        │            │            │
   ┌────┴────┐  ┌────┴────┐  ┌────┴────┐
   │搜索 MCP │  │数据 MCP │  │文档 MCP │
   │ Server  │  │ Server  │  │ Server  │
   └─────────┘  └─────────┘  └─────────┘

编排模式

顺序编排——Agent 按顺序执行,前一个的输出作为后一个的输入。适合有明确先后关系的任务流。

并行编排——多个 Agent 同时执行独立任务,最后汇总结果。适合可分解的独立子任务。

层级编排——一个主 Agent 负责任务分解和调度,多个子 Agent 负责具体执行。适合复杂的层级任务。

实现:研究分析 Agent 系统

让我们实现一个层级编排的多 Agent 系统。主 Agent 接收用户请求,将任务分配给专门的子 Agent。

定义 Agent 基类

import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import Anthropic from '@anthropic-ai/sdk';

abstract class BaseAgent {
  protected claude = new Anthropic();
  protected mcpClients: Client[] = [];
  protected abstract systemPrompt: string;

  async connectServer(command: string, args: string[]) {
    const client = new Client({ name: this.constructor.name, version: '1.0.0' });
    await client.connect(new StdioClientTransport({ command, args }));
    this.mcpClients.push(client);
  }

  protected async getTools() {
    const tools: any[] = [];
    for (const client of this.mcpClients) {
      const { tools: serverTools } = await client.listTools();
      for (const tool of serverTools) {
        tools.push({
          name: tool.name,
          description: tool.description,
          input_schema: tool.inputSchema,
        });
      }
    }
    return tools;
  }

  protected async executeTool(name: string, args: any): Promise<string> {
    for (const client of this.mcpClients) {
      try {
        const result = await client.callTool({ name, arguments: args });
        return result.content.map((c: any) => c.text || '').join('\n');
      } catch { continue; }
    }
    throw new Error(`Tool ${name} not found`);
  }

  abstract execute(task: string): Promise<string>;

  async cleanup() {
    for (const client of this.mcpClients) {
      await client.close();
    }
  }
}

实现研究员 Agent

class ResearchAgent extends BaseAgent {
  systemPrompt = `你是一个专业的研究员。你的任务是根据给定的主题,使用搜索工具收集全面、准确的信息。
输出要求:收集到的信息应该是结构化的,包含关键事实、数据和来源。`;

  async execute(task: string): Promise<string> {
    const tools = await this.getTools();
    const messages: any[] = [{ role: 'user', content: task }];

    while (true) {
      const response = await this.claude.messages.create({
        model: 'claude-sonnet-4-20250514',
        max_tokens: 4096,
        system: this.systemPrompt,
        tools,
        messages,
      });

      if (response.stop_reason === 'tool_use') {
        const results = [];
        for (const block of response.content) {
          if (block.type === 'tool_use') {
            const r = await this.executeTool(block.name, block.input);
            results.push({ type: 'tool_result', tool_use_id: block.id, content: r });
          }
        }
        messages.push({ role: 'assistant', content: response.content });
        messages.push({ role: 'user', content: results });
        continue;
      }

      return response.content
        .filter((b): b is any => b.type === 'text')
        .map((b: any) => b.text)
        .join('');
    }
  }
}

实现分析师 Agent

class AnalystAgent extends BaseAgent {
  systemPrompt = `你是一个数据分析师。你的任务是分析提供的信息,提取关键洞察,识别趋势和模式。
输出要求:分析结果应该包含数据支持的结论和可行的建议。`;

  async execute(task: string): Promise<string> {
    const tools = await this.getTools();
    const response = await this.claude.messages.create({
      model: 'claude-sonnet-4-20250514',
      max_tokens: 4096,
      system: this.systemPrompt,
      tools,
      messages: [{ role: 'user', content: task }],
    });

    return response.content
      .filter((b): b is any => b.type === 'text')
      .map((b: any) => b.text)
      .join('');
  }
}

实现编排器

class Orchestrator {
  private researchAgent: ResearchAgent;
  private analystAgent: AnalystAgent;

  constructor() {
    this.researchAgent = new ResearchAgent();
    this.analystAgent = new AnalystAgent();
  }

  async initialize() {
    await this.researchAgent.connectServer('npx', [
      '-y', '@modelcontextprotocol/server-brave-search'
    ]);
    await this.analystAgent.connectServer('npx', [
      '-y', '@modelcontextprotocol/server-filesystem', '/tmp/analysis'
    ]);
  }

  async execute(task: string): Promise<string> {
    // 阶段 1:研究
    console.log('🔍 研究阶段...');
    const research = await this.researchAgent.execute(
      `研究以下主题并收集关键信息:${task}`
    );

    // 阶段 2:分析
    console.log('📊 分析阶段...');
    const analysis = await this.analystAgent.execute(
      `基于以下研究结果进行深入分析:\n\n${research}\n\n原始任务:${task}`
    );

    return analysis;
  }

  async cleanup() {
    await this.researchAgent.cleanup();
    await this.analystAgent.cleanup();
  }
}

// 使用
const orchestrator = new Orchestrator();
await orchestrator.initialize();
const result = await orchestrator.execute('分析 2026 年 AI Agent 市场的发展趋势');
console.log(result);
await orchestrator.cleanup();

Agent 间通信模式

共享上下文

最简单的通信方式是通过编排器传递文本上下文。适合信息量不大的场景。

共享存储

多个 Agent 通过同一个 MCP Server(如数据库或文件系统)读写数据。适合需要共享大量结构化数据的场景。

消息传递

Agent 之间通过专门的消息 MCP Server 进行异步通信。适合需要实时协作的场景。

常见问题(FAQ)

多 Agent 系统的延迟会很高吗?

确实会比单 Agent 高,因为涉及多次 LLM 调用和工具调用。关键优化策略是尽可能让独立任务并行执行。

如何处理 Agent 之间的冲突?

在设计阶段明确每个 Agent 的职责边界和数据访问权限。使用编排器进行统一调度,避免多个 Agent 同时修改同一资源。

Agent 数量多少合适?

根据任务复杂度决定,通常 3-5 个 Agent 是比较合理的范围。过多的 Agent 会增加编排复杂度和通信开销。

总结

MCP 为多 Agent 系统提供了标准化的基础设施——每个 Agent 作为 MCP Client 连接到所需的 Server,通过协议实现能力发现和工具调用。编排层负责任务分解和 Agent 调度,形成一个灵活、可扩展的协作系统。

关键设计原则:职责单一、上下文隔离、通信标准化。遵循这些原则,你可以构建出能够处理复杂任务的 AI Agent 系统。