Every long Claude Code session hits the same wall. You ask it to explore the codebase, then review a diff, then check the database, then run the tests — and by the third task the conversation is so full of file listings, logs, and half-finished threads that the model starts losing the plot. The fix is not a bigger context window. It is giving the side quests to someone else.

That someone else is a subagent: a second Claude that runs in its own context window, with its own instructions and its own tool limits, and returns only a summary to your main conversation. Claude Code has shipped with built-in subagents for a while, but the feature matured fast in late 2026 — Anthropic's subagents documentation was updated on November 28, 2026, and fork mode, which lets Claude split off a copy of your whole conversation to try something in parallel, is now on by default. This tutorial builds a working team of subagents from scratch: a code reviewer, a researcher, and a database agent with a hook-enforced read-only rule. Every command, flag, and field below was checked against that documentation, and every file and script was validated in a sandbox before publication.

What you'll need#

  • Claude Code, up to date. Run claude --version and update if you are behind. Several features in this tutorial are version-gated — the notes below say which version each one needs — so "latest" is the only safe assumption.
  • A git repository to practise in. Any real project works; a scratch repo works too. Steps 7 and 8 assume git is available.
  • A Claude subscription or API access. Subagents send their own requests, and those requests count toward the same usage limits as your main conversation. There is no separate subagent allowance.
  • Python 3 for the Step 8 hook script, and a text editor. Nothing else to install.

1. Meet the built-ins you already have#

Before writing anything, use what ships with Claude Code. It includes built-in subagents that Claude delegates to automatically, and you have probably seen them work without noticing:

Built-inWhat it doesToolsModel
ExploreFast, read-only codebase search and analysisRead-only; Write and Edit deniedYour session's model
PlanGathers context during plan mode, before a plan is presentedRead-onlyInherits your session's model
general-purposeMulti-step tasks needing exploration and changesEvery tool available to subagentsInherits your session's model
statusline-setup, claude-code-guideHelpers for the status line and for questions about Claude Code itselfNarrowVaries

Try Explore right now. In a Claude Code session inside your repo, ask something that requires searching, not editing:

Where is retry logic implemented for the payment API, and which
files call it?

Watch the transcript. Claude delegates the search to Explore, which reads files in its own context window and returns a summary — file paths, a short description of each call site, nothing else. Your main conversation never sees the hundreds of lines Explore read. That is the whole point: the verbose middle of the work stays in a window you never pay for again.

Two details matter here. First, when Claude invokes Explore it picks a thoroughness level — quick for a targeted lookup, medium for balanced exploration, very thorough for a comprehensive sweep. If an answer feels shallow, say so: "that was too shallow, search very thoroughly" changes the delegation. Second, Explore and Plan start without your CLAUDE.md files and without the git status snapshot, deliberately, to keep research fast and cheap. A subagent that needs your project instructions should be one you define yourself, which is Step 2.

To see what is running, use /tasks. It lists every live subagent and, on recent versions, the model each one runs on. A finished background subagent stays listed as done for 30 seconds, and pressing Enter on it opens its transcript — the fastest way to check what a subagent actually did versus what it reported.

Diagram: a main conversation delegating to three subagents — Explore, Reviewer, and Researcher — each in its own context window, with summaries returning
AI-generated diagram: the main conversation delegates; each subagent works in its own context window and returns only a summary.

2. Write your first custom subagent#

A custom subagent is one Markdown file with YAML frontmatter. The frontmatter configures it; the body becomes its system prompt. Only two fields are required: name and description. The description is the important one — Claude reads it to decide when to delegate, so write it as a trigger condition ("use when…") rather than a job title.

Create a project-level reviewer at .claude/agents/code-reviewer.md in your repo. Project subagents live in .claude/agents/, are checked into version control, and are shared with your team. (User-level agents go in ~/.claude/agents/ and work in every project; the two directories are scanned recursively, so subfolders are fine.)

---
name: code-reviewer
description: Reviews code changes for bugs, security issues, and style problems. Use proactively after any code is written or modified, or when asked to review a diff or pull request.
tools: Read, Grep, Glob, Bash
disallowedTools: Write, Edit
model: haiku
maxTurns: 25
---

You are a senior code reviewer. Review the code or diff you are given and report findings as a short, prioritized list: critical bugs first, then security issues, then style nits. For each finding, cite the file and line number and suggest the fix. Do not rewrite the code yourself — you have no Edit or Write tools. If a finding is uncertain, say so rather than guessing. Keep the report under 400 words.

Three choices in that file deserve explanation. model: haiku routes review work to the fastest, cheapest model — review is a pattern-matching task that rarely needs the flagship. maxTurns: 25 caps how long the reviewer can work before Claude Code returns its output marked partial; without a cap, a reviewer can chew through a large diff for a long time. And description starts with the trigger and includes "use proactively" — the docs' own advice for encouraging delegation.

Verify the file loads. Claude Code ships a validator for agent directories:

claude plugin validate .claude/agents

It flags frontmatter that does not parse. Note what it does not flag: a file that parses but has no name is treated as documentation kept beside your agents, and a file with a name but no description is skipped with the reason written to the debug log. If an agent never fires, run claude --debug and search ~/.claude/debug/<session-id>.txt for the skip reason — that log is where silent loading failures surface.

Now trigger it. In your session, ask Claude to write or change some code, then watch for the delegation. Or invoke it directly (Step 5). Either way, the first thing to check is the report length: if the reviewer returns a 2,000-word essay, tighten the system prompt — "keep the report under 400 words" is doing real work here, because every word of the report lands in your main conversation's context.

3. Control what it can touch#

Tool restrictions are the reason to define a subagent instead of just asking nicely. Two fields control them: tools is an allowlist, disallowedTools is a denylist. If both are set, the denylist applies first, then the allowlist is resolved against what remains. A tool in both lists is removed. If nothing in the tools list resolves to a real tool — every entry misspelled, or naming a tool subagents cannot use — Claude Code usually refuses to launch the subagent and the error names the unresolved entries.

There is one hole you must know about, and the documentation is blunt about it: a reviewer with no Edit or Write tools can still change files through Bash. The allowlist restricts tools, not the shell. If "read-only" must actually mean read-only, you need a hook, which is Step 8 — the tool list alone is a statement of intent, not a sandbox.

Other useful limits in the same frontmatter:

  • permissionMode — default, acceptEdits, auto, dontAsk, bypassPermissions, plan, or manual (an alias for default). A reviewer on default asks before anything sensitive; a research agent can run on auto because it has nothing to break.
  • skills — skills to preload into the subagent's context at startup. The full skill content is injected, not just the description, so list only the skills this agent actually needs.
  • omitClaudeMd: true — start the subagent without your user, project, and local CLAUDE.md files. Use it for agents that take everything they need from the delegation prompt. Requires Claude Code v2.1.271 or later.
  • background: true — keep the subagent in the background even when Claude asks to wait for it. (Subagents Claude spawns from the main conversation already start in the background by default.)

Background subagents run with a smaller built-in tool set than foreground ones — the background filter keeps Read, Grep, Glob, Bash, Edit, Write, WebFetch, WebSearch, and the task and messaging tools, and removes most of the rest. If a background agent mysteriously lacks a tool you listed, that filter is the usual cause, not your frontmatter.

4. Pick the model (and the bill)#

By default a subagent runs on the same model as the conversation that started it. To choose, set model in the definition to an alias — sonnet, opus, haiku, or fable — a full model ID such as claude-opus-5-5, or inherit to explicitly take the parent's model. When more than one source sets a model, Claude Code uses the first that applies, in this order: the per-invocation model parameter Claude can pass when it starts the subagent, the model field in the definition, the CLAUDE_CODE_SUBAGENT_MODEL environment variable, and finally the parent conversation's model.

The practical setup is a cost ladder. Put exploration and review on Haiku, keep the main conversation on Sonnet or Opus, and reserve Opus for the one agent whose judgement actually matters — say, a security reviewer. If you want every subagent on one model regardless of definitions, set both CLAUDE_CODE_SUBAGENT_MODEL and CLAUDE_CODE_SUBAGENT_MODEL_FORCE to 1 (requires v2.1.257 or later), for example in the env block of a settings file:

{
  "env": {
    "CLAUDE_CODE_SUBAGENT_MODEL": "haiku",
    "CLAUDE_CODE_SUBAGENT_MODEL_FORCE": "1"
  }
}

While the force flag is on, Claude Code ignores the model field in subagent definitions. Check that it took effect with /tasks while a subagent is running — each row names its model. One caveat: a subagent's effort level is separate from its model. The effort field (low, medium, high, xhigh, max) sets how hard the subagent works at its model, and the CLAUDE_CODE_EFFORT_LEVEL environment variable overrides both the field and the per-invocation parameter. Subagents otherwise inherit your main conversation's extended-thinking configuration — there is no per-subagent thinking toggle.

Also watch the description budget. Claude Code loads every custom subagent's description into context at startup, and when the combined descriptions pass 15,000 tokens it shows a startup warning with the total. Keep descriptions to one or two sentences and move the detail into the system prompt, which only loads when that subagent actually runs.

5. Call a subagent when you want one#

Automatic delegation covers the common cases, but three explicit patterns escalate from a hint to a session-wide default:

  • Natural language. Name the subagent in your prompt and Claude typically delegates: "have the code-reviewer look at this diff." No special syntax, and Claude writes the task prompt for the subagent from what you asked.
  • @-mention. Type @ and pick the subagent from the typeahead, the same way you @-mention files — or type it manually as @agent-code-reviewer. Your full message still goes to Claude, which writes the subagent's task prompt, but the mention pins which agent runs. Plugin subagents appear under their scoped name, such as @agent-my-plugin:code-reviewer.
  • Session-wide. Pass --agent <name> to start a session where the main thread itself takes on that subagent's tool restrictions and model: claude --agent code-reviewer. The agent's system prompt replaces the default Claude Code system prompt entirely (unless the prompt is empty), and the agent name appears as @<name> in the startup header so you can confirm it is active. To make a subagent the default for a project, set agent in .claude/settings.json; the CLI flag overrides the setting.

You can also define a subagent for one session only, without writing a file, with the --agents flag:

claude --agents '{
  "reviewer": {
    "description": "Reviews code for bugs and security issues",
    "prompt": "You review code. Report findings as a short prioritized list with file and line numbers.",
    "model": "haiku"
  }
}'

CLI-defined agents exist only for that session. In non-interactive mode, --agents also accepts a path to a JSON file holding the same object (requires v2.1.281 or later), which is the sane way to use it in scripts: claude -p --agents ./agents.json "Review my changes".

6. Run them in parallel, chain them, fork them#

Parallel research is the pattern that pays for the whole feature. For independent investigations, ask Claude to spawn several subagents at once — each explores its own area, then Claude synthesizes the findings:

Research this migration in parallel: one subagent on the current
auth flow, one on the database schema it touches, one on the tests
that cover it. Then summarize the three findings and propose a plan.

Each subagent runs in the background while you keep working. When one reaches a tool call that needs permission, Claude Code surfaces the prompt in your main session and names the subagent that is asking — approve to let it continue, or press Esc to deny that one call without stopping the subagent. Results arrive as completion notifications in a later turn, and Claude waits for the notification before reporting them. If you ask about progress first, it will simply tell you the subagent is still running.

Diagram: a main session splitting into three parallel lanes — Research, Review, and Tests — that merge back into a single summary
AI-generated diagram: independent investigations run in parallel and merge into one summary.

Chaining is the sequential version: each subagent completes its task and returns results to Claude, which passes the relevant context to the next one — research, then plan, then implement, then review. A subagent can also spawn subagents of its own, up to three layers below the main conversation; at the depth limit Claude Code withholds the Agent tool, so the deepest agent does its delegated work itself and returns one summary. To change the limit, set CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH in settings — 1 turns nesting off. And there is a hard ceiling on concurrency: when 20 subagents are running in a session, spawning another fails with "Concurrent subagent limit reached." Raise it with CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS if you genuinely need more, but 20 parallel agents is already a sign the work should be split across sessions.

Forks are the third shape, and the one people confuse with subagents. A fork inherits the entire conversation so far — system prompt, tools, model, message history — instead of starting fresh. Use one when any other subagent would need too much background to be useful, or when you want to try several approaches in parallel from the same starting point. Start one yourself with /subtask followed by a task; Claude can also start forks on its own while fork mode is on, which it is by default (since v2.1.302). Because a fork's system prompt and tool definitions are identical to the parent's, its first request reuses the parent's prompt cache — a fork costs less than a fresh subagent for tasks that need the same context. A fork cannot spawn further forks.

The tradeoff of fork mode is control: while it is on, Claude cannot wait for a subagent other than web-fetch in interactive sessions — it forks instead. If you want Claude to wait for a result before continuing, turn fork mode off by setting CLAUDE_CODE_FORK_SUBAGENT to 0 in settings, restart, and ask Claude to wait: "run the reviewer subagent and wait for its report." To stop forks only, without touching anything else, add "Agent(fork)" to permissions.deny.

7. Isolate risky work in a worktree#

A subagent that edits files shares your checkout by default, which means two agents can step on each other's edits. The isolation: worktree frontmatter field gives the subagent an isolated copy of the repository instead — a temporary git worktree it works in alone:

---
name: experimenter
description: Tries a risky refactor in isolation and reports whether it worked. Use when an approach might break the build or touch many files.
tools: Read, Grep, Glob, Bash, Edit, Write
model: sonnet
isolation: worktree
---

You are an experimental refactorer. Attempt the change you are given, run the tests, and report what worked, what failed, and the exact commands you ran. Do not merge anything back — the main conversation decides what to keep.

By default the worktree branches from your default branch rather than the parent session's HEAD, and Claude Code can remove the worktree if the subagent makes no changes. The isolation is enforced, not advisory: Bash commands are checked to make sure any git they run stays inside the worktree, and a command that redirects git into the main checkout is blocked. If your main session itself runs isolated in a worktree, the same checks apply to the session and to every subagent it spawns, even ones without isolation: worktree.

Reach for this whenever the delegated work is speculative — a big refactor, a dependency upgrade, an alternative implementation you want to compare. The main conversation keeps a clean checkout, and the experiment either earns a merge or gets discarded with its worktree.

8. Add guardrails: hooks, deny rules, and output scanning#

Step 3 left a hole: tool lists do not stop a subagent from editing files through Bash. Hooks close it. A PreToolUse hook runs a script before each matching tool call, receives the call as JSON on stdin, and blocks it by exiting with code 2. Here is a complete, tested example: a database agent whose Bash commands are validated to allow only read-only SQL.

First, the agent file, .claude/agents/db-validator.md:

---
name: db-validator
description: Runs read-only SQL queries against the project database and reports results. Use when data needs checking before a decision. Never writes to the database.
tools: Read, Bash
hooks:
  PreToolUse:
    - matcher: Bash
      hooks:
        - type: command
          command: ./.claude/scripts/validate-sql.py
---

You are a database assistant. Answer questions about the project database using SELECT queries only. Never run INSERT, UPDATE, DELETE, DROP, ALTER, or any other write statement, and refuse any request that asks you to change data.

Then the validator, .claude/scripts/validate-sql.py (make it executable with chmod +x):

#!/usr/bin/env python3
"""PreToolUse hook: allow only read-only SQL in Bash commands."""
import json
import re
import sys

WRITE_RE = re.compile(
    r"\b(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE|GRANT|REVOKE)\b",
    re.IGNORECASE,
)

def main() -> int:
    try:
        payload = json.load(sys.stdin)
    except Exception:
        return 0  # Unparseable input: do not block.
    if payload.get("tool_name") != "Bash":
        return 0
    command = payload.get("tool_input", {}).get("command", "")
    # Strip single-quoted string literals first, so a word like
    # "update" inside data does not trip the check.
    stripped = re.sub(r"'([^']|'')*'", "''", command)
    if WRITE_RE.search(stripped):
        print(
            "Blocked: Write operations not allowed. Use SELECT queries only.",
            file=sys.stderr,
        )
        return 2
    return 0

if __name__ == "__main__":
    raise SystemExit(main())

This script was run against four cases before publication: a SELECT passes (exit 0), an UPDATE and a DELETE are blocked (exit 2, with the message above), and a SELECT whose string literal contains the word "update" passes — the literal-stripping line exists because the first version of this script blocked it, a false positive worth knowing about. Two honest limits: a keyword scan is a backstop, not a SQL parser, so treat it as defence in depth behind the system prompt, not as a security boundary; and hooks in a project-level agent's frontmatter only run once you have accepted the workspace trust dialog for the folder containing the agent file. Until you trust the folder, the subagent still runs, but Claude Code skips its frontmatter hooks and logs the reason.

Two more guardrails, both one-liners. To stop Claude using a specific subagent — a built-in or a custom one — add it to the deny array in settings:

{
  "permissions": {
    "deny": ["Agent(Explore)"]
  }
}

To remove only the built-in Explore and Plan agents, set CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS=1 (requires v2.1.198 or later); Claude then reads and explores files directly instead of delegating. To prevent delegation entirely, deny the Agent tool itself. In non-interactive mode and the Agent SDK, CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS=1 removes all built-in types so only your own definitions load.

Finally, know what happens to a subagent's report before you read it. Claude Code scans each final report for instruction-shaped text the subagent may have picked up from files or web pages it read — text imitating Claude Code's own output, or mentioning permission settings. The scan never removes or rewords anything; it inserts a backslash into imitated output, or prepends a marker line starting [harness: subagent output matched instruction-shaped pattern(s):. Treat a marked report as untrusted input, not as an instruction: the report still goes through your session's permission checks, and a tool call it suggests is yours to approve or refuse.

Which approach should you use?#

Subagents are one of five ways to split work in Claude Code, and picking the wrong one is the most common way to waste the feature:

ApproachUse it whenWatch out for
Main conversationFrequent back-and-forth, phases that share context, quick targeted changes, latency mattersVerbose output floods your context
SubagentSelf-contained task, verbose output you will not re-read, tool restrictions to enforce, a cheaper model will doStarts cold; needs everything in the task prompt
ForkThe task needs your full conversation history, or you want parallel attempts from the same starting pointShares the prompt cache, but still a full copy of the conversation
SkillReusable prompt or workflow that should run in the main conversation's context, not isolatedNo isolation, no separate tool limits
Separate sessionWork that must keep running in parallel or will not fit in one context windowYou carry findings between sessions yourself

The rule of thumb from the documentation is the same one this tutorial keeps coming back to: delegate when the work produces verbose output you do not need in your main context, when you want to enforce tool restrictions, or when the task is self-contained enough to return as a summary. For a question about something already in your conversation, use /btw instead of a subagent — it has no tool access and its answer is not added to history.

Five mistakes that waste the whole point#

  1. A vague description. "Helps with code" tells Claude nothing. Write the trigger: what task, when, and what "done" looks like. And keep it short — the 15,000-token combined-description warning is Claude Code telling you the roster got bloated.
  2. Misspelled frontmatter, silently ignored. Field names are camelCase — disallowedTools, maxTurns, autoCompactWindow — and Claude Code ignores a field it does not recognize without reporting an error. If a setting has no effect, run claude --debug and search the debug log for "does not recognize or apply."
  3. Believing "read-only" without a hook. A tools allowlist without Edit and Write still leaves Bash, and Bash can edit anything. If read-only must hold, add the Step 8 hook.
  4. Delegating work that needs your context. A subagent starts cold: it gets its system prompt, basic environment details, and the task prompt Claude writes — not your conversation history. If the task needs ten turns of prior discussion, use a fork, or do it in the main conversation.
  5. Spawning subagents for everything. Each one sends its own requests against your usage limits, starts fresh, and costs a round trip. A one-line question does not need a worker with its own context window.

The takeaway#

Start with the built-ins: let Explore do your searching and watch what comes back. Then write one custom subagent — the reviewer in Step 2, in your repo, on Haiku, with a 400-word report cap — and use it for a week. Add the researcher when you catch yourself pasting the same exploration prompt twice. Add the database validator with its hook when a read-only promise actually matters. Check /tasks while they run, read a transcript when a report looks thin, and keep descriptions short enough that the 15,000-token warning never appears. The payoff is not parallelism for its own sake; it is a main conversation that stays small enough to think in, because everything verbose lives in a window you never have to re-read.