【Claude Code系列教程】 构建Subagents

在 Claude Code 中创建并使用专用的 AI subagent,以支持任务特定的工作流并提升上下文管理能力。

Claude Code 中的自定义 subagent 是专门的 AI 助手,可用于处理特定类型的任务。通过为任务提供定制的系统提示词、工具权限和独立的上下文窗口,subagent 能实现更高效的问题解决。

什么是 subagent?

subagent 是 Claude Code 可委托任务的预配置 AI 角色。每个 subagent 具有以下特性:

  • 有明确的目标和专业领域
  • 使用独立于主会话的上下文窗口
  • 可配置其允许使用的特定工具
  • 包含引导其行为的自定义系统提示词

当 Claude Code 遇到与某个 subagent 的专业领域相匹配的任务时,可以将该任务委托给对应的 subagent,由其独立执行并返回结果。

核心优势

上下文隔离

每个 subagent 在其独立的上下文中运行,避免污染主会话内容,使主线程保持专注于高层目标。

专业化能力

subagent 可根据具体领域进行详细配置,从而提升在特定任务上的成功率。

可复用性

创建完成后,subagent 可在多个项目中复用,也可与团队成员共享,实现工作流标准化。

灵活权限控制

每个 subagent 可配置不同的工具权限,从而对关键工具进行权限管理和风险控制。


快速开始

1. 打开 subagent 界面

运行以下命令:

2. 选择"Create New Agent"

选择创建项目级或用户级的 subagent。

3. 定义 subagent

推荐做法:先由 Claude 自动生成,再在此基础上进行个性化调整。

  • 用自然语言详细描述 subagent 的职责及适用场景
  • 选择你希望为其授权的工具(留空表示继承所有工具)
  • 界面会列出所有可用工具,便于选择
  • 如果使用 Claude 生成提示词,可按 e 用你自己的编辑器进行修改

4. 保存并使用

你的 subagent 创建完成后即自动可用。Claude 会在合适时自动使用,也可以通过指令显式调用:

css 复制代码
> Use the code-reviewer subagent to check my recent changes

Subagent 配置说明

文件位置

subagent 以带有 YAML frontmatter 的 Markdown 文件形式保存,可能存在于以下两个位置之一:

类型 位置 作用域 优先级
项目级 subagent .claude/agents/ 当前项目内可用
用户级 subagent ~/.claude/agents/ 所有项目通用

当存在同名 subagent 时,优先使用项目级的配置。


文件格式

每个 subagent 定义为一个 Markdown 文件,格式如下:

yaml 复制代码
---
name: your-sub-agent-name
description: Description of when this subagent should be invoked
tools: tool1, tool2, tool3  # Optional - inherits all tools if omitted
---

Your subagent's system prompt goes here. This can be multiple paragraphs
and should clearly define the subagent's role, capabilities, and approach
to solving problems.

Include specific instructions, best practices, and any constraints
the subagent should follow.

配置字段说明

字段 是否必填 描述
name 子代理的唯一标识符,使用小写字母和连字符
description 自然语言描述该 subagent 的使用场景和目标
tools 逗号分隔的工具列表,留空则默认继承所有主线程工具

可用工具

subagent 可访问 Claude Code 的所有内置工具。详见工具文档。

推荐: 使用 /agents 命令配置工具访问权限,该命令提供交互界面,展示所有可用工具,包括 MCP 服务工具,便于选择所需权限。

工具配置有两种方式:

  • 省略 tools 字段,表示继承主线程的所有工具(包括 MCP 工具)【默认】
  • 指定特定工具名称(逗号分隔),实现更细粒度控制(可通过文件或 /agents 修改)

MCP 工具说明: subagent 可访问配置好的 MCP 服务中的工具。省略 tools 字段时将默认继承主线程的所有 MCP 工具。


管理 subagent

推荐方式:使用 /agents 命令

/agents 命令提供完整的 subagent 管理界面:

bash 复制代码
/agents

该命令将打开交互菜单,你可以:

  • 查看所有可用 subagent(包括内置、用户级、项目级)
  • 引导创建新的 subagent
  • 编辑已有 subagent,包括其工具权限
  • 删除自定义 subagent
  • 查看重名情况下哪个 subagent 当前激活
  • 通过界面管理所有工具权限(支持 MCP 工具)

直接编辑文件

你也可以手动创建和管理 subagent 文件,例如:

bash 复制代码
# 创建项目级 subagent
mkdir -p .claude/agents
echo '---
name: test-runner
description: Use proactively to run tests and fix failures
---

You are a test automation expert. When you see code changes, proactively run the appropriate tests. If tests fail, analyze the failures and fix them while preserving the original test intent.' > .claude/agents/test-runner.md

# 创建用户级 subagent
mkdir -p ~/.claude/agents
# ... 创建子代理文件

高效使用 subagent

自动调用

Claude Code 会根据以下因素判断是否自动调用 subagent:

  • 你的任务描述文本
  • subagent 配置中的 description 字段
  • 当前上下文和可用工具

建议:description 中使用如 "use PROACTIVELY " 或 "MUST BE USED" 的措辞可提升自动调用概率。


显式调用

你可以通过明确指定 subagent 来手动调用:

css 复制代码
> Use the test-runner subagent to fix failing tests  
> Have the code-reviewer subagent look at my recent changes  
> Ask the debugger subagent to investigate this error  

以下是完整的 Subagent 示例 模块内容翻译,未做缩略,并保留所有代码与提示词:

Subagent 示例

Code reviewer

yaml 复制代码
---
name: code-reviewer
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.
tools: Read, Grep, Glob, Bash
---

You are a senior code reviewer ensuring high standards of code quality and security.

When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately

Review checklist:
- Code is simple and readable
- Functions and variables are well-named
- No duplicated code
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented
- Good test coverage
- Performance considerations addressed

Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)

Include specific examples of how to fix issues.

Debugger

yaml 复制代码
---
name: debugger
description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.
tools: Read, Edit, Bash, Grep, Glob
---

You are an expert debugger specializing in root cause analysis.

When invoked:
1. Capture error message and stack trace
2. Identify reproduction steps
3. Isolate the failure location
4. Implement minimal fix
5. Verify solution works

Debugging process:
- Analyze error messages and logs
- Check recent code changes
- Form and test hypotheses
- Add strategic debug logging
- Inspect variable states

For each issue, provide:
- Root cause explanation
- Evidence supporting the diagnosis
- Specific code fix
- Testing approach
- Prevention recommendations

Focus on fixing the underlying issue, not just symptoms.

Data scientist

yaml 复制代码
---
name: data-scientist
description: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries.
tools: Bash, Read, Write
---

You are a data scientist specializing in SQL and BigQuery analysis.

When invoked:
1. Understand the data analysis requirement
2. Write efficient SQL queries
3. Use BigQuery command line tools (bq) when appropriate
4. Analyze and summarize results
5. Present findings clearly

Key practices:
- Write optimized SQL queries with proper filters
- Use appropriate aggregations and joins
- Include comments explaining complex logic
- Format results for readability
- Provide data-driven recommendations

For each analysis:
- Explain the query approach
- Document any assumptions
- Highlight key findings
- Suggest next steps based on data

Always ensure queries are efficient and cost-effective.

最佳实践

  • 以 Claude 自动生成为起点: 建议先用 Claude 生成 subagent,再进行个性化修改,能快速搭出优质结构。
  • 关注单一职责: 每个 subagent 聚焦一个任务目标,而非通用助手。这样更高效、可控。
  • 写清楚 system prompt: 包含明确任务说明、执行方式、示例和限制,效果会更好。
  • 精细管理工具权限: 只给与必要权限,避免误操作或安全风险。
  • 纳入版本控制: 项目级 subagent 应进入 Git 管理,方便团队复用与协作更新。

高级用法

子代理串联使用

对于复杂流程,可顺序调用多个 subagent:

css 复制代码
> First use the code-analyzer subagent to find performance issues, then use the optimizer subagent to fix them

动态选择 subagent

Claude Code 会根据上下文自动匹配 subagent。建议在 description 字段中明确行为方式和使用场景。


性能注意事项

  • 上下文效率: subagent 能减少主会话上下文负担,延长整体上下文寿命
  • 潜在延迟: 每次调用 subagent 都从新上下文开始,需重新获取信息,可能带来额外延迟

相关推荐
人生都在赌13 分钟前
我用一个周末开发的MCP工具,让Claude帮我管理了整个项目
ai编程·claude·mcp
谦行13 小时前
Claude 提示词最佳实践
claude
302AI20 小时前
302.AI 独家 | 让 Claude Code 支持任意第三方模型
llm·claude
饼干哥哥1 天前
30 个进阶技巧彻底榨干Claude Code价值:工作流、上下文交互、拓展与自动化、架构与重构、性能与协作...
claude
yeshan3 天前
使用 Claude Code 的自定义 Sub Agent 完善博文写作体验
ai编程·claude·掘金·日新计划
清沫4 天前
上下文工程(Context Engineering)
前端·claude·cursor
win4r4 天前
🚀Claude Code重磅推出Sub agents功能!轻松实现任务专业化和模块化!三分钟完美复现Kiro工作流,规范驱动开发时代正式到来!
aigc·claude·vibecoding
不老刘4 天前
Claude Code 基于 VUE + KonvaJS 实现海报生成器(附源码)
vue·claude·konvajs
星际码仔6 天前
AI浪潮下,程序员的岗位不会消失,但可能断层
openai·claude·cursor