CoreCodeBlog

Guides

Claude Code subagents: how to create, configure and use them

Published · Last checked

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.

Key points
  • 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 name and description are required. Claude uses description to decide when to delegate.
  • tools limits what it can use and inherits everything if omitted. model can be sonnet, opus, haiku, fable, a full model ID, or inherit.
  • 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:

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.

SubagentPurposeToolsModel
ExploreA fast, read-only agent optimized for searching and analyzing codebases: file discovery, code search, codebase explorationRead-only tools; Write and Edit are deniedThe main conversation's model (the documentation covers what happens when the main conversation runs Fable)
PlanGathers context in plan mode before Claude presents a planRead-only tools; Write and Edit are deniedInherits from the main conversation, unless you set CLAUDE_CODE_SUBAGENT_MODEL and force it onto every subagent
General-purposeComplex research, multi-step operations, code modificationsEvery tool available to subagentsThe 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:

AgentModelWhen Claude uses it
claudeNone of its own; follows the model order when Claude spawns it as a subagentWhen a task does not fit a more specialized agent. A catch-all with every tool available to subagents
statusline-setupSonnetWhen you run /statusline to configure your status line
claude-code-guideHaikuWhen 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.

LocationScopePriorityHow to create
Managed settingsOrganization-wide1 (highest)Deployed via managed settings
--agents CLI flagCurrent session2Pass JSON when launching Claude Code
.claude/agents/Current project3Ask Claude, or create the file manually
~/.claude/agents/All your projects4Ask Claude, or create the file manually
Plugin's agents/ directoryWhere plugin is enabled5 (lowest)Installed with plugins

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.

FieldRequiredWhat it does
nameYesUnique 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.
descriptionYesWhen Claude should delegate to this subagent.
toolsNoTools 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.
disallowedToolsNoTools to deny, removed from the inherited or specified list. Same format as tools.
modelNoModel 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.
permissionModeNoPermission mode: default, acceptEdits, auto, dontAsk, bypassPermissions, plan, or manual as an alias for default. Ignored for plugin subagents.
maxTurnsNoMaximum number of agentic turns before the subagent stops.
skillsNoSkills to preload into the subagent's context at startup. The full skill content is injected, not only the description.
mcpServersNoMCP servers available to this subagent. Ignored for plugin subagents.
hooksNoLifecycle hooks scoped to this subagent. Ignored for plugin subagents.
memoryNoPersistent memory scope: user, project, or local. Enables cross-session learning.
backgroundNoSet to true to keep this subagent in the background even when Claude asks to wait for it.
effortNoEffort 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.
isolationNoSet 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:

  1. The per-invocation model parameter
  2. The subagent definition's model frontmatter, where inherit selects the main conversation's model
  3. The CLAUDE_CODE_SUBAGENT_MODEL environment variable, when you set it to a model alias or model ID
  4. 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:

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:

Common patterns from the documentation:

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:

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