Guides
Claude Code subagents: how to create, configure and use them
A subagent is a specialized AI assistant that handles one type of task in its own context window and returns only a summary to your main conversation. This page walks through Anthropic's Create custom subagents documentation: what a subagent is, the built-in ones, creating your own, where the files live, how to write the frontmatter, choosing a model, how to invoke one, and what to check when one is not found. The documentation was checked on October 30, 2026.
- A subagent is a Markdown file with YAML frontmatter. Each one runs in its own context window with a custom system prompt, specific tool access, and independent permissions.
- A personal subagent goes in
~/.claude/agents/and a project subagent in.claude/agents/. On a name clash, the project one wins over the personal one. - Only
nameanddescriptionare required. Claude usesdescriptionto decide when to delegate. toolslimits what it can use and inherits everything if omitted.modelcan besonnet,opus,haiku,fable, a full model ID, orinherit.- To guarantee a particular subagent runs, @-mention it. To run the whole session as one, use
claude --agent <name>.
What a subagent is and when to use one
The documentation's test: use a subagent when a side task would flood your main conversation with search results, logs, or file contents you will not reference again. The subagent does that work in its own context and returns only the summary. Define a custom subagent when you keep spawning the same kind of worker with the same instructions.
Each subagent runs in its own context window with a custom system prompt, specific tool access, and independent permissions. It also sends its own requests, which count toward the same usage limits as your main conversation. When Claude meets a task that matches a subagent's description, it delegates to that subagent, which works independently and returns results. The documentation lists these benefits:
- Preserve context by keeping exploration and implementation out of your main conversation
- Enforce constraints by limiting which tools a subagent can use
- Reuse configurations across projects with user-level subagents
- Specialize behavior with focused system prompts for specific domains
- Control costs by routing tasks to faster, lower-cost models like Haiku
One more note from the documentation: subagents work within a single session. To run many independent sessions in parallel and monitor them from one place, it points to background agents. For a coordinated team of sessions Claude spawns and supervises, it points to agent teams.
Built-in subagents
Claude Code includes built-in subagents that Claude automatically uses when appropriate. Each inherits the parent conversation's permission rules, and most run with a restricted tool set.
| Subagent | Purpose | Tools | Model |
|---|---|---|---|
Explore | A fast, read-only agent optimized for searching and analyzing codebases: file discovery, code search, codebase exploration | Read-only tools; Write and Edit are denied | The main conversation's model (the documentation covers what happens when the main conversation runs Fable) |
Plan | Gathers context in plan mode before Claude presents a plan | Read-only tools; Write and Edit are denied | Inherits from the main conversation, unless you set CLAUDE_CODE_SUBAGENT_MODEL and force it onto every subagent |
General-purpose | Complex research, multi-step operations, code modifications | Every tool available to subagents | The CLAUDE_CODE_SUBAGENT_MODEL model if you set one and nothing assigns a model another way, otherwise the main conversation's model |
Explore and Plan start without your CLAUDE.md files and the git status snapshot to keep research fast and inexpensive. Other built-in and custom subagents load both. When invoking Explore, Claude specifies a thoroughness level: quick for targeted lookups, medium for balanced exploration, or very thorough for comprehensive analysis.
The documentation also lists helper agents that are typically invoked automatically:
| Agent | Model | When Claude uses it |
|---|---|---|
claude | None of its own; follows the model order when Claude spawns it as a subagent | When a task does not fit a more specialized agent. A catch-all with every tool available to subagents |
statusline-setup | Sonnet | When you run /statusline to configure your status line |
claude-code-guide | Haiku | When you ask questions about Claude Code features |
To block a specific built-in type, add it to permissions.deny, as shown in the FAQ below. To remove only the built-in Explore and Plan subagents, set CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS=1; Claude then reads and explores files directly. It requires Claude Code v2.1.198 or later.
Create your first subagent
Subagents are Markdown files with YAML frontmatter. You can ask Claude to write one for you, or write the file yourself. This walkthrough comes from the documentation and creates a user-level subagent that reviews code and suggests improvements.
First, in Claude Code, describe the subagent you want and where to save it:
Create a personal code-improver subagent in ~/.claude/agents/ that scans
files and suggests improvements for readability, performance, and best
practices. It should explain each issue, show the current code, and
provide an improved version. Make it read-only and have it use Sonnet.
Claude writes the file with a name, a description, a tools list, a model, and a system prompt. Second, open ~/.claude/agents/code-improver.md and confirm the frontmatter matches what you asked for. The result looks like this:
---
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 you find, explain
the problem, show the current code, and provide an improved version.
Because the file lives in ~/.claude/agents/, the subagent is available in every project on your machine. To scope it to one project instead, move it to that project's .claude/agents/ directory. Third, ask Claude to delegate to it:
Use the code-improver agent to suggest improvements in this project
Claude delegates to your new subagent, which scans the codebase and returns improvement suggestions. In the transcript, the delegation appears as a tool call row showing the subagent's name followed by a short task description, such as code-improver(Suggest code improvements).
About /agents: the documentation says running /agents prints a reminder to ask Claude or edit .claude/agents/ and ~/.claude/agents/ directly. On Claude Code v2.1.197 and earlier, /agents opens an interactive wizard with a Running tab that lists live subagents and a Library tab for creating, editing, and deleting them.
You do not need to restart after a change. The documentation says Claude Code watches ~/.claude/agents/ and .claude/agents/: when you add or edit a subagent file on disk, or ask Claude to write one, it detects the change within a few seconds and the next delegation uses the updated definition. Three cases still need a restart; they are in the troubleshooting section.
Where subagent files live
A subagent's file location determines who it is available to, and its frontmatter determines what it can do. When multiple subagents share the same name, Claude Code uses the one from the higher-priority location.
| Location | Scope | Priority | How to create |
|---|---|---|---|
| Managed settings | Organization-wide | 1 (highest) | Deployed via managed settings |
--agents CLI flag | Current session | 2 | Pass JSON when launching Claude Code |
.claude/agents/ | Current project | 3 | Ask Claude, or create the file manually |
~/.claude/agents/ | All your projects | 4 | Ask Claude, or create the file manually |
Plugin's agents/ directory | Where plugin is enabled | 5 (lowest) | Installed with plugins |
- Project subagents (
.claude/agents/) are ideal for subagents specific to a codebase. The documentation suggests checking them into version control so your team can use and improve them collaboratively. - User subagents (
~/.claude/agents/) are personal subagents available in all your projects. - Claude Code scans
.claude/agents/and~/.claude/agents/recursively, so you can organize definitions into subfolders such asagents/review/oragents/research/. The subdirectory path does not affect how a subagent is identified or invoked, because identity comes only from thenamefrontmatter field. - Keep
namevalues unique across the whole tree: if two files under the same.claude/agents/directory, including its subfolders, declare the same name, Claude Code loads only one of them, chosen by filesystem read order rather than a documented precedence.
Project subagents are discovered by walking up from the current working directory, so every .claude/agents/ between there and the repository root is scanned. When more than one of these nested directories defines the same name, Claude Code uses the definition closest to the working directory.
The frontmatter fields that matter most
Configure a subagent with YAML frontmatter between --- markers at the top of its file, and write its system prompt as Markdown after the closing ---. Only name and description are required. Multi-word field names use camelCase, such as maxTurns and disallowedTools, and must match the table exactly: Claude Code ignores a field it does not recognize without reporting an error.
| Field | Required | What it does |
|---|---|---|
name | Yes | Unique identifier of at most 256 characters, such as code-reviewer or reviewer-v2. The filename does not have to match. Names cannot contain :, which is reserved for plugin-scoped identifiers. |
description | Yes | When Claude should delegate to this subagent. |
tools | No | Tools the subagent can use, as a comma-separated string such as Read, Grep, Bash or a YAML list. Inherits every tool available to subagents if omitted. |
disallowedTools | No | Tools to deny, removed from the inherited or specified list. Same format as tools. |
model | No | Model to use: sonnet, opus, haiku, fable, a full model ID such as claude-opus-5-5, or inherit. When you omit it, Claude Code picks the model in the subagent model order. |
permissionMode | No | Permission mode: default, acceptEdits, auto, dontAsk, bypassPermissions, plan, or manual as an alias for default. Ignored for plugin subagents. |
maxTurns | No | Maximum number of agentic turns before the subagent stops. |
skills | No | Skills to preload into the subagent's context at startup. The full skill content is injected, not only the description. |
mcpServers | No | MCP servers available to this subagent. Ignored for plugin subagents. |
hooks | No | Lifecycle hooks scoped to this subagent. Ignored for plugin subagents. |
memory | No | Persistent memory scope: user, project, or local. Enables cross-session learning. |
background | No | Set to true to keep this subagent in the background even when Claude asks to wait for it. |
effort | No | Effort level when this subagent is active. Overrides the session effort level, but not the CLAUDE_CODE_EFFORT_LEVEL environment variable. Options: low, medium, high, xhigh, max; available levels depend on the model. |
isolation | No | Set to worktree to run the subagent in a temporary git worktree, giving it an isolated copy of the repository. The worktree is automatically cleaned up if the subagent makes no changes. |
The documentation lists more fields, including autoCompactWindow, omitClaudeMd, color, initialPrompt and experimental; they are not covered here. One more point: the file's body becomes the system prompt. Subagents receive only this system prompt plus basic environment details like the working directory, not the Claude Code system prompt.
Restricting tools
To restrict tools, use the tools field as an allowlist or the disallowedTools field as a denylist. If both are set, disallowedTools is applied first, then tools is resolved against the remaining pool. A tool listed in both is removed. This example from the documentation uses tools to allow only Read, Grep, Glob, and Bash. The subagent cannot edit files, write files, or use any MCP tools:
---
name: safe-researcher
description: Research agent with restricted capabilities
tools: Read, Grep, Glob, Bash
---
This one uses disallowedTools to inherit the subagent's tool pool except Write and Edit. The subagent keeps Bash, MCP tools, and the rest of its pool:
---
name: no-writes
description: Inherits the available tools except file writes
disallowedTools: Write, Edit
---
Choosing a model
The model field controls which model the subagent uses. It can be an alias (sonnet, opus, haiku, or fable), a full model ID such as claude-opus-5-5 or claude-sonnet-5 (it accepts the same values as the --model flag), or inherit, which uses the same model as the main conversation. When Claude invokes a subagent, it can also pass a model parameter for that specific invocation. Claude Code resolves the subagent's model in this order:
- The per-invocation
modelparameter - The subagent definition's
modelfrontmatter, whereinheritselects the main conversation's model - The
CLAUDE_CODE_SUBAGENT_MODELenvironment variable, when you set it to a model alias or model ID - The main conversation's model
To check which model a subagent is running on, run /tasks. Claude Code names the model on the subagent's row (it requires Claude Code v2.1.242 or later). The documentation's example for running every subagent on Haiku sets both variables in the env block of a settings file:
{
"env": {
"CLAUDE_CODE_SUBAGENT_MODEL": "haiku",
"CLAUDE_CODE_SUBAGENT_MODEL_FORCE": "1"
}
}
CLAUDE_CODE_SUBAGENT_MODEL_FORCE requires Claude Code v2.1.257 or later. While it is on, Claude Code ignores the model field in subagent definitions.
A subagent can run on a different model from the main conversation, and it sends its own requests. So if you pay per token, those requests show up under the subagent's own model rather than the main session's. We explain this in our note. For choosing a model, see choosing a model and effort level.
Automatic delegation and explicit invocation
Automatic delegation. Claude automatically delegates tasks based on the task description in your request, the description field in subagent configurations, and current context. To encourage proactive delegation, include phrases like "use proactively" in your subagent's description field. Keep descriptions brief: Claude Code shows a startup warning when your subagents' combined descriptions (the built-in ones excepted) pass 15,000 tokens, and still loads every subagent.
Explicit invocation. When automatic delegation is not enough, you can request a subagent yourself. Three patterns escalate from a one-off suggestion to a session-wide default:
- Natural language: name the subagent in your prompt; Claude decides whether to delegate
- @-mention: guarantees the subagent runs for one task
- Session-wide: the whole session runs as that subagent via the
--agentflag or theagentsetting
For natural language, there is no special syntax. Name the subagent and Claude typically delegates:
Use the test-runner subagent to fix failing tests
Have the code-reviewer subagent look at my recent changes
To @-mention, type @ and pick the subagent from the typeahead, the same way you @-mention files. This ensures that specific subagent runs rather than leaving the choice to Claude:
@"code-reviewer (agent)" look at the auth changes
Your full message still goes to Claude, which writes the subagent's task prompt based on what you asked. The @-mention controls which subagent Claude invokes, not what prompt it receives. You can also type the mention manually without using the picker: @agent-<name>.
To run the whole session as a subagent, pass --agent <name> to start a session where the main thread itself takes on that subagent's tool restrictions and model:
claude --agent code-reviewer
The agent name appears as @<name> in the startup header so you can confirm it is active. To make it the default for every session in a project, set agent in .claude/settings.json. The CLI flag overrides the setting if both are present:
{
"agent": "code-reviewer"
}
Foreground and background: foreground subagents block the main conversation until complete, and permission prompts are passed through to you. Background subagents run concurrently while you continue working. The documentation says that with nothing configured, a subagent that Claude spawns from your main conversation starts in the background.
A complete example: a code reviewer
This example comes from the documentation's Example subagents: a read-only subagent that reviews code without modifying it. It shows how to design a focused subagent with limited tool access that excludes Edit and Write, and a detailed prompt that specifies exactly what to look for and how to format output. Save it as .claude/agents/code-reviewer.md.
---
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
model: inherit
---
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 clear 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.
In this file model: inherit means it uses the same model as the main conversation, and the "Proactively" and "Use immediately after writing or modifying code" wording in description tells Claude when to delegate.
Tips from the documentation
The documentation's best practices:
- Design focused subagents: each subagent should excel at one specific task.
- Write descriptions that single out one subagent: Claude uses the description to decide when to delegate. Make each description specific enough to route to the right subagent, and keep the combined set within the 15,000-token description budget.
- Limit tool access: grant only necessary permissions for security and focus.
- Check into version control: share project subagents with your team.
Common patterns from the documentation:
- Isolate high-volume operations. Running tests, fetching documentation, or processing log files can consume significant context. Delegating these keeps the verbose output in the subagent's context while only the relevant summary returns to your main conversation. For example:
Use a subagent to run the test suite and report only the failing tests with their error messages - Run parallel research. For independent investigations, spawn multiple subagents to work simultaneously. For example:
Research the authentication, database, and API modules in parallel using separate subagents. This works best when the research paths do not depend on each other. - Chain subagents. For multi-step workflows, ask Claude to use subagents in sequence. For example:
Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them
The documentation's warning: when subagents complete, their results return to your main conversation. Running many subagents that each return detailed results can consume significant context, and each subagent spends tokens of its own while it runs.
When not to use one: use the main conversation when the task needs frequent back-and-forth or iterative refinement, multiple phases share significant context, you are making a quick, targeted change, or latency matters (a subagent that is not a fork starts fresh and may need time to gather context). For reusable prompts or workflows that run in the main conversation context rather than isolated subagent context, the documentation suggests considering skills instead.
Troubleshooting
Claude cannot find the new subagent
Restart Claude Code and try again. The documentation says this happens only when ~/.claude/agents/ did not exist before the session started, because a running session does not detect a newly created agents directory. Three cases still need a restart: after creating a scope's first agent file in a new agents directory; after adding or editing a subagent in a directory added with --add-dir or /add-dir; and in sessions started with --disable-slash-commands, which do not watch these directories at all.
The file is skipped silently
The documentation says Claude Code skips a file, without reporting it in the session, when the frontmatter has any of these problems:
- No
name: Claude Code treats the file as documentation kept beside your agents. - An opening
---that is not the file's first line: Claude Code reads the file as having no frontmatter and treats it as documentation. - A
namethat starts with-, contains:, or is longer than 256 characters: Claude Code skips the file and writes an error to the debug log. - A
namebut nodescription: Claude Code skips the file and writes the reason to the debug log. - YAML that does not parse: Claude Code reads no fields from the file, skips it, and writes the parse error to the debug log.
To see the debug log, run Claude Code with --debug. To find files whose frontmatter does not parse, run claude plugin validate against the directory, for example .claude/agents or ~/.claude/agents (it requires Claude Code v2.1.233 or later). It does not flag a file whose frontmatter parses but has no name.
A field is misspelled and nothing reports it
Claude Code ignores a field it does not recognize without reporting an error. For a subagent that loaded, run claude --debug in your shell and search the debug log at ~/.claude/debug/<session-id>.txt for does not recognize or apply. The log names up to five top-level fields in the subagent's file that Claude Code does not recognize, with the likely intended name when a supported field is close (it requires Claude Code v2.1.296 or later).
The subagent fails to launch
When nothing in the tools list resolves to a tool, for example because every entry is misspelled or names a tool that is not available to subagents, Claude Code usually refuses to launch the subagent and the Agent tool returns an error naming the unresolved entries.
The subagent does not know your rules or conversation
Each subagent starts with a fresh, isolated context window. It does not see your conversation history, the skills you have already invoked, or the files Claude has already read. Claude composes a delegation message that summarizes the task, and the subagent works from there. If a rule must reach the subagent, such as "ignore the vendor/ directory," restate it in the prompt you give Claude when delegating.
FAQ
How do I stop Claude from using a particular subagent?
Add it to the deny array in your settings, using the format Agent(subagent-name), where subagent-name matches the subagent's name field. It works for both built-in and custom subagents: {"permissions": {"deny": ["Agent(Explore)", "Agent(my-custom-agent)"]}}. You can also use claude --disallowedTools "Agent(Explore)". To prevent Claude from delegating to any subagent, the documentation says to deny the Agent tool itself.
Can a subagent spawn its own subagents?
By default, yes, up to three layers below the main conversation. To change the limit, set CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH to the number of layers you want; set 1 to turn nesting off. To keep one subagent from spawning, omit Agent from its tools list or add it to disallowedTools.
Should I use a subagent or a skill?
The documentation's split: use a subagent when the task produces verbose output you do not need in your main context, you want to enforce specific tool restrictions or permissions, or the work is self-contained and can return a summary. Consider a skill when you want reusable prompts or workflows that run in the main conversation context rather than isolated subagent context; see Claude Code skills. For the built-in commands, see Claude Code commands, and for spending less, spending less on Claude Code.
Sources
- Claude Code: Create custom subagents (built-in subagents, the creation walkthrough, file locations and priority, frontmatter fields, model order, invocation, common patterns, examples, troubleshooting)