概述
Subagents 是 Claude Code 中处理特定类型任务的专门 AI 助手。每个 subagent 在独立的 context window 中运行,具有自定义系统提示、特定工具访问权限和独立权限。它们帮助保留主对话上下文、强制执行约束、跨项目重用配置、专门化行为,并通过路由到更便宜的模型控制成本。
什么是 Subagents
Subagents 是专门的 AI 助手,特点:
- 在独立上下文窗口中运行,不占用主对话上下文
- 支持自定义系统提示和工具访问限制
- Claude 根据描述自动决定何时委托任务
- 内置多个 subagents,也支持创建自定义
主要优势:
- 保留上下文 - 将探索和实现保持在主对话之外
- 强制执行约束 - 限制 subagent 可用工具
- 跨项目重用配置 - 用户级 subagents 可在所有项目使用
- 专门化行为 - 特定领域使用专注的系统提示
- 控制成本 - 将任务路由到更快、更便宜的模型(如 Haiku)
Note: 如果需要多个代理并行工作并相互通信,请参阅 agent teams。Subagents 在单个会话中工作;agent teams 跨多个会话协调。
内置 Subagents
Claude Code 包含多个内置 subagents,自动在适当时机使用:
| Agent | Model | Tools | Purpose |
|---|---|---|---|
| Explore | Haiku | 只读工具 | 文件发现、代码搜索、代码库探索 |
| Plan | 继承 | 只读工具 | 规划阶段的代码库研究 |
| General-purpose | 继承 | 所有工具 | 复杂研究、多步骤操作、代码修改 |
| statusline-setup | Sonnet | - | 配置状态行 |
| Claude Code Guide | Haiku | - | 回答关于 Claude Code 功能的问题 |
Explore 代理接受彻底程度级别参数:
quick- 针对性查找medium- 平衡探索very thorough- 全面分析
快速入门:创建第一个 Subagent
Subagents 在带有 YAML frontmatter 的 Markdown 文件中定义,推荐使用 /agents 命令创建:
使用 /agents 命令创建步骤
-
打开 subagents 界面
/agents -
选择位置 → Create new agent → Personal(保存到
~/.claude/agents/,所有项目可用) -
使用 Claude 生成 → 描述你的 subagent 功能
-
选择工具 - 可取消选择不需要的工具,例如只读审查只保留 Read-only tools
-
选择模型 - sonnet/opus/haiku/inherit
-
选择颜色 - 在 UI 中识别 subagent
-
配置内存 - 选择 User scope/Project scope/None
-
保存并尝试 - 保存后即可使用:
Use the code-improver agent to suggest improvements in this project
配置 Subagents
选择 Subagent 范围
Subagents 根据存储位置有不同优先级(高优先覆盖低优先):
| 位置 | 范围 | 优先级 |
|---|---|---|
| 托管设置 | 组织范围 | 1(最高) |
--agents CLI 标志 | 当前会话 | 2 |
.claude/agents/ | 当前项目 | 3 |
~/.claude/agents/ | 所有项目 | 4 |
Plugin 的 agents/ | 启用 plugin 的位置 | 5(最低) |
项目 subagents (.claude/agents/):适合特定代码库,可检入版本控制,团队协作使用。
用户 subagents (~/.claude/agents/):个人所有项目可用。
CLI 定义的 subagents:通过 JSON 传递,仅存在于当前会话,适合测试或自动化:
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer. Use proactively after code changes.",
"prompt": "You are a senior code reviewer...",
"tools": ["Read", "Grep", "Glob", "Bash"],
"model": "sonnet"
}
}'
编写 Subagent 文件
格式:YAML frontmatter + Markdown 系统提示:
---
name: code-reviewer
description: Reviews code for quality and best practices
tools: Read, Glob, Grep
model: sonnet
---
You are a code reviewer. When invoked, analyze the code and provide
specific, actionable feedback on quality, security, and best practices.
支持的 Frontmatter 字段
| 字段 | 必填 | 说明 |
|---|---|---|
name | Yes | 唯一标识符(小写+连字符) |
description | Yes | Claude 何时委托给此 subagent |
tools | No | 允许的工具列表(白名单) |
disallowedTools | No | 拒绝的工具列表(黑名单) |
model | No | 使用的模型:sonnet/opus/haiku/inherit |
permissionMode | No | 权限模式:default/acceptEdits/auto/dontAsk/bypassPermissions/plan |
maxTurns | No | 最大代理轮数 |
skills | No | 启动时预加载的技能列表 |
mcpServers | No | 可用的 MCP 服务器 |
hooks | No | 生命周期 hooks |
memory | No | 持久内存范围:user/project/local |
background | No | 是否始终作为后台任务运行 |
effort | No | 努力级别:low/medium/high/max |
isolation | No | 设置为 worktree 在临时 git worktree 运行 |
color | No | 显示颜色:red/blue/green/yellow/purple/orange/pink/cyan |
initialPrompt | No | 作为主会话代理运行时的首个提示 |
选择模型
解析顺序:
CLAUDE_CODE_SUBAGENT_MODEL环境变量- 每次调用的
model参数 - Subagent 定义的
modelfrontmatter - 主对话的模型
控制 Subagent 能力
工具访问控制
使用 tools(允许列表)或 disallowedTools(拒绝列表)限制:
# 只允许特定只读工具
tools: Read, Grep, Glob, Bash
# 继承所有工具,除了 Write 和 Edit
disallowedTools: Write, Edit
如果两者都设置,先应用 disallowedTools,再解析 tools。
限制可生成的 Subagents 类型
当使用 claude --agent 作为主线程运行时,可限制能生成哪些 subagents:
# 只允许生成 worker 和 researcher 两种 subagents
tools: Agent(worker, researcher), Read, Bash
# 允许生成任何 subagents
tools: Agent, Read, Bash
如果 Agent 完全省略,代理无法生成任何 subagents。Subagents 本身无法生成其他 subagents。
MCP 服务器作用域
可为 subagent 提供独立的 MCP 服务器访问:
mcpServers:
# 内联定义,仅作用于此 subagent
- playwright:
type: stdio
command: npx
args: ["-y", "@playwright/mcp@latest"]
# 按名称引用,复用已配置的服务器
- github
内联定义不会将工具描述暴露给主对话,节省上下文。
权限模式
| 模式 | 行为 |
|---|---|
default | 标准权限检查,带提示 |
acceptEdits | 自动接受文件编辑(受保护目录除外) |
auto | Auto 模式,后台分类器审查 |
dontAsk | 自动拒绝权限提示 |
bypassPermissions | 跳过权限提示(谨慎使用) |
plan | Plan 模式(只读探索) |
Warning:
bypassPermissions会跳过权限提示。对.git、.claude等目录写入仍会提示确认。
预加载技能到 Subagents
skills:
- api-conventions
- error-handling-patterns
Subagents 不继承来自父对话的技能,必须明确列出。
启用持久内存
memory 字段为 subagent 提供跨会话持久化目录:
memory: user
| 范围 | 位置 | 使用时机 |
|---|---|---|
user | ~/.claude/agent-memory/<name>/ | 所有项目中记住学习 |
project | .claude/agent-memory/<name>/ | 知识特定于项目,可版本控制共享 |
local | .claude/agent-memory-local/<name>/ | 知识特定于项目但不检入 |
启用后,subagent 会自动获得读写内存目录的权限。
使用 Hooks 实现条件规则
可通过 PreToolUse hooks 在执行前验证操作,实现精细控制:
---
name: db-reader
description: Execute read-only database queries
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
---
验证脚本可检查并阻止写入操作,详见文档。
禁用特定 Subagents
在 settings.json 中添加到 deny 数组:
{
"permissions": {
"deny": ["Agent(Explore)", "Agent(my-custom-agent)"]
}
}
为 Subagents 定义 Hooks
在 subagent frontmatter 中定义:hooks 仅在该 subagent 活跃时运行:
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-command.sh"
PostToolUse:
- matcher: "Edit|Write"
hooks:
- type: command
command: "./scripts/run-linter.sh"
在 settings.json 中定义:响应主会话中的 subagent 生命周期事件:
{
"hooks": {
"SubagentStart": [
{
"matcher": "db-agent",
"hooks": [{ "type": "command", "command": "./scripts/setup-db.sh" }]
}
],
"SubagentStop": [
{
"hooks": [{ "type": "command", "command": "./scripts/cleanup-db.sh" }]
}
]
}
}
使用 Subagents
自动委托 vs 显式调用
自动委托:Claude 根据任务描述和 subagent 的 description 自动决定何时委托。在 description 中包含 "use proactively" 鼓励主动委托。
三种显式调用方式:
-
自然语言:在提示中命名 subagent
Use the test-runner subagent to fix failing tests -
@-mention:保证特定 subagent 运行
@"code-reviewer (agent)" look at the auth changes -
会话范围:整个会话使用该 subagent
claude --agent code-reviewer或在
.claude/settings.json中设置默认:{ "agent": "code-reviewer" }
前台 vs 后台运行
- 前台:阻塞主对话直到完成,权限提示和澄清问题会传递给用户
- 后台:并发运行,可继续工作。启动前会提示预先批准所需工具权限
可要求 Claude "run this in the background" 或按 Ctrl+B 将运行中任务放后台。
常见使用模式
1. 隔离高容量操作
将产生大量输出的操作(运行测试、获取文档、处理日志)委托给 subagent,只有摘要返回主对话:
Use a subagent to run the test suite and report only the failing tests with their error messages
2. 并行运行研究
独立调查可生成多个 subagents 同时工作:
Research the authentication, database, and API modules in parallel using separate subagents
3. 链接 Subagents
多步骤工作流可按顺序使用 subagents:
Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them
何时使用 Subagents vs 主对话
使用主对话:
- 任务需要频繁来回迭代
- 多个阶段共享重要上下文
- 快速针对性更改
- 延迟很重要
使用 Subagents:
- 任务产生不需要保留在主上下文的详细输出
- 需要强制执行特定工具限制或权限
- 工作自包含,只需返回摘要
Note: Subagents 无法生成其他 subagents。如果需要嵌套委托,使用 Skills 或从主对话链接 subagents。
管理 Subagent 上下文
恢复 subagents:每个调用创建新实例,可恢复现有 subagent 保留完整对话历史。需要启用 agent teams 功能。
自动压缩:Subagents 支持与主对话相同的自动压缩逻辑,默认在 95% 容量时触发。
示例 Subagents
代码审查者(只读)
---
name: code-reviewer
description: Expert code review specialist. Proactively reviews code for quality, security, maintainability. Use immediately after code changes.
tools: Read, Grep, Glob, Bash
---
You are a senior code reviewer ensuring high standards of code quality and security.
...
特点:无 Edit/Write 权限,专注审查,提供分优先级反馈。
调试器
---
name: debugger
description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering issues.
tools: Read, Edit, Bash, Grep, Glob
---
特点:包含 Edit 工具,从诊断到修复完整工作流。
数据科学家
---
name: data-scientist
description: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks.
tools: Bash, Read, Write
model: sonnet
---
特点:特定领域专门化,明确指定模型。
数据库查询验证器
使用 PreToolUse hook 验证只允许只读查询:
---
name: db-reader
description: Execute read-only database queries. Use when analyzing data.
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
---
验证脚本阻止 INSERT/UPDATE/DELETE 等写入操作。
核心要点
- Subagents 隔离上下文:将探索、测试等大输出任务放入独立上下文,保持主对话清洁
- 细粒度访问控制:可限制工具、权限、MCP 服务器,满足安全需求
- 多种范围选择:项目级共享团队工作流,用户级个人工具,CLI 级临时测试
- 持久内存支持:可让 subagent 跨会话积累知识,越来越智能
- 灵活调用方式:自动委托、@显式调用、整个会话作为 subagent 运行,满足不同场景
- Hooks 实现动态控制:可在工具执行前验证,实现复杂条件规则(如只允许只读 SQL)
Best practices:
- 设计专注的 subagents,每个做好一件事
- 编写清晰详细的 description 帮助 Claude 正确委托
- 限制工具访问,只授予必要权限
- 项目 subagents 检入版本控制,与团队共享