Subagents — Specialized AI Workers
When you ask Claude Code to investigate your authentication module, run the test suite, and then fix failing tests, everything happens in one conversation. Every file read, every command output, every intermediate result accumulates in the same context window. By the time Claude gets to fixing the tests, the context is cluttered with exploration output it no longer needs.
Subagents solve this. They are specialized AI instances that Claude spawns to handle specific tasks in isolated contexts. Each subagent gets its own context window, its own system prompt, and a defined set of tools. When the subagent finishes, only a summary of its results returns to the main conversation -- keeping your primary context clean and focused.
Think of subagents as function calls to other AI instances. You describe the task, the subagent works autonomously, and you get back the result without paying the context cost of every intermediate step.
Learning Objectives
- Understand what subagents are and why context isolation matters
- Use the three built-in subagent types: Explore, Plan, and general-purpose
- Create custom subagents with focused prompts and restricted tool access
- Control subagent capabilities through tool allowlists and permission modes
- Apply subagent patterns for parallel research, chained workflows, and cost optimization
Built-in Subagent Types
Claude Code ships with three built-in subagents that it automatically delegates to when appropriate. You do not need to configure anything -- Claude recognizes when a task fits a subagent's profile and delegates accordingly.
Explore
The Explore subagent is a fast, read-only agent optimized for codebase navigation. It runs on Haiku for low-latency responses and has access only to read-only tools (Glob, Grep, Read). It cannot edit or write files.
"Search the codebase and find every file that imports the AuthService class"
Claude delegates this to Explore because it requires searching across many files without making changes. The exploration happens in Explore's isolated context, and only the summarized findings return to your main conversation.
When invoking Explore, Claude specifies a thoroughness level:
- Quick -- targeted lookups for specific files or patterns
- Medium -- balanced exploration across related modules
- Very thorough -- comprehensive analysis spanning the entire codebase
When Explore Shines
Use Explore for tasks that produce high-volume output you do not need in your main context: searching for all usages of a function, mapping out import graphs, or understanding how a module is structured. The verbose output stays in Explore's context while you get a clean summary.
Plan
The Plan subagent is a research agent used during plan mode to gather context before presenting an implementation plan. It inherits the model from your main conversation and has read-only tool access (no Write or Edit).
When you activate plan mode and ask Claude to design an approach, it delegates the codebase research to Plan. The subagent reads files, traces dependencies, and maps out the relevant code -- then returns its findings so Claude can synthesize them into a coherent plan.
"I want to add WebSocket support to the notification system. Enter plan mode
and design an approach."
Claude's Plan subagent researches the existing notification system, identifies integration points, and feeds its findings back. You receive a structured plan without your main context being filled with every file the subagent read.
General-Purpose
The general-purpose subagent is a full-capability agent with access to all tools, including Bash, Write, and Edit. It inherits the model from your main conversation and handles complex, multi-step tasks that require both exploration and modification.
"Use a subagent to run the full test suite and fix any failing tests"
This task requires reading test files, executing commands, interpreting output, and editing code -- a combination that only the general-purpose subagent can handle. The test output (which can be enormous) stays in the subagent's context, and you get back a summary of what failed and what was fixed.
Choosing the Right Built-in Subagent
| Subagent | Model | Tools | Best For |
|---|---|---|---|
| Explore | Haiku (fast) | Read-only (Glob, Grep, Read) | Codebase search, file discovery, architecture mapping |
| Plan | Inherited | Read-only (Glob, Grep, Read) | Research for implementation planning, dependency analysis |
| General-purpose | Inherited | All tools | Multi-step tasks, code modifications, test-fix cycles |
Claude automatically selects the right subagent based on the task. You can also explicitly request one:
"Use the Explore subagent to map out the database schema across all migration files"
When to Use Subagents
Not every task warrants a subagent. The overhead of spawning a separate context and summarizing results means subagents add latency compared to doing the work inline. Use them when the benefits outweigh the cost.
Use subagents when:
- The task produces verbose output -- Test suites, log analysis, and documentation fetches generate output you do not need cluttering your main context.
- You want parallel investigation -- Spawn multiple subagents to research authentication, database, and API modules simultaneously.
- You need tool restrictions -- A code review subagent that can read but not modify files enforces discipline.
- The work is self-contained -- Tasks with clear inputs and outputs that do not require back-and-forth with you.
Stay in the main conversation when:
- You need iterative refinement -- Tasks requiring frequent back-and-forth with you are awkward through a subagent.
- Context is shared across phases -- If planning and implementation need the same context, splitting them wastes effort.
- The task is quick -- Simple edits or single-file changes do not justify the subagent overhead.
- Latency matters -- Subagents need time to build their own context from scratch.
Subagent Nesting Limit
Subagents cannot spawn other subagents. This is a hard constraint that prevents infinite nesting. If your workflow requires sequential delegation, chain subagents from the main conversation instead of trying to nest them.
Creating Custom Subagents
The built-in subagents cover common patterns, but custom subagents let you define specialized workers tailored to your project. Custom subagents are Markdown files with YAML frontmatter stored in the .claude/agents/ directory.
Subagent File Structure
A subagent file has two parts: YAML frontmatter for configuration and a Markdown body that becomes the system prompt.
---
name: code-reviewer
description: Reviews code for quality, security, and best practices. Use after writing or modifying code.
tools: Read, Grep, Glob, Bash
model: sonnet
---
You are a senior code reviewer. When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately
Review checklist:
- Code clarity and readability
- Proper error handling
- No exposed secrets or API keys
- Input validation
- Test coverage
Provide feedback by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)
Include specific examples of how to fix issues.Creating Subagents with /agents
The easiest way to create a subagent is through the interactive /agents command:
Open the subagents interface
Run /agents in Claude Code. This shows all available subagents (built-in and custom) and gives you options to create, edit, or delete.
Choose scope
Select Create new agent, then choose the scope:
- Project-level (
.claude/agents/) -- available only in this project, shareable via version control - User-level (
~/.claude/agents/) -- available in all your projects
Define the agent
Choose Generate with Claude and describe what the subagent should do. Claude generates a system prompt and configuration. Press e to open it in your editor for customization.
Select tools and model
Choose which tools the subagent can access and which model it should use. For read-only agents, deselect everything except read-only tools.
Save and use
Save the subagent. It is available immediately without restarting. Test it by asking Claude to use it:
Use the code-reviewer subagent to review my recent changes
Key Frontmatter Fields
| Field | Required | Description |
|---|---|---|
name | Yes | Unique identifier (lowercase, hyphens) |
description | Yes | When Claude should delegate to this subagent |
tools | No | Allowlist of tools (inherits all if omitted) |
disallowedTools | No | Denylist of tools to remove from inherited set |
model | No | sonnet, opus, haiku, or inherit (default: inherit) |
permissionMode | No | default, acceptEdits, dontAsk, bypassPermissions, or plan |
maxTurns | No | Maximum agentic turns before the subagent stops |
memory | No | Persistent memory scope: user, project, or local |
The description field is critical -- Claude uses it to decide when to delegate tasks. Write it as a clear statement of the subagent's purpose, optionally including "use proactively" to encourage automatic delegation.
Tool Restrictions and Permission Modes
One of the most powerful aspects of custom subagents is controlling what they can and cannot do. This lets you enforce safety constraints and create focused, predictable workers.
Tool Allowlists
The tools field specifies exactly which tools a subagent can access:
---
name: safe-researcher
description: Research agent that can explore but never modify code
tools: Read, Grep, Glob
---This subagent can search and read files but cannot execute commands, edit files, or write new files. If it attempts a restricted operation, the tool call fails.
Tool Denylists
When you want a subagent to inherit most tools but exclude a few, use disallowedTools:
---
name: careful-coder
description: Implements features but cannot run arbitrary bash commands
disallowedTools: Bash
---This subagent can read and edit files but cannot execute shell commands -- useful when you want code modifications without the risk of unintended side effects from scripts.
Permission Modes
The permissionMode field controls how the subagent handles permission prompts:
| Mode | Behavior |
|---|---|
default | Standard permission checking with prompts |
acceptEdits | Auto-accept file edits without prompting |
dontAsk | Auto-deny permission prompts (only explicitly allowed tools work) |
plan | Read-only exploration mode |
bypassPermissions | Skip all permission checks (use with extreme caution) |
For most custom subagents, stick with default or dontAsk. Reserve bypassPermissions for trusted automation scripts where you have reviewed the subagent's prompt and tool access carefully.
Conditional Validation with Hooks
For fine-grained control beyond simple allowlists, use PreToolUse hooks. This lets a subagent have access to a tool but validates each invocation:
---
name: db-reader
description: Execute read-only database queries for analysis and reporting
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
---
You are a database analyst with read-only access.
Execute SELECT queries to answer questions about the data.The validation script receives the command as JSON via stdin and exits with code 2 to block write operations (INSERT, UPDATE, DELETE, DROP). This gives you tool access with guardrails -- the subagent can run Bash commands, but only ones that pass your validation.
Subagent Communication and Context
Understanding how information flows between the main conversation and subagents helps you use them effectively.
Information Flow
- Main agent sends a task -- Claude describes what the subagent should do, including any relevant context
- Subagent works autonomously -- It reads files, runs commands, and reasons independently in its own context
- Results return summarized -- The subagent's findings are compressed into a summary that returns to the main conversation
The subagent does not see your full conversation history. It receives only the task description, its own system prompt, and basic environment details (working directory, etc.).
Foreground vs. Background Execution
Subagents can run in two modes:
- Foreground (blocking) -- The main conversation waits until the subagent finishes. Permission prompts pass through to you.
- Background (concurrent) -- The subagent runs while you continue working. Claude pre-approves permissions before launching. Press
Ctrl+Bto background a running subagent.
Background subagents are ideal for long-running tasks like test suites or large-scale searches. If a background subagent fails due to missing permissions, you can resume it in the foreground.
Persistent Memory
Custom subagents can maintain memory across sessions with the memory field:
---
name: code-reviewer
description: Reviews code with growing knowledge of project patterns
memory: project
---
You are a code reviewer. As you review code, update your agent memory
with patterns, conventions, and recurring issues you discover.The memory scope determines where the knowledge is stored:
user(~/.claude/agent-memory/<name>/) -- learnings apply across all projectsproject(.claude/agent-memory/<name>/) -- project-specific, shareable via version controllocal(.claude/agent-memory-local/<name>/) -- project-specific, not checked into version control
When memory is enabled, the subagent automatically gets Read, Write, and Edit tools for its memory directory, and its system prompt includes instructions for maintaining a MEMORY.md file. Over time, the subagent builds institutional knowledge that makes it more effective.
CLAUDE.md Access
Subagents can access your project's CLAUDE.md and any project context files. This means project conventions, coding standards, and architectural decisions are available to every subagent automatically. Custom subagents can supplement this with their own system prompt for domain-specific instructions.
Practical Patterns
Parallel Research
Investigate multiple areas of a codebase simultaneously:
Research the authentication, database, and API modules in parallel
using separate subagents. Summarize how each module handles errors.
Claude spawns three subagents that work independently. Each explores its area and returns findings. Claude then synthesizes a unified summary. This is faster than sequential investigation and keeps all the exploration output out of your main context.
Chained Workflows
Use subagents in sequence where each step builds on the previous:
Use the code-reviewer subagent to find performance issues, then use
the optimizer subagent to fix them.
The code-reviewer finds the issues, its results return to Claude, and Claude passes the relevant findings to the optimizer subagent with clear instructions on what to fix.
Cost Optimization with Model Selection
Route simple tasks to cheaper, faster models:
---
name: quick-search
description: Fast codebase searches for simple lookups
tools: Read, Grep, Glob
model: haiku
---By assigning Haiku to routine search tasks and reserving Opus or Sonnet for complex reasoning, you reduce costs without sacrificing quality where it matters.
Create a Security Auditor Subagent
intermediate20 minBuild a custom subagent that audits your codebase for common security issues. This subagent should have read-only access to prevent accidental modifications during the audit.
Create the agent file
Create .claude/agents/security-auditor.md with the following content:
---
name: security-auditor
description: Audits code for security vulnerabilities, exposed secrets, and unsafe patterns. Use proactively after code changes or before deployments.
tools: Read, Grep, Glob
model: sonnet
---
You are a security auditor. When invoked, scan the codebase for:
1. **Exposed secrets**: API keys, tokens, passwords in source files
2. **Injection vulnerabilities**: SQL injection, XSS, command injection
3. **Authentication issues**: Missing auth checks, weak token validation
4. **Dependency risks**: Known vulnerable packages in lock files
5. **Unsafe patterns**: eval(), dangerouslySetInnerHTML, shell exec with user input
For each finding, report:
- Severity: Critical / High / Medium / Low
- File and line number
- Description of the vulnerability
- Recommended fix
Start by scanning for exposed secrets (grep for API_KEY, SECRET, PASSWORD, TOKEN
in non-test files), then check for injection patterns, then review auth flows.Verify tool restrictions
Notice the tools field only includes Read, Grep, Glob. The subagent cannot modify your code, run shell commands, or write files. This is intentional -- an auditor should observe and report, not change anything.
Test the subagent
Ask Claude to use your new subagent:
Use the security-auditor subagent to audit the src/ directory
Review the results
The subagent returns a prioritized list of findings. Review each one and decide which need immediate attention. Because the subagent is read-only, you can trust that it has not modified any files during the audit.
Iterate on the prompt
Based on the results, refine the system prompt. If the subagent produces too many false positives, add exclusion patterns. If it misses certain vulnerability types, add them to the checklist.
Bonus challenge: Create a second subagent called security-fixer with Write and Edit tools that takes the auditor's findings and applies fixes. Chain them together: audit first, then fix.
Disabling Subagents
If a built-in subagent is not useful for your workflow, you can disable it in your settings:
{
"permissions": {
"deny": ["Task(Explore)", "Task(my-custom-agent)"]
}
}Or via the CLI flag:
claude --disallowedTools "Task(Explore)"This prevents Claude from delegating to the specified subagents. Use this when a subagent consistently makes poor decisions for your particular codebase or when you want full control over delegation.
Key Takeaway
- Subagents are isolated AI workers that keep your main context clean by handling tasks in separate context windows
- Three built-in types cover most needs: Explore (fast search), Plan (architecture research), and general-purpose (full capabilities)
- Custom subagents are Markdown files in
.claude/agents/with a system prompt and tool configuration - Tool restrictions enforce safety -- read-only auditors, no-bash coders, and validated database queries
- Persistent memory lets subagents build knowledge across sessions, becoming more effective over time
- Parallel subagents speed up research; chained subagents enable multi-step workflows; model selection optimizes costs
Next Steps
You now know how to delegate work to specialized subagents within a single session. But what happens when you need multiple agents working in parallel across separate sessions, communicating with each other in real time? The next lesson covers Agent Teams -- Claude Code's system for orchestrating coordinated multi-agent workflows at scale.
Resources:
- Claude Code Subagents Documentation
- Run
/agentsin Claude Code to manage your subagents interactively - Example subagents in the official documentation cover code reviewers, debuggers, data scientists, and database validators