Claude Code Subagents (Subagent)
In Claude Code, you can createspecialized AI subagents (Subagent), to handle specific types of tasks, thereby achieving better context isolation, stronger constraint control, and higher execution efficiency.
Subagents run inan independent context window, where each subagent can have its own system prompt, designated model, explicit tool access permissions, independent permission mode, and persistent memory across sessions. When Claude determines that your request matches a subagent's description, it automatically delegates the task to it, and the subagent completes it independently and returns the result.
Subagents only receive their own system prompt and basic environment information (such as the working directory),they do not inherit the full Claude Code system prompt, which ensures clean and controllable behavior.
Why use subagents
The core value of subagents lies inisolation + specialization, mainly reflected in the following aspects:
Preserve the main conversation context: Put "heavy tasks" such as exploration and log analysis into subagents; the main conversation only receives a summary of conclusions, not flooded by large amounts of intermediate output. Research shows that running three subagents in parallel to analyze a 50,000-line project takes about 45 seconds, while serial execution takes 3 minutes.
Enforce constraints: Restrict subagent capabilities through tool whitelists or blacklists, such as read-only analysis, prohibiting dangerous commands.
Behavior specialization: Design dedicated AI for specific domains (code review, debugging, data analysis), clearly stating the agent's capability boundaries in the system prompt to avoid unnecessary invocation.
Control costs: Assign simple tasks to Haiku and complex analysis to Sonnet, through environment variables CLAUDE_CODE_SUBAGENT_MODEL uniformly set the model used by all subagents.
Cross-project reuse: User-level subagents are configured once and available in all projects.
Subagents vs Multi-agents
These two concepts are easily confused; the difference lies in task granularity and running scope:
| Comparison Item | Subagent | Multi-agent |
|---|---|---|
| Running scope | Launched within a single Claude Code session, processes subtasks and returns results | Multiple Claude Code sessions run in parallel or serial, usually managed by an orchestrator |
| Context | Independent context window, isolated from the main conversation | Each session's context is completely independent |
| Nested | Subagents cannot create further subagents (use Skills when nesting is needed) | Multi-level tasks can be coordinated by an orchestrator |
| Applicable scenarios | Focused subtasks, large output isolation, specialized analysis | Full-featured development pipeline (design to implementation to testing to release) |
Built-in subagents
Claude Code has several built-in subagents, usually used automatically, with no manual configuration needed.
1. Explore (exploration agent)
Used for read-only search and analysis of the codebase. The model defaults to Haiku (fast, low latency), with only read-only tools available (cannot Edit / Write). When Claude needs to view code but not modify it, it automatically uses the Explore agent. Supports different exploration depths:quick、medium、very thorough。
2. Plan (planning agent)
Gathers codebase information in plan mode, helping Claude understand the project structure and accumulating context for subsequent solution planning. Only read-only tools are available, safely collecting the information needed for planning without producing nested agents.
3. General-purpose
Used for complex, multi-step tasks, with all tools available, inheriting the main conversation's model. Suitable for comprehensive "view + modify + reason" scenarios, and tasks requiring multi-step code modifications.
4. Other internal agents
| Agent name | Description |
|---|---|
| Bash | Run Shell commands in an independent context |
| statusline-setup | Configure terminal status bar display |
| Claude Code Guide | Answer questions related to Claude Code usage |
Create your first subagent
1. Open the subagent management interface
Execute the following command in Claude Code to open the full subagent management interface:
/agents
This interface provides all subagent management capabilities: view all available agents (built-in / user-level / project-level / plugin), create new agents, edit existing agents, and see which version actually takes effect when there is a name conflict.
2. Choose to create a user-level subagent
In the interface, select Create new agent:

then select Project (.claude/agents/), the agent file will be saved to the .claude/agents/ directory of the current directory; if you select ~/.claude/agents/ directory, it will take effect for all projects:

Use Claude's recommended:

3. Describe the agent's responsibilities
We can directly tell Claude in natural language what this agent should do, and Claude will automatically generate the system prompt and initial configuration. For example:
一个代码改进代理,扫描项目文件,
针对可读性、性能和最佳实践提出建议,
并给出改进示例。

After generation is complete, press e key to manually edit all configuration content.
4. Configure tool permissions and model
- Code review only: check only read-only tools (Read / Grep / Glob)
- Need to modify code: keep the Edit / Write tools
- Model recommendation: select Sonnet, with a good balance between analysis capability and execution speed
Just select Contiune and press Enter:

For the following ones, just select the default and press Enter.
5. Select the memory scope (optional)
- Choice User: In
~/.claude/agent-memory/Establish persistent memory, accumulating experience across all projects - Choice None: Do not retain learning results; each task starts from scratch

6. Use the newly created agent
使用 code-improver 子代理为此项目提出改进建议

The agent runs in an independent context and, upon completion, returns a summary of the results to the main conversation.
Subagent scope
Subagents are essentially Markdown files with YAML frontmatter; the storage location determines their scope and priority:
| Storage location | Scope | Precedence |
|---|---|---|
CLI --agents Flag |
Current session only | Highest |
.claude/agents/ |
Current projects | High |
~/.claude/agents/ |
All projects (global) | Medium |
| Plugin agents | Plugin scope | Minimum |
When a subagent with the same name exists in multiple locations, the one with higher priority overrides the lower ones. You can use the /agents command to see which version currently takes effect.
Suggestions for choosing a storage location: project agents (.claude/agents/) can be committed along with the code for team sharing; user agents (~/.claude/agents/) store personal habits and general tools, taking effect across projects; CLI agents (--agents) are used for temporary testing or automation scripts and are not retained on disk.
Configuration file structure
Each subagent configuration file consists of two parts: YAML frontmatter (metadata and configuration) and Markdown body (the system prompt).
Example
name
:
code-reviewer
Required: unique identifier, lowercase letters + hyphens
description
:
Reviews code for quality, best practices, and security issues.
Invoke when the user asks to review, audit, or check code quality.
Required: determines when Claude automatically invokes this agent; recommended to write as "when to invoke + what it can do"
tools
:
Read, Grep, Glob
Tool whitelist (only these tools can be used)
model
:
sonnet
Specify model: haiku / sonnet / opus / inherit
permissionMode
:
default
Permission mode (see the permission mode section below)
memory
:
project
Persistent memory scope (see the memory section below)
You are a senior code reviewer.
Analyze code and provide actionable feedback organized by severity
:
Critical / Major / Minor.
Update your agent memory with recurring patterns, conventions, and known issues you discover.
Complete field descriptions
| Field | Required | Description |
|---|---|---|
name |
Required | Unique identifier, also the name when explicitly invoked. Format: lowercase letters + hyphens, such as code-reviewer |
description |
Required | The most important field, whether and when Claude automatically invokes this agent depends entirely on this; be sure to clearly write the usage scenarios |
tools |
Optional | Tool whitelist; once set, only the listed tools can be used, and MCP tools are also excluded |
disallowedTools |
Optional | Tool blacklist; inherits all tools from the main conversation but excludes the listed tools (MCP tools are retained) |
model |
Optional | Specify the model; can be filled with haiku、sonnet、opus, full model ID, or inherit(default, inherits the main conversation) |
permissionMode |
Optional | Permission behavior control, see the permission mode section below |
memory |
Optional | Persistent memory scope:user / project / local, see the memory section below |
background |
Optional | Set to true when, the agent always runs in the background (does not block the main conversation) |
isolation |
Optional | Set to worktree when, runs in a temporary git worktree, completely isolated from the main repository |
skills |
Optional | List of Skills automatically loaded when this agent starts |
hooks |
Optional | Lifecycle hooks:SubagentStart / SubagentStop / PreToolUse / PostToolUse |
The difference between tools and disallowedTools
| Configuration method | Behavior | Typical scenario |
|---|---|---|
| Neither is set | Inherits all tools from the main conversation, including MCP tools | General-purpose agent, no restrictions needed |
Only set tools |
Only tools in the whitelist can be used, MCP tools are excluded | Read-only analysis agents, strictly constrained scenarios |
Only set disallowedTools |
Inherits all tools, excludes blacklisted tools, MCP tools are retained | Retains MCP capabilities but prohibits write operations |
| Both are set | First apply disallowedTools, then filter from the remaining tools by tools filtering |
Fine-grained control of tool access |
Example
Example 1: Only allow read-only operations (using the tools whitelist)
name
:
safe-researcher
description
:
Research agent with read-only access. Use when analyzing code without making changes.
tools
:
Read, Grep, Glob, Bash
Only these four tools are available; Write and Edit are not in the whitelist and cannot be used
Example
Example 2: Inherit all tools but prohibit writing files (using the disallowedTools blacklist)
name
:
no-writes
description
:
Analysis agent that inherits
all
tools except file writes.
disallowedTools
:
Write, Edit
Retain MCP tools, exclude only Write and Edit
Permission modes
Pass permissionMode The field controls the permission behavior when a subagent performs operations:
| Mode | Behavior | Applicable scenarios |
|---|---|---|
default |
Normal permission prompts, asking the user before each operation | General scenarios, recommended default value |
acceptEdits |
Automatically accept file edits without confirmation each time | For agents that frequently modify files, reduces interaction interruptions |
dontAsk |
Automatically reject unauthorized operations without interrupting the execution flow | Strictly read-only scenarios, silently skip when an operation fails |
bypassPermissions |
Skip all permission checks and execute directly | Only for fully trusted, controlled automation environments |
plan |
Read-only planning mode, no write operations performed | Solution planning, architecture analysis |
bypassPermissionsOnly suitable for fully trusted subagents. In addition, subagents willinherit the parent session's permission mode—if the main session has bypass enabled, all subagents will also bypass; please exercise extra caution when using this.
Persistent Memory
Pass memory field, subagents can accumulate knowledge across sessions, such as codebase patterns, debugging experience, architecture decisions, etc., without needing to re-explore each time.
| Scope values | Storage location | Applicable scenarios |
|---|---|---|
user |
~/.claude/agent-memory/ |
The agent's knowledge applies to all projects, such as general code review standards |
project |
.claude/agent-memory/ |
Knowledge is bound to the project and can be shared across the team via git (recommended default) |
local |
.claude/agent-memory-local/ |
Knowledge is bound to the project but not committed to git, storing only personal local experience |
Example
name
:
code-reviewer
description
:
Reviews code for quality and best practices. Invoke when reviewing code changes.
memory
:
user
User-level memory: accumulate review experience across projects
You are a code reviewer.
As you review code, update your agent memory with patterns, conventions,
and recurring issues you discover in this codebase.
Control how memory is used in the conversation:
- Before the task starts:
请先查阅你的记忆,再开始审查(let the agent leverage existing experience) - After the task ends:
任务完成后,把你发现的规律保存到记忆中(continuous accumulation) - You can also directly write an instruction to "proactively maintain memory" in the system prompt, letting the agent execute automatically without manual reminders each time
worktree isolation mode
Settings isolation: worktree , the subagent runs in a temporary git worktree, completely isolated from the main repository. Suitable for the following scenarios:
- Exploratory tasks requiring extensive file modifications with uncertain results
- Run multiple solutions in parallel for comparison, without interfering with each other
- Operations requiring a clean environment, such as automated testing and CI verification
Example
name
:
experimental-refactor
description
:
Tries refactoring approaches in an isolated worktree.
Use when exploring risky refactoring that shouldn't affect main branch.
isolation
:
worktree
Run in a temporary worktree; modifications do not affect the main repository
tools
:
Read, Write, Edit, Bash
You are a refactoring agent working in an isolated environment.
Feel free to make changes—they won't affect the main branch.
Summarize what you changed and whether the approach was successful.
Background Running
Subagents support two running modes, foreground and background, with different behaviors:
| How to run | Behavior | Limitation |
|---|---|---|
| Foreground | Blocks the main conversation until completion; permission prompts and clarification questions are delivered to the user in real time | No special restrictions |
| Background | Executes in parallel without interrupting the main conversation; required permissions are confirmed in advance before startup | Cannot use MCP, cannot perform interactive clarification; when permissions are insufficient, the task fails rather than pausing to wait |
Claude automatically decides whether to use foreground or background based on task characteristics. You can also control it manually:
Ctrl + B: Switch the currently running subagent to the backgroundCtrl + F(press twice to confirm): terminate all background agents- Set in the frontmatter
background: true: the agent always runs in the background - Add at the beginning of the message
&: send the task as a background task to the claude.ai web version - Pass
/taskscommand to view background task progress at any time
To completely disable the background task feature, set the following environment variables:
export CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1
To uniformly set the model used by all subagents (for example, the main conversation uses Opus for complex reasoning, subagents use Sonnet to save costs):
export CLAUDE_CODE_SUBAGENT_MODEL="claude-sonnet-4-6"
Lifecycle Hooks
Subagents support the following hook events, which can be used for automation scenarios such as logging, operation validation, and result notification:
| Hook events | Trigger Timing | Typical use |
|---|---|---|
SubagentStart |
When the subagent starts | Log startup, initialize the environment |
SubagentStop |
When a subagent task completes | Log results, trigger downstream tasks, send notifications. Includes agent_id and agent_transcript_path Field |
PreToolUse |
Before tool call | Validate the legitimacy of operations; when the script exit code is 2, it can block the tool invocation |
PostToolUse |
After a tool call | Format output, generate changelog |
Advanced usage: through PreToolUse hooks to dynamically control tool behavior. For example, allowing a database agent to only execute read-only SQL queries, with any write operation intercepted by the script:
Example
name
:
db-analyst
description
:
Read-only database analysis agent. Use for querying and reporting, never for writes.
tools
:
Bash
Configure the hook in .claude/settings.json:
PreToolUse on Bash -> validate-readonly-query.sh
The script returns with exit code 2 when it detects a non-SELECT operation, blocking the command from executing
You are a database analyst. Only run SELECT queries.
Never run INSERT, UPDATE, DELETE, DROP, or
any
DDL statements.
Disable a specific subagent
If you don't want Claude to automatically invoke a certain built-in subagent, you can add it to the disable list in .claude/settings.json :
Example
{
"subagents": {
"deny": ["explore", "plan"] // Disable the explore and plan built-in agents
// After disabling, Claude won't automatically invoke them, but you can still call them explicitly by hand
}
}
How to invoke a subagent
1. Automatic delegation
Claude will, based on the description field automatically determine whether the task suits a certain subagent, no need to manually specify in the prompt:
帮我检查最近的代码改动质量
2. Explicit invocation
Explicitly specify in the prompt which agent to use:
让 code-reviewer 子代理检查最近的改动
Typical usage patterns
1. Isolate high-output tasks
Put tasks that produce large amounts of intermediate output (such as running tests, scanning logs) into subagents; the main conversation only receives concise conclusions:
使用子代理运行所有测试,只返回失败的测试和根因分析
2. Parallel research
Launch multiple subagents simultaneously to handle different modules, greatly reducing analysis time:
并行使用子代理分别分析认证模块、数据库模块和 API 模块,汇总后给出整体架构建议
3. Chain subagent pipeline
Split a complex workflow into multiple specialized agents, passing results in sequence:
先用 code-reviewer 找出问题,再用 optimizer 子代理修复这些问题
Design principle of a chained workflow: each agent does one thing and defines its interface through a clear "input to process to output to handoff signal". The following is a three-stage pipeline example from production practice:
- pm-spec: Read requirements, generate work specifications, mark after confirmation
READY_FOR_ARCH - architect-review: Verify design constraints, produce Architecture Decision Records (ADR), mark
READY_FOR_BUILD - implementer-tester: Implement code and tests, update documentation, mark
DONE
Pass SubagentStop Hooks listen to the status file and automatically trigger the next agent, without manual intervention.
4. Parallel code review
同时启动 style-checker、security-scanner、test-coverage 三个子代理并行审查,
将审查时间从数分钟压缩到数十秒
When to use a subagent
Scenarios suitable for subagents:
- The task is self-contained, with clear input and expected output
- The output is large, significantly occupying the main conversation context
- Strong constraints are needed (read-only, isolated worktree, etc.)
- Similar tasks recur and are worth solidifying into an agent
- Involves multiple independent subdomains that can be processed in parallel
Scenarios suitable for the main conversation:
- Requires frequent back-and-forth adjustments, highly interactive
- Multi-stage tasks have strong dependencies, context needs to be continuous
- Quick, small changes, where the overhead of starting an agent isn't worth it
- Practical experience: with more than 3-4 subagents, management overhead may actually reduce overall efficiency
Subagents cannot create further subagents (to prevent infinite nesting). If nested logic is needed, use Skills。
Best Practices
How to write the description
- Use action-oriented descriptions:
当用户要求审查 / 分析 / 检查代码质量时调用 - State prerequisites:
在规格文档确认后使用,产出架构决策记录 - Clearly write the agent's boundaries and scenarios it is not good at, to prevent incorrect invocation
Tool permission design (principle of least privilege)
- Read-only agents (review, audit):
Read, Grep, Glob - Research agents (information gathering):
Read, Grep, Glob, WebFetch, WebSearch - Implementation agents (writing code):
Read, Write, Edit, Bash, Glob, Grep
Single Responsibility
- Each agent does one thing, with clear input / output / handoff rules
- Don't try to make one agent do everything
System prompt suggestions
- Clearly define the agent's personality in the system prompt:
请保持批判性,不要只说好话 - Point out the agent's weaknesses and limitations to avoid overconfidence
- If memory is enabled, write an instruction to "proactively maintain memory" in the system prompt, letting the agent execute automatically
Parallel vs Serial choice
- Independent subdomains: prefer parallel, saving time
- The next step depends on the previous result: must be serial, ensuring quality
- Avoid parallelizing for the sake of parallelizing: 10 parallel agents handling a simple task instead waste Tokens and coordination costs