Subagents & Delegation
Product facts change. The file format below matches the official subagents documentation as of October 2026. Model aliases, tool names and experimental features move, so check the current docs for anything not shown here.
After this lesson, you will be able to:
- Define a sub-agent as a Markdown file with YAML frontmatter in `.claude/agents/`, with the right tools, prompt, and model alias
- Distinguish a sub-agent (fresh context, reusable definition) from continuing in your main session or a fork (keeps your conversation)
- Use sub-agents to protect your main context by delegating research, code review, or large file reads
- Recognize when a sub-agent wins (specialization, isolation) and when the main session is better (the work needs your conversation)
Before you start
#What a Sub-Agent Is
A sub-agent is a separate Claude Code session with:
- Its own context window (starts fresh, doesn't see your main conversation)
- Its own permissions (can be more restrictive than parent)
- Its own tool set (only the tools you grant)
- Its own model (a small fast model for cheap fan-out, a larger one for hard reasoning, or the same as your session)
Task in older versions and Agent in newer ones). The sub-agent runs to completion and returns a single message. Several delegations in one turn can run in parallel. A sub-agent cannot start further sub-agents, so keep the nesting in the main session.#Defining a Sub-Agent
.claude/agents/<name>.md (shared through git) or personal ones in ~/.claude/agents/. The /agents command lists them and can create one for you.---
name: code-reviewer
description: Reviews a diff for bugs, security issues and missing tests. Use after code changes.
tools: Read, Grep, Glob, Bash
model: sonnet
---
You are a senior code reviewer. Read the provided diff or files
and produce a focused review. Look for:
- Bugs and edge cases
- Security issues (injection, XSS, secret leaks)
- Performance regressions (N+1 queries, large allocations)
- Missing tests for new logic
- Violations of the conventions in the project's CLAUDE.md
Format: a bullet list of findings, ordered by severity.
Skip nitpicks unless asked.
Key frontmatter fields:
name(required): a lowercase identifier with hyphensdescription(required): when to use this agent. Claude reads it to decide whether to delegate, so write it as a triggertools: a comma-separated allowlist. Leave it out and the agent inherits every tool, including MCP toolsmodel: an alias such assonnet,opusorhaiku, orinheritto use your session's model. Aliases avoid pinning a version that goes stale
--- is the prompt. Agent files are read when a session starts; create them with /agents to use them immediately, or restart the session after hand-editing..yaml file in .claude/agents/ is not a sub-agent. Older tutorials show that shape, and it will not be loaded.#Invoking a Sub-Agent
description, or you can name the agent:> Use the code-reviewer agent to review my changes in src/api/auth.py
Claude then calls its built-in delegation tool with the agent's name and a task prompt. You do not write that call yourself. The sub-agent runs in isolation, finishes, and returns one message to your main session.
Because the sub-agent sees only the prompt Claude gives it, a good request names the files and the goal, for example "focus on security because this touches the auth flow".
#Sub-Agents vs Forks
| Pattern | Sub-agent | Main session or fork |
|---|---|---|
| Context | Fresh: sees only the prompt it is given | Keeps your full conversation |
| Reusable | Yes: define once in .claude/agents/, use many times | No: one-off |
| Best for | Specialized recurring tasks (review, docs, research) | Continuing the task you are already on |
| Prompt cache | Separate from yours | Your session's cache |
| When to use | "I need a docs-writer for any module" | "Get a second opinion on this refactor, you know why I am doing it" |
A fork (a copy of your session that carries your conversation) is a newer feature and its availability depends on your version, so check the docs. If your version has none, the main session does the same job.
Rule of thumb:
- Specialized and recurring: sub-agent
- Needs the history of this conversation: main session or fork
You start 5 sub-agents in one turn to review a PR from 5 angles. Suppose each takes about 90 seconds on its own. Roughly how long do you wait?
#Parallel Fanout
Several delegations in one turn can run concurrently:
> Review this PR from three angles in parallel:
> 1. security-reviewer for auth, personal data and injection
> 2. performance-reviewer for N+1 queries and slow loops
> 3. test-reviewer for missing coverage
> Then combine the three reports into one ranked list.
Each agent works in its own context. The wait is roughly the slowest agent, not the sum. If each of three reviewers took 90 seconds, you would wait about 90 seconds instead of 4.5 minutes. Those numbers are an illustration, not a benchmark: your real times depend on the diff and the model.
Common fan-out patterns:
| Pattern | Agents | Use case |
|---|---|---|
| Review fan-out | security, performance, tests, style | A PR gate |
| Codebase exploration | several searchers with different query angles | "Where is X used?" in a large repo |
| Multi-source research | a few researchers with different queries | Cross-check a library's best practice |
| Refactor pre-flight | rename impact, test impact, docs impact | Estimate the blast radius of a rename |
Fan-out costs more tokens in total, because every agent reads its own context. Use it when speed or isolation is worth that.
#Common Sub-Agent Recipes
#code-reviewer
---
name: code-reviewer
description: Senior code reviewer. Use proactively after a change is made.
tools: Read, Grep, Glob, Bash
model: sonnet
---
Review for bugs, security issues, performance, missing tests and
style violations. Format: a severity-ordered bullet list.
#docs-writer
---
name: docs-writer
description: Writes API docs, README sections and code comments for a module.
tools: Read, Edit, Write, Grep
model: sonnet
---
Write clear, concise developer documentation.
Match the project's existing voice (read the README first).
Include a code example for every public function.
#test-generator
---
name: test-generator
description: Generates and runs tests for a given module.
tools: Read, Edit, Write, Bash
model: sonnet
---
Read the target module. Write tests covering:
- The happy path
- Edge cases (null, empty, maximum size)
- Error paths
Run the tests and fix any that fail.
#research-investigator
---
name: research-investigator
description: Multi-source web research with a sourced summary.
tools: WebFetch, WebSearch, Read
model: sonnet
---
Research the question across several sources.
Cross-reference at least three reputable ones.
Give a focused answer with links.
#When to Use Sub-Agents
| Scenario | Sub-agent? |
|---|---|
| Review a specific PR for quality | ✅ code-reviewer agent |
| Generate docs for a new module | ✅ docs-writer agent |
| Research best practices for a library | ✅ research-investigator agent |
| Continue refactoring a file you are already editing | ❌ stay in the main session |
| A quick syntax question | ❌ overkill |
| A multi-step deploy that needs your context | ❌ main session or fork |
#Cost & Performance
Each sub-agent has its own context and its own prompt cache, so it pays for its own reads. A quick delegation can cost more in total than doing the work inline, and a fan-out of five agents costs about five agents' worth of tokens.
haiku and a tight prompt. For one-off hard reasoning, a larger model is worth it. Prices and model names change, so look at the current pricing page instead of memorizing numbers.#Hands-On
.claude/agents/code-reviewer.md.Tests: Every line should print OK. Then save the finished text as .claude/agents/code-reviewer.md in a real project and run /agents in Claude Code to confirm the agent is listed.
#Key Takeaways
- Sub-agents protect your main context. Delegate isolated tasks to keep your session focused
- Definition: a Markdown file
.claude/agents/<name>.mdwith YAML frontmatter (name,description,tools,model) and the system prompt as the body. A.yamlfile is not loaded - Use model aliases (
sonnet,opus,haiku,inherit) so the file does not go stale when versions change - Sub-agent vs main session: sub-agent for reusable specialized tasks; main session (or a fork) when the work needs your conversation
- Tighten
toolsper agent. Only grant what the agent needs
#Quick Check
You are refactoring 8 files in a feature. Halfway through, you want a second opinion on the changes so far. What is the best choice?
Which file defines a project sub-agent called code-reviewer?