Claude Code Learning Hub
中文 Mingyu's Library

Hub / Course / D10

D10 · Subagents

Subagents are the "clones" your main session sends off to do the work: they search, run tests, and read logs in their own separate context windows, and hand back nothing but a report. This lesson covers the built-in types, writing your own, when to use them, and the boundaries.

The one-line version: any job whose process output is noisy but whose conclusion fits in a paragraph belongs in a subagent — it digests search results, test logs, and file contents in its own context, and your main session pays context cost only for the final summary.

Why this lesson comes today

D2 made the point: the context window is your scarcest resource, and stuffing it with irrelevant content drags model quality down. Subagents are Claude Code's built-in answer — separate "exploration" from "implementation", and keep the exploration noise inside the clone's window. Our takeYou have actually used one already: in D5's plan mode, the codebase research Claude delegates goes to the built-in Plan subagent.

Looking ahead, this lesson is the foundation of parallel workflows: D11's worktrees give each subagent an isolated copy of the code, and D12's agent teams upgrade "delegation within one session" to "collaboration across sessions". If the line between "open more sessions" and "have one session delegate to several subagents" feels blurry, finish this lesson and read the comparison tip: Multiple sessions vs multiple agents — how to choose.

Core concepts, explained

OfficialA subagent is a specialized AI assistant for a particular kind of task: it runs in its own context window, with its own system prompt, tool set, and permissions. When a task matches a subagent's description, Claude delegates the work; the subagent completes it independently and hands back the result. The core problem it solves: side tasks flood the main conversation with search results, logs, and file contents you will never reference again.

An analogy: the colleague on loan

Our takeThink of a subagent as a colleague on loan: you hand them a written task brief (the delegation message), they dig through the archives, run experiments, and fill an entire scratchpad of their own (their context), then hand back a one-page memo. Your notebook grows by exactly that one page; their scratchpad you never have to see. Borrow several people and they each work heads-down, none of them can see each other's scratchpads — consolidating is your job (the main session's).

Main session context window Subagent A · own context search results and intermediate output stay here Subagent B · own context test logs stay here Subagent C · own context contents of files it read stay here delegate tasks one report each solid = the delegation prompt; dashed = the returned summary; the three clones cannot see each other
Fan-out/fan-in: the main session delegates to several subagents; each works in its own context, and only summaries flow back.

Built-in subagents

OfficialClaude Code ships with several built-in subagents, and Claude delegates to them automatically when the moment fits:

TypeModelToolsPurpose
ExploreInherits the main session (capped at Opus on the Claude API)Read-only, Write/Edit disabledFile discovery, code search, understanding a codebase
PlanInherits the main sessionRead-only, Write/Edit disabledCodebase research in plan mode
general-purposeInherits the main sessionEvery tool available to subagentsComplex multi-step tasks that both explore and make changes

OfficialTwo special traits: to stay fast and cheap, Explore and Plan do not load CLAUDE.md or the parent session's git status; every other built-in and custom subagent loads both. If some rule (say, "ignore the vendor/ directory") must reach them, write it into the delegation prompt. There are also a few auto-triggered helper agents (claude, statusline-setup, claude-code-guide) you generally never manage directly.

Custom subagents: .claude/agents/*.md

OfficialA custom subagent is just a Markdown file with YAML frontmatter: the frontmatter is configuration, the body is its system prompt. What the subagent receives is this system prompt plus basic environment info — not the full Claude Code system prompt. A minimal working example:

---
name: code-reviewer
description: Reviews code for quality and best practices
tools: Read, Glob, Grep
model: sonnet
---

You are a code reviewer. When invoked, analyze the code and provide
specific, actionable feedback on quality, security, and best practices.

OfficialOnly name and description are required; the description decides when Claude delegates to it — write it clearly, and add "use proactively" if you want it picked up on Claude's own initiative. Common optional fields:

FieldWhat it does
tools / disallowedToolsTool allowlist / blocklist; omit tools to inherit every available tool
modelsonnet / opus / haiku / fable / a full model ID / inherit (default); this is how you route exploration tasks to a cheaper model
permissionModePermission mode: plan (read-only), acceptEdits, bypassPermissions (use with care), etc.
skillsPreloads the named Skills' full content into context at startup (builds on D7)
mcpServersPer-subagent MCP servers; inline definitions stay out of the main session, saving tool-description context (builds on D9)
hooksHooks that apply only while this subagent is active (builds on D8)
memoryPersistent memory across sessions, scope: user / project / local
backgroundtrue always runs it in the background; unset lets Claude decide
isolationworktree: works in a temporary git worktree without touching your checkout (previewing D11)
maxTurnsMaximum number of turns

OfficialWhere the file lives decides who can use it; on a name clash the higher priority wins, from high to low: managed settings > the --agents CLI flag (that session only) > project .claude/agents/ (commit it to the repo, shared with the team) > user ~/.claude/agents/ (all your projects) > a plugin's agents/ directory. Since v2.1.198, /agents no longer opens a creation wizard — just ask Claude to write the file, or edit it yourself; changes take effect within seconds, with one exception: the first agent file in a given scope needs a session restart to be discovered.

When to use one, when not to

OfficialThree signals to reach for a subagent: the task will generate lots of output the main context has no use for (running tests, fetching docs, scanning logs); you want to force a narrower tool set or permissions (a read-only reviewer); the work is self-contained and a single summary is a complete deliverable. Conversely, stay in the main session when: you need tight back-and-forth iteration; multiple stages share a lot of context; it's a quick small change; you care about latency — a subagent starts from zero and spends time regathering context.

OfficialThe two most common patterns: isolating high-noise operations ("run the tests in a subagent and report only the failing cases") and parallel exploration (one subagent per independent research direction, all running at once, Claude consolidates). The docs also warn: many subagents each returning a verbose report will still eat a good chunk of main-session context — for sustained large-scale parallelism, consider D12's agent teams.

Boundaries: no shared context, one report back

OfficialEvery subagent starts from a fresh, isolated context: it cannot see your conversation history, the skills you've invoked, or the files Claude has already read. What it gets is — its own system prompt, the delegation message Claude wrote, the full CLAUDE.md hierarchy (except Explore/Plan), a snapshot of git state from when the parent session started, and any preloaded skills. When the work is done, the only thing that returns to the main session is one final report — everything in between stays in its own transcript.

OfficialSeveral boundaries follow. Parallel subagents share no context and do not talk to each other; if B needs A's findings, the main session has to write the relevant parts of A's report into B's delegation message. After a subagent finishes, Claude can continue the same instance (a "resume" that keeps its full history) — but Explore and Plan are one-shot and cannot be resumed. Subagents can also spawn subagents of their own: by default at most three levels of nesting below the main session, with a per-session total cap of 200 and a concurrency cap of 20 (all adjustable via environment variables). The inverse special case is fork (the /subtask command): it inherits the main session's full conversation history before going off on the side task, trading input isolation for "no need to re-explain the background" — the output is still just one result.

Background execution

OfficialSince v2.1.198, subagents run in the background by default, so you can keep working in the main session; the foreground (blocking) mode is used only when Claude needs the result immediately. When a background subagent hits an operation that needs authorization, the permission prompt floats up into the main session, labeled with which subagent is asking; approve to let it proceed, or press Esc to deny just that one call. You can steer this yourself too: tell Claude to "run it in the background", press Ctrl+B to send a running task to the background; /tasks lists every background item, with view, take-over, and stop. Two costs: a background subagent's built-in tool set is smaller than the foreground one (all MCP tools are kept); and results arrive as a completion notification in a later turn — ask for progress early and Claude can only tell you it's still running.

Hands-on: doable today

The whole set takes about 30 minutes, in any project that has tests or a reasonable amount of code.

  1. Feel the isolation. Run /context first and note the current usage (from D1), then hand Claude Code the prompt below. Expected: a subagent delegation line appears (agent name + short task description), the full test output never enters the main conversation, and only the failure summary comes back; run /context again — the increase is far smaller than the volume of the test output.
Run the full test suite in a subagent and report back only the failing tests
with their error messages. Do not bring the full test output into the main session.
  1. Create a custom subagent. Use the prompt below to have Claude write the file. Expected: .claude/agents/code-reviewer.md appears, with name, description, tools, and model in the frontmatter, and a reviewer system prompt as the body. If this is the first time the project has a .claude/agents/ directory, restart the session so it gets discovered.
Create a code-reviewer subagent in .claude/agents/: read-only (Read, Grep, Glob),
using the sonnet model. Its job is to review recent code changes and output a list
of issues in three tiers — must fix / should fix / could improve — each item with
the current code and the improved version. In the description, say it should be
used proactively after code changes.
  1. Invoke it explicitly. Say "use the code-reviewer subagent to review my recent changes", or type @ and pick it from the completion list (an @-mention guarantees this run goes to it). Expected: a code-reviewer (…) delegation line appears, and a few minutes later you receive the three-tier issue list.
  2. Parallel fan-out. Tell Claude: "Use three parallel subagents to research this project's auth, database, and API modules; have each summarize its responsibilities and key files, then consolidate." Expected: three subagents run in the background at once, /tasks shows each one's status, and when they finish Claude delivers the consolidated summary — exactly the fan-out/fan-in from this lesson's diagram.

How to know you've learned it

  • Without notes, you can list what a subagent has in context at startup (its own system prompt, the delegation message, CLAUDE.md, the git snapshot, preloaded skills) and what comes back at the end (one report).
  • You can explain the division of labor between Explore / Plan / general-purpose, and the two special traits of Explore and Plan: read-only; no CLAUDE.md or git status loaded.
  • Your project has a .claude/agents/*.md you wrote yourself, and it has successfully executed at least one delegation.
  • Self-check: three subagents research in parallel — can B directly cite A's findings? How do you get A's conclusions to B? (Answer: no, subagents share no context; A's report returns to the main session first, and Claude writes the relevant parts into B's delegation message; direct worker-to-worker communication is D12 agent teams territory.)
Next stepSubagents all work on your one and only checkout (unless isolation: worktree). D11 covers how worktrees give each strand of parallel work an isolated copy; when you're unsure whether to "open another session" or "delegate a subagent", see Multiple sessions vs multiple agents — how to choose.