Sub-Agents in Claude Code
Status: Production Ready β
Last Updated: 2026-02-02
Source: https://code.claude.com/docs/en/sub-agents
Sub-agents are specialized AI assistants that Claude Code can delegate tasks to. Each sub-agent has its own context window, configurable tools, and custom system prompt.
Why Use Sub-Agents: Context Hygiene
The primary value of sub-agents isn't specializationβit's keeping your main context clean.
Without agent (context bloat):
Main context accumulates:
ββ git status output (50 lines)
ββ npm run build output (200 lines)
ββ tsc --noEmit output (100 lines)
ββ wrangler deploy output (100 lines)
ββ curl health check responses
ββ All reasoning about what to do next
ββ Context: π 500+ lines consumed
With agent (context hygiene):
Main context:
ββ "Deploy to cloudflare"
ββ [agent summary - 30 lines]
ββ Context: π ~50 lines consumed
Agent context (isolated):
ββ All verbose tool outputs
ββ All intermediate reasoning
ββ Discarded after returning summary
The math: A deploy workflow runs ~10 tool calls. That's 500+ lines in main context vs 30-line summary with an agent. Over a session, this compounds dramatically.
When this matters most:
- Repeatable workflows (deploy, migrate, audit, review)
- Verbose tool outputs (build logs, test results, API responses)
- Multi-step operations where only the final result matters
- Long sessions where context pressure builds up
Key insight: Use agents for workflows you repeat, not just for specialization. The context savings compound over time.
Built-in Sub-Agents
Claude Code includes three built-in sub-agents available out of the box:
Explore Agent
Fast, lightweight agent optimized for read-only codebase exploration.
| Property |
Value |
| Model |
Haiku (fast, low-latency) |
| Mode |
Strictly read-only |
| Tools |
Glob, Grep, Read, Bash (read-only: ls, git status, git log, git diff, find, cat, head, tail) |
Thoroughness levels (specify when invoking):
quick - Fast searches, targeted lookups
medium - Balanced speed and thoroughness
very thorough - Comprehensive analysis across multiple locations
When Claude uses it: Searching/understanding codebase without making changes. Findings don't bloat the main conversation.
User: Where are errors from the client handled?
Claude: [Invokes Explore with "medium" thoroughness]
β Returns: src/services/process.ts:712
Plan Agent
Specialized for plan mode research and information gathering.
| Property |
Value |
| Model |
Sonnet |
| Mode |
Read-only research |
| Tools |
Read, Glob, Grep, Bash |
| Invocation |
Automatic in plan mode |
When Claude uses it: In plan mode when researching codebase to create a plan. Prevents infinite nesting (sub-agents cannot spawn sub-agents).
General-Purpose Agent
Capable agent for complex, multi-step tasks requiring both exploration AND action.
| Property |
Value |
| Model |
Sonnet |
| Mode |
Read AND write |
| Tools |
All tools |
| Purpose |
Complex research, multi-step operations, code modifications |
When Claude uses it:
- Task requires both exploration and modification
- Complex reasoning needed to interpret search results
- Multiple strategies may be needed
- Task has multiple dependent steps
Creating Custom Sub-Agents
File Locations
| Type |
Location |
Scope |
Priority |
| Project |
.claude/agents/ |
Current project only |
Highest |
| User |
~/.claude/agents/ |
All projects |
Lower |
| CLI |
--agents '{...}' |
Current session |
Middle |
When names conflict, project-level takes precedence.
β οΈ CRITICAL: Session Restart Required
Agents are loaded at session startup only. If you create new agent files during a session:
- They won't appear in
/agents
- Claude won't be able to invoke them
- Solution: Restart Claude Code session to discover new agents
This is the most common reason custom agents "don't work" - they were created after the session started.
File Format
Markdown files with YAML frontmatter:
---
name: code-reviewer
description: Expert code reviewer. Use proactively after code changes.
tools: Read, Grep, Glob, Bash
model: inherit
permissionMode: default
skills: project-workflow
hooks:
PostToolUse:
- matcher: "Edit|Write"
hooks:
- type: command
command: "./scripts/run-linter.sh"
---
Your sub-agent's system prompt goes here.
Include specific instructions, best practices, and constraints.
Configuration Fields
| Field |
Required |
Description |
name |
Yes |
Unique identifier (lowercase, hyphens) |
description |
Yes |
When Claude should use this agent |
tools |
No |
Comma-separated list. Omit entirely = inherit ALL tools (including MCP) |
model |
No |
sonnet, opus, haiku, or inherit. Default: sonnet |
permissionMode |
No |
default, acceptEdits, dontAsk, bypassPermissions, plan, ignore |
skills |
No |
Comma-separated skills to auto-load (sub-agents don't inherit parent skills) |
hooks |
No |
PreToolUse, PostToolUse, Stop event handlers |
MCP Tool Inheritance (CRITICAL)
To access MCP tools from a sub-agent, you MUST omit the tools field entirely.
When you specify ANY tools in the tools field, it becomes an allowlist. There is no wildcard syntax.
tools: Read, Grep, Glob, "*"
tools: Read, Grep, Glob
model: sonnet
Key insight: The "*" is NOT valid wildcard syntax. When parsed, it's treated as a literal tool name that doesn't exist.
Agent restart required: Changes to agent config files only take effect after restarting Claude Code session.
Available Tools Reference
Complete list of tools that can be assigned to sub-agents:
| Tool |
Purpose |
Type |
| Read |
Read files (text, images, PDFs, notebooks) |
Read-only |
| Write |
Create or overwrite files |
Write |
| Edit |
Exact string replacements in files |
Write |
| MultiEdit |
Batch edits to single file |
Write |
| Glob |
File pattern matching (**/*.ts) |
Read-only |
| Grep |
Content search with regex (ripgrep) |
Read-only |
| LS |
List directory contents |
Read-only |
| Bash |
Execute shell commands |
Execute |
| BashOutput |
Get output from background shells |
Execute |
| KillShell |
Terminate background shell |
Execute |
| Task |
Spawn sub-agents |
Orchestration |
| WebFetch |
Fetch and analyze web content |
Web |
| WebSearch |
Search the web |
Web |
| TodoWrite |
Create/manage task lists |
Organization |
| TodoRead |
Read current task list |
Organization |
| NotebookRead |
Read Jupyter notebooks |
Notebook |
| NotebookEdit |
Edit Jupyter notebook cells |
Notebook |
| AskUserQuestion |
Interactive user questions |
UI |
| EnterPlanMode |
Enter planning mode |
Planning |
| ExitPlanMode |
Exit planning mode with plan |
Planning |
| Skill |
Execute skills in conversation |
Skills |
| LSP |
Language Server Protocol integration |
Advanced |
| MCPSearch |
MCP tool discovery |
Advanced |
Tool Access Patterns by Agent Type:
| Agent Type |
Recommended Tools |
Notes |
| Read-only reviewers |
Read, Grep, Glob, LS |
No write capability |
| File creators |
Read, Write, Edit, Glob, Grep |
β οΈ No Bash - avoids approval spam |
| Script runners |
Read, Write, Edit, Glob, Grep, Bash |
Use when CLI execution needed |
| Research agents |
Read, Grep, Glob, WebFetch, WebSearch |
Read-only external access |
| Documentation |
Read, Write, Edit, Glob, Grep, WebFetch |
No Bash for cleaner workflow |
| Orchestrators |
Read, Grep, Glob, Task |
Minimal tools, delegates to specialists |
| Full access |
Omit tools field (inherits all) |
Use sparingly |
β οΈ Tool Access Principle: If an agent doesn't need Bash, don't give it Bash. Each bash command requires approval, causing workflow interruptions. See "Avoiding Bash Approval Spam" below.
Avoiding Bash Approval Spam (CRITICAL)
When sub-agents have Bash in their tools list, they often default to using cat > file << 'EOF' heredocs for file creation instead of the Write tool. Each unique bash command requires user approval, causing:
- Dozens of approval prompts per agent run
- Slow, frustrating workflow
- Hard to review (heredocs are walls of minified content)
Root Causes:
- Models default to bash for file ops - Training data bias toward shell commands
- Bash in tools list = Bash gets used - Even if Write tool is available
- Instructions get buried - A "don't use bash" rule at line 300 of a 450-line prompt gets ignored
Solutions (in order of preference):
-
Remove Bash from tools list (if not needed):
tools: Read, Write, Edit, Glob, Grep, Bash
tools: Read, Write, Edit, Glob, Grep
If the agent only creates files, it doesn't need Bash. The orchestrator can run necessary scripts after.
-
Put critical instructions FIRST (immediately after frontmatter):
---
name: site-builder
tools: Read, Write, Edit, Glob, Grep
model: sonnet
---
## β CRITICAL: USE WRITE TOOL FOR ALL FILES
**You do NOT have Bash access.** Create ALL files using the **Write tool**.
---
[rest of prompt...]
Instructions at the top get followed. Instructions buried 300 lines deep get ignored.
-
Remove contradictory instructions:
# BAD - contradictory
Line 75: "Copy images with `cp -r intake/images/* build/images/`"
Line 300: "NEVER use cp, mkdir, cat, or echo"
# GOOD - consistent
Only mention the pattern you want used. Remove all bash examples if you want Write tool.
When to keep Bash:
- Agent needs to run external CLIs (wrangler, npm, git)
- Agent needs to execute scripts
- Agent needs to check command outputs
Testing: Before vs after removing Bash:
- Before (with Bash): 11+ heredoc approval prompts, wrong patterns applied
- After (no Bash): Mostly Write tool usage, correct patterns, minimal prompts
Using /agents Command (Recommended)
/agents
Interactive menu to:
- View all sub-agents (built-in, user, project)
- Create new sub-agents with guided setup
- Edit existing sub-agents and tool access
- Delete custom sub-agents
- See which sub-agents are active
CLI Configuration
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer. Use proactively after code changes.",
"prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
"tools": ["Read", "Grep", "Glob", "Bash"],
"model": "sonnet"
}
}'
Using Sub-Agents
Automatic Delegation
Claude proactively delegates based on:
- Task description in your request
description field in sub-agent config
- Current context and available tools
Tip: Include "use PROACTIVELY" or "MUST BE USED" in description for more automatic invocation.
Explicit Invocation
> Use the test-runner subagent to fix failing tests
> Have the code-reviewer subagent look at my recent changes
> Ask the debugger subagent to investigate this error
Resumable Sub-Agents
Sub-agents can be resumed to continue previous conversations:
# Initial invocation
> Use the code-analyzer agent to review the auth module
[Agent completes, returns agentId: "abc123"]
<