Library · Hooks and helper agents

Subagents: specialized workers

Builder75 minUpdated: October 2026
37 of 105 in the library

Module: 8. An army of agents | Time: about 30 min theory + 45 min practice


The gist

You're the CEO of a company. When you need a legal audit, you don't study law yourself. You hire a lawyer, explain the task, they do the work in their own office and bring you the result. You didn't see what they did in there: you only need the outcome. A subagent works exactly the same way: the main agent hires a specialist, the specialist works in its own context and returns a condensed result.


Key concepts

  • A subagent = a separate agent with an independent context (its own context window)
  • 5 reasons to use them: context, tools, reuse, specialization, cost
  • Built-in subagents: Explore (read-only), Plan (read-only), General-purpose (all tools)
  • File format: Markdown with YAML frontmatter in .claude/agents/<name>.md
  • Creating a custom subagent: ask Claude or write the file by hand (the /agents wizard from older versions has been removed)
  • Scopes: project (.claude/agents/), user (~/.claude/agents/), CLI, managed, plugin
  • Configuration: 18 frontmatter fields (role, tools, model, hooks, memory, color and more)
  • Nesting is limited: by default subagents can call other subagents, but no more than three levels deep
  • When NOT to use subagents

Theory

What a subagent is, technically

🎨 Picture this: a subagent is like an outsourced lawyer. You're the CEO and you need legal expertise, so you don't learn law yourself. You hire a lawyer, explain the task, they work in their own office and bring back a finished result. Your desk stays clean.

According to Anthropic's official documentation, subagents are specialized AI assistants that handle specific types of tasks. Each subagent works in its own context window with a custom system prompt, limited access to tools and independent permissions.

Use a subagent when a side task would clutter the main conversation with search results, logs or file contents you won't use again. The subagent does the work in its own context and returns only a summary.

Create a custom subagent when you keep launching the same worker with the same instructions.

When the main agent calls a subagent, a separate instance of Claude is created with a clean context. This instance:

  • Gets a specific assignment and a custom system prompt (NOT the full Claude Code system prompt)
  • Works independently and doesn't see the main session's history (the exception is fork, see below)
  • Has access only to the tools it's allowed
  • When it's done, returns the result to the main agent and "dies"
  • Its context is freed up
Code
Main agent (accumulated context: 30K tokens)
│
├── Calls the "researcher" subagent
│   ├── The subagent gets: the assignment + the data it needs
│   ├── Works in a clean context (0 + assignment = ~2K tokens)
│   ├── Gathers information, analyzes
│   └── Returns: a condensed summary (500 tokens) → dies
│
The main agent continues with the summary
(30K + 500 = 30.5K, not 30K + all of the subagent's work)

🎨 Picture this: a subagent burns through its context like a disposable cup: it does the job and goes in the trash. The main agent gets only the distillate: one paragraph instead of 50 pages of logs.

Without subagents, every action gets added to the main context. After 2 hours of work the context is overloaded, and the model starts "forgetting" earlier parts of the conversation.

About nesting: in early versions, subagents couldn't call other subagents. Now they can, but no more than three levels below the main conversation (the limit is set with the CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH variable). To start, it's simpler to keep the chain flat: call subagents one at a time from the main conversation, which makes it easier to see who did what.


5 reasons to use subagents

Reason 1: Preserving context

Collecting 50 pages of data in the main agent = 50 pages in the context for good. Delegate it to a subagent → it collects the data, compresses it into a 1-page summary → returns it. The main agent's context stays clean.

Reason 2: Limiting tools

🎨 Picture this: the principle of least privilege is like a surgeon and an orderly. The orderly brings the instruments, but nobody hands them the scalpel. The researcher reads but doesn't write, so it can't break what it isn't supposed to touch.

A "researcher" subagent has access only to web search and reading files. A "coder" subagent has access to bash and file editing. The main agent has everything.

Why does this matter? A subagent can't accidentally delete a file if it doesn't have bash access. The principle of least privilege.

Reason 3: Reuse

Create a "competitor-researcher" subagent once → use it in 10 different projects. You don't have to explain how to do competitive analysis every time.

Reason 4: Specialization

An agent focused on one task does it better than a general-purpose agent. A "researcher" with a special prompt for finding information → better than a "do everything" agent trying to search, analyze and write all at once.

Reason 5: Cost control

🎨 Picture this: don't hire a head chef to peel potatoes. Haiku for mechanical work (gathering data, formatting), Opus only for strategy. The price gap between Haiku and Opus is several times over, and up to the most powerful model it's about ten times.

Different tasks need different models:

Code
Data collection (mechanical work) → Claude Haiku ($1 input / $5 output per 1M tokens)
Data analysis (requires reasoning) → Claude Sonnet ($2 / $10)
Strategic decisions → Claude Opus ($4 / $20)

API prices as of October 2026. Current prices and versions: What's current. By choosing the right model for each task, you save several times over on mechanical tasks.


Claude Code's built-in subagents

Claude Code comes with several built-in subagents. Each one inherits the main session's permissions plus extra tool restrictions. The model the built-in agents use depends on your version and settings, so check the documentation for the current details:

Explore: fast read-only codebase search

  • Model: the same as the main session by default, can be overridden
  • Tools: read-only (Write and Edit are blocked)
  • Purpose: finding files, navigating code, analyzing project structure
  • When calling it, Claude sets a thoroughness level: quick (targeted search), medium (balanced), very thorough (full analysis)

Plan: the researcher for plan mode

  • Model: inherited from the main session
  • Tools: read-only (Write and Edit are blocked)
  • Purpose: gathering context before drawing up a plan
  • Used when you're in plan mode and Claude needs to understand the codebase

General-purpose: the all-rounder for complex tasks

  • Model: inherited from the main session
  • Tools: everything available
  • Purpose: complex research, multi-step operations, changing code

Helpers:

Agent When it's used
statusline-setup When you run /statusline
claude-code-guide When you ask about Claude Code features
fork When you need a subagent that inherits the whole conversation (see below)

These subagents kick in automatically when the main agent decides a task is a good fit for delegation.


The subagent file format (official)

Subagents are defined as Markdown files with YAML frontmatter. This is Anthropic's official format:

Type this into the chat
---
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.

Structure: YAML frontmatter (settings) + a Markdown body (the subagent's system prompt). The subagent receives this system prompt, the assignment from the main agent, the project's CLAUDE.md and a snapshot of git status, but NOT the full Claude Code system prompt and NOT the conversation history.

All YAML frontmatter fields (18 fields)

Field Required What it does
name Yes Unique identifier (lowercase letters + hyphens)
description Yes When Claude should delegate a task to this subagent
tools No List of allowed tools. If not set, inherits all
disallowedTools No Tools to block (from the inherited ones)
model No Model: sonnet, opus, haiku, fable, a full ID (for example, claude-opus-5-5), or inherit. If not set, uses the main session's model
permissionMode No Mode: default, acceptEdits, auto, dontAsk, bypassPermissions, plan, manual
maxTurns No Maximum number of agent steps before stopping
skills No Skills to preload into the context at startup
mcpServers No MCP servers available only to this subagent
hooks No Lifecycle hooks tied to the subagent
memory No Persistent memory: user, project, or local
background No true: keep it in the background even when Claude asks to wait for the result
omitClaudeMd No true: don't load the project's CLAUDE.md into this subagent
effort No Effort level: low, medium, high, xhigh, max
isolation No worktree: an isolated copy of the repository via git worktree
color No Color in the terminal: red, blue, green, yellow, purple, orange, pink, cyan
initialPrompt No An automatic prompt when it's launched as the main agent (via --agent)
experimental No Experimental settings, for example the prompt cache lifetime

Where to store subagents (scopes)

Location Scope Priority
Managed settings Organization 1 (highest)
--agents CLI flag Current session 2
.claude/agents/ Current project 3
~/.claude/agents/ All of the user's projects 4
Plugin agents/ Wherever the plugin is enabled 5 (lowest)

Project subagents (.claude/agents/) are for the team: commit them to git. User subagents (~/.claude/agents/) are personal and available everywhere.

If names clash, the higher priority wins.

Creating a subagent: three ways

Way 1: Ask Claude (recommended)

Older versions had an /agents wizard for this. It was removed in version 2.1.198: the /agents command now just reminds you what to do. You create a subagent by asking Claude:

Type this into the chat
Create a personal subagent called market-researcher in ~/.claude/agents/:
it researches markets and competitors, only reads files and searches the web,
model haiku, color green

Claude will write a file with the right frontmatter. Check the result and adjust the description so it's clear when to call the agent.

Way 2: By hand: create an .md file

Create the file .claude/agents/market-researcher.md:

Type this into the chat
---
name: market-researcher
description: Researches markets and collects data on competitors. Use when you need to gather information about a market, competitors, prices or trends.
tools: Read, Glob, Grep, WebFetch, WebSearch
model: haiku
color: green
---

You are a market researcher. Collect data from public sources,
analyze competitors, find trends. Return a structured
summary with the key findings.

Subagents are loaded when a session starts. If you created the file by hand, restart the session to load it.

Way 3: Through the CLI (for automation / a quick test)

bash
claude --agents '{
  "code-reviewer": {
    "description": "Expert code reviewer. Use proactively after code changes.",
    "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  }
}'

CLI subagents live only in the current session and aren't saved to disk.

Choosing a model

Code
Claude Haiku  → for mechanical tasks (data collection, formatting, search)
Claude Sonnet → for tasks that need reasoning (analysis, code, writing)
Claude Opus   → for complex strategic tasks (architecture, critical analysis)

Model selection priority (highest to lowest):

  1. The model parameter on a specific call
  2. The model field in the subagent's frontmatter
  3. The CLAUDE_CODE_SUBAGENT_MODEL environment variable
  4. The main session's model

To force all subagents onto one model, add a second variable, CLAUDE_CODE_SUBAGENT_MODEL_FORCE=1: then it overrides everything else.

A note as of October 2026: Claude Haiku 4.5 may be retired from the API no earlier than October 15, 2026. Keep an eye on the What's current page.

Managing tools: tools vs disallowedTools

Allowlist: list ONLY what's allowed:

yaml
tools: Read, Grep, Glob, Bash

The subagent can NOT edit files, write, or use MCP.

Denylist: block specific tools, inherit everything else:

yaml
disallowedTools: Write, Edit

The subagent inherits EVERYTHING except writing and editing files.

If both are set, disallowedTools is applied first, then tools.

Limiting nested calls: Agent(type)

When a subagent runs as the main agent (via --agent), you can limit which subagents it's allowed to call. If you remove Agent from the tools list entirely, the subagent can't launch anyone:

yaml
tools: Agent(worker, researcher), Read, Bash

Only worker and researcher are allowed. The rest are blocked. The nesting depth as a whole is limited by CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH (a value of 1 turns nesting off).

Persistent memory (memory)

🎨 Picture this: a subagent with memory is like an accountant who keeps a notebook. After ten audits of your code, it knows all your patterns by heart. Without memory, it starts from scratch every time, like its first day on the job.

A subagent can build up knowledge between sessions:

yaml
memory: project
Scope Where it's stored When to use it
user ~/.claude/agent-memory/<name>/ Knowledge for all projects
project .claude/agent-memory/<name>/ Knowledge for the project (commit to git)
local .claude/agent-memory-local/<name>/ Knowledge for the project (NOT in git)

With memory turned on, the subagent automatically gets instructions for reading and writing its own MEMORY.md.

Color coding

In the terminal, different subagents show up in different colors. Available: red, blue, green, yellow, purple, orange, pink, cyan.

You can see at a glance who's working right now.


Examples of custom subagents (in the official format)

Code Reviewer (read-only):

Type this into the chat
---
name: code-reviewer
description: Analyzes code for bugs, security and quality. Use AFTER writing any code, before committing.
tools: Read, Glob, Grep
model: sonnet
color: red
memory: project
---

You are a code reviewer. Focus on code quality, security, and best practices.
Check your memory for patterns you've seen before.

Debugger:

Type this into the chat
---
name: debugger
description: Debugging specialist for errors and test failures. Use when there's a specific error message.
tools: Read, Grep, Glob, Bash
model: sonnet
color: yellow
---

You are an expert debugger. Analyze errors, identify root causes, and provide fixes.

Build Validator (on a cheap model):

Type this into the chat
---
name: build-validator
description: Runs tests and checks that the code builds. Use before every deploy.
tools: Bash, Read
model: haiku
color: green
---

Run tests and build checks. Report only failures with error messages.

A subagent with its own MCP server:

Type this into the chat
---
name: browser-tester
description: Tests features in a real browser using Playwright
mcpServers:
  - playwright:
      type: stdio
      command: npx
      args: ["-y", "@playwright/mcp@latest"]
---

Use the Playwright tools to navigate, screenshot, and interact with pages.

Calling a subagent: four ways

1. Automatic delegation: Claude decides on its own based on the subagent's description:

Code
Analyze the database performance
→ Claude sees there's a db-reader subagent → delegates

2. Mentioning it in the prompt: give Claude a hint:

Type this into the chat
Use the code-reviewer subagent to look at my recent changes

3. @-mention: guarantees that a specific subagent is called:

Type this into the chat
@"code-reviewer (agent)" take a look at the auth module

4. Running the whole session as a subagent:

bash
claude --agent code-reviewer

The main prompt is replaced with the subagent's system prompt.

Foreground vs background, and fork

🎨 Picture this: foreground means you hand off the assignment and wait at the door until it's done. Background means you hand it off and go do your own thing: the agent works in parallel, and you're not sitting idle.

  • Foreground: blocks the main conversation until it finishes. Permission requests come through to you.
  • Background: works in parallel while you keep going. In current interactive sessions, subagents run in the background by default (fork mode is on). Permission requests pop up in the main session with the subagent's name.

Press Ctrl+B to send the current task to the background.

Fork: a subagent that inherits the whole conversation (system prompt, history, tools, model) instead of starting from a blank slate. It uses the shared prompt cache, so it's cheaper than a regular subagent. To launch a fork manually: /subtask <task description>.

When to use subagents

✅ Use subagents when:

  • A task produces lots of output you don't need in the main context (tests, logs, documentation)
  • You need to limit the available tools or permissions
  • The work is self-contained and a summary can be returned
  • The task gets run many times across different projects

✅ Parallel research:

Type this into the chat
Explore the authentication, database and API modules in parallel in separate subagents

Each subagent explores its own area independently, then Claude synthesizes the findings.

❌ Don't use subagents when:

  • The task needs a lot of back-and-forth (iterative refinement)
  • Several phases share significant context (plan → implement → test)
  • It's a quick targeted edit (the overhead outweighs the task itself)
  • Speed matters: a subagent starts from zero and spends time gathering context

For a quick question about the current context, use /btw instead of a subagent: it sees the full context but has no tools.


Practice

Assignment 1: Create a "researcher" subagent by asking Claude

  1. Open Claude Code
  2. Ask: "Create a personal subagent market-researcher in ~/.claude/agents/," and describe the parameters:
    • Name: market-researcher
    • Description: explain when to use it (2-3 sentences)
    • Tools: read-only and web search
    • Model: haiku (to save money)
    • Color: green
    • Memory: not needed
  3. Open the file it created and check the frontmatter
  4. Test it: ask Claude to "use the market-researcher subagent to research the top 3 competitors in the online education niche"
  5. Watch the main agent delegate the task to the subagent in the terminal (in green)
  6. Make sure the subagent returned a structured summary

Assignment 2: Create a subagent by hand as a file

  1. Create the file .claude/agents/code-reviewer.md:
Type this into the chat
---
name: code-reviewer
description: Reviews code for quality, security, and best practices. Use proactively after code changes.
tools: Read, Glob, Grep
model: sonnet
color: red
memory: project
---

You are a senior code reviewer. Analyze code and provide specific,
actionable feedback on quality, security, and best practices.
Update your agent memory with patterns and conventions you discover.
  1. Restart your Claude Code session
  2. Check: type @ and make sure code-reviewer shows up in the suggestions
  3. Test it: @"code-reviewer (agent)" take a look at the file server.ts

Assignment 3 (bonus): Create a subagent through the CLI

bash
claude --agents '{"quick-search": {"description": "Fast codebase search", "prompt": "Search the codebase and return concise findings.", "tools": ["Read", "Grep", "Glob"], "model": "haiku"}}'

Tools and resources

  • Asking Claude: the main way to create a subagent (the /agents wizard was removed in version 2.1.198; the command now just reminds you about the folders)
  • claude agents: a screen showing all background sessions (agent view, research preview), not a list of subagent files
  • .claude/agents/: the folder for project subagents (.md files with YAML frontmatter)
  • ~/.claude/agents/: the folder for user subagents (available in all projects)
  • Built-in agents: Explore (read-only), Plan (read-only), General-purpose (all tools), fork
  • Documentation: https://code.claude.com/docs/en/sub-agents

Key takeaways

A subagent is a hired specialist. Hire them, explain the task, get the result, let them go. Your main context stays clean.

A subagent file = Markdown with YAML frontmatter. 18 configuration fields: from model and tools to memory, hooks and its own MCP servers.

The principle of least privilege: tools: Read, Grep, Glob means the researcher reads and doesn't write. disallowedTools: Write, Edit is another route to the same result.

Haiku for data collection, Sonnet for analysis, Opus for strategy. The right model = savings several times over.

Nesting is limited to three levels. To start, keep the chain flat: call subagents one at a time from the main conversation.

A subagent with memory: project builds up knowledge between sessions. After 10 code reviews, it knows your project's patterns.


What's next

→ Agent teams: working in parallel

The mark stays in this browser only and is never sent anywhere. My progress