Claude Code Sub-Agents 指南

Subagents 是 Claude Code 中处理特定类型任务的专门 AI 助手。每个 subagent 在自己独立的 context window 中运行,具有自定义系统提示、特定的工具访问权限和独立的权限控制。当 Claude 遇到与 subagent 描述相匹配的任务时,它会委托给该 subagent,subagent 独立工作后返回结果。

本文将从创建方法、使用场景和最佳实践三个维度,全面介绍 Claude Code Sub-Agents 的使用。

一、如何创建 Sub-Agent

1.1 使用 /agents 命令(推荐方式)

/agents 命令提供了交互式界面来管理 subagents,这是推荐的创建方式:

1
/agents

在交互界面中可以:

  • 查看所有可用的 subagents(内置、用户、项目和插件)
  • 使用引导式设置或 Claude 生成创建新的 subagents
  • 编辑现有 subagent 配置和工具访问权限
  • 删除自定义 subagents

创建步骤示例:

  1. 选择 Create new agent

  2. 选择范围:User-level(用户级)或 Project-level(项目级)

  3. 选择 Generate with Claude 让 Claude 自动生成配置

  4. 描述你的 subagent,例如:

    1
    2
    A code improvement agent that scans files and suggests improvements
    for readability, performance, and best practices.
  5. 选择工具权限(只读审查者只需选择 Read-only tools)

  6. 选择模型(Sonnet 平衡能力和速度,Haiku 更快更便宜)

  7. 保存后立即可用,无需重启

1.2 手动创建 YAML Frontmatter 文件

Subagent 文件使用 YAML frontmatter 进行配置,后跟 Markdown 格式的系统提示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
---
name: code-reviewer
description: Expert code reviewer. Use proactively after code changes.
model: sonnet
tools:
- Read
- Grep
- Glob
- Bash
---

You are a senior code reviewer with expertise in software best practices.

Your responsibilities:

1. Review code for quality, security, and maintainability
2. Identify potential bugs and performance issues
3. Suggest improvements with clear explanations

When reviewing:

- Focus on meaningful issues, not style nitpicks
- Explain WHY something is an issue
- Provide concrete suggestions for improvement
- Consider the context and purpose of the code

Format your output as:

## Summary

[Brief overview of changes reviewed]

## Issues Found

[List of issues with severity and location]

## Suggestions

[Actionable improvement recommendations]

1.3 文件存储位置与优先级

位置 范围 优先级 说明
--agents CLI 标志 当前会话 1(最高) 启动时传递 JSON
.claude/agents/ 当前项目 2 提交到版本控制,团队共享
~/.claude/agents/ 所有项目 3 个人 subagents,跨项目可用
插件的 agents/ 目录 插件启用处 4(最低) 随插件安装

项目级 subagents.claude/agents/)适合特定于代码库的 subagents,建议提交到版本控制让团队协作使用。

用户级 subagents~/.claude/agents/)适合个人在所有项目中复用的 subagents。

1.4 完整配置字段说明

以下是 YAML frontmatter 支持的所有字段:

字段 必需 说明
name 唯一标识符,使用小写字母和连字符
description 描述何时应该委托给此 subagent
model 使用的模型:sonnetopushaiku、完整模型 ID 或 inherit(默认)
tools 允许使用的工具列表。省略则继承所有工具
disallowedTools 禁用的工具列表
permissionMode 权限模式:defaultacceptEditsdontAskbypassPermissionsplan
maxTurns subagent 停止前最大执行轮数
skills 启动时加载到上下文的技能
mcpServers 此 subagent 可用的 MCP 服务器
hooks 生命周期钩子
memory 持久化内存范围:userprojectlocal
background 设为 true 总是作为后台任务运行
effort 努力级别:lowmediumhighmax
isolation 设为 worktree 在隔离的 git worktree 中运行

1.5 模型选择策略

  • Haiku:快速、低延迟,适合只读探索、代码搜索
  • Sonnet:平衡能力和速度,适合大多数分析任务
  • Opus:最强能力,适合复杂推理任务
  • inherit:继承主对话的模型(默认)

1.6 工具控制

使用 tools 字段(白名单):

1
2
3
4
5
tools:
- Read
- Grep
- Glob
- Bash

使用 disallowedTools 字段(黑名单):

1
2
3
disallowedTools:
- Write
- Edit

优先级:先应用 disallowedTools,再解析 tools

1.7 持久化内存

通过 memory 字段启用跨会话的知识积累:

1
memory: project
范围 位置 适用场景
user ~/.claude/agent-memory/<name>/ 跨项目的通用知识
project .claude/agent-memory/<name>/ 项目特定知识,可版本控制
local .claude/agent-memory-local/<name>/ 项目特定但不应提交的知识

二、Sub-Agent 使用场景

2.1 内置 Subagents

Claude Code 包含以下内置 subagents:

Explore Agent

  • 模型:Haiku(快速、低延迟)
  • 工具:只读工具(拒绝 Write 和 Edit)
  • 用途:文件发现、代码搜索、代码库探索
  • 调用方式:Claude 自动委托,支持三种彻底程度:quickmediumvery thorough

Plan Agent

  • 模型:继承主对话
  • 工具:只读工具
  • 用途:Plan mode 下收集上下文的研究代理

General-purpose Agent

  • 模型:继承主对话
  • 工具:所有工具
  • 用途:复杂研究、多步骤操作、代码修改

2.2 典型使用场景

场景一:隔离大量输出的操作

运行测试、获取文档、处理日志文件等操作会产生大量输出,消耗大量上下文。通过委托给 subagent,冗长的输出保留在 subagent 的上下文中,只有相关摘要返回到主对话。

1
Run the test suite in the background and report any failures

场景二:并行研究

对于独立的调查任务,可以同时启动多个 subagents:

1
2
3
4
In parallel:
1. Use the explore agent to find all API endpoint definitions
2. Use the explore agent to find all database schema files
3. Then compare them for consistency

场景三:链式工作流

对于多步骤工作流,可以按顺序使用 subagents:

1
2
3
1. Use code-reviewer to review the changes in src/auth/
2. Based on the review, implement the suggested improvements
3. Run tests to verify the fixes work

场景四:强制执行约束

通过限制 subagent 可用的工具来强制执行特定约束:

1
2
3
4
5
6
7
8
---
name: read-only-analyzer
description: Analyzes code without making any changes
tools:
- Read
- Grep
- Glob
---

场景五:成本控制

将任务路由到更快、更便宜的模型:

1
2
3
4
5
6
7
8
---
name: quick-search
description: Fast code search using Haiku
model: haiku
tools:
- Grep
- Glob
---

2.3 调用方式

自动委托

Claude 根据任务描述和 subagent 的 description 字段自动决定是否委托。在描述中包含 “use proactively” 等短语可鼓励主动委托。

自然语言调用

1
Use the code-reviewer agent to review this PR

@-mention 调用

1
@code-reviewer review the changes in src/

会话级启动

1
claude --agent code-reviewer

或在 .claude/settings.json 中设置默认:

1
2
3
{
"agent": "code-reviewer"
}

2.4 前台与后台运行

  • 前台 subagents:阻塞主对话直到完成,权限提示和澄清问题会传递给你
  • 后台 subagents:并发运行,你可以继续工作

启动后台任务的方式:

  • 请求 Claude “run this in the background”
  • Ctrl+B 将运行中的任务放入后台

三、最佳实践

3.1 编写清晰的描述

Claude 使用 description 字段决定何时委托任务。描述应该清晰、具体:

1
2
3
4
5
# 好的描述
description: Expert code reviewer for security vulnerabilities. Use proactively after code changes to check for SQL injection, XSS, and other OWASP Top 10 issues.

# 差的描述
description: Reviews code

3.2 选择合适的范围

  • 项目级:特定于代码库的 subagents,如了解项目架构的审查者
  • 用户级:跨项目复用的通用 subagents,如通用的代码风格审查者
  • CLI 定义:快速测试或自动化脚本

3.3 限制工具访问

遵循最小权限原则:

1
2
3
4
5
6
7
8
9
10
11
12
13
# 只读审查者
tools:
- Read
- Grep
- Glob

# 允许修复的调试者
tools:
- Read
- Grep
- Glob
- Edit
- Bash

3.4 利用持久化内存

在 subagent 的系统提示中包含内存维护指令:

1
2
3
4
5
6
7
8
9
10
11
12
13
---
name: project-expert
memory: project
---

Before starting any task, check your memory in .claude/agent-memory/project-expert/
for relevant patterns and architectural decisions.

After completing work, save important learnings to MEMORY.md:

- Code patterns discovered
- Common pitfalls identified
- Architectural decisions made

3.5 使用 Hooks 进行条件验证

当需要比 tools 字段更细粒度的控制时,使用 PreToolUse hooks:

1
2
3
4
5
6
7
8
9
---
name: db-query-validator
hooks:
PreToolUse:
- matcher: Bash
hooks:
- type: command
command: scripts/validate-sql-readonly.sh
---

验证脚本示例:

1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
# 只允许只读 SQL 查询

COMMAND="$TOOL_INPUT_COMMAND"

if echo "$COMMAND" | grep -qiE "(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE)"; then
echo "Error: Only read-only SQL queries are allowed"
exit 2 # 阻止操作
fi

exit 0 # 允许操作

3.6 选择模型的经济性

任务类型 推荐模型 原因
代码搜索、文件发现 Haiku 快速、低成本
代码审查、分析 Sonnet 平衡能力和速度
复杂推理、架构设计 Opus 最强推理能力

3.7 何时使用 Subagent vs 主对话

使用主对话

  • 任务需要频繁的来回交互或迭代优化
  • 多个阶段共享大量上下文(规划 → 实现 → 测试)
  • 做快速、针对性的更改
  • 延迟很重要(subagents 需要时间收集上下文)

使用 Subagent

  • 任务产生大量你不需要在主上下文中的输出
  • 想强制执行特定的工具限制或权限
  • 工作是独立的,可以返回摘要

3.8 禁用特定 Subagents

settings.json 中:

1
2
3
4
5
{
"permissions": {
"deny": ["Agent(explore-agent)"]
}
}

四、示例 Subagents

4.1 代码审查者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
---
name: code-reviewer
description: Expert code reviewer. Use proactively after code changes to review for quality, security, and best practices.
model: sonnet
tools:
- Read
- Grep
- Glob
---

You are a senior code reviewer with 15 years of experience.

Review code for:

1. **Security**: SQL injection, XSS, auth issues, secrets in code
2. **Performance**: N+1 queries, inefficient algorithms, memory leaks
3. **Maintainability**: Code smell, complexity, naming conventions
4. **Best Practices**: SOLID principles, DRY, error handling

Output format:

## Summary

[Brief overview]

## Critical Issues

[Security vulnerabilities, bugs]

## Suggestions

[Improvement recommendations]

## Nitpicks

[Minor style suggestions]

4.2 调试者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
---
name: debugger
description: Debug agent that analyzes and fixes issues. Use when encountering bugs or errors.
model: sonnet
tools:
- Read
- Grep
- Glob
- Edit
- Bash
---

You are a debugging specialist.

Workflow:

1. **Reproduce**: Understand the error and how to trigger it
2. **Analyze**: Use logs, stack traces, and code inspection to find root cause
3. **Fix**: Implement minimal, targeted fix
4. **Verify**: Run tests or reproduction steps to confirm fix

Always explain your reasoning before making changes.

4.3 数据科学家

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
---
name: data-scientist
description: Data analysis specialist for CSV, JSON, and database queries. Use for data exploration, statistics, and visualization tasks.
model: sonnet
tools:
- Read
- Write
- Bash
---

You are a data scientist with expertise in Python, SQL, and data analysis.

Capabilities:

- Analyze CSV, JSON, and structured data
- Write SQL queries for data extraction
- Create statistical summaries and visualizations
- Identify patterns and anomalies in data

Use Python with pandas, numpy, and matplotlib for analysis.
Output both findings and the code used to generate them.

五、总结

Subagents 是 Claude Code 的强大特性,通过以下方式提升开发效率:

  1. 上下文隔离:将探索和实现保持在主对话之外,保留宝贵的上下文空间
  2. 约束执行:通过限制工具访问强制执行安全边界
  3. 配置复用:通过用户级 subagents 跨项目共享配置
  4. 行为专业化:为特定领域使用专注的系统提示
  5. 成本控制:将任务路由到更便宜的模型如 Haiku

创建 subagent 时,记住:

  • 编写清晰的 description 让 Claude 知道何时使用
  • 根据任务选择合适的工具权限
  • 利用 memory 字段实现跨会话学习
  • 使用 hooks 实现细粒度的条件控制

通过合理使用 subagents,你可以让 Claude Code 成为一个更加高效、安全的编程助手。