Skip to main content
Claude Code Subagent
Claude Code Subagent Practical Guide 的文章封面图

Claude Code Subagent Practical Guide

AI-assisted

Creating a Claude Code subagent from scratch: configuration format, triggering mechanism, practical templates and advanced techniques

Quick review

In the previous article, we learned about the core concept of Subagent: it is a context-independent specialized AI assistant that solves the problem of information overload in complex tasks through context isolation. Claude Code has three built-in subagents: Explore, Plan, and General-purpose. This article will take you from a practical perspective to create a custom Subagent and master advanced usage.

Manage Subagent

Via /agents command

The easiest way is to use the interactive interface:

/agents

This will open a menu where you can:

  • View all Subagents (built-in + custom) -Create new Subagent
  • Edit configuration and tool permissions for existing Subagent
  • Delete unnecessary Subagent
  • See which Subagent is active when there is a name conflict

Through file management

Subagent is stored as a Markdown file. You can also create and edit files directly.

Storage location:

locationpathscope
Project level.claude/agents/Dedicated to the current project and can be submitted to Git
User level~/.claude/agents/Available across all projects
PluginPlugin's agents/ directoryInstalled with Plugin

Priority: Project level > User level > Plugin level

When a Subagent with the same name exists in multiple locations, the one with higher priority will overwrite the one with lower priority.

Create your first Subagent

Step 1: Create a directory

mkdir -p .claude/agents

Step 2: Create Markdown file

.claude/agents/code-reviewer.md:

---
name: code-reviewer
description: 专业的代码审查代理,用于代码质量检查。在完成代码编写后主动使用。
tools: Read, Grep, Glob, Bash
---

你是一位资深的代码审查专家,专注于确保代码质量和安全性。

当被调用时:
1. 运行 `git diff` 查看最近的更改
2. 分析修改的文件
3. 提供结构化的审查反馈

审查清单:
- 代码可读性和命名规范
- 错误处理和边界条件
- 安全漏洞(注入、敏感信息泄露)
- 性能优化机会
- 测试覆盖情况

输出格式:
- 严重问题(必须修复)
- 警告(建议修复)
- 建议(可以改进)

Step 3: Test Subagent

In Claude Code:

> 用 code-reviewer 代理审查我最近的修改

Or let Claude choose automatically:

> 帮我审查一下代码质量

If description is written clearly enough, Claude will automatically recognize and call your Subagent.

Detailed explanation of configuration fields

Subagent configuration file consists of two parts: YAML frontmatter and Markdown body.

YAML Frontmatter

---
name: your-agent-name
description: 描述这个代理做什么,以及何时应该被使用
tools: Tool1, Tool2, Tool3
model: sonnet
permissionMode: default
skills: skill1, skill2
---
FieldRequiredDescription
nameisa unique identifier, use lowercase letters and hyphens
descriptionYesNatural language description (Claude uses this to determine when to call)
toolsNoComma separated list of tools. If omitted, all tools are inherited
modelNoModel selection: sonnet, opus, haiku, or inherit
permissionModeNoPermission Mode (see below)
skillsNoAutoloaded Skills (Subagent does not inherit the parent session's Skills)

Permission mode

ModeDescription
defaultNormal permission check
acceptEditsAutomatically accept editing operations
bypassPermissionsSkip all permission checks
planOnly propose a plan, not execute it
ignoreIgnore this Subagent

Markdown text

The text is Subagent's system prompt. The more detailed you write, the better Subagent performs.

A good system prompt should include:

  • Clear role definition
  • Specific work steps
  • Key checklist
  • Output format requirements

Trigger mechanism

Automatic delegation

Claude will automatically decide whether to delegate based on the task content and Subagent's description.

Tip to encourage automatic use: Use trigger words in description:

description: Use PROACTIVELY after writing code for quality checks

or:

description: MUST BE USED when encountering errors or test failures

Explicit call

Directly tell Claude which Subagent to use:

> 使用 code-reviewer 代理检查我的代码
> 让 debugger 代理分析这个错误
> 调用 test-runner 代理运行测试

Tool configuration

List of commonly used tools

ToolsInstructions
ReadRead file content
WriteWrite to file
EditEdit file
GlobFile pattern matching
GrepRegular expression search
BashExecute shell command
WebFetchGet web content
WebSearchSearch the web

Tool configuration strategy

Read only Subagent (exploration, analysis):

tools: Read, Grep, Glob, Bash

NOTE: Even if Bash is included, Subagent should only be used for read-only commands (ls, git status, git log, etc.).

Read and write Subagent (repair, refactor):

tools: Read, Edit, Write, Bash, Grep, Glob

Principle of Least Privilege: Grant only necessary tools to avoid accidental operations.

Practical Subagent template

Code Reviewer

---
name: code-reviewer
description: Expert code review. Use PROACTIVELY after writing or modifying code.
tools: Read, Grep, Glob, Bash
model: inherit
---

你是一位资深的代码审查专家,确保代码质量和安全性。

当被调用时:
1. 运行 `git diff` 查看最近的更改
2. 聚焦于修改的文件
3. 立即开始审查

审查清单:
- 代码清晰可读
- 函数和变量命名规范
- 无重复代码
- 正确的错误处理
- 无暴露的密钥或 API 密码
- 输入验证完整
- 测试覆盖充分
- 性能考虑到位

按优先级组织反馈:
- 严重问题(必须修复)
- 警告(建议修复)
- 建议(可以改进)

包含具体的修复示例。

Debugging Expert

---
name: debugger
description: Debugging specialist. Use PROACTIVELY when encountering errors or test failures.
tools: Read, Edit, Bash, Grep, Glob
---

你是一位调试专家,专注于根因分析。

当被调用时:
1. 捕获错误信息和堆栈跟踪
2. 识别复现步骤
3. 定位失败位置
4. 实施最小修复
5. 验证解决方案有效

调试流程:
- 分析错误信息和日志
- 检查最近的代码更改
- 形成并测试假设
- 添加战略性的调试日志
- 检查变量状态

对每个问题提供:
- 根因解释
- 支持诊断的证据
- 具体的代码修复
- 测试方法
- 预防建议

专注于修复根本问题,而非表面症状。

Test runner

---
name: test-runner
description: Test automation expert. Use PROACTIVELY to run tests and fix failures.
tools: Read, Edit, Bash, Grep, Glob
permissionMode: acceptEdits
---

你是一位测试自动化专家。

当你看到代码更改时:
1. 识别相关的测试文件
2. 运行适当的测试
3. 如果测试失败,分析原因并修复

测试策略:
- 优先运行与更改相关的测试
- 分析失败的测试输出
- 区分代码问题和测试问题
- 修复后重新运行验证

对于新功能:
- 确认测试覆盖关键路径
- 检查边界条件测试
- 验证错误处理测试

Document generator

---
name: doc-generator
description: Documentation specialist. Use when creating or updating documentation.
tools: Read, Write, Grep, Glob
---

你是一位技术文档专家。

当被调用时:
1. 分析代码结构和注释
2. 识别公共 API 和关键功能
3. 生成清晰的文档

文档风格:
- 简洁明了
- 包含代码示例
- 解释为什么,而不只是是什么
- 考虑读者背景

输出格式:
- API 参考用 Markdown
- 使用恰当的标题层级
- 包含目录(如果文档较长)

Security Scanner

---
name: security-scanner
description: Security specialist. Use PROACTIVELY when reviewing code for security issues.
tools: Read, Grep, Glob, Bash
---

你是一位安全专家,专注于发现代码中的安全漏洞。

扫描范围:
- 注入漏洞(SQL、命令、XSS)
- 认证和授权问题
- 敏感数据暴露
- 安全配置错误
- 依赖漏洞

检查清单:
- 用户输入是否经过验证和转义
- 敏感数据是否加密存储
- API 密钥是否硬编码
- 是否使用安全的默认配置
- 依赖是否有已知漏洞

输出格式:
- 严重(立即修复)
- 高危(尽快修复)
- 中危(计划修复)
- 低危(考虑修复)

每个问题包含:
- 漏洞描述
- 风险说明
- 修复建议
- 参考资料

Advanced usage

Production-level design patterns

In production environments, there are several proven patterns for multi-agent collaboration:

3 Amigos Mode

A collaboration model composed of three roles: product, architecture, and implementation:

PM Agent          →  Architect Agent  →  Claude Code
(产品定义)           (技术设计)           (代码实现)
RolesResponsibilitiesTool Configuration
PM AgentFunction definition, requirement sortingRead, WebSearch
Architect AgentTechnical Solution DesignRead, Glob, Grep
Claude CodeCode ImplementationAll Tools

Three-stage pipeline

Break down complex tasks into three clear stages:

规格制定 → 架构评审 → 实现测试
(Spec)     (Review)    (Implement)

Each stage is responsible for a dedicated Subagent, and the output serves as the input to the next stage.

Model orchestration strategy

Different models are used at different stages to optimize costs and effects:

StageRecommended modelReason
Planning phaseSonnetDeep reasoning required
Execution phaseHaikuFast, low cost
Review stageSonnetComprehensive judgment required

Configuration example:

---
name: quick-executor
model: haiku
---

For complex workflows, multiple Subagents can be linked:

> 首先用 code-analyzer 代理找出性能问题,
> 然后用 optimizer 代理修复它们

Resumeable execution

Subagent execution can be paused and resumed, maintaining the full previous context:

Initial call:

> 用 code-analyzer 代理开始分析认证模块

[Agent 完成初始分析并返回 agentId: "abc123"]

Recovery Agent:

> 恢复代理 abc123,继续分析授权逻辑

[Agent 继续,保持之前的完整上下文]

Usage Scenario:

  • Long-running studies, completed in multiple sessions
  • Iterative improvements, keeping context
  • Multi-step workflow to process related tasks in sequence

Configure Skills for Subagent

Subagent does not automatically inherit skills from the parent session. If necessary, declare it explicitly:

---
name: code-reviewer
skills: code-standards, security-checklist
---

CLI dynamic definition

No need to save the file, define the temporary Subagent directly on the command line:

claude --agents '{
  "quick-reviewer": {
    "description": "Quick code review",
    "prompt": "You are a code reviewer...",
    "tools": ["Read", "Grep", "Glob"],
    "model": "haiku"
  }
}'

Suitable for quick testing or one-time use.

Best Practices

1. Stay focused

✅ 好:单一责任
---
name: code-reviewer
description: Expert code review for quality and security
---

❌ 差:试图做太多
---
name: super-agent
description: Does everything - reviews, tests, deploys, documents...
---

A Subagent that does one thing well is better than a Subagent that does many things.

2. Write a clear description

Claude uses description to decide when to use Subagent. A good description should answer:

  1. **What does this Subagent do? ** List specific abilities
  2. **When should it be used? ** Contains trigger words
✅ 好:具体和清晰
description: 从 PDF 文件提取文本和表格,填写表单,合并文档。
当处理 PDF 文件或用户提到 PDF、表单、文档提取时使用。

❌ 差:太模糊
description: 处理文档

3. Restrict tool access

Grant only the tools you need:

---
name: code-reviewer
tools: Read, Grep, Glob, Bash
---

This prevents Subagent from accidentally modifying files and allows it to focus more on its review work.

4. Write detailed system prompts

The more detailed the system prompts, the better Subagent performs:

  • Clear role definition
  • Specific work steps
  • Key checklist
  • Output format requirements

5. Version control

Commit project-level Subagent to Git:

git add .claude/agents/
git commit -m "Add code-reviewer subagent"

Team members automatically get the same Subagent after cloning the project.

Troubleshooting common problems

ProblemPossible CauseSolution
Subagent is not calleddescription is not clear enoughAdd trigger words to make it more specific
Subagent not being calledWrong file locationMake sure the file is in .claude/agents/ or ~/.claude/agents/
Tools are not availableTools field configuration errorCheck the spelling of tool names and make sure they are separated by commas
The output is unstableThe system prompt is too vagueAdd specific steps and output format requirements
Context lostSession endedUsing resumable execution
Name conflictSubagent with the same name in multiple locationsUse /agents to see which one is active

Share with team

Method 1: Through Git

Place Subagent in the .claude/agents/ directory and submit it to the project repository. Team members are automatically obtained after cloning.

Method 2: Through Plugin

Place Subagent in the agents/ directory of Plugin and distribute it through the Plugin mechanism.

Method 3: User-level sharing

Place commonly used Subagents in ~/.claude/agents/ to make them available across all projects. Synchronization between multiple machines can be managed using dotfiles.

Learning resources

Official Documentation

ResourcesLinksInstructions
Claude Code Documentationdocs.anthropic.comOfficial Documentation Entry
Subagent GuideClaude Code DocsSubagent configuration details
Agentic Design PatternsAnthropic DocsSix core design patterns
Multi-agent studyAnthropic EngineeringStudy details of 90.2% performance improvement

Community Resources

ResourcesLinksInstructions
wshobson/agentsGitHub99 Agents + 15 Orchestrator Templates
Compound EngineeringGitHubPlugins for 17 specialized agents
awesome-claude-codeGitHubSummary of Claude Code best practices
ArticleSourceTopic
Building effective agentsAnthropicAgent design principles
How we built our multi-agent research systemAnthropicMulti-agent architecture practice
Claude Skills, Commands, Subagents, and PluginsYoung Leaders TechFunction comparison analysis

Summary

Claude Code Subagent is a powerful tool to improve AI programming efficiency. It makes complex tasks manageable through independent contexts and specialized configurations.

Quick start:

  1. Run /agents to open the management interface
  2. Create a simple Subagent (such as a code reviewer)
  3. Test automatic delegation and explicit calls
  4. Adjust configuration as needed

As you deepen your use, you can gradually:

  • Create exclusive Subagent for your team
  • Configure Subagent links to handle complex workflows
  • Handle long-term tasks with resumable execution

If you want to package and distribute Subagent with other configurations, please read "Claude Code Plugin Practical Guide".

Comments

Table of Contents

Claude Code Subagent Practical Guide | Yu's Cyber Desk