Picture this: you’re three hours into a complex refactor. Your Claude Code session has read dozens of files, worked through multiple rounds of changes, and built up a rich understanding of your codebase. Then you ask it to also investigate whether these changes break anything in the authentication system — and you watch the context window balloon toward its limit. Claude starts compacting. You lose the thread. You spend twenty minutes getting back to where you were. That experience, repeated across thousands of developers, is exactly the problem subagents were designed to solve.
Subagents are one of Claude Code’s most powerful features and, by far, its most misunderstood. Most beginners either don’t know they exist or assume they’re only for “advanced” users building complex pipelines. Neither is true. Subagents are already working inside your sessions right now — Claude uses them automatically to keep codebase exploration out of your main conversation. Understanding how they work, and learning to direct them deliberately, is what separates developers who burn through their context window on every complex task from developers who finish those same tasks with their context still healthy and their work fully verified. This guide makes subagents click.
## 📋 TL;DR
– Subagents are isolated Claude instances that your main session spawns to handle specific tasks — each with its own context window, tools, and focus.
– Claude Code already uses subagents automatically (the built-in Explore agent keeps codebase search out of your main conversation). You’re benefiting from them without knowing it.
– The main reason to use subagents deliberately: context isolation (keep side tasks from bloating your main session) and parallel execution (run multiple investigations at the same time).
– Custom subagents are Markdown files with YAML frontmatter stored in.claude/agents/(project) or~/.claude/agents/(personal).
– You can invoke subagents explicitly by name in your prompt, or let Claude auto-route to the right one based on thedescriptionfield.
– Fork subagents (context: forkorCLAUDE_CODE_FORK_SUBAGENT=1) inherit the parent session’s context instead of starting fresh — used when a side task needs your existing conversation’s knowledge.
– Start with the three built-in agents, understand what they do, then build one custom agent for a real recurring need. That’s the right on-ramp.
Table of Contents
- What Is a Subagent — and Why Does It Exist?
- The Three Built-in Subagents Claude Uses Automatically
- The Two Reasons to Use Subagents Deliberately
- How to Create a Custom Subagent File
- How to Invoke a Subagent
- Running Parallel Tasks with Subagents
- Fork Subagents — When a Child Needs Your Context
- Subagents vs Skills — What’s the Difference?
- Common Beginner Mistakes and How to Fix Them
- Quick Reference Cheatsheet
- What to Learn Next
- Key Takeaways
What Is a Subagent — and Why Does It Exist?
A subagent is a fully independent Claude instance that your main Claude Code session can create to handle a specific, bounded task. Think of it as hiring a specialist for a side quest. Your main session — the one you’re actively talking to — stays focused on the main task. The subagent goes off, does its work in its own isolated context window, and returns a summary of what it found or did.
Here’s the analogy that makes this click: imagine you’re a project manager working on a large feature. You need someone to research how the authentication system works, someone else to run the test suite, and a third person to check whether the database schema will need to change. You don’t do all three yourself simultaneously — you delegate. Each person works independently, then reports back. You synthesize the results and make decisions. That’s exactly the relationship between your main Claude Code session (the project manager) and its subagents (the specialists).
Every subagent has four things the parent session doesn’t share with it:
- Its own context window** — fresh, empty, not cluttered by the main session’s conversation history
- Its own system prompt** — you define what this agent specializes in and how it should approach problems
- Its own tool access** — you can restrict what it’s allowed to do (read-only? bash-only? no file edits?)
- Its own model selection** — run Haiku for cheap codebase searches, Opus for deep security analysis
When the subagent finishes, it returns a compact summary to the parent. The parent reads that summary and continues working — having gained the subagent’s findings without having to do the work itself or absorb all the intermediate steps into its own context.
This architecture matters most when tasks get complex. Simple queries don’t need it. But anything involving exploring a large codebase, running parallel analyses, or delegating a task with side effects that would clutter the main conversation — that’s exactly what subagents are for.
[What Are Subagents in Claude Code?]
[Why Use Subagents? The Context Window Problem]
The Three Built-in Subagents Claude Uses Automatically
Here’s something that surprises most people: you’re already using subagents. Claude Code ships with three built-in subagents it activates automatically when the task calls for them. You don’t configure them, invoke them, or even see them most of the time. They just work — quietly keeping your main session clean.
Explore
Explore is a fast, read-only agent optimized for searching and analyzing codebases. It runs on Haiku for speed and low cost, is denied the Write and Edit tools, and exists for file discovery, code search, and codebase exploration.
This is the agent you benefit from most often in everyday sessions. When Claude needs to find which files contain a specific function, map out your directory structure, or understand how data flows between modules, it delegates that work to Explore — keeping all those file reads and search results out of your main conversation. When Claude invokes Explore it specifies a thoroughness level: quick for targeted lookups, medium for balanced exploration, or very thorough for comprehensive analysis.
Explore also skips reading your CLAUDE.md files and the parent’s git status to keep research fast and cheap. It’s purpose-built to be the fastest, cheapest way to understand a codebase without touching anything.
Plan
Plan is a read-only research agent used during plan mode to gather context before Claude presents a plan. It inherits the main conversation’s model, is denied Write and Edit, and exists to research the codebase for planning.
When you type /plan or ask Claude to plan something before doing it, Plan is often what does the research pass. It reads your code, maps the relevant files and dependencies, and returns what the parent session needs to propose a coherent implementation strategy — without adding all that research noise to your main conversation.
General-purpose
General-purpose handles tasks that need both exploration and modification. You rarely invoke these directly; Claude routes to them automatically based on what you are asking.
The general-purpose agent is a full-capability instance — it can read, write, edit, and run commands. Claude routes to it when a subtask is significant enough to benefit from isolation but doesn’t fit cleanly into the Explore or Plan categories.
💡 Pro Tip: You can request that Claude use the Explore agent explicitly for a research task even if it wouldn’t automatically route there. Just say it in your prompt: “Use the Explore agent to map out how the payment flow works across all relevant files.” Being explicit about which agent you want for which task gives you more control over how your context budget gets spent.
[Subagent Types Explained]
The Two Reasons to Use Subagents Deliberately
Claude Code’s automatic subagent routing already helps. But there are two specific situations where deliberately directing subagents yourself makes a meaningful difference to your results.
Reason 1: Context isolation — keeping side quests out of your main session
Your main session’s context window is a precious resource. Every file Claude reads, every command output it processes, every back-and-forth message you exchange — all of it accumulates there. When a side investigation (checking for security vulnerabilities, running a test suite, analyzing a third-party integration) dumps its full output into your main conversation, you eat through your context budget faster and your main session gets harder to navigate.
Subagents let you delegate that investigation cleanly. A subagent in Claude Code is a fully independent agent instance that the main orchestrating session can spawn to handle a discrete, bounded task. Each subagent has its own context window, its own tool access, and its own execution scope. When the subagent finishes, it returns a result to the parent session. Your main session gets a compact summary. The thousands of tokens of intermediate work stay in the subagent’s context — and disappear when it finishes. Your main session stays lean and focused.
Reason 2: Parallel execution — doing multiple things at once
Normal Claude Code works sequentially. You ask a question, it responds, you ask the next one. One thing at a time.
Subagents break that constraint. Your main session can spawn multiple subagents simultaneously. The main session can spawn multiple subagents that run concurrently and return results independently. While one subagent searches for authentication endpoints, another runs your test suite, and a third reads the database schema. All at the same time.
Natural language patterns that reliably invoke parallel subagents include: “Research this in parallel. Check the API routes, database models, and frontend components simultaneously” and “Spin up subagents to fix these TypeScript errors across the different packages.” Being explicit about wanting parallel execution — and naming the parallel tasks — is how you direct the orchestration.
The real-world speedup here can be significant. A task that would take 15 sequential minutes of Claude reading files, running checks, and analyzing outputs can collapse to 4–5 minutes with parallel subagents dividing the work.
[Running Parallel Tasks with Subagents]
How to Create a Custom Subagent File
Custom subagents are Markdown files with YAML frontmatter. The structure is similar to skills, but the storage location and purpose are different. Subagents go in .claude/agents/ (project-level) or ~/.claude/agents/ (personal, available across all projects).
The basic structure
.claude/agents/
└── code-reviewer.md
---
name: code-reviewer
description: Reviews a feature branch diff for bugs, security issues, and code quality. Use after staging changes on a feature branch.
tools: Read, Grep, Glob
model: sonnet
---
You are a senior code reviewer. When invoked:
1. Identify the files changed on the current branch (`git diff --name-only main`)
2. Read each changed file and its corresponding tests
3. Report issues in this format for each one:
- File and line reference
- Issue description (what's wrong and why it matters)
- Severity: Critical / High / Medium / Low
- Concrete suggested fix
Review for: logic errors, security vulnerabilities, performance issues, and consistency with existing patterns.
Do NOT comment on formatting or style — the linter handles that.
Return a prioritized list, Critical issues first.
The frontmatter fields that matter most
name — The agent’s identifier. This is what you use when invoking it by name in a prompt: “Use the code-reviewer agent to check this branch.”
description — Like skills, this is the routing signal. Claude reads descriptions when deciding whether to automatically delegate to a custom agent. Write clear descriptions that explain when the subagent should be used, and Claude will automatically delegate appropriate tasks. You can also explicitly request a subagent by name in your prompt.
tools — Restricts which of Claude’s six tools this agent can use. For a read-only reviewer: tools: Read, Grep, Glob. For an agent that can also run tests: tools: Read, Grep, Glob, Bash. Omitting this gives the agent full tool access.
model — Which model to run this agent on. Use haiku for cheap, fast search-and-read tasks. Use sonnet (default) for general-purpose work. Use opus for tasks that genuinely require deep reasoning. Running Haiku for Explore-style agents and Opus only for the work that needs it is how you keep subagent costs under control.
memory — Set to user, project, or local to give the agent persistent storage across sessions. Useful for agents that build up knowledge over time (a documentation agent that remembers what it’s already documented, for example).
Storage locations
Project agents (.claude/agents/) — Committed to Git and shared with your team. Every developer gets the same custom agents automatically when they use Claude Code in this project.
Personal agents (~/.claude/agents/) — Available in all your projects, not shared. For personal workflow helpers that make sense everywhere you work.
💡 Pro Tip: For anything coupled to the codebase — a code reviewer that knows your conventions, a test writer that targets your framework — use project scope and check it into Git. Pair the subagent with your CLAUDE.md so it inherits the project’s working agreements. Personal scope is for helpers that travel with you, like a “summarize this PR in my preferred format” agent that’s the same everywhere.
[How to Create a Subagent File]
How to Invoke a Subagent
You have two ways to get a subagent into play: let Claude route automatically, or ask for it explicitly.
Automatic routing
Claude reads your prompt, compares it against every available subagent’s description, and delegates to the best match if there’s one. This happens without you doing anything. If your description is specific and clear, automatic routing works reliably. If the description is vague, the agent may never get used.
Explicit invocation
You can bypass the matching and request a specific agent by name:
Use the code-reviewer agent to check the current staged diff.
Have the code-reviewer agent look at these changes before we proceed.
Ask a subagent to investigate how the payment webhooks work, then report back.
Being explicit matters. Specify the scope, request parallel execution when tasks are independent, and describe the desired output.
Explicit invocation is the right choice when:
- The task is too important to risk the wrong routing
- You want a specific agent’s tool restrictions to apply (a read-only agent for an audit task)
- You’re orchestrating multiple agents and need precise control over which handles what
Using /agents for interactive management
The /agents command inside a Claude Code session opens an interactive interface for browsing your available agents, viewing their definitions, and managing agent sessions. It’s the equivalent of /help but specifically for subagents.
[How to Invoke a Subagent]
Running Parallel Tasks with Subagents
Parallel execution is where subagents deliver their biggest practical payoff. Instead of Claude working through a list of investigations one at a time, it splits the work across multiple simultaneous agents.
Here’s how to ask for parallel subagent work explicitly in your prompt:
Use subagents to explore this codebase in parallel:
1. Find all API endpoints and summarize their purposes
2. Identify the database schema and relationships
3. Map out the authentication flow — where it starts, what middleware it uses, how it ends
Return a summary of each finding, not the full file contents.
That single prompt can spin up three parallel Explore agents, each investigating a different aspect of the codebase simultaneously. The parent session receives three compact summaries and synthesizes them into a coherent picture.
Another pattern — running tests in the background while you keep working:
Run the full test suite in a background subagent.
Notify me when it finishes. I'll keep implementing this feature in the meantime.
The background subagent runs the tests. You keep working. When the tests complete (pass or fail), Claude notifies you. You didn’t have to wait.
By default, Claude Code can spawn up to 200 subagents per session. For most developers, this limit never comes up. For teams running automated pipelines with heavy parallelism, the limit can be raised with the CLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION environment variable.
Subagents can also spawn their own subagents — up to 5 levels deep. A parent delegates to a child, which encounters a problem that’s better handled by spinning up its own child. This nesting is useful for genuinely complex tasks but adds cost and complexity, so most teams stay at 1–2 levels deep.
[Running Parallel Tasks with Subagents]
Fork Subagents — When a Child Needs Your Context
Standard subagents start fresh. They have no knowledge of your main session’s conversation history — they begin with only their own system prompt, the delegation message from the parent, and any CLAUDE.md files in the project.
That’s usually what you want. But sometimes a side task needs the context you’ve already built up. Maybe you’ve spent an hour investigating a bug and you now want a separate agent to verify a fix using everything you’ve already discovered. Starting that agent fresh and re-explaining everything is wasteful.
Fork subagents solve this. A fork subagent inherits your full conversation context instead of starting fresh. It gets a copy of everything your main session knows — the conversation history, the files it has read, the analysis it has done.
There are two ways to create a fork subagent:
In a skill’s frontmatter (the context: fork field):
---
name: verify-fix
description: Verify that a proposed fix resolves the issue without breaking anything
context: fork
tools: Read, Bash
---
Using the context of this session's investigation, verify the proposed fix:
1. Read the changed files
2. Run the relevant tests
3. Check for any regressions in related functionality
4. Report: does this fix work, and does anything break?
Via environment variable for session-wide behavior:
export CLAUDE_CODE_FORK_SUBAGENT=1
With this set, parallel subagents share the parent’s prompt cache prefix instead of rebuilding from scratch. Five agents working in parallel: without fork you spend roughly 243,500 tokens on shared context. With fork you spend around 48,700 for child one plus around 20,200 for children two through five. That’s approximately a 10x cost reduction per additional parallel child.
When to use forks vs standard subagents:
Use a standard subagent when the task is self-contained and doesn’t need your main session’s history. Codebase exploration, test runs, independent analysis — these work better as fresh instances because they don’t need the accumulated context and starting clean keeps them focused.
Use a fork subagent when the side task genuinely needs to know what the main session knows. A verification pass after a complex fix. An audit of work the main session just completed. Any task where “here’s the context we’ve built up — use it” is more efficient than re-explaining from scratch.
[context:fork Explained]
Subagents vs Skills — What’s the Difference?
Both subagents and skills are defined as Markdown files with YAML frontmatter. Both can be invoked with slash commands or automatically. The surface similarity confuses a lot of beginners. The difference is about where the work happens.
Subagents run in an isolated child context and return a summary. Skills run in the main conversation and load on demand.
Skills add instructions to your current conversation. When you invoke a skill, its SKILL.md content loads into your main session’s context, and Claude follows those instructions as part of the existing conversation. Everything happens in one place. The history, the context, the tool calls — all visible in your main session.
Subagents create a separate Claude instance. The work happens elsewhere, in an isolated context window, and you receive a summary of the results. The intermediate steps — all the file reads, the command outputs, the internal reasoning — never appear in your main conversation unless you ask for them.
The decision rule:
Use a skill when you want the instructions inline — when you want the workflow woven into your existing conversation and don’t need isolation.
Use a subagent when you want the noisy intermediate work to stay out of the parent transcript — when you care about the result but not the process, or when you need isolation for parallel execution.
A practical example: a code review skill loads your review checklist into the main conversation and Claude works through it there — you see every step. A code review subagent runs the review separately and returns “here are the 4 issues I found” — you see only the output.
[Subagent Best Practices]
Common Beginner Mistakes and How to Fix Them
Mistake 1: Not knowing that subagents are already working in your sessions
The problem: You learn about subagents and think “I need to set all this up.” Meanwhile, the Explore and Plan subagents have been running inside your sessions for months, already keeping codebase exploration out of your main context.
The fix: Before building anything custom, watch what Claude is already doing. In a long session involving file exploration, check whether Claude mentions spawning subagents or using Explore. Understanding the built-ins first makes the whole system clearer and helps you recognize when custom subagents will actually add value versus when the built-ins already handle it.
Mistake 2: Using a subagent when a skill would work fine
The problem: You create a subagent for a simple workflow that would work perfectly as a skill. You get the overhead of a separate agent invocation (extra tokens, extra latency, context isolation you didn’t need) for a task that could have run inline.
The fix: Ask yourself: do I need isolation, or do I just need reusable instructions? If you want the instructions inline and visible in your main conversation, that’s a skill. If you need the task to happen in a separate context — because it’s noisy, because it should run in parallel, or because you don’t want the intermediate work in your main session — that’s a subagent. Most simple prompt shortcuts are skills. Most parallel investigative or verification tasks are subagents.
Mistake 3: Writing a vague description and wondering why auto-routing doesn’t work
The problem: You define a custom code review subagent with description: "Helps with code." Claude never routes to it. You conclude subagent routing doesn’t work.
The fix: The description is the routing signal. It needs to describe exactly when Claude should use this agent, in terms of what a user would be saying or doing. “Use after staging changes on a feature branch to review for bugs, security issues, and code quality” gives Claude specific routing criteria. “Helps with code” does not. Rewrite descriptions to include trigger phrases and specific use-case language.
Mistake 4: Giving subagents full tool access by default
The problem: You create a research subagent to analyze your codebase, don’t restrict its tools, and it ends up making file edits you didn’t intend because it “helpfully” tried to fix something it found.
The fix: Always specify tools in your subagent’s frontmatter, especially for agents designed to be read-only. A codebase explorer should have tools: Read, Grep, Glob — not Write or Bash. A test runner should have tools: Bash — not Edit. Scoping tools tightly makes subagents safer and more predictable. It also helps Claude understand what the agent is for.
Mistake 5: Using fork subagents when standard subagents are the right choice
The problem: You read about fork subagents, like the context-inheritance feature, and start using context: fork for everything. Some agents start picking up irrelevant noise from the parent session, producing confused or inconsistent output.
The fix: Forks are for tasks that genuinely need the parent’s history — verification passes, follow-up analyses on work the main session just did. For independent tasks — codebase exploration, parallel analysis, background test runs — fresh standard subagents are almost always better. They start clean, stay focused, and their isolation is a feature, not a limitation.
Quick Reference Cheatsheet
| **Topic** | **The answer** |
|---|---|
| What is a subagent? | An isolated Claude instance spawned by the main session to handle a scoped task |
| Built-in subagents | Explore (read-only, Haiku), Plan (read-only, research), General-purpose (full tools) |
| Explore agent’s purpose | Codebase search and file reading — keeps exploration out of main context |
| Where custom agents live (project) | `.claude/agents/agent-name.md` |
| Where custom agents live (personal) | `~/.claude/agents/agent-name.md` |
| Manage agents interactively | `/agents` command inside a session |
| Required frontmatter fields | `name` and `description` |
| Restrict tools in a subagent | `tools: Read, Grep, Glob` (or any combination of the six tools) |
| Set agent model | `model: haiku` / `model: sonnet` / `model: opus` in frontmatter |
| Invoke by name | “Use the code-reviewer agent to check this branch” |
| Request parallel work | “Research this in parallel: [task 1], [task 2], [task 3]” |
| Run a task in background | “Run the test suite in a background subagent. Notify me when done.” |
| Fork subagent (inherits context) | `context: fork` in frontmatter, or set `CLAUDE_CODE_FORK_SUBAGENT=1` |
| Max subagents per session | 200 by default (`CLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION` to raise) |
| Subagent nesting depth | Up to 5 levels deep |
| Subagents vs skills | Subagents = isolated child context, returns summary. Skills = inline in main conversation. |
| Disable built-in Explore/Plan | Set `CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS=1` |
| Persistent memory for an agent | Add `memory: project` (or `user` / `local`) to frontmatter |
What to Learn Next
Subagents are a layered topic — the concepts build on each other. Here’s the right path through the cluster:
Start with the fundamentals:
- [What Are Subagents in Claude Code?] — A focused conceptual explanation of what subagents are, illustrated with examples of before/after session behavior.
- [Why Use Subagents? The Context Window Problem] — The deeper dive on why context isolation matters and what happens when you don’t use it.
- [Subagent Types Explained] — All three built-in types covered in detail, plus the taxonomy of what you can build custom.
Build your first one:
- [How to Create a Subagent File] — Step-by-step file creation walkthrough, with every frontmatter field explained and annotated examples.
- [How to Invoke a Subagent] — How to request specific agents by name, write prompts that reliably trigger auto-routing, and use the
/agentsinterface.
Go parallel:
- [Running Parallel Tasks with Subagents] — Patterns and example prompts for spinning up multiple simultaneous agents, with real-world workflow examples.
- [context:fork Explained] — Deep dive on fork subagents: what they inherit, when to use them, and the cost math that makes them worth it for parallel work.
Real-world examples to copy:
- [Building a Code Review Subagent] — Build a complete code review agent from scratch, with the full agent file, frontmatter settings, and routing guidance.
- [Building a Documentation Writer Subagent] — Build a documentation agent that reads your code and writes or updates documentation automatically.
Pull it all together:
- [Subagent Best Practices] — The guidelines experienced Claude Code users follow to design reliable, cost-effective, well-scoped subagents.
Key Takeaways
- Subagents are already working in your sessions.** The built-in Explore and Plan agents run automatically to keep codebase research out of your main conversation. Understanding what they do — and when to augment them with custom agents — is the most practical place to start.
- The two core reasons to use subagents deliberately:** context isolation (keep side investigations from bloating your main session) and parallel execution (run multiple analyses or operations simultaneously instead of sequentially). Both translate directly into faster, cleaner sessions.
- Custom subagents are Markdown files with YAML frontmatter** stored in
.claude/agents/. Thedescriptionfield drives automatic routing — write it with specific trigger phrases, not generic descriptions. Thetoolsfield scopes what the agent can do — always restrict it to only what’s needed.
- Fork subagents** (
context: fork) inherit your main session’s full context, making them ideal for verification passes and follow-up analyses that need to know what the parent already discovered. Standard subagents start fresh, which is usually what you want for independent parallel tasks.
- Subagents and skills solve different problems.** Skills load instructions inline into your main conversation. Subagents create an isolated instance that does work elsewhere and returns a summary. Use skills for workflow instructions you want visible; use subagents when you want the noisy intermediate work to stay out of your main session entirely.
Last updated: July 2026. The subagents system is under active development — check Anthropic’s official documentation at code.claude.com/docs for the latest features and frontmatter options.