子 Agent 是主 Agent 可以派生的独立 Agent 实例,用于处理专注的子任务。核心价值:上下文隔离(子 Agent 的中间工具调用不污染主对话)、并行化(多个子 Agent 并发运行)、专项指令(独立 system prompt)、工具限制(只能访问特定工具)。

核心机制

三种定义方式:

  1. 编程式(推荐):通过 agents 参数传入 AgentDefinition 对象
  2. 文件系统式:在 .claude/agents/ 目录下创建 Markdown 文件
  3. 内置通用 Agent:无需定义,Claude 可随时通过 Agent 工具调用

子 Agent 的上下文:

  • 继承:自己的 system prompt、Agent 工具的 prompt 字符串、项目 CLAUDE.md、工具定义
  • 不继承:父 Agent 的对话历史、父 Agent 的 system prompt、预加载的 Skill 内容

调用机制:子 Agent 通过 Agent 工具调用,主 Agent 的 allowedTools 必须包含 "Agent"。

子 Agent 不能再派生子 Agent:不要在 AgentDefinition 的 tools 中包含 "Agent"。

关键细节

from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition
 
async for message in query(
    prompt="Review the authentication module for security issues",
    options=ClaudeAgentOptions(
        allowed_tools=["Read", "Grep", "Glob", "Agent"],  # 必须包含 Agent
        agents={
            "code-reviewer": AgentDefinition(
                description="Expert code review specialist. Use for quality, security reviews.",
                prompt="You are a code review specialist...",
                tools=["Read", "Grep", "Glob"],  # 只读工具
                model="sonnet",  # 可覆盖模型
            ),
        },
    ),
):
    ...

AgentDefinition 关键字段:

  • description:Claude 据此决定何时调用(写清楚触发条件)
  • prompt:子 Agent 的 system prompt
  • tools:允许的工具列表(省略则继承所有工具)
  • model:模型别名(sonnet/opus/haiku/inherit)或完整 model ID
  • effort:推理深度
  • maxTurns:最大轮次
  • background:是否作为非阻塞后台任务运行

显式调用:在 prompt 中提及子 Agent 名称可强制调用:"Use the code-reviewer agent to..."

恢复子 Agent:从 Agent 工具结果中提取 agentId,配合 resume: sessionId 可恢复子 Agent 继续工作。

与其他概念的关联

  • agent-loop - 子 Agent 的上下文管理(子 Agent 只返回最终结果给父 Agent)
  • hooks - SubagentStart/SubagentStop Hooks 追踪子 Agent 活动
  • permissions - 子 Agent 继承父 Agent 的权限模式

实践要点

  • 子 Agent 的 description 要具体,包含触发关键词,Claude 才能准确匹配任务
  • 子 Agent 只通过 Agent 工具的 prompt 字符串接收信息,需要的文件路径、错误信息等要显式传入
  • 父 Agent 收到子 Agent 的最终消息,可能会在自己的响应中摘要,如需保留原文需在 system prompt 中说明
  • Windows 上子 Agent prompt 过长可能因命令行长度限制(8191 字符)失败,建议用文件系统方式定义