Claude Code Subagents enable parallel task delegation through specialized AI assistants with isolated context windows, toolsets, and system prompts. This guide covers creating, configuring, and working with subagents defined as markdown files with YAML frontmatter, which can be managed via CLI flags, project directories, or user directories across different projects.
Subagents can also leverage advanced MCP configuration to access external tools and data sources.Subagents maintain clean context during lengthy tasks, enable parallel work, and allow packaging domain expertise into reusable agents. Configuration options include tool restrictions, model selection, reasoning depth control, and isolation settings like worktree separation for safe code modifications without affecting the main working tree.
Claude Code Subagents enable parallel task delegation. This guide covers agent isolation, multi-agent workflows, and when to delegate work to subagents.

- Claude Code Subagents: What You’ll Learn
- Creating Subagents
- Configuration Options
- Using and Chaining Subagents
- Real-World Subagent Examples
- Pro Tips
- Hands-On Challenge
- Knowledge Check
- Q1: What is the main advantage of subagents over inline conversation?
- Q2: What is the priority order for agent definitions?
- Q3: Which built-in subagent uses the Haiku model and is optimized for read-only codebase exploration?
- Q4: How do you restrict which subagents a coordinator agent can spawn?
- Q5: What does isolation: worktree do for a subagent?
- Test Your Knowledge
- Additional Resources
- Delegating a Task to a Subagent: A Step-by-Step Walkthrough
- Claude Code Subagents: Common Mistakes to Avoid
- Claude Code Subagents: Best Practices
- Claude Code Subagents: Frequently Asked Questions
- Continue Learning
Claude Code Subagents: What You’ll Learn
For a side-by-side comparison of when to choose subagents over skills, hooks, or plugins, see our extensibility decision guide.In this guide to Claude Code Subagents, you’ll work through practical, hands-on steps with real examples. Claude Code Subagents is explained from the ground up so you can apply it immediately in your own projects.
Subagents enable Claude to hand off work to specialized AI assistants, each operating with its own isolated context window, toolset, and system prompt. This approach keeps context clean during lengthy tasks, enables parallel work, and lets you package domain expertise into reusable agents. This lesson walks through creating, configuring, and working with subagents.
Creating Subagents
Subagents are defined as markdown files with YAML frontmatter. You can make them available in several ways: use the --agents CLI flag for a single session, place them in .claude/agents/ for project-wide availability (and commit them to git), or put them in ~/.claude/agents/ for personal use across all projects. Plugins can also bundle agents. The priority order is: managed first, then CLI flag, project, user, and finally plugin. Built-in subagents are always present and don’t participate in the name-override system. The /agents command opens an interactive menu to create, edit, and manage your agents.
The frontmatter establishes the agent’s identity, while the markdown body serves as its system prompt — think of it as briefing a specialist:
---
name: security-reviewer
description: Security-focused code reviewer. Use proactively after writing authentication, authorization, or data handling code.
tools: Read, Grep, Glob
---
You are a senior security engineer specializing in application security.
Review priorities:
1. Authentication and authorization flaws
2. Injection vulnerabilities (SQL, XSS, command)
3. Data exposure and sensitive information handling
4. Cryptographic weaknesses
5. Insecure direct object references
For each finding, provide: severity (Critical/High/Medium/Low), location (file:line), description, and a concrete fix with code example.
When invoked: run `git diff HEAD` first to focus on changed code.
The tools field limits which tools the agent can access. A security reviewer only needs Read, Grep, and Glob — no write permissions required. An implementation agent, on the other hand, needs the complete toolset. Restricting tools makes agents both safer and more predictable. If you leave out the tools field, the agent inherits every available tool.
Configuration Options
Beyond basic tool access, the frontmatter supports a range of powerful configuration options. The model field selects which model the agent runs on — haiku for quick lightweight tasks, sonnet for balanced workloads, or opus for complex reasoning. Use inherit to take the parent’s model. The effort field controls reasoning depth on supported models, accepting values low, medium, high, xhigh, max, and auto. maxTurns limits how long the agent can run, and permissionMode sets the permission level. Additional fields include disallowedTools, skills to preload specific skills, mcpServers for agent-scoped MCP access, and initialPrompt to automatically submit the first turn.
The memory field gives agents persistent storage that survives across sessions. The first 200 lines of a MEMORY.md file in the agent’s memory directory are automatically loaded into its system prompt — Claude writes to this file as it learns:
---
name: researcher
memory: user
description: Long-running research assistant with persistent notes
---
You are a research assistant. Check your MEMORY.md at session start to recall previous findings. Update it with new discoveries.
Setting isolation: worktree gives the agent its own git worktree and branch, so it can make changes without touching your main working tree. When the agent completes, it returns the worktree path and branch name for you to review and merge. If no changes were made, the worktree is automatically cleaned up. While the agent is running, Claude locks the worktree to prevent concurrent cleanup, releasing the lock once it finishes. The worktree branches from your repository’s default branch (origin/HEAD) unless you configure worktree.baseRef to head in settings, which makes isolated agents start from your local HEAD and carry along unpushed work.
Setting background: true forces the agent to always run as a background task, freeing up the main conversation. You can also press Ctrl+B to background an agent that’s currently running in the foreground.
Two CLI flags extend what a session can reach. --add-dir <path> grants Read/Edit access to extra directories beyond the primary working directory — handy when your code references shared libraries or monorepo packages in sibling folders. Skills in .claude/skills/ within added directories load automatically. Persist these with permissions.additionalDirectories in settings. --mcp-config <path> loads MCP server definitions from JSON files for the current session only, merged with your user/project sources. Add --strict-mcp-config to ignore user/project sources and use only the provided files:
claude --add-dir ~/projects/shared-types --add-dir ~/projects/design-tokens
claude --mcp-config ./ci-servers.json
Using and Chaining Subagents
Claude invokes agents automatically when a task matches the agent’s description field. Phrases like “use proactively” can encourage delegation, but for reliable results when you need a specific agent, explicit invocation is the way to go. Use the @"agent-name (agent)" syntax to guarantee a specific agent is used, bypassing automatic matching.
Natural language explicit invocation also works:
Use the security-reviewer agent to audit the new auth module.
Have the test-engineer agent write integration tests for the payment service.
Ask the debugger agent to investigate the memory leak in src/workers/queue.ts.
Agents can be chained sequentially, where one agent’s output feeds into the next. Running claude agents from the terminal opens the Agent view — a roster of all Claude Code sessions showing their state (working, waiting, completed, failed, idle, stopped) and last activity. This is great for monitoring multiple agents running in parallel. Pass --cwd <path> to filter the roster to sessions started under that directory — useful when you juggle several repos and want a scoped view. Set CLAUDE_CODE_DISABLE_AGENT_VIEW=1 to disable it. You can also run a full session with a specific agent via claude --agent <name>, and restrict which agents a coordinator can spawn using Agent(...) tool allowlists.
# Only show agent sessions started under ~/work/api
claude agents --cwd ~/work/api
For scripts that need to consume the roster — tmux-resurrect-style boot scripts, custom status bars, session pickers — pass --json to claude agents to get machine-readable data as an array instead of the interactive view. Each entry includes pid, cwd, kind, and startedAt, plus sessionId, name, and status when available. When status is waiting, waitingFor specifies exactly what the session is blocked on, such as permission prompt or input needed, allowing scripts to route those cases to different actions:
# Wake up every session that's blocked on a permission prompt
claude agents --json | jq -r '.[] | select(.status == "waiting" and .waitingFor == "permission prompt") | .sessionId' | xargs -I {} claude respawn {}
First use the code-analyzer agent to find performance bottlenecks, then use the optimizer agent to fix them.
Claude Code includes several built-in agents you don’t need to create: general-purpose handles broad multi-step tasks, Explore uses Haiku for fast read-only codebase analysis, Plan researches the codebase before presenting implementation plans, and claude-code-guide answers questions about Claude Code features. Agents can also be resumable, allowing Claude to continue a previous agent conversation by ID when a workflow spans multiple turns.
Set CLAUDE_CODE_FORK_SUBAGENT=1 to enable forked subagents. A forked subagent inherits the full conversation context from the main session instead of starting from scratch. When enabled, /fork spawns a forked subagent rather than acting as an alias for /branch, and all subagent spawns run in the background. This works in interactive sessions, non-interactive mode, the Agent SDK, and on external builds:
CLAUDE_CODE_FORK_SUBAGENT=1 claude
The experimental Agent Teams feature (requires CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 or the --agent-teams CLI flag) coordinates multiple Claude instances working in parallel through a shared task list and mailbox. This is designed for large multi-file projects where independent agents can work on different parts simultaneously without stepping on each other.
SendMessage automatically resumes stopped agents when a message is sent to them, so you no longer need to explicitly resume an agent before communicating with it. As of v2.1.178, the TeamCreate and TeamDelete tools were removed: with the flag set, every session already has one implicit team, so you spawn teammates directly through the Agent tool’s name parameter — no setup step — and cleanup happens automatically when the session exits.
Real-World Subagent Examples
Here are production-ready subagent definitions you can drop into your project’s .claude/agents/ directory:
Example 1: Code Reviewer Agent
A specialized reviewer that automatically inspects modified code for security vulnerabilities, performance issues, and quality standards:
---
name: code-reviewer
description: Expert code review specialist. Use PROACTIVELY after writing or modifying code.
tools: Read, Grep, Glob, Bash
model: inherit
---
# Code Reviewer Agent
When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately
## Review Priorities (in order)
1. Security Issues - Authentication, authorization, data exposure
2. Performance Problems - O(n^2) operations, memory leaks, inefficient queries
3. Code Quality - Readability, naming, documentation
4. Test Coverage - Missing tests, edge cases
5. Design Patterns - SOLID principles, architectureExample 2: Performance Optimizer Agent
An agent that profiles, identifies bottlenecks, and implements optimizations with before/after metrics:
---
name: performance-optimizer
description: Performance analysis and optimization specialist. Use PROACTIVELY after writing or modifying code.
tools: Read, Edit, Bash, Grep, Glob
model: inherit
---
# Performance Optimizer Agent
When invoked:
1. Profile the target code or system
2. Identify the most impactful bottlenecks
3. Propose and implement optimizations
4. Measure and verify improvements
## Common Profiling Commands
# Node.js
node --prof app.js
# Python
python -m cProfile -s cumulative script.py
# Go
go test -cpuprofile=cpu.out ./...
# Database (PostgreSQL)
EXPLAIN ANALYZE SELECT ...;Example 3: Test Engineer Agent
A test automation expert that writes comprehensive tests including edge cases and error scenarios:
For automated pipelines, Claude Code headless mode lets you script subagent interactions without interactive prompts.---
name: test-engineer
description: Test automation expert. Use PROACTIVELY when new features are implemented.
tools: Read, Write, Bash, Grep
model: inherit
---
# Test Engineer Agent
## Coverage Requirements
- Minimum 80% code coverage
- 100% for critical paths (auth, payments, data handling)
## Test Structure Example
describe('Feature: User Authentication', () => {
beforeEach(() => { /* Setup */ });
afterEach(() => { /* Cleanup */ });
it('should authenticate valid credentials', async () => {
// Arrange, Act, Assert
});
it('should reject invalid credentials', async () => {
// Test error case
});
});Pro Tips
- Start restrictive, expand on demand. Grant only the tools a subagent genuinely needs—for example, a reviewer only needs
Read, Grep, Glob. You can always add tools later when requirements demand it. - Write focused, single-purpose prompts. A code reviewer should not also write documentation. Overlapping responsibilities create confusion and reduce success rates. Design each subagent around one clear responsibility.
- Encourage proactive invocation. Add the phrase “use PROACTIVELY” or “MUST BE USED” to the
descriptionfield so Claude delegates automatically when the situation arises, instead of waiting for explicit requests. - Version-control project agents. Check
.claude/agents/into git so your whole team benefits from the same specialized subagents and configuration stays consistent. - Use chaining for complex workflows. Ask Claude to run agents in sequence (e.g. “first analyze with the code-analyzer agent, then fix issues with the optimizer agent”) to build pipelines where one agent's output feeds the next.
Hands-On Challenge
Build a team of specialized subagents to automate your code review workflow end-to-end.
Task
Create a project-level subagent team with two agents: a read-only security reviewer and a test engineer that can write missing tests. Then chain them so that security findings are addressed before test coverage is checked.
Steps
- Create the
.claude/agents/directory in your project. - Write
secure-reviewer.mdwith YAML frontmatter granting onlyRead, Greptools and a system prompt focused on authentication, injection, and data-exposure vulnerabilities. Include the phrase “use PROACTIVELY” in the description so it is auto-invoked. - Write
test-engineer.mdwith toolsRead, Write, Bash, Grepand a prompt targeting >80% coverage and edge-case identification. - Run
/agentsto verify both agents appear in the interactive list. - Make a small code change, then ask Claude to “First use the secure-reviewer subagent to audit the changes, then use the test-engineer subagent to add any missing tests.”
- Verify the security agent could not modify files (read-only) while the test agent could.
Expected Outcome
Two subagent files in .claude/agents/, both visible in /agents, chained execution producing a security report followed by new or updated test files, and confirmation that tool restrictions were enforced.
Hint
Remember that the
toolsfield controls what each agent can do. Omit it to inherit everything, or list specific tools liketools: Read, Grepfor a read-only agent. Use the@prefix (e.g.@"secure-reviewer (agent)") to guarantee a specific agent is invoked.
Knowledge Check
Test your understanding of Claude Code subagents with these questions:
Q1: What is the main advantage of subagents over inline conversation?
A) They are faster
B) They operate in a separate, clean context window preventing context pollution
C) They can use more tools
D) They have better error handling
Correct answer: B — Subagents get a fresh context window, receiving only what the main agent passes. This prevents the main conversation from being polluted with task-specific details.
Q2: What is the priority order for agent definitions?
A) Project > User > CLI
B) CLI > Project > User
C) User > Project > CLI
D) They all have equal priority
Correct answer: B — CLI-defined agents (--agents flag) override Project-level (.claude/agents/), which override User-level (~/.claude/agents/).
Q3: Which built-in subagent uses the Haiku model and is optimized for read-only codebase exploration?
A) general-purpose
B) Plan
C) Explore
D) Bash
Correct answer: C — The Explore subagent uses Haiku for fast, read-only codebase exploration. It supports three thoroughness levels: quick, medium, very thorough.
Q4: How do you restrict which subagents a coordinator agent can spawn?
A) Use allowed-agents: field
B) Use Task(agent_name) syntax in the tools field
C) Set spawn-limit: 2
D) Use restrict-agents: [name1, name2]
Correct answer: B — Adding Task(worker, researcher) in the tools field creates an allowlist — the agent can only spawn subagents named “worker” or “researcher”.
Q5: What does isolation: worktree do for a subagent?
A) Runs the agent in a Docker container
B) Gives the agent its own git worktree so changes don’t affect the main tree
C) Prevents the agent from reading any files
D) Runs the agent in a sandbox
Correct answer: B — Worktree isolation creates a separate git worktree. If the agent makes no changes, it auto-cleans up. If changes are made, the worktree path and branch are returned.
Test Your Knowledge
Additional Resources
| Resource | Type | What You'll Learn |
|---|---|---|
| Official Subagents Documentation | Docs | Core concepts, configuration fields, and the full lifecycle of a subagent |
| Agent Teams (Experimental) | Docs | Multi-agent coordination with shared task lists and inter-agent messaging |
CLI Reference — --agents flag | Reference | Defining agents via JSON for single-session use |
| Claude Code Changelog | Changelog | Subagent nesting (v2.1.172), case-insensitive matching (v2.1.140), observability headers (v2.1.139) |
| Plugins Guide | Guide | Bundling subagents into distributable plugin packages |
Claude Code Subagents gives you a solid, repeatable workflow. Bookmark this Claude Code Subagents guide and revisit the steps whenever you need them.

Delegating a Task to a Subagent: A Step-by-Step Walkthrough
Subagents earn their keep on tasks that are well-scoped but noisy — the kind of work that would otherwise fill your main context with file listings, log output, and dead ends. This walkthrough builds a migration-runner subagent that can safely apply a database migration in isolation and hand back a clean summary.
- Write the agent file. Create
.claude/agents/migration-runner.mdwith frontmatter that limits the toolset to exactly what the task needs and turns on worktree isolation:--- name: migration-runner description: Applies pending database migrations and reports the result. Use PROACTIVELY when the user mentions running or testing a migration. tools: Read, Bash, Grep isolation: worktree --- You are a database migration specialist. Run pending migrations against the test database, capture the output, and report success or the exact failure. Never touch the production connection string. - Scope the tools deliberately. This subagent gets
Read,Bash, andGrep— noWriteorEdit, since it only needs to run commands and inspect output, not modify application code. - Invoke it explicitly the first few times. Say “use the migration-runner agent to apply the pending migrations” or use the
@"migration-runner (agent)"syntax to guarantee it’s the one that runs, rather than relying on automatic matching while you’re still building confidence in its behavior. - Let worktree isolation do its job. Because
isolation: worktreeis set, the subagent works in its own git worktree and branch. If the migration fails partway through, your main working tree is untouched — you review the worktree path Claude Code returns, decide whether to keep or discard it, and only merge once you’re satisfied. - Chain it with a follow-up agent. Once migrations succeed, ask Claude to “use the test-engineer agent to run the integration suite against the migrated schema” — the second subagent starts with a fresh context and only the summary the first one produced, not the raw migration logs.
- Check the roster while it runs. Run
claude agentsin a second terminal to see the subagent’s live status — working, waiting, or completed — which is especially useful once you’re running more than one subagent for the same task.
The pattern generalizes past database migrations: any task with a clear boundary, a small toolset, and output you don’t want cluttering your main conversation is a good candidate for one of your Claude Code Subagents. The isolation and tool restrictions are what make delegation safe rather than just convenient.
Claude Code Subagents: Common Mistakes to Avoid
Subagents are easy to misuse in ways that cost more time than they save. These four mistakes show up most often once teams start delegating work.
- Granting the full default toolset to every subagent instead of scoping tools to what the task actually needs, which turns a “safe” read-only reviewer into one that can also edit files.
- Spinning up a subagent for a two-line fix — the overhead of a fresh context and a summary hand-off costs more than just making the change directly in the main session.
- Writing an overlapping description for two subagents, so Claude can’t reliably decide which one should handle a given task automatically.
- Forgetting that a subagent’s context is isolated, then being surprised it doesn’t remember something discussed earlier in the main conversation — pass that context explicitly instead of assuming it carries over.
Claude Code Subagents: Best Practices
- Delegate independent, parallelizable work to subagents; keep sequential work in the main thread.
- Give each subagent a single clear objective and the context it needs.
- Use isolation so parallel agents do not clobber each other in shared files.
- Summarize subagent results back into the main thread to keep context tight.
- Avoid over-delegation; spinning up agents for trivial tasks adds overhead.

Claude Code Subagents: Frequently Asked Questions
Do subagents share the main conversation’s context?
No. Each of the Claude Code Subagents starts with a fresh, isolated context window and only receives what the main agent explicitly passes to it.
Can a subagent spawn other subagents?
Yes, subject to nesting limits and any Task(…) allowlist set in the parent’s tools field, which restricts which named agents it’s permitted to spawn.
What happens if a worktree-isolated subagent makes no changes?
The worktree is cleaned up automatically. If changes were made, Claude Code returns the worktree path and branch name so you can review before merging.
How do I force a specific subagent instead of automatic matching?
Use the @”agent-name (agent)” syntax, or ask in plain language — “use the test-engineer agent to…” — for reliable, explicit invocation.
Which model should a subagent run on?
Match the model to the task: haiku for fast, lightweight work, sonnet for balanced tasks, and opus for complex reasoning, or set model: inherit to match the parent session.
Continue Learning
- Claude Code Extensibility: Skills vs Hooks vs Subagents
- Claude Code Advanced Features Guide
- Claude Code Workflows and Automation
- Claude Code Plugins Guide
- Claude Code Headless Mode Guide
- Claude Code MCP Configuration Guide
- Claude Code Worktrees Guide
- Claude Code Token Management Guide
- Agent Teams Orchestration