hippo: This post is part of the Claude Code Official Docs Breakdown series.


1. What Are Subagents?

Subagents are specialized AI assistants that run independently in their own context window. Think of them as a team of specialists—the main conversation acts as the project manager, while each subagent is a domain expert that works in an isolated workspace and reports back a concise summary once done.

Key characteristics: each subagent has its own system prompt, specific tool access, and independent permission controls. Claude reads your description field to decide automatically when to delegate a task to a given subagent.

Why use subagents instead of doing everything in the main conversation?

  • Preserve context: Operations like exploring a codebase or running tests produce massive intermediate output. Isolating them in a separate context window keeps the main conversation clean.
  • Enforce constraints: Use tools and disallowedTools to restrict capabilities—for example, granting a code reviewer strictly read-only access.
  • Reuse across projects: User-level subagents placed in ~/.claude/agents/ apply across all projects.
  • Specialize behavior: Tailor system prompts to specific domains such as data science or database analysis.
  • Control costs: Route routine tasks to cheaper models (such as Haiku) via the model field.

Built-in Subagents Overview:

Agent Model Tool Restrictions Purpose
Explore Haiku Read-only (denies Write/Edit) Fast read-only codebase exploration with three thoroughness levels: quick, medium, and very thorough
Plan Inherits parent Read-only (denies Write/Edit) Invoked automatically in Plan mode to gather context for planning
General-purpose Inherits parent All Handles complex multi-step tasks
statusline-setup Sonnet When running /statusline Configures the status line
Claude Code Guide Haiku When asked about Claude Code features Answers questions about Claude Code capabilities

2. Official Docs Deep Dive

2.1 Quickstart: The /agents Command

Claude Code provides an interactive /agents command to manage subagents:

  • View all available subagents (built-in, user, project, and plugin)
  • Create a new subagent interactively or let Claude generate one automatically
  • Edit existing subagent configurations and tool access
  • Delete custom subagents
  • Inspect priority overrides when multiple subagents share the same name

You can also run the non-interactive claude agents CLI command to list every subagent grouped by source, with priority overrides highlighted. This is the officially recommended workflow for creating and managing subagents.

2.2 Configuration Format and Tool Controls

File Format

Each subagent is a Markdown file with YAML frontmatter. The frontmatter defines configuration, and the Markdown body serves as the system prompt:

1
2
3
4
5
6
7
8
9
10
11
---
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
memory: project
---

You are a senior code reviewer ensuring high standards.
As you review code, update your agent memory with patterns,
conventions, and recurring issues you discover.

Only name and description are required; every other field is optional. Where you place the file determines its scope and precedence:

Location Scope Priority Notes
Managed settings Organization-wide 1 (Highest) Deployed by organization admins via managed settings
CLI --agents flag Current session 2 JSON format passed at startup
Project .claude/agents/ Current project 3 Recommended for version control and team sharing
User ~/.claude/agents/ All projects 4 Personal configuration shared across projects
Plugin agents/ directory Projects with the plugin enabled 5 (Lowest) Installed alongside the plugin

Three Ways to Control Tools

Subagent tool access can be restricted in three ways, which can also be combined:

**1. tools (Allowlist)**—grant only the tools needed:

1
2
3
4
5
---
name: safe-researcher
description: Read-only research agent
tools: Read, Grep, Glob, Bash
---

This configuration grants only Read, Grep, Glob, and Bash, preventing file edits or writes.

**2. disallowedTools (Denylist)**—inherit all tools while excluding specific ones:

1
2
3
4
5
---
name: no-writes
description: Inherits all tools except file writes
disallowedTools: Write, Edit
---

**3. PreToolUse Hooks (Conditional Rules)**—the finest level of control, evaluating commands dynamically:

1
2
3
4
5
6
7
8
9
10
11
12
13
---
name: db-reader
description: Execute read-only database queries
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
---

You are a database analyst with read-only access.

Even though Bash is enabled here, the hook script inspects each command and permits only SELECT queries—far more granular than simple tool allow/deny lists.

When both tools and disallowedTools are specified, disallowedTools is applied first to strip excluded tools, and tools is then resolved against the remaining pool.

Advanced Configuration Fields

Field Required Description
name Yes Unique identifier using lowercase letters and hyphens
description Yes Natural-language guidance on when Claude should delegate; include phrases like "Use proactively" to clarify trigger conditions
tools No Allowlist; supports Agent(agent_type) syntax to restrict which subagent types can be spawned
disallowedTools No Denylist; applied before tools when both are set
model No Model selection: sonnet/opus/haiku/full model ID/inherit (defaults to inherit)
memory No Persistent memory scope: user/project/local; auto-loads the first 200 lines of MEMORY.md
skills No Injects full Skill contents at startup (subagents do not inherit parent skills and must list them explicitly)
mcpServers No MCP server list supporting inline definitions (scoped to the subagent) and string references (sharing parent connections)
permissionMode No Permission mode: default/acceptEdits/auto/dontAsk/bypassPermissions/plan
maxTurns No Maximum agent turns before the subagent stops
effort No Effort level: low/medium/high/max (max is supported on Opus 4.6 only)
isolation No Set to worktree to run inside a temporary git worktree, automatically cleaned up if no changes are made
background No Set to true to always run in the background
initialPrompt No First user turn submitted automatically when running as the main session agent (--agent)
color No Display color in task lists and transcripts: red/blue/green/yellow/purple/orange/pink/cyan
hooks No Lifecycle hooks scoped to this subagent (PreToolUse/PostToolUse/Stop)

4-tier model resolution priority chain: CLAUDE_CODE_SUBAGENT_MODEL environment variable > per-invocation model parameter > frontmatter model field > main conversation’s model.

permissionMode precedence rules: If the parent session sets bypassPermissions, the subagent cannot override it. If the parent uses auto mode, the subagent inherits auto mode and its permissionMode field is ignored—the classifier evaluates the subagent’s tool calls using the exact same block/allow rules as the parent session.

Three memory scopes:

Scope Storage Location Characteristics
user ~/.claude/agent-memory/<name>/ Global, shared across all projects
project .claude/agent-memory/<name>/ Version-controllable, shared with the team
local .claude/agent-memory-local/<name>/ Excluded from git, personal and local only

When memory is enabled, the subagent automatically receives Read/Write/Edit tools and loads the first 200 lines or 25KB of MEMORY.md (whichever comes first) into its context, along with instructions to curate MEMORY.md as it approaches the limit. This lets a subagent accumulate domain knowledge across sessions. The official docs recommend project scope by default so teams can share it via version control.

Two forms of mcpServers:

1
2
3
4
5
6
7
8
9
10
# Inline definition: scoped to this subagent, connects on start, disconnects on completion
mcpServers:
- playwright:
type: stdio
command: npx
args: ["-y", "@playwright/mcp@latest"]

# String reference: shares an existing MCP connection from the parent session
mcpServers:
- github

Inline definitions fit MCP servers that only a specific subagent needs, avoiding context overhead in the main conversation. String references reuse connections already established by the parent session.

2.3 Invocation, Execution Modes, and Common Patterns

Three Ways to Invoke a Subagent

1. Natural language (Claude decides whether to delegate): Mention the subagent in your prompt, and Claude evaluates its description to decide whether to delegate.

1
Use the test-runner subagent to fix failing tests

2. @-mention (guaranteed execution): Type @ and select the subagent from autocomplete to ensure that specific subagent runs.

1
@"code-reviewer (agent)" look at the auth changes

You can also type it manually: @agent-<name> for a local subagent, or @agent-<plugin-name>:<agent-name> for a plugin subagent. Plugin subagents appear as <plugin-name>:<agent-name> in autocomplete.

3. --agent flag (session-wide replacement): The subagent’s system prompt completely replaces the default Claude Code system prompt, running the entire session inside that subagent’s context.

1
claude --agent code-reviewer

You can also set it as the default in .claude/settings.json:

1
2
3
{
"agent": "code-reviewer"
}

Foreground vs. Background

Capability Foreground Subagent Background Subagent
Execution Blocks the main conversation until completion Runs concurrently without blocking the main conversation
Permission prompts Permission prompts and clarifying questions surface to you Inherits pre-approved permissions; auto-denies unapproved actions
Clarifying questions Can interact with you directly Tool call fails, but the subagent continues
Trigger Default behavior, or ask to “run in foreground” Ask to “run in background”, or set background: true in frontmatter
Switching Press Ctrl+B while running to move to background —

Disable background tasks via environment variable:

1
export CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1

Common Patterns

1. Isolate high-volume operations: Run a test suite inside a dedicated test-runner subagent and return only the summary, keeping verbose test logs out of the main context.

2. Parallel research: Launch multiple subagents simultaneously to explore different modules of a codebase independently, then aggregate their findings.

3. Chaining subagents: Use a coordinator agent to orchestrate multiple specialized subagents across a multi-step workflow:

1
2
3
4
5
---
name: coordinator
description: Coordinates work across specialized agents
tools: Agent(worker, researcher), Read, Bash
---

Here, Agent(worker, researcher) restricts coordinator to spawning only worker and researcher subagents. Bare Agent (without parentheses) allows spawning any subagent type, while omitting Agent from tools altogether prevents spawning any subagents. Note: this restriction only applies to an agent running as the main thread via claude --agent; subagents themselves cannot spawn nested subagents, so Agent(agent_type) has no effect inside a subagent definition.

Hooks Configuration

Subagent hooks operate at two levels:

Frontmatter-level (scoped to a single subagent):

Event Trigger Timing
PreToolUse Before the subagent invokes a tool
PostToolUse After the subagent invokes a tool
Stop When the subagent finishes (automatically converted to SubagentStop)

Project-level settings.json (global):

Event Matcher Trigger Timing
SubagentStart Agent type name When any matching subagent starts
SubagentStop Agent type name When any matching subagent finishes
1
2
3
4
5
6
7
8
9
10
11
12
{
"hooks": {
"SubagentStart": [
{
"matcher": "db-agent",
"hooks": [
{ "type": "command", "command": "./scripts/setup-db-connection.sh" }
]
}
]
}
}

To disable specific subagents, use permissions.deny with Agent(name) in settings.json or pass a CLI flag:

1
2
3
4
5
{
"permissions": {
"deny": ["Agent(Explore)", "Agent(my-custom-agent)"]
}
}
1
claude --disallowedTools "Agent(Explore)"

Subagents vs. Skills vs. /btw

Mechanism Execution Context Tool Access Best For
Subagent Isolated context window Restrictable High-volume output, tool restrictions, cost control
Skills Main conversation context Inherits main session Reusable prompts and workflows in the main context
/btw Reads existing context No tool access Quick side questions about existing context without taking actions

Subagents do not inherit Skills from the parent conversation—you must list them explicitly in frontmatter.

Resumable Subagents

Each invocation creates a new instance with a fresh context. To continue prior work instead of starting over, ask Claude to resume the subagent—it retains the full conversation history and picks up where it left off.

Once a subagent completes, Claude receives its agent ID. Resuming works through the SendMessage tool (requires CLAUDE_CODE_SUBAGENT_MODEL and agent teams enabled) using the agent ID as the to field. When a stopped subagent receives a SendMessage, it resumes automatically in the background without requiring a new Agent call.

Transcripts persist independently of the main conversation: main-conversation compaction does not affect subagents; after a restart, you can continue by resuming the same session; automatic cleanup is governed by cleanupPeriodDays (30 days by default). Transcripts are stored at ~/.claude/projects/{project}/{sessionId}/subagents/agent-{agentId}.jsonl.

Auto-compaction triggers at roughly 95% capacity by default. You can lower this threshold via the CLAUDE_AUTOCOMPACT_PCT_OVERRIDE environment variable (for example, 50). Compaction events are logged in the transcript, with the preTokens field recording token usage prior to compaction.

2.4 Official Examples Walkthrough

Code Reviewer: Read-Only + Structured Output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
---
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
memory: project
---

You are a senior code reviewer ensuring high standards.
As you review code, update your agent memory with patterns,
conventions, and recurring issues you discover.

When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately

Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)

Three design choices stand out here: tools grants only read-only tools (Read/Grep/Glob/Bash) without Edit/Write, so the reviewer cannot modify files; memory: project lets it accumulate codebase patterns and conventions over time; and the prompt enforces structured output across Critical issues, Warnings, and Suggestions.

Debugger: Write Access + End-to-End Workflow

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
---
name: debugger
description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.
tools: Read, Edit, Bash, Grep, Glob
---

You are an expert debugger specializing in root cause analysis.

When invoked:
1. Capture error message and stack trace
2. Identify reproduction steps
3. Isolate the failure location
4. Implement minimal fix
5. Verify solution works

Focus on fixing the underlying issue, not the symptoms.

Compared to code-reviewer, debugger adds the Edit tool so it can actually patch bugs, backed by a complete diagnostic loop: capture → reproduce → isolate → fix → verify.

Data Scientist: Domain-Specific + Model Routing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
---
name: data-scientist
description: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries.
tools: Bash, Read, Write
model: sonnet
---

You are a data scientist specializing in SQL and BigQuery analysis.

When invoked:
1. Understand the data analysis requirement
2. Write efficient SQL queries
3. Use BigQuery command line tools (bq) when appropriate
4. Analyze and summarize results
5. Present findings clearly

Setting model: sonnet routes data analysis tasks to Sonnet—ideal for keeping costs down when maximum reasoning capacity is unnecessary. The updated official prompt also tightens the scope around SQL and BigQuery workflows, emphasizing query efficiency and cost awareness.

Database Query Validator: Conditional Control via Hooks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
---
name: db-reader
description: Execute read-only database queries
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
---

You are a database analyst with read-only access.
Execute SELECT queries to answer questions about the data.

The validation script validate-readonly-query.sh:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/bin/bash
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

if [ -z "$COMMAND" ]; then
exit 0
fi

if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE)\b' > /dev/null; then
echo "Blocked: Write operations not allowed. Use SELECT queries only." >&2
exit 2
fi

exit 0

This goes beyond static tool restrictions: Bash is enabled, but the PreToolUse hook validates every command beforehand and allows only SELECT queries. Neither tools nor disallowedTools can express this—they only control whether Bash is available, whereas hooks control what can run inside Bash.


3. Hippo’s Field Notes

hippo: A few pitfalls and lessons from real-world usage:

Single Responsibility Comes First

When I first started using subagents, I wrote a few “do-it-all” definitions that reviewed code, ran tests, and updated docs all in one agent. Claude constantly struggled to pick the right agent, delegation timing became unpredictable, and output quality drifted.

Splitting them along single responsibilities fixed it immediately: test-runner (tests only), changelog-writer (changelogs only), and code-reviewer (reviews only). The other critical piece is spelling out the trigger explicitly in description—phrases like "Use proactively after code changes" make Claude’s delegation decisions dramatically more reliable.

Accumulating Cross-Session Knowledge with memory

Adding memory: project to code-reviewer lets it record codebase patterns, team conventions, and recurring issues into MEMORY.md on every review. After a few iterations, review quality improves noticeably because it remembers project-specific idioms and anti-patterns.

Use memory for subagents that run repeatedly and benefit from institutional knowledge. Skip it for one-off or stateless tasks like changelog-writer.

Choosing the Right Tool: Main Conversation vs. Subagent vs. Skill

Scenario Choice Why
Quick bug fix Main conversation Needs fast back-and-forth and shared context
Running a full test suite Subagent High-volume output; only the summary matters
Reusable review checklist Skill Runs in the main context with shared tools and state
Recalling earlier discussion /btw No tools needed—just inspecting existing context

Series Navigation


Based on the official Subagents - Claude Code Docs documentation.

Last updated: 2026-04-09