A subagent is a specialized AI assistant that handles a focused type of work. Claude Code can delegate a matching task to that worker. The subagent works in its own context window and then returns the useful result to the main conversation.
| Feature | Main purpose |
|---|---|
| Subagent | Focused delegated work inside a single Claude session. |
| Background session / agent view | Run independent Claude sessions and monitor them. |
| Agent team | Coordinate multiple Claude sessions that can communicate. |
| Worktree | Isolate file changes in separate Git checkouts. |
A subagent is especially useful when you want the result of a side task, not all of the side task's intermediate context.
Claude Code includes built-in subagents that Claude can use automatically when appropriate.
| Built-in agent | Purpose | Typical access |
|---|---|---|
| Explore | Search and analyze a codebase without changing it. | Read-only tools. |
| Plan | Research the codebase while preparing a plan. | Read-only tools. |
| General-purpose | Complex multi-step work requiring exploration and action. | Broad subagent tools. |
| Other helpers | Special Claude Code tasks such as status-line setup or Claude Code feature questions. | Depends on the agent. |
Custom subagents are Markdown files with YAML frontmatter. The recommended current workflow is to ask Claude to create
the file or create it manually. The older interactive /agents wizard was removed in Claude Code v2.1.198.
Create a personal code-improver subagent in ~/.claude/agents/
that scans files and suggests improvements for readability,
performance, and best practices. Make it read-only and use Sonnet.
---
name: code-improver
description: Scans files and suggests improvements for readability,
performance, and best practices. Use after writing or modifying code.
tools: Read, Grep, Glob
model: sonnet
---
You are a code improvement specialist.
For each issue, explain the problem, show the current code,
and provide an improved version.
The file location determines the subagent's scope and priority.
| Location | Scope | Priority |
|---|---|---|
| Managed settings | Organization-wide | Highest |
--agents CLI flag | Current session | 2 |
.claude/agents/ | Current project | 3 |
~/.claude/agents/ | All projects for the user | 4 |
Plugin agents/ | Where the plugin is enabled | Lowest |
.claude/agents/code-reviewer.md
Best when the agent is specific to one repository and should be shared through version control.
~/.claude/agents/code-reviewer.md
Best when you want the same agent available across your projects.
You can define subagents directly when launching Claude Code. These definitions exist only for that session, which makes them useful for experiments and automation.
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer. Use proactively after code changes.",
"prompt": "You are a senior code reviewer. Focus on quality, security, and best practices.",
"tools": ["Read", "Grep", "Glob", "Bash"],
"model": "sonnet"
},
"debugger": {
"description": "Debugging specialist for errors and test failures.",
"prompt": "Analyze errors, identify root causes, and provide fixes."
}
}'
The --agent option can start Claude Code with a subagent's system prompt, tool restrictions, and model
as the main session configuration.
claude --agent code-reviewer
This is different from asking the main Claude session to delegate one task. Here, the selected subagent becomes the main session's agent identity.
The most important fields include:
| Field | Purpose |
|---|---|
name | Unique identifier for the subagent. |
description | Tells Claude when the subagent should be used. |
tools | Controls which tools the subagent can use. |
disallowedTools | Removes specific tools from its available set. |
model | Selects the model, such as sonnet, opus, haiku, fable, or inherit. |
permissionMode | Controls how permissions work for the subagent. |
skills | Preloads selected skills into the subagent's context. |
memory | Enables persistent memory for the subagent. |
hooks | Defines lifecycle hooks for the subagent. |
mcpServers | Provides MCP servers specifically to the subagent. |
isolation | Can isolate subagent work in a worktree. |
Claude uses the description field to decide when automatic delegation makes sense.
Make it clear, specific, and short.
Helps with code.
Reviews TypeScript changes for security, error handling,
and project conventions. Use after modifying API or authentication code.
The model field controls which model a subagent uses.
model: haiku
or:
model: sonnet
or:
model: opus
or:
model: inherit
Use a faster model for simple searches or classification when appropriate. Use a stronger model for complex reasoning or implementation.
A powerful advantage of subagents is that you can restrict what they are allowed to do. A read-only reviewer can be prevented from editing files.
---
name: reviewer
description: Review code without changing files.
tools: Read, Grep, Glob
model: sonnet
---
Review the code and report problems.
Do not modify any files.
The permissionMode field controls the subagent's permission behavior.
| Mode | Meaning |
|---|---|
default | Manual mode; prompts for permission. |
acceptEdits | Automatically accepts file edits and common filesystem commands in allowed paths. |
auto | Uses Auto mode's background classifier. |
dontAsk | Automatically denies permission prompts. |
bypassPermissions | Skips permission prompts; use with caution. |
plan | Read-only plan mode. |
bypassPermissions can allow operations without approval.
Do not use it casually, especially on untrusted projects or sensitive environments.
Use the skills field when a subagent needs specific domain knowledge at startup.
---
name: api-developer
description: Implement API endpoints using team conventions.
skills:
- api-conventions
- error-handling-patterns
---
Implement API endpoints following the preloaded conventions.
This is useful when the agent repeatedly needs the same instructions and patterns.
A subagent can have persistent memory so it can accumulate useful knowledge across conversations. For example, it can remember recurring codebase patterns or common issues.
A subagent can receive MCP servers that are scoped specifically to it. This keeps those tool descriptions and external integrations out of the main conversation when they are not needed there.
---
name: browser-tester
description: Tests features in a real browser.
mcpServers:
- playwright:
type: stdio
command: npx
args: ["-y", "@playwright/mcp@latest"]
- github
---
Use Playwright to navigate, screenshot,
and interact with the browser.
Hooks can run at important points in a subagent's lifecycle.
Common events include PreToolUse, PostToolUse, and Stop.
---
name: code-reviewer
description: Review code with automatic validation.
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-command.sh $TOOL_INPUT"
PostToolUse:
- matcher: "Edit|Write"
hooks:
- type: command
command: "./scripts/run-linter.sh"
---
Project-level settings.json can also react to SubagentStart and SubagentStop events.
Claude decides whether to delegate based on your request, the subagent's description, and the current context. You can encourage proactive delegation by including wording such as “Use proactively” in the description.
There are three useful levels of control.
Use the test-runner subagent to fix the failing tests.
Claude decides whether to delegate.
@"code-reviewer (agent)" review the authentication changes.
This explicitly selects the subagent for that task.
claude --agent code-reviewer
The entire session runs using that agent configuration.
A subagent can run in the foreground or background.
| Foreground | Background |
|---|---|
| Main conversation waits for the result. | Main conversation can continue while the worker runs. |
| Useful for dependent tasks. | Useful for independent or long-running work. |
| Result returns directly. | Status/result can be checked while it runs. |
One of the strongest use cases is isolating operations that generate a lot of output. Examples include test suites, documentation searches, and large log files.
Use a subagent to run the test suite and report
only the failing tests with their error messages.
The detailed output remains in the subagent context, while the main conversation receives the useful summary.
Independent investigations can be delegated to multiple subagents at the same time.
Research the authentication, database, and API modules
in parallel using separate subagents.
Each worker explores one area, and Claude combines the findings. This works best when the research paths do not depend on one another.
Subagents can be used sequentially when one specialist's result becomes the next specialist's input.
Use the code-reviewer subagent to find performance issues,
then use the optimizer subagent to fix them.
Stay in the main conversation when:
Consider a Skill instead when you want reusable instructions that run in the main conversation context.
/btw can be better than starting a subagent.
A normal subagent gets its own context window rather than automatically receiving every detail of the parent conversation. This separation is one of the main reasons subagents save context.
If a subagent needs specific information, give it the relevant files, task description, or instructions rather than assuming it knows everything the main conversation knows.
A forked subagent starts from the current conversation context instead of starting completely fresh. This is useful when the new worker needs the discussion that has already happened.
When a subagent needs to make code changes and you want those changes isolated, worktree isolation can be used. This gives the worker a separate Git checkout.
---
name: refactorer
description: Apply a large mechanical refactor safely.
isolation: worktree
---
Apply the refactor, run tests,
and report the changed files.
This is especially useful when several workers may edit overlapping areas.
The documentation supports configuring whether a subagent can spawn its own subagents. This creates a hierarchy of workers.
Claude Code limits how many subagents can run concurrently. When the limit is reached, additional work waits until capacity becomes available.
The practical lesson is simple: parallelism has a capacity and cost. More workers do not automatically mean faster results.
Claude Code scans subagent final reports before returning them to the main conversation. This helps distinguish text that imitates Claude Code system messages or permission-setting instructions from actual conversation structure.
A subagent can be resumed when you want to continue work using its existing context rather than starting a new worker. This is useful for long-running investigations or multi-step specialist work.
Long-running subagents can compact their context when necessary. The purpose is the same general idea as normal Claude context management: keep important information while reducing redundant history.
| Pattern | Example |
|---|---|
| High-volume isolation | Run tests and return only failures. |
| Parallel research | Research auth, database, and API independently. |
| Chaining | Reviewer finds issues → optimizer fixes them. |
| Specialized reviewer | Security agent checks authentication changes. |
| Read-only exploration | Explore agent maps an unfamiliar codebase. |
| Isolated implementation | Refactorer works in a worktree. |
Check that the Markdown file starts with YAML frontmatter, has a valid name and description,
and is stored in a supported agents directory. If you create a new agents directory while Claude Code is already
running, restarting the session may be necessary.
Keep names unique within the relevant directory tree. For nested project agents, the definition closest to the working directory takes precedence.
Claude Code skips files with missing required fields, invalid YAML, or invalid names. Use --debug to inspect
debug information. Current documentation also describes claude plugin validate for checking an agents directory.
bypassPermissions.description instead of the system prompt.description short and specific.description field control?tools and disallowedTools?model field do?.claude/agents/ in a test project.code-reviewer.md.name and description.Read, Grep, and Glob.Subagent
↓
Own context + focused instructions
↓
Limited tools / selected model
↓
Specialized work
↓
Concise result
↓
Main Claude continues