How to Use Subagents in Claude Code
Subagents are specialized AI helpers that Claude spawns automatically for specific tasks. Learn how Explore, Plan, and custom agents work together to handle complex work efficiently.
Subagents in Claude Code are specialized AI helpers that the main Claude agent spawns automatically to handle specific tasks. The three built-in types are Explore (fast, read-only codebase search), Plan (research and architecture), and custom subagents you define yourself using Skills. They run in parallel, inherit permissions from the parent, and cannot spawn further subagents.
Understanding how subagents work helps you predict when delegation happens, why some tasks finish faster, and how to build your own specialized agents for repetitive workflows.
What Are Subagents?
A subagent is a separate AI agent that Claude Code creates to handle a specific task. Think of it like delegating to a specialist: instead of doing everything itself, Claude assigns certain work to agents that are optimized for that type of task.
Subagents inherit permissions from the parent conversation but have restricted tool access. An exploration subagent can read files but not write them. A planning subagent can research but not modify code.
Key principle: Subagents cannot spawn other subagents. This prevents infinite nesting and keeps things predictable.
When does delegation happen? Claude automatically decides when to use subagents. You don't need to request them explicitly - they appear when the task benefits from specialization.
Built-in Subagent Types
Claude Code includes three built-in subagents, each optimized for different scenarios:
Explore
A fast, lightweight agent for searching and understanding codebases. Claude uses Explore when it needs to search files, understand code structure, or find specific information without making changes. Write and Edit tools are explicitly denied.
Available tools:
- Glob - pattern matching for file discovery
- Grep - content search with regex
- Read - read specific files
- Bash - read-only commands only
Blocked: Write, Edit, and any file modification operations
Plan
A research agent used during plan mode. When you're in planning mode and Claude needs to understand your codebase before proposing changes, it delegates research to Plan. Write and Edit tools are denied.
Available tools:
- Glob - file pattern matching
- Grep - content search
- Read - file reading
- Bash - read-only commands
When it's used: Automatically during /plan mode when Claude needs to gather context before implementation.
General-Purpose
A capable agent for complex, multi-step tasks. Claude uses this when the work requires both exploration and modification, complex reasoning, or multiple dependent steps.
Available tools: All tools available to the main agent
When it's used: Complex tasks that need both reading and writing, or when the task has multiple interdependent parts.
Other Built-in Agents
Claude Code includes additional helper agents for specific tasks. These are typically invoked automatically:
- Bash - Running terminal commands in a separate context (inherits model)
- statusline-setup - Used by
/statuslineto configure your status line (Sonnet) - Claude Code Guide - Answers questions about Claude Code features (Haiku)
When Claude Uses Each Subagent
Claude makes delegation decisions automatically based on what you're asking:
| Task Type | Subagent Used | Why |
|---|---|---|
| "Find all files that import React" | Explore | Read-only search, benefits from speed |
| "How is authentication implemented here?" | Explore | Codebase exploration, no changes needed |
| /plan followed by implementation question | Plan | Research phase of planning mode |
| "Refactor this module and update its tests" | General-Purpose | Complex task requiring read and write |
| "Add error handling to all API endpoints" | General-Purpose | Multiple files, needs both analysis and changes |
Thoroughness Levels
When invoking the Explore subagent, Claude specifies a thoroughness level:
- quick: Targeted lookups, specific questions, fast answers
- medium: Balanced exploration, good default for most searches
- very thorough: Comprehensive analysis, when completeness matters
You don't control this directly - Claude picks based on your question. Asking "where is the User model defined?" triggers quick. Asking "explain the entire authentication system" triggers very thorough.
Viewing Subagent Activity
Use the /agents command to see subagent activity in your session. This shows you which agents have been spawned and their current status.
When a subagent is working, you'll see it indicated in the Claude Code interface. The main conversation waits for the subagent to complete before continuing.
Subagent hooks
You can use the SubagentStop hook event to run commands when subagents finish. This is useful for logging or triggering notifications on complex tasks.
Creating Custom Subagents
Beyond the built-in agents, you can create your own for specialized workflows.
Step 1: Create an agents folder
Create a folder for your custom agent in ~/.claude/agents/:
mkdir -p ~/.claude/agents/reviewer
Step 2: Create AGENT.md
Inside that folder, create an AGENT.md file with your agent's configuration:
---
name: reviewer
description: Reviews code changes for quality and security. Use proactively after code changes.
model: sonnet
tools: Read, Glob, Grep, Bash
---
# Code Reviewer Agent
You review code changes for quality, security, and best practices.
## Process
1. Use `git diff` to see recent changes
2. Read modified files for full context
3. Check for security issues (hardcoded secrets, input validation)
4. Check for performance problems (N+1 queries, missing indexes)
5. Verify test coverage
## Output Format
Report findings as:
- **Critical** - Must fix before merging
- **Warnings** - Should fix, but not blocking
- **Suggestions** - Nice to have improvements
Step 3: Use your agent
Claude can now use your custom agent when appropriate. You can also reference it explicitly in your prompts.
Custom Agent Configuration Options
The AGENT.md frontmatter supports these options:
| Option | Description |
|---|---|
name |
Agent identifier, lowercase with hyphens (required) |
description |
What the agent does and when Claude should delegate to it (required) |
model |
Model alias: sonnet, opus, haiku, or inherit (default: inherit) |
tools |
Tools the agent can use (inherits all if omitted). Use Task(name) to restrict which subagents it can spawn. |
disallowedTools |
Tools to deny, removed from the inherited or specified list |
permissionMode |
Permission mode: default, acceptEdits, dontAsk, delegate, bypassPermissions, or plan |
maxTurns |
Maximum number of agentic turns before the subagent stops |
skills |
Skills to preload into the agent's context at startup |
mcpServers |
MCP servers available to this subagent |
hooks |
Lifecycle hooks scoped to this subagent |
memory |
Persistent memory scope: user, project, or local (enables cross-session learning) |
Custom Agent Example: Documentation Generator
---
name: doc-generator
description: Generates documentation for code. Use proactively for documentation tasks.
model: sonnet
tools: Glob, Read, Write
---
# Documentation Generator
Generate clear, comprehensive documentation for code.
## Process
1. Read the source files to understand the code
2. Identify public APIs, functions, and classes
3. Generate markdown documentation with:
- Overview and purpose
- Installation/setup instructions
- API reference with examples
- Common use cases
## Style Guidelines
- Use clear, simple language
- Include code examples for every public function
- Add "See also" links between related sections
Managing Subagents with /agents
The /agents command provides an interactive interface for managing subagents. Run /agents to:
- View all available subagents (built-in, user, project, and plugin)
- Create new subagents with guided setup or Claude generation
- Edit existing subagent configuration and tool access
- Delete custom subagents
You can also define subagents with the --agents CLI flag when launching Claude Code for quick testing or automation scripts, without saving files to disk.
Foreground vs. Background Execution
Subagents can run in the foreground (blocking) or background (concurrent):
- Foreground subagents block the main conversation until complete. Permission prompts and questions are passed through to you.
- Background subagents run concurrently while you continue working. Before launching, Claude Code prompts for any tool permissions the subagent will need upfront. Press
Ctrl+Bto background a running task.
Claude decides whether to run subagents in foreground or background based on the task. You can also ask Claude to "run this in the background".
Persistent Memory for Subagents
The memory field gives a subagent a persistent directory that survives across conversations. The subagent uses this to build up knowledge over time -- codebase patterns, debugging insights, architectural decisions.
---
name: code-reviewer
description: Reviews code for quality and best practices
memory: user
---
You are a code reviewer. As you review code, update your agent
memory with patterns, conventions, and recurring issues you discover.
Memory scopes: user (across all projects, in ~/.claude/agent-memory/), project (shareable via git, in .claude/agent-memory/), or local (project-specific, gitignored). When enabled, the subagent's system prompt includes the first 200 lines of its MEMORY.md, and Read/Write/Edit tools are automatically enabled for memory management.
Agent Teams (Research Preview)
For tasks that need sustained parallelism or agents that communicate with each other, Claude Code supports agent teams. Instead of a single agent working sequentially, a lead agent can delegate to multiple teammates that work in parallel -- researching, debugging, and building while coordinating with each other.
Agent teams differ from subagents: subagents work within a single session and return results to the main conversation. Agent teams coordinate across separate sessions with independent context windows. This is useful for parallel code review (one teammate on security, one on performance, one on test coverage) or multi-component development.
Cost consideration: Agent teams are token-heavy. Every teammate is a full Claude Code session with its own context window. More agents means more tokens means more cost. Use subagents for quick, focused tasks and agent teams when you need sustained parallel work.
Best Practices for Using Subagents
- Let Claude decide: In most cases, let Claude automatically choose when to delegate. It's optimized to make good decisions. Include phrases like "use proactively" in your description to encourage automatic delegation.
- Match model to task: Use
haikufor fast, simple agents. Usesonnetfor complex reasoning. Useopusonly for the most challenging tasks. Useinherit(default) to match the main conversation's model. - Restrict tools appropriately: Give agents only the tools they need. Read-only agents should use
disallowedTools: Write, Editto explicitly block modifications. - Write clear descriptions: Claude uses the
descriptionfield to decide when to delegate. Write detailed descriptions about what the agent does and when Claude should use it. - Isolate high-volume operations: Running tests, fetching docs, or processing logs can consume significant context. Delegate these to subagents so verbose output stays in the subagent's context while only the summary returns to your main conversation.
- Test with simple tasks: Before using custom agents on important work, test them with simple examples to verify behavior.
- Check into version control: Put project-specific agents in
.claude/agents/and commit them to git so your team can use and improve them collaboratively.
Common Mistakes
- Over-specifying agents: Creating custom agents for tasks that don't benefit from specialization. The built-in agents handle most cases well.
- Wrong model choice: Using Opus for simple tasks wastes money. Using Haiku for complex reasoning gives poor results.
- Too many tools: Giving an agent full-access when read-only would suffice. This increases risk without benefit.
- Vague instructions: Custom agent instructions that are too general. Be specific about the process and expected output.
- Forgetting AGENT.md filename: The file must be exactly
AGENT.md(uppercase AGENT, lowercase .md).
Security note: Full-access custom agents can modify files and run commands. Review custom agent configurations before using them, especially if shared by others.
FAQ
Can I force Claude to use a specific subagent?
You can mention the agent by name in your prompt ("use the reviewer agent to check this"), and Claude will delegate. You can also disable specific subagents by adding Task(agent-name) to the deny array in your permissions settings.
Why do subagents use different models?
Different tasks need different capabilities. Explore uses Haiku because speed matters more than deep reasoning for search. Plan and General-Purpose inherit the main conversation's model by default. Custom agents can specify any model alias (haiku, sonnet, opus, or inherit).
Can I resume a subagent?
Yes. Each subagent invocation creates a new instance, but you can ask Claude to continue an existing subagent's work. Resumed subagents retain their full conversation history. Subagent transcripts persist independently of the main conversation and survive compaction events.
Can subagents access my CLAUDE.md settings?
Yes. Subagents inherit the conversation context, including any CLAUDE.md configuration. Your project conventions apply to subagents too.
How do I know when a subagent is running?
Claude Code shows subagent activity in the interface. You can also use the /agents command to see all subagent activity in your session.
Do custom agents count against my usage?
Yes. Custom agents consume tokens like any other Claude interaction. Using faster models (Haiku) for appropriate tasks helps manage costs.
Related Guides
- How to Use Hooks - automate workflows with hook events
- How to Use Plan Mode - research before implementation
- How to Use Skills - create custom slash commands that can run in subagents
- How to Use CLAUDE.md Files - configure Claude's behavior
Like Claude Code? Meet Your Chief AI Officer
Watch me build a complete website using only plain English - no coding required. Then try it yourself.
Get the Free Blueprint href="/blueprint">Watch the Free Setup Video →rarr;