Spawn isolated Claude instances for focused tasks with controlled capabilities
Subagents are isolated Claude Code instances that run within your session. They get their own context window, complete a task, and return results to the main session.
Think of them as delegating a focused task to a junior developer — they do the work in their own space and report back.
| Agent | Purpose |
|---|---|
| Explore | Codebase exploration and analysis (read-only) |
| Plan | Planning and architecture (read-only) |
| General | Custom tasks with full capabilities |
✅ Focused tasks where only the result matters ✅ Keeping the main session context clean ✅ Running multiple tasks in parallel ✅ Tasks that need a different model (e.g., Haiku for simple work)
❌ Tasks requiring back-and-forth discussion → Use agent teams ❌ Tasks needing to modify the main session → Work directly
Q: Why would you use a subagent instead of doing the work in the main session?
<details> <summary>💡 Reveal Answer</summary>Subagents keep your main session context clean. They get their own context window, so a complex research task doesn't eat up your main session's tokens. Only the summarized results return to the parent. This is especially valuable when running multiple tasks in parallel — each subagent works independently without polluting the main conversation.
</details>Create a markdown file in .claude/agents/:
Full access
Unlock all 14 lessons, templates, and resources for Claude Code Mastery. Free.
---
description: Expert code reviewer. Use after code changes to review quality.
model: sonnet
tools:
- Read
- Grep
- Glob
maxTurns: 10
---
# Code Reviewer
You are a senior code reviewer. Review code changes for:
1. **Correctness** — Does the code do what it claims?
2. **Security** — Any vulnerabilities?
3. **Performance** — Any obvious bottlenecks?
4. **Style** — Consistent with project conventions?
5. **Tests** — Are new features tested?
## Output Format
### Review Summary
- Overall: APPROVE / REQUEST_CHANGES / COMMENT
- Files Reviewed: [list]
### Issues Found
| Severity | File | Line | Issue |
|----------|------|------|-------|
Define subagents dynamically with --agents:
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer",
"prompt": "You are a senior code reviewer. Focus on quality and security.",
"tools": ["Read", "Grep", "Glob"],
"model": "sonnet"
}
}'
---
description: "When to use this subagent"
model: sonnet | opus | haiku | inherit # Default: inherit
tools: # Restrict available tools
- Read
- Grep
- Glob
- Bash
disallowedTools: # Block specific tools
- Edit
- Write
maxTurns: 10 # Limit agentic turns
skills: # Preload skills
- security-review
mcpServers: # MCP servers for this agent
- github
---
Q: What does model: inherit mean for a subagent?
inherit means the subagent uses the same model as the parent session. If you're running Opus in your main session, the subagent also uses Opus. This is the default behavior. You can override with sonnet, opus, or haiku to control cost and capability per subagent.
Choose the right model for each subagent:
| Model | Use Case | Cost |
|---|---|---|
opus | Complex reasoning, architecture decisions | High |
sonnet | General coding, reviews | Medium |
haiku | Simple tasks, formatting, lookups | Low |
inherit | Same as parent session (default) | Varies |
Override globally:
export CLAUDE_CODE_SUBAGENT_MODEL=sonnet
Subagents can have their own auto memory:
~/.claude/projects/<project>/memory/
├── MEMORY.md # Main session memory
├── code-reviewer.md # Reviewer subagent memory
└── debugger.md # Debugger subagent memory
Subagents learn from past invocations and improve over time.
{
"permissions": {
"deny": ["Task(Explore)"]
}
}
Use the tools field in frontmatter:
---
tools:
- Read
- Grep
- Glob
# No Edit, Write, or Bash → read-only
---
Fill in the blanks:
.claude/___/maxTurns: ___Task(___).claude/agents/maxTurns: 10 (or any number)Task(Explore) (or the agent name)| Feature | Subagents | Agent Teams |
|---|---|---|
| Context | Own window, results return to parent | Own window, fully independent |
| Communication | One-way (report back only) | Teammates message each other |
| Coordination | Parent manages all work | Shared task list, self-coordination |
| Token cost | Lower (results summarized) | Higher (each is a full instance) |
| Best for | Focused tasks | Complex collaborative work |
Rule of thumb: If workers need to talk to each other → agent teams. If they just need to report results → subagents.
Q: You need three different analyses of your codebase (auth, payments, notifications). Should you use subagents or agent teams?
Subagents. Each analysis is independent — they don't need to talk to each other. Subagents run in parallel, each in their own context, and return summarized results. This is cheaper and keeps your main session clean. Agent teams would only be needed if the analyses depended on each other or required coordination.
> I need to understand three things about this codebase:
> 1. How authentication works
> 2. How the database migrations are structured
> 3. What the testing strategy is
> Use subagents to research each in parallel.
# .claude/agents/reviewer.md
---
description: Review staged changes before commit
model: sonnet
tools: ["Read", "Grep", "Glob", "Bash"]
maxTurns: 5
---
Review `git diff --staged` for quality, security, and style issues.
# .claude/agents/doc-gen.md
---
description: Generate API documentation from source code
model: haiku
tools: ["Read", "Grep", "Glob"]
---
Read the API route files and generate OpenAPI-compatible documentation.
Fill in the blanks:
export CLAUDE_CODE_SUBAGENT_MODEL=___summarizedGeneralsonnet).claude/agents/analyzer.md:
---
description: Analyze code quality metrics
model: haiku
tools:
- Read
- Grep
- Glob
maxTurns: 5
---
Analyze the codebase for:
- Total file count by extension
- Largest files
- TODO/FIXME comments
Report findings in a markdown table.
Reflection: How does the subagent's output differ from a direct request? Is it more focused?
Scenario: You want Claude to generate documentation for your API, but the process requires reading 50+ files and you're worried about context window overflow in your main session.
Create a dedicated documentation subagent:
# .claude/agents/doc-gen.md
---
description: Generate comprehensive API documentation
model: sonnet
tools: ["Read", "Grep", "Glob", "Write"]
maxTurns: 20
---
Generate complete API documentation by:
1. Finding all route files in src/api/
2. Reading each file and extracting endpoints, params, responses
3. Writing the documentation to docs/api-reference.md
The subagent gets its own context window, so it can read all 50+ files without affecting your main session. Only the final summary returns to the parent.
| Concept | One-Liner |
|---|---|
| What they are | Isolated Claude instances within your session |
| Built-in agents | Explore (read-only), Plan (read-only), General (full) |
| Custom agents | .claude/agents/*.md or --agents flag |
| Model selection | opus, sonnet, haiku, or inherit (default) |
| Tool control | tools: and disallowedTools: in frontmatter |
| Turn limits | maxTurns: prevents runaway sessions |
| vs. Agent teams | Subagents report back; teams coordinate with each other |
| Memory | Each subagent can have its own auto memory file |
Next up: MCP — Model Context Protocol → — Connect Claude to external tools and services.