1# Subagents1# Create custom subagents
2 2
3> Create and use specialized AI subagents in Claude Code for task-specific workflows and improved context management.3> Create and use specialized AI subagents in Claude Code for task-specific workflows and improved context management.
4 4
5Custom subagents in Claude Code are specialized AI assistants that can be invoked to handle specific types of tasks. They enable more efficient problem-solving by providing task-specific configurations with customized system prompts, tools and a separate context window.5Subagents are specialized AI assistants that handle specific types of tasks. Each subagent runs in its own context window with a custom system prompt, specific tool access, and independent permissions. When Claude encounters a task that matches a subagent's description, it delegates to that subagent, which works independently and returns results.
6 6
7## What are subagents?7Subagents help you:
8 8
9Subagents are pre-configured AI personalities that Claude Code can delegate tasks to. Each subagent:9* **Preserve context** by keeping exploration and implementation out of your main conversation
10* **Enforce constraints** by limiting which tools a subagent can use
11* **Reuse configurations** across projects with user-level subagents
12* **Specialize behavior** with focused system prompts for specific domains
13* **Control costs** by routing tasks to faster, cheaper models like Haiku
10 14
11* Has a specific purpose and expertise area15Claude uses each subagent's description to decide when to delegate tasks. When you create a subagent, write a clear description so Claude knows when to use it.
12* Uses its own context window separate from the main conversation
13* Can be configured with specific tools it's allowed to use
14* Includes a custom system prompt that guides its behavior
15 16
16When Claude Code encounters a task that matches a subagent's expertise, it can delegate that task to the specialized subagent, which works independently and returns results.17Claude Code includes several built-in subagents like **Explore**, **Plan**, and **general-purpose**. You can also create custom subagents to handle specific tasks. This page covers the [built-in subagents](#built-in-subagents), [how to create your own](#quickstart-create-your-first-subagent), [full configuration options](#configure-subagents), [patterns for working with subagents](#work-with-subagents), and [example subagents](#example-subagents).
17 18
18## Key benefits19## Built-in subagents
20
21Claude Code includes built-in subagents that Claude automatically uses when appropriate. Each inherits the parent conversation's permissions with additional tool restrictions.
22
23<Tabs>
24 <Tab title="Explore">
25 A fast, read-only agent optimized for searching and analyzing codebases.
26
27 * **Model**: Haiku (fast, low-latency)
28 * **Tools**: Read-only tools (denied access to Write and Edit tools)
29 * **Purpose**: File discovery, code search, codebase exploration
30
31 Claude delegates to Explore when it needs to search or understand a codebase without making changes. This keeps exploration results out of your main conversation context.
32
33 When invoking Explore, Claude specifies a thoroughness level: **quick** for targeted lookups, **medium** for balanced exploration, or **very thorough** for comprehensive analysis.
34 </Tab>
35
36 <Tab title="Plan">
37 A research agent used during [plan mode](/en/common-workflows#use-plan-mode-for-safe-code-analysis) to gather context before presenting a plan.
38
39 * **Model**: Inherits from main conversation
40 * **Tools**: Read-only tools (denied access to Write and Edit tools)
41 * **Purpose**: Codebase research for planning
42
43 When you're in plan mode and Claude needs to understand your codebase, it delegates research to the Plan subagent. This prevents infinite nesting (subagents cannot spawn other subagents) while still gathering necessary context.
44 </Tab>
45
46 <Tab title="General-purpose">
47 A capable agent for complex, multi-step tasks that require both exploration and action.
48
49 * **Model**: Inherits from main conversation
50 * **Tools**: All tools
51 * **Purpose**: Complex research, multi-step operations, code modifications
19 52
20<CardGroup cols={2}>53 Claude delegates to general-purpose when the task requires both exploration and modification, complex reasoning to interpret results, or multiple dependent steps.
21 <Card title="Context preservation" icon="layer-group">54 </Tab>
22 Each subagent operates in its own context, preventing pollution of the main conversation and keeping it focused on high-level objectives.
23 </Card>
24 55
25 <Card title="Specialized expertise" icon="brain">56 <Tab title="Other">
26 Subagents can be fine-tuned with detailed instructions for specific domains, leading to higher success rates on designated tasks.57 Claude Code includes additional helper agents for specific tasks. These are typically invoked automatically, so you don't need to use them directly.
27 </Card>
28 58
29 <Card title="Reusability" icon="rotate">59 | Agent | Model | When Claude uses it |
30 Once created, you can use subagents across different projects and share them with your team for consistent workflows.60 | :---------------- | :------- | :------------------------------------------------------- |
31 </Card>61 | Bash | Inherits | Running terminal commands in a separate context |
62 | statusline-setup | Sonnet | When you run `/statusline` to configure your status line |
63 | Claude Code Guide | Haiku | When you ask questions about Claude Code features |
64 </Tab>
65</Tabs>
32 66
33 <Card title="Flexible permissions" icon="shield-check">67Beyond these built-in subagents, you can create your own with custom prompts, tool restrictions, permission modes, hooks, and skills. The following sections show how to get started and customize subagents.
34 Each subagent can have different tool access levels, allowing you to limit powerful tools to specific subagent types.
35 </Card>
36</CardGroup>
37 68
38## Quick start69## Quickstart: create your first subagent
39 70
40To create your first subagent:71Subagents are defined in Markdown files with YAML frontmatter. You can [create them manually](#write-subagent-files) or use the `/agents` slash command.
72
73This walkthrough guides you through creating a user-level subagent with the `/agent` command. The subagent reviews code and suggests improvements for the codebase.
41 74
42<Steps>75<Steps>
43 <Step title="Open the subagents interface">76 <Step title="Open the subagents interface">
44 Run the following command:77 In Claude Code, run:
45 78
46 ```79 ```
47 /agents80 /agents
48 ```81 ```
49 </Step>82 </Step>
50 83
51 <Step title="Select 'Create New Agent'">84 <Step title="Create a new user-level agent">
52 Choose whether to create a project-level or user-level subagent85 Select **Create new agent**, then choose **User-level**. This saves the subagent to `~/.claude/agents/` so it's available in all your projects.
86 </Step>
87
88 <Step title="Generate with Claude">
89 Select **Generate with Claude**. When prompted, describe the subagent:
90
91 ```
92 A code improvement agent that scans files and suggests improvements
93 for readability, performance, and best practices. It should explain
94 each issue, show the current code, and provide an improved version.
95 ```
96
97 Claude generates the system prompt and configuration. Press `e` to open it in your editor if you want to customize it.
98 </Step>
99
100 <Step title="Select tools">
101 For a read-only reviewer, deselect everything except **Read-only tools**. If you keep all tools selected, the subagent inherits all tools available to the main conversation.
102 </Step>
103
104 <Step title="Select model">
105 Choose which model the subagent uses. For this example agent, select **Sonnet**, which balances capability and speed for analyzing code patterns.
53 </Step>106 </Step>
54 107
55 <Step title="Define the subagent">108 <Step title="Choose a color">
56 * **Recommended**: generate with Claude first, then customize to make it yours109 Pick a background color for the subagent. This helps you identify which subagent is running in the UI.
57 * Describe your subagent in detail, including when Claude should use it
58 * Select the tools you want to grant access to, or leave this blank to inherit all tools
59 * The interface shows all available tools
60 * If you're generating with Claude, you can also edit the system prompt in your own editor by pressing `e`
61 </Step>110 </Step>
62 111
63 <Step title="Save and use">112 <Step title="Save and try it out">
64 Your subagent is now available. Claude uses it automatically when appropriate, or you can invoke it explicitly:113 Save the subagent. It's available immediately (no restart needed). Try it:
65 114
66 ```115 ```
67 > Use the code-reviewer subagent to check my recent changes116 Use the code-improver agent to suggest improvements in this project
68 ```117 ```
118
119 Claude delegates to your new subagent, which scans the codebase and returns improvement suggestions.
69 </Step>120 </Step>
70</Steps>121</Steps>
71 122
72## Subagent configuration123You now have a subagent you can use in any project on your machine to analyze codebases and suggest improvements.
73 124
74### File locations125You can also create subagents manually as Markdown files, define them via CLI flags, or distribute them through plugins. The following sections cover all configuration options.
75 126
76Subagents are stored as Markdown files with YAML frontmatter in two possible locations:127## Configure subagents
77 128
78| Type | Location | Scope | Priority |129### Use the /agents command
79| :-------------------- | :------------------ | :---------------------------- | :------- |
80| **Project subagents** | `.claude/agents/` | Available in current project | Highest |
81| **User subagents** | `~/.claude/agents/` | Available across all projects | Lower |
82 130
83When subagent names conflict, project-level subagents take precedence over user-level subagents.131The `/agents` command provides an interactive interface for managing subagents. Run `/agents` to:
84 132
85### Plugin agents133* View all available subagents (built-in, user, project, and plugin)
134* Create new subagents with guided setup or Claude generation
135* Edit existing subagent configuration and tool access
136* Delete custom subagents
137* See which subagents are active when duplicates exist
86 138
87[Plugins](/en/plugins) can provide custom subagents that integrate seamlessly with Claude Code. Plugin agents work identically to user-defined agents and appear in the `/agents` interface.139This is the recommended way to create and manage subagents. For manual creation or automation, you can also add subagent files directly.
88 140
89**Plugin agent locations**: plugins include agents in their `agents/` directory (or custom paths specified in the plugin manifest).141### Choose the subagent scope
90 142
91**Using plugin agents**:143Subagents are Markdown files with YAML frontmatter. Store them in different locations depending on scope. When multiple subagents share the same name, the higher-priority location wins.
92 144
93* Plugin agents appear in `/agents` alongside your custom agents145| Location | Scope | Priority | How to create |
94* Can be invoked explicitly: "Use the code-reviewer agent from the security-plugin"146| :--------------------------- | :---------------------- | :---------- | :------------------------------------ |
95* Can be invoked automatically by Claude when appropriate147| `--agents` CLI flag | Current session | 1 (highest) | Pass JSON when launching Claude Code |
96* Can be managed (viewed, inspected) through `/agents` interface148| `.claude/agents/` | Current project | 2 | Interactive or manual |
149| `~/.claude/agents/` | All your projects | 3 | Interactive or manual |
150| Plugin's `agents/` directory | Where plugin is enabled | 4 (lowest) | Installed with [plugins](/en/plugins) |
97 151
98See the [plugin components reference](/en/plugins-reference#agents) for details on creating plugin agents.152**Project subagents** (`.claude/agents/`) are ideal for subagents specific to a codebase. Check them into version control so your team can use and improve them collaboratively.
99 153
100### CLI-based configuration154**User subagents** (`~/.claude/agents/`) are personal subagents available in all your projects.
101 155
102You can also define subagents dynamically using the `--agents` CLI flag, which accepts a JSON object:156**CLI-defined subagents** are passed as JSON when launching Claude Code. They exist only for that session and aren't saved to disk, making them useful for quick testing or automation scripts:
103 157
104```bash theme={null}158```bash theme={null}
105claude --agents '{159claude --agents '{
112}'166}'
113```167```
114 168
115**Priority**: CLI-defined subagents have lower priority than project-level subagents but higher priority than user-level subagents.169The `--agents` flag accepts JSON with the same fields as [frontmatter](#supported-frontmatter-fields). Use `prompt` for the system prompt (equivalent to the markdown body in file-based subagents). See the [CLI reference](/en/cli-reference#agents-flag-format) for the full JSON format.
116 170
117**Use case**: This approach is useful for:171**Plugin subagents** come from [plugins](/en/plugins) you've installed. They appear in `/agents` alongside your custom subagents. See the [plugin components reference](/en/plugins-reference#agents) for details on creating plugin subagents.
118 172
119* Quick testing of subagent configurations173### Write subagent files
120* Session-specific subagents that don't need to be saved
121* Automation scripts that need custom subagents
122* Sharing subagent definitions in documentation or scripts
123 174
124For detailed information about the JSON format and all available options, see the [CLI reference documentation](/en/cli-reference#agents-flag-format).175Subagent files use YAML frontmatter for configuration, followed by the system prompt in Markdown:
125 176
126### File format177<Note>
127 178 Subagents are loaded at session start. If you create a subagent by manually adding a file, restart your session or use `/agents` to load it immediately.
128Each subagent is defined in a Markdown file with this structure:179</Note>
129 180
130```markdown theme={null}181```markdown theme={null}
131---182---
132name: your-sub-agent-name183name: code-reviewer
133description: Description of when this subagent should be invoked184description: Reviews code for quality and best practices
134tools: tool1, tool2, tool3 # Optional - inherits all tools if omitted185tools: Read, Glob, Grep
135model: sonnet # Optional - specify model alias or 'inherit'186model: sonnet
136permissionMode: default # Optional - permission mode for the subagent
137skills: skill1, skill2 # Optional - skills to auto-load
138---187---
139 188
140Your subagent's system prompt goes here. This can be multiple paragraphs189You are a code reviewer. When invoked, analyze the code and provide
141and should clearly define the subagent's role, capabilities, and approach190specific, actionable feedback on quality, security, and best practices.
142to solving problems.
143
144Include specific instructions, best practices, and any constraints
145the subagent should follow.
146```191```
147 192
148#### Configuration fields193The frontmatter defines the subagent's metadata and configuration. The body becomes the system prompt that guides the subagent's behavior. Subagents receive only this system prompt (plus basic environment details like working directory), not the full Claude Code system prompt.
194
195#### Supported frontmatter fields
196
197The following fields can be used in the YAML frontmatter. Only `name` and `description` are required.
149 198
150| Field | Required | Description |199| Field | Required | Description |
151| :--------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |200| :---------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
152| `name` | Yes | Unique identifier using lowercase letters and hyphens |201| `name` | Yes | Unique identifier using lowercase letters and hyphens |
153| `description` | Yes | Natural language description of the subagent's purpose |202| `description` | Yes | When Claude should delegate to this subagent |
154| `tools` | No | Comma-separated list of specific tools. If omitted, inherits all tools from the main thread |203| `tools` | No | [Tools](#available-tools) the subagent can use. Inherits all tools if omitted |
155| `model` | No | Model to use for this subagent. Can be a model alias (`sonnet`, `opus`, `haiku`) or `'inherit'` to use the main conversation's model. If omitted, defaults to the [configured subagent model](/en/model-config) |204| `disallowedTools` | No | Tools to deny, removed from inherited or specified list |
156| `permissionMode` | No | Permission mode for the subagent. Valid values: `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, `plan`, `ignore`. Controls how the subagent handles permission requests |205| `model` | No | [Model](#choose-a-model) to use: `sonnet`, `opus`, `haiku`, or `inherit`. Defaults to `sonnet` |
157| `skills` | No | Comma-separated list of skill names to auto-load when the subagent starts. Subagents do not inherit Skills from the parent conversation. If omitted, no Skills are preloaded. |206| `permissionMode` | No | [Permission mode](#permission-modes): `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, or `plan` |
158| `hooks` | No | Define hooks scoped to this subagent's lifecycle. Supports `PreToolUse`, `PostToolUse`, and `Stop` events. See [Define hooks for subagents](#define-hooks-for-subagents). |207| `skills` | No | [Skills](/en/skills) to load into the subagent's context at startup. The full skill content is injected, not just made available for invocation. Subagents don't inherit skills from the parent conversation |
208| `hooks` | No | [Lifecycle hooks](#define-hooks-for-subagents) scoped to this subagent |
159 209
160### Model selection210### Choose a model
161 211
162The `model` field allows you to control which [AI model](/en/model-config) the subagent uses:212The `model` field controls which [AI model](/en/model-config) the subagent uses:
163 213
164* **Model alias**: Use one of the available aliases: `sonnet`, `opus`, or `haiku`214* **Model alias**: Use one of the available aliases: `sonnet`, `opus`, or `haiku`
165* **`'inherit'`**: Use the same model as the main conversation (useful for consistency)215* **inherit**: Use the same model as the main conversation (useful for consistency)
166* **Omitted**: If not specified, uses the default model configured for subagents (`sonnet`)216* **Omitted**: If not specified, uses the default model configured for subagents (`sonnet`)
167 217
168<Note>218### Control subagent capabilities
169 Using `'inherit'` is particularly useful when you want your subagents to adapt to the model choice of the main conversation, ensuring consistent capabilities and response style throughout your session.
170</Note>
171 219
172### Available tools220You can control what subagents can do through tool access, permission modes, and conditional rules.
173 221
174Subagents can be granted access to any of Claude Code's internal tools. See the [tools documentation](/en/settings#tools-available-to-claude) for a complete list of available tools.222#### Available tools
175 223
176<Tip>224Subagents can use any of Claude Code's [internal tools](/en/settings#tools-available-to-claude). By default, subagents inherit all tools from the main conversation, including MCP tools.
177 **Recommended:** Use the `/agents` command to modify tool access - it provides an interactive interface that lists all available tools, including any connected MCP server tools, making it easier to select the ones you need.
178</Tip>
179 225
180You have two options for configuring tools:226To restrict tools, use the `tools` field (allowlist) or `disallowedTools` field (denylist):
181 227
182* **Omit the `tools` field** to inherit all tools from the main thread (default), including MCP tools228```yaml theme={null}
183* **Specify individual tools** as a comma-separated list for more granular control (can be edited manually or via `/agents`)229---
230name: safe-researcher
231description: Research agent with restricted capabilities
232tools: Read, Grep, Glob, Bash
233disallowedTools: Write, Edit
234---
235```
184 236
185**MCP Tools**: Subagents can access MCP tools from configured MCP servers. When the `tools` field is omitted, subagents inherit all MCP tools available to the main thread.237#### Permission modes
186 238
187### Define hooks for subagents239The `permissionMode` field controls how the subagent handles permission prompts. Subagents inherit the permission context from the main conversation but can override the mode.
240
241| Mode | Behavior |
242| :------------------ | :----------------------------------------------------------------- |
243| `default` | Standard permission checking with prompts |
244| `acceptEdits` | Auto-accept file edits |
245| `dontAsk` | Auto-deny permission prompts (explicitly allowed tools still work) |
246| `bypassPermissions` | Skip all permission checks |
247| `plan` | Plan mode (read-only exploration) |
188 248
189Subagents can define hooks that run during the subagent's lifecycle. Use the `hooks` field to specify `PreToolUse`, `PostToolUse`, or `Stop` handlers:249<Warning>
250 Use `bypassPermissions` with caution. It skips all permission checks, allowing the subagent to execute any operation without approval.
251</Warning>
252
253If the parent uses `bypassPermissions`, this takes precedence and cannot be overridden.
254
255#### Conditional rules with hooks
256
257For more dynamic control over tool usage, use `PreToolUse` hooks to validate operations before they execute. This is useful when you need to allow some operations of a tool while blocking others.
258
259This example creates a subagent that only allows read-only database queries by validating commands before execution:
190 260
191```yaml theme={null}261```yaml theme={null}
192---262---
193name: code-reviewer263name: db-reader
194description: Review code changes with automatic linting264description: Execute read-only database queries
265tools: Bash
195hooks:266hooks:
196 PostToolUse:267 PreToolUse:
197 - matcher: "Edit|Write"268 - matcher: "Bash"
198 hooks:269 hooks:
199 - type: command270 - type: command
200 command: "./scripts/run-linter.sh"271 command: "./scripts/validate-readonly-query.sh"
201---272---
202```273```
203 274
204Hooks defined in a subagent are scoped to that subagent's execution and are automatically cleaned up when the subagent finishes.275The validation script inspects `$TOOL_INPUT` and exits with a non-zero code to block write operations. See [Define hooks for subagents](#define-hooks-for-subagents) for more hook configuration options.
205 276
206See [Hooks](/en/hooks) for the complete hook configuration format.277#### Disable specific subagents
207 278
208## Managing subagents279You can prevent Claude from using specific subagents by adding them to the `deny` array in your [settings](/en/settings#permission-settings). Use the format `Task(subagent-name)` where `subagent-name` matches the subagent's name field.
209 280
210### Using the /agents command (Recommended)281```json theme={null}
282{
283 "permissions": {
284 "deny": ["Task(Explore)", "Task(my-custom-agent)"]
285 }
286}
287```
211 288
212The `/agents` command provides a comprehensive interface for subagent management:289This works for both built-in and custom subagents. You can also use the `--disallowedTools` CLI flag:
213 290
214```291```bash theme={null}
215/agents292claude --disallowedTools "Task(Explore)"
216```293```
217 294
218This opens an interactive menu where you can:295See [IAM documentation](/en/iam#tool-specific-permission-rules) for more details on permission rules.
219 296
220* View all available subagents (built-in, user, and project)297### Define hooks for subagents
221* Create new subagents with guided setup
222* Edit existing custom subagents, including their tool access
223* Delete custom subagents
224* See which subagents are active when duplicates exist
225* **Manage tool permissions** with a complete list of available tools
226 298
227### Direct file management299Subagents can define [hooks](/en/hooks) that run during the subagent's lifecycle. There are two ways to configure hooks:
228 300
229You can also manage subagents by working directly with their files:3011. **In the subagent's frontmatter**: Define hooks that run only while that subagent is active
3022. **In `settings.json`**: Define hooks that run in the main session when subagents start or stop
230 303
231```bash theme={null}304#### Hooks in subagent frontmatter
232# Create a project subagent
233mkdir -p .claude/agents
234echo '---
235name: test-runner
236description: Use proactively to run tests and fix failures
237 305
238You are a test automation expert. When you see code changes, proactively run the appropriate tests. If tests fail, analyze the failures and fix them while preserving the original test intent.' > .claude/agents/test-runner.md306Define hooks directly in the subagent's markdown file. These hooks only run while that specific subagent is active and are cleaned up when it finishes.
239 307
240# Create a user subagent308| Event | Matcher input | When it fires |
241mkdir -p ~/.claude/agents309| :------------ | :------------ | :------------------------------ |
242# ... create subagent file310| `PreToolUse` | Tool name | Before the subagent uses a tool |
311| `PostToolUse` | Tool name | After the subagent uses a tool |
312| `Stop` | (none) | When the subagent finishes |
313
314This example validates Bash commands with the `PreToolUse` hook and runs a linter after file edits with `PostToolUse`:
315
316```yaml theme={null}
317---
318name: code-reviewer
319description: Review code changes with automatic linting
320hooks:
321 PreToolUse:
322 - matcher: "Bash"
323 hooks:
324 - type: command
325 command: "./scripts/validate-command.sh $TOOL_INPUT"
326 PostToolUse:
327 - matcher: "Edit|Write"
328 hooks:
329 - type: command
330 command: "./scripts/run-linter.sh"
331---
243```332```
244 333
245<Note>334`Stop` hooks in frontmatter are automatically converted to `SubagentStop` events.
246 Subagents created by manually adding files will be loaded the next time you start a Claude Code session. To create and use a subagent immediately without restarting, use the `/agents` command instead.335
247</Note>336#### Project-level hooks for subagent events
248 337
249### Disabling specific subagents338Configure hooks in `settings.json` that respond to subagent lifecycle events in the main session. Use the `matcher` field to target specific agent types by name.
250 339
251You can disable specific built-in or custom subagents using the `Task(AgentName)` permission rule syntax. Add these rules to the `deny` array in your [settings](/en/settings#permission-settings) or use the `--disallowedTools` CLI flag.340| Event | Matcher input | When it fires |
341| :-------------- | :-------------- | :------------------------------- |
342| `SubagentStart` | Agent type name | When a subagent begins execution |
343| `SubagentStop` | Agent type name | When a subagent completes |
252 344
253**Example settings.json configuration:**345This example runs setup and cleanup scripts only when the `db-agent` subagent starts and stops:
254 346
255```json theme={null}347```json theme={null}
256{348{
257 "permissions": {349 "hooks": {
258 "deny": ["Task(Explore)", "Task(Plan)"]350 "SubagentStart": [
351 {
352 "matcher": "db-agent",
353 "hooks": [
354 { "type": "command", "command": "./scripts/setup-db-connection.sh" }
355 ]
356 }
357 ],
358 "SubagentStop": [
359 {
360 "matcher": "db-agent",
361 "hooks": [
362 { "type": "command", "command": "./scripts/cleanup-db-connection.sh" }
363 ]
364 }
365 ]
259 }366 }
260}367}
261```368```
262 369
263**Example CLI usage:**370See [Hooks](/en/hooks) for the complete hook configuration format.
264 371
265```bash theme={null}372## Work with subagents
266claude --disallowedTools "Task(Explore)"
267```
268 373
269This is useful when you want to prevent Claude from delegating tasks to specific subagents, either for security reasons or to enforce a particular workflow.374### Understand automatic delegation
270 375
271See [IAM documentation](/en/iam#tool-specific-permission-rules) for more details on permission rules.376Claude 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.
272 377
273## Using subagents effectively378You can also request a specific subagent explicitly:
274 379
275### Automatic delegation380```
381Use the test-runner subagent to fix failing tests
382Have the code-reviewer subagent look at my recent changes
383```
276 384
277Claude Code proactively delegates tasks based on:385### Run subagents in foreground or background
278 386
279* The task description in your request387Subagents can run in the foreground (blocking) or background (concurrent):
280* The `description` field in subagent configurations
281* Current context and available tools
282 388
283<Tip>389* **Foreground subagents** block the main conversation until complete. Permission prompts and clarifying questions (like [`AskUserQuestion`](/en/settings#tools-available-to-claude)) are passed through to you.
284 To encourage more proactive subagent use, include phrases like "use PROACTIVELY" or "MUST BE USED" in your `description` field.390* **Background subagents** run concurrently while you continue working. They inherit the parent's permissions and auto-deny anything not pre-approved. If a background subagent needs a permission it doesn't have or needs to ask clarifying questions, that tool call fails but the subagent continues. MCP tools are not available in background subagents.
285</Tip>
286 391
287### Explicit invocation392If a background subagent fails due to missing permissions, you can [resume it](#resume-subagents) in the foreground to retry with interactive prompts.
288 393
289Request a specific subagent by mentioning it in your command:394Claude decides whether to run subagents in the foreground or background based on the task. You can also:
290 395
291```396* Ask Claude to "run this in the background"
292> Use the test-runner subagent to fix failing tests397* Press **Ctrl+B** to background a running task
293> Have the code-reviewer subagent look at my recent changes
294> Ask the debugger subagent to investigate this error
295```
296 398
297## Built-in subagents399### Common patterns
298 400
299Claude Code includes built-in subagents that are available out of the box:401#### Isolate high-volume operations
300 402
301### General-purpose subagent403One of the most effective uses for subagents is isolating operations that produce large amounts of output. Running tests, fetching documentation, or processing log files can consume significant context. By delegating these to a subagent, the verbose output stays in the subagent's context while only the relevant summary returns to your main conversation.
302 404
303The general-purpose subagent is a capable agent for complex, multi-step tasks that require both exploration and action. Unlike the Explore subagent, it can modify files and execute a wider range of operations.405```
406Use a subagent to run the test suite and report only the failing tests with their error messages
407```
304 408
305**Key characteristics:**409#### Run parallel research
306 410
307* **Model**: Uses Sonnet for more capable reasoning411For independent investigations, spawn multiple subagents to work simultaneously:
308* **Tools**: Has access to all tools
309* **Mode**: Can read and write files, execute commands, make changes
310* **Purpose**: Complex research tasks, multi-step operations, code modifications
311 412
312**When Claude uses it:**413```
414Research the authentication, database, and API modules in parallel using separate subagents
415```
313 416
314Claude delegates to the general-purpose subagent when:417Each subagent explores its area independently, then Claude synthesizes the findings. This works best when the research paths don't depend on each other.
315 418
316* The task requires both exploration and modification419<Warning>
317* Complex reasoning is needed to interpret search results420 When subagents complete, their results return to your main conversation. Running many subagents that each return detailed results can consume significant context.
318* Multiple strategies may be needed if initial searches fail421</Warning>
319* The task has multiple steps that depend on each other
320 422
321**Example scenario:**423#### Chain subagents
322 424
323```425For multi-step workflows, ask Claude to use subagents in sequence. Each subagent completes its task and returns results to Claude, which then passes relevant context to the next subagent.
324User: Find all the places where we handle authentication and update them to use the new token format
325 426
326Claude: [Invokes general-purpose subagent]427```
327[Agent searches for auth-related code across codebase]428Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them
328[Agent reads and analyzes multiple files]
329[Agent makes necessary edits]
330[Returns detailed writeup of changes made]
331```429```
332 430
333### Plan subagent431### Choose between subagents and main conversation
334 432
335The Plan subagent is a specialized built-in agent designed for use during plan mode. When Claude is operating in plan mode (non-execution mode), it uses the Plan subagent to conduct research and gather information about your codebase before presenting a plan.433Use the **main conversation** when:
336 434
337**Key characteristics:**435* The task needs frequent back-and-forth or iterative refinement
436* Multiple phases share significant context (planning → implementation → testing)
437* You're making a quick, targeted change
438* Latency matters. Subagents start fresh and may need time to gather context
338 439
339* **Model**: Uses Sonnet for more capable analysis440Use **subagents** when:
340* **Tools**: Has access to Read, Glob, Grep, and Bash tools for codebase exploration
341* **Purpose**: Searches files, analyzes code structure, and gathers context
342* **Automatic invocation**: Claude automatically uses this agent when in plan mode and needs to research the codebase
343 441
344**How it works:**442* The task produces verbose output you don't need in your main context
345When you're in plan mode and Claude needs to understand your codebase to create a plan, it delegates research tasks to the Plan subagent. This prevents infinite nesting of agents (subagents cannot spawn other subagents) while still allowing Claude to gather the necessary context.443* You want to enforce specific tool restrictions or permissions
444* The work is self-contained and can return a summary
346 445
347**Example scenario:**446Consider [Skills](/en/skills) instead when you want reusable prompts or workflows that run in the main conversation context rather than isolated subagent context.
348 447
349```448<Note>
350User: [In plan mode] Help me refactor the authentication module449 Subagents cannot spawn other subagents. If your workflow requires nested delegation, use [Skills](/en/skills) or [chain subagents](#chain-subagents) from the main conversation.
450</Note>
351 451
352Claude: Let me research your authentication implementation first...452### Manage subagent context
353[Internally invokes Plan subagent to explore auth-related files]
354[Plan subagent searches codebase and returns findings]
355Claude: Based on my research, here's my proposed plan...
356```
357 453
358<Tip>454#### Resume subagents
359 The Plan subagent is only used in plan mode. In normal execution mode, Claude uses the general-purpose agent or other custom subagents you've created.
360</Tip>
361 455
362### Explore subagent456Each subagent invocation creates a new instance with fresh context. To continue an existing subagent's work instead of starting over, ask Claude to resume it.
363 457
364The Explore subagent is a fast, lightweight agent optimized for searching and analyzing codebases. It operates in strict read-only mode and is designed for rapid file discovery and code exploration.458Resumed subagents retain their full conversation history, including all previous tool calls, results, and reasoning. The subagent picks up exactly where it stopped rather than starting fresh.
365 459
366**Key characteristics:**460When a subagent completes, Claude receives its agent ID. To resume a subagent, ask Claude to continue the previous work:
367 461
368* **Model**: Uses Haiku for fast, low-latency searches462```
369* **Mode**: Strictly read-only - cannot create, modify, or delete files463Use the code-reviewer subagent to review the authentication module
370* **Tools available**:464[Agent completes]
371 * Glob - File pattern matching
372 * Grep - Content searching with regular expressions
373 * Read - Reading file contents
374 * Bash - Read-only commands only (ls, git status, git log, git diff, find, cat, head, tail)
375 465
376**When Claude uses it:**466Continue that code review and now analyze the authorization logic
467[Claude resumes the subagent with full context from previous conversation]
468```
377 469
378Claude will delegate to the Explore subagent when it needs to search or understand a codebase but doesn't need to make changes. This is more efficient than the main agent running multiple search commands directly, as content found during the exploration process doesn't bloat the main conversation.470You can also ask Claude for the agent ID if you want to reference it explicitly, or find IDs in the transcript files at `~/.claude/projects/{project}/{sessionId}/subagents/`. Each transcript is stored as `agent-{agentId}.jsonl`.
379 471
380**Thoroughness levels:**472For programmatic usage, see [Subagents in the Agent SDK](/en/agent-sdk/subagents).
381 473
382When invoking the Explore subagent, Claude specifies a thoroughness level:474Subagent transcripts persist independently of the main conversation:
383 475
384* **Quick** - Fast searches with minimal exploration. Good for targeted lookups.476* **Main conversation compaction**: When the main conversation compacts, subagent transcripts are unaffected. They're stored in separate files.
385* **Medium** - Moderate exploration. Balances speed and thoroughness.477* **Session persistence**: Subagent transcripts persist within their session. You can [resume a subagent](#resume-subagents) after restarting Claude Code by resuming the same session.
386* **Very thorough** - Comprehensive analysis across multiple locations and naming conventions. Used when the target might be in unexpected places.478* **Automatic cleanup**: Transcripts are cleaned up based on the `cleanupPeriodDays` setting (default: 30 days).
387 479
388**Example scenarios:**480#### Auto-compaction
389 481
390```482Subagents support automatic compaction using the same logic as the main conversation. When a subagent's context approaches its limit, Claude Code summarizes older messages to free up space while preserving important context.
391User: Where are errors from the client handled?
392 483
393Claude: [Invokes Explore subagent with "medium" thoroughness]484Compaction events are logged in subagent transcript files:
394[Explore uses Grep to search for error handling patterns]
395[Explore uses Read to examine promising files]
396[Returns findings with absolute file paths]
397Claude: Client errors are handled in src/services/process.ts:712...
398```
399 485
486```json theme={null}
487{
488 "type": "system",
489 "subtype": "compact_boundary",
490 "compactMetadata": {
491 "trigger": "auto",
492 "preTokens": 167189
493 }
494}
400```495```
401User: What's the codebase structure?
402 496
403Claude: [Invokes Explore subagent with "quick" thoroughness]497The `preTokens` value shows how many tokens were used before compaction occurred.
404[Explore uses Glob and ls to map directory structure]
405[Returns overview of key directories and their purposes]
406```
407 498
408## Example subagents499## Example subagents
409 500
501These examples demonstrate effective patterns for building subagents. Use them as starting points, or generate a customized version with Claude.
502
503<Tip>
504 **Best practices:**
505
506 * **Design focused subagents:** each subagent should excel at one specific task
507 * **Write detailed descriptions:** Claude uses the description to decide when to delegate
508 * **Limit tool access:** grant only necessary permissions for security and focus
509 * **Check into version control:** share project subagents with your team
510</Tip>
511
410### Code reviewer512### Code reviewer
411 513
514A read-only subagent that reviews code without modifying it. This example shows how to design a focused subagent with limited tool access (no Edit or Write) and a detailed prompt that specifies exactly what to look for and how to format output.
515
412```markdown theme={null}516```markdown theme={null}
413---517---
414name: code-reviewer518name: code-reviewer
445 548
446### Debugger549### Debugger
447 550
551A subagent that can both analyze and fix issues. Unlike the code reviewer, this one includes Edit because fixing bugs requires modifying code. The prompt provides a clear workflow from diagnosis to verification.
552
448```markdown theme={null}553```markdown theme={null}
449---554---
450name: debugger555name: debugger
480 585
481### Data scientist586### Data scientist
482 587
588A domain-specific subagent for data analysis work. This example shows how to create subagents for specialized workflows outside of typical coding tasks. It explicitly sets `model: sonnet` for more capable analysis.
589
483```markdown theme={null}590```markdown theme={null}
484---591---
485name: data-scientist592name: data-scientist
513Always ensure queries are efficient and cost-effective.620Always ensure queries are efficient and cost-effective.
514```621```
515 622
516## Best practices623## Next steps
517
518* **Start with Claude-generated agents**: We highly recommend generating your initial subagent with Claude and then iterating on it to make it personally yours. This approach gives you the best results - a solid foundation that you can customize to your specific needs.
519
520* **Design focused subagents**: Create subagents with single, clear responsibilities rather than trying to make one subagent do everything. This improves performance and makes subagents more predictable.
521
522* **Write detailed prompts**: Include specific instructions, examples, and constraints in your system prompts. The more guidance you provide, the better the subagent will perform.
523
524* **Limit tool access**: Only grant tools that are necessary for the subagent's purpose. This improves security and helps the subagent focus on relevant actions.
525
526* **Version control**: Check project subagents into version control so your team can benefit from and improve them collaboratively.
527
528## Advanced usage
529
530### Chaining subagents
531
532For complex workflows, you can chain multiple subagents:
533
534```
535> First use the code-analyzer subagent to find performance issues, then use the optimizer subagent to fix them
536```
537
538### Dynamic subagent selection
539
540Claude Code intelligently selects subagents based on context. Make your `description` fields specific and action-oriented for best results.
541
542### Resumable subagents
543
544Subagents can be resumed to continue previous conversations, which is particularly useful for long-running research or analysis tasks that need to be continued across multiple invocations.
545
546**How it works:**
547
548* Each subagent execution is assigned a unique `agentId`
549* The agent's conversation is stored in a separate transcript file: `agent-{agentId}.jsonl`
550* You can resume a previous agent by providing its `agentId` via the `resume` parameter
551* When resumed, the agent continues with full context from its previous conversation
552
553**Example workflow:**
554
555Initial invocation:
556
557```
558> Use the code-analyzer agent to start reviewing the authentication module
559
560[Agent completes initial analysis and returns agentId: "abc123"]
561```
562
563Resume the agent:
564
565```
566> Resume agent abc123 and now analyze the authorization logic as well
567
568[Agent continues with full context from previous conversation]
569```
570
571**Use cases:**
572
573* **Long-running research**: Break down large codebase analysis into multiple sessions
574* **Iterative refinement**: Continue refining a subagent's work without losing context
575* **Multi-step workflows**: Have a subagent work on related tasks sequentially while maintaining context
576
577**Technical details:**
578
579* Agent transcripts are stored in your project directory
580* Recording is disabled during resume to avoid duplicating messages
581* Both synchronous and asynchronous agents can be resumed
582* The `resume` parameter accepts the agent ID from a previous execution
583
584**Programmatic usage:**
585
586If you're using the Agent SDK or interacting with the AgentTool directly, you can pass the `resume` parameter:
587
588```typescript theme={null}
589{
590 "description": "Continue analysis",
591 "prompt": "Now examine the error handling patterns",
592 "subagent_type": "code-analyzer",
593 "resume": "abc123" // Agent ID from previous execution
594}
595```
596
597<Tip>
598 Keep track of agent IDs for tasks you may want to resume later. Claude Code displays the agent ID when a subagent completes its work.
599</Tip>
600
601## Performance considerations
602
603* **Context efficiency**: Agents help preserve main context, enabling longer overall sessions
604* **Latency**: Subagents start off with a clean slate each time they are invoked and may add latency as they gather context that they require to do their job effectively.
605 624
606## Related documentation625Now that you understand subagents, explore these related features:
607 626
608* [Plugins](/en/plugins) - Extend Claude Code with custom agents through plugins627* [Distribute subagents with plugins](/en/plugins) to share subagents across teams or projects
609* [Slash commands](/en/slash-commands) - Learn about other built-in commands628* [Run Claude Code programmatically](/en/headless) with the Agent SDK for CI/CD and automation
610* [Settings](/en/settings) - Configure Claude Code behavior629* [Use MCP servers](/en/mcp) to give subagents access to external tools and data
611* [Hooks](/en/hooks) - Automate workflows with event handlers
612 630
613 631
614---632---