Skip to Content
SubagentsSubagents

Subagents - Complete Reference Guide

Subagents are specialized AI assistants that Claude Code can delegate tasks to. Each subagent has a specific purpose, uses its own context window separate from the main conversation, and can be configured with specific tools and a custom system prompt.

Table of Contents

  1. Overview
  2. Key Benefits
  3. File Locations
  4. Configuration
  5. Built-in Subagents
  6. Managing Subagents
  7. Using Subagents
  8. Resumable Agents
  9. Chaining Subagents
  10. Persistent Memory for Subagents
  11. Background Subagents
  12. Worktree Isolation
  13. Restrict Spawnable Subagents
  14. claude agents CLI Command
  15. Agent Teams (Experimental)
  16. Plugin Subagent Security
  17. Architecture
  18. Context Management
  19. When to Use Subagents
  20. Best Practices
  21. Example Subagents in This Folder
  22. Installation Instructions
  23. Related Concepts

Overview

Subagents enable delegated task execution in Claude Code by:

  • Creating isolated AI assistants with separate context windows
  • Providing customized system prompts for specialized expertise
  • Enforcing tool access control to limit capabilities
  • Preventing context pollution from complex tasks
  • Enabling parallel execution of multiple specialized tasks

Each subagent operates independently with a clean slate, receiving only the specific context necessary for their task, then returning results to the main agent for synthesis.

Quick Start: Use the /agents command to create, view, edit, and manage your subagents interactively.


Key Benefits

BenefitDescription
Context preservationOperates in separate context, preventing pollution of main conversation
Specialized expertiseFine-tuned for specific domains with higher success rates
ReusabilityUse across different projects and share with teams
Flexible permissionsDifferent tool access levels for different subagent types
ScalabilityMultiple agents work on different aspects simultaneously

File Locations

Subagent files can be stored in multiple locations with different scopes:

PriorityTypeLocationScope
1 (highest)CLI-definedVia --agents flag (JSON)Session only
2Project subagents.claude/agents/Current project
3User subagents~/.claude/agents/All projects
4 (lowest)Plugin agentsPlugin agents/ directoryVia plugins

When duplicate names exist, higher-priority sources take precedence.


Configuration

File Format

Subagents are defined in YAML frontmatter followed by the system prompt in markdown:

--- name: your-sub-agent-name description: Description of when this subagent should be invoked tools: tool1, tool2, tool3 # Optional - inherits all tools if omitted disallowedTools: tool4 # Optional - explicitly disallowed tools model: sonnet # Optional - sonnet, opus, haiku, or inherit permissionMode: default # Optional - permission mode maxTurns: 20 # Optional - limit agentic turns skills: skill1, skill2 # Optional - skills to preload into context mcpServers: server1 # Optional - MCP servers to make available memory: user # Optional - persistent memory scope (user, project, local) background: false # Optional - run as background task effort: high # Optional - reasoning effort (low, medium, high, max) isolation: worktree # Optional - git worktree isolation initialPrompt: "Start by analyzing the codebase" # Optional - auto-submitted first turn hooks: # Optional - component-scoped hooks PreToolUse: - matcher: "Bash" hooks: - type: command command: "./scripts/security-check.sh" --- Your subagent's system prompt goes here. This can be multiple paragraphs and should clearly define the subagent's role, capabilities, and approach to solving problems.

Configuration Fields

FieldRequiredDescription
nameYesUnique identifier (lowercase letters and hyphens)
descriptionYesNatural language description of purpose. Include “use PROACTIVELY” to encourage automatic invocation
toolsNoComma-separated list of specific tools. Omit to inherit all tools. Supports Agent(agent_name) syntax to restrict spawnable subagents
disallowedToolsNoComma-separated list of tools the subagent must not use
modelNoModel to use: sonnet, opus, haiku, full model ID, or inherit. Defaults to configured subagent model
permissionModeNodefault, acceptEdits, dontAsk, bypassPermissions, plan
maxTurnsNoMaximum number of agentic turns the subagent can take
skillsNoComma-separated list of skills to preload. Injects full skill content into the subagent’s context at startup
mcpServersNoMCP servers to make available to the subagent
hooksNoComponent-scoped hooks (PreToolUse, PostToolUse, Stop)
memoryNoPersistent memory directory scope: user, project, or local
backgroundNoSet to true to always run this subagent as a background task
effortNoReasoning effort level: low, medium, high, or max
isolationNoSet to worktree to give the subagent its own git worktree
initialPromptNoAuto-submitted first turn when the subagent runs as the main agent

Tool Configuration Options

Option 1: Inherit All Tools (omit the field)

--- name: full-access-agent description: Agent with all available tools ---

Option 2: Specify Individual Tools

--- name: limited-agent description: Agent with specific tools only tools: Read, Grep, Glob, Bash ---

Option 3: Conditional Tool Access

--- name: conditional-agent description: Agent with filtered tool access tools: Read, Bash(npm:*), Bash(test:*) ---

CLI-Based Configuration

Define subagents for a single session using the --agents flag with JSON format:

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" } }'

JSON Format for --agents flag:

{ "agent-name": { "description": "Required: when to invoke this agent", "prompt": "Required: system prompt for the agent", "tools": ["Optional", "array", "of", "tools"], "model": "optional: sonnet|opus|haiku" } }

Priority of Agent Definitions:

Agent definitions are loaded with this priority order (first match wins):

  1. CLI-defined - --agents flag (session only, JSON)
  2. Project-level - .claude/agents/ (current project)
  3. User-level - ~/.claude/agents/ (all projects)
  4. Plugin-level - Plugin agents/ directory

This allows CLI definitions to override all other sources for a single session.


Built-in Subagents

Claude Code includes several built-in subagents that are always available:

AgentModelPurpose
general-purposeInheritsComplex, multi-step tasks
PlanInheritsResearch for plan mode
ExploreHaikuRead-only codebase exploration (quick/medium/very thorough)
BashInheritsTerminal commands in separate context
statusline-setupSonnetConfigure status line
Claude Code GuideHaikuAnswer Claude Code feature questions

General-Purpose Subagent

PropertyValue
ModelInherits from parent
ToolsAll tools
PurposeComplex research tasks, multi-step operations, code modifications

When used: Tasks requiring both exploration and modification with complex reasoning.

Plan Subagent

PropertyValue
ModelInherits from parent
ToolsRead, Glob, Grep, Bash
PurposeUsed automatically in plan mode to research codebase

When used: When Claude needs to understand the codebase before presenting a plan.

Explore Subagent

PropertyValue
ModelHaiku (fast, low-latency)
ModeStrictly read-only
ToolsGlob, Grep, Read, Bash (read-only commands only)
PurposeFast codebase searching and analysis

When used: When searching/understanding code without making changes.

Thoroughness Levels - Specify the depth of exploration:

  • “quick” - Fast searches with minimal exploration, good for finding specific patterns
  • “medium” - Moderate exploration, balanced speed and thoroughness, default approach
  • “very thorough” - Comprehensive analysis across multiple locations and naming conventions, may take longer

Bash Subagent

PropertyValue
ModelInherits from parent
ToolsBash
PurposeExecute terminal commands in a separate context window

When used: When running shell commands that benefit from isolated context.

Statusline Setup Subagent

PropertyValue
ModelSonnet
ToolsRead, Write, Bash
PurposeConfigure the Claude Code status line display

When used: When setting up or customizing the status line.

Claude Code Guide Subagent

PropertyValue
ModelHaiku (fast, low-latency)
ToolsRead-only
PurposeAnswer questions about Claude Code features and usage

When used: When users ask questions about how Claude Code works or how to use specific features.


Managing Subagents

/agents

This provides an interactive menu to:

  • View all available subagents (built-in, user, and project)
  • Create new subagents with guided setup
  • Edit existing custom subagents and tool access
  • Delete custom subagents
  • See which subagents are active when duplicates exist

Direct File Management

# Create a project subagent mkdir -p .claude/agents cat > .claude/agents/test-runner.md << 'EOF' --- name: test-runner description: Use proactively to run tests and fix failures --- You are a test automation expert. When you see code changes, proactively run the appropriate tests. If tests fail, analyze the failures and fix them while preserving the original test intent. EOF # Create a user subagent (available in all projects) mkdir -p ~/.claude/agents

Using Subagents

Automatic Delegation

Claude proactively delegates tasks based on:

  • Task description in your request
  • The description field in subagent configurations
  • Current context and available tools

To encourage proactive use, include “use PROACTIVELY” or “MUST BE USED” in your description field:

--- name: code-reviewer description: Expert code review specialist. Use PROACTIVELY after writing or modifying code. ---

Explicit Invocation

You can explicitly request a specific subagent:

> Use the test-runner subagent to fix failing tests > Have the code-reviewer subagent look at my recent changes > Ask the debugger subagent to investigate this error

@-Mention Invocation

Use the @ prefix to guarantee a specific subagent is invoked (bypasses automatic delegation heuristics):

> @"code-reviewer (agent)" review the auth module

Session-Wide Agent

Run an entire session using a specific agent as the main agent:

# Via CLI flag claude --agent code-reviewer # Via settings.json { "agent": "code-reviewer" }

Listing Available Agents

Use the claude agents command to list all configured agents from all sources:

claude agents

Resumable Agents

Subagents can continue previous conversations with full context preserved:

# Initial invocation > Use the code-analyzer agent to start reviewing the authentication module # Returns agentId: "abc123" # Resume the agent later > Resume agent abc123 and now analyze the authorization logic as well

Use cases:

  • Long-running research across multiple sessions
  • Iterative refinement without losing context
  • Multi-step workflows maintaining context

Chaining Subagents

Execute multiple subagents in sequence:

> First use the code-analyzer subagent to find performance issues, then use the optimizer subagent to fix them

This enables complex workflows where the output of one subagent feeds into another.


Persistent Memory for Subagents

The memory field gives subagents a persistent directory that survives across conversations. This allows subagents to build up knowledge over time, storing notes, findings, and context that persist between sessions.

Memory Scopes

ScopeDirectoryUse Case
user~/.claude/agent-memory/<name>/Personal notes and preferences across all projects
project.claude/agent-memory/<name>/Project-specific knowledge shared with the team
local.claude/agent-memory-local/<name>/Local project knowledge not committed to version control

How It Works

  • The first 200 lines of MEMORY.md in the memory directory are automatically loaded into the subagent’s system prompt
  • The Read, Write, and Edit tools are automatically enabled for the subagent to manage its memory files
  • The subagent can create additional files in its memory directory as needed

Example Configuration

--- name: researcher memory: user --- You are a research assistant. Use your memory directory to store findings, track progress across sessions, and build up knowledge over time. Check your MEMORY.md file at the start of each session to recall previous context.

Background Subagents

Subagents can run in the background, freeing up the main conversation for other tasks.

Configuration

Set background: true in the frontmatter to always run the subagent as a background task:

--- name: long-runner background: true description: Performs long-running analysis tasks in the background ---

Keyboard Shortcuts

ShortcutAction
Ctrl+BBackground a currently running subagent task
Ctrl+FKill all background agents (press twice to confirm)

Disabling Background Tasks

Set the environment variable to disable background task support entirely:

export CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1

Worktree Isolation

The isolation: worktree setting gives a subagent its own git worktree, allowing it to make changes independently without affecting the main working tree.

Configuration

--- name: feature-builder isolation: worktree description: Implements features in an isolated git worktree tools: Read, Write, Edit, Bash, Grep, Glob ---

How It Works

  • The subagent operates in its own git worktree on a separate branch
  • If the subagent makes no changes, the worktree is automatically cleaned up
  • If changes exist, the worktree path and branch name are returned to the main agent for review or merging

Restrict Spawnable Subagents

You can control which subagents a given subagent is allowed to spawn by using the Agent(agent_type) syntax in the tools field. This provides a way to allowlist specific subagents for delegation.

Note: In v2.1.63, the Task tool was renamed to Agent. Existing Task(...) references still work as aliases.

Example

--- name: coordinator description: Coordinates work between specialized agents tools: Agent(worker, researcher), Read, Bash --- You are a coordinator agent. You can delegate work to the "worker" and "researcher" subagents only. Use Read and Bash for your own exploration.

In this example, the coordinator subagent can only spawn the worker and researcher subagents. It cannot spawn any other subagents, even if they are defined elsewhere.


claude agents CLI Command

The claude agents command lists all configured agents grouped by source (built-in, user-level, project-level):

claude agents

This command:

  • Shows all available agents from all sources
  • Groups agents by their source location
  • Indicates overrides when an agent at a higher priority level shadows one at a lower level (e.g., a project-level agent with the same name as a user-level agent)

Agent Teams (Experimental)

Agent Teams coordinate multiple Claude Code instances working together on complex tasks. Unlike subagents (which are delegated subtasks returning results), teammates work independently with their own context and communicate directly through a shared mailbox system.

Note: Agent Teams is experimental and requires Claude Code v2.1.32+. Enable it before use.

Subagents vs Agent Teams

AspectSubagentsAgent Teams
Delegation modelParent delegates subtask, waits for resultTeam lead assigns work, teammates execute independently
ContextFresh context per subtask, results distilled backEach teammate maintains its own persistent context
CoordinationSequential or parallel, managed by parentShared task list with automatic dependency management
CommunicationReturn values onlyInter-agent messaging via mailbox
Session resumptionSupportedNot supported with in-process teammates
Best forFocused, well-defined subtasksLarge multi-file projects requiring parallel work

Enabling Agent Teams

Set the environment variable or add it to your settings.json:

export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1

Or in settings.json:

{ "env": { "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1" } }

Starting a team

Once enabled, ask Claude to work with teammates in your prompt:

User: Build the authentication module. Use a team — one teammate for the API endpoints, one for the database schema, and one for the test suite.

Claude will create the team, assign tasks, and coordinate the work automatically.

Display modes

Control how teammate activity is displayed:

ModeFlagDescription
Auto--teammate-mode autoAutomatically chooses the best display mode for your terminal
In-process--teammate-mode in-processShows teammate output inline in the current terminal (default)
Split-panes--teammate-mode tmuxOpens each teammate in a separate tmux or iTerm2 pane
claude --teammate-mode tmux

You can also set the display mode in settings.json:

{ "teammateMode": "tmux" }

Note: Split-pane mode requires tmux or iTerm2. It is not available in VS Code terminal, Windows Terminal, or Ghostty.

Use Shift+Down to navigate between teammates in split-pane mode.

Team Configuration

Team configurations are stored at ~/.claude/teams/{team-name}/config.json.

Architecture

Key components:

  • Team Lead: The main Claude Code session that creates the team, assigns tasks, and coordinates
  • Shared Task List: A synchronized list of tasks with automatic dependency tracking
  • Mailbox: An inter-agent messaging system for teammates to communicate status and coordinate
  • Teammates: Independent Claude Code instances, each with their own context window

Task assignment and messaging

The team lead breaks work into tasks and assigns them to teammates. The shared task list handles:

  • Automatic dependency management — tasks wait for their dependencies to complete
  • Status tracking — teammates update task status as they work
  • Inter-agent messaging — teammates send messages via the mailbox for coordination (e.g., “Database schema is ready, you can start writing queries”)

Plan approval workflow

For complex tasks, the team lead creates an execution plan before teammates begin work. The user reviews and approves the plan, ensuring the team’s approach aligns with expectations before any code changes are made.

Hook events for teams

Agent Teams introduce two additional hook events:

EventFires WhenUse Case
TeammateIdleA teammate finishes its current task and has no pending workTrigger notifications, assign follow-up tasks
TaskCompletedA task in the shared task list is marked completeRun validation, update dashboards, chain dependent work

Best practices

  • Team size: Keep teams at 3-5 teammates for optimal coordination
  • Task sizing: Break work into tasks that take 5-15 minutes each — small enough to parallelize, large enough to be meaningful
  • Avoid file conflicts: Assign different files or directories to different teammates to prevent merge conflicts
  • Start simple: Use in-process mode for your first team; switch to split-panes once comfortable
  • Clear task descriptions: Provide specific, actionable task descriptions so teammates can work independently

Limitations

  • Experimental: Feature behavior may change in future releases
  • No session resumption: In-process teammates cannot be resumed after a session ends
  • One team per session: Cannot create nested teams or multiple teams in a single session
  • Fixed leadership: The team lead role cannot be transferred to a teammate
  • Split-pane restrictions: tmux/iTerm2 required; not available in VS Code terminal, Windows Terminal, or Ghostty
  • No cross-session teams: Teammates exist only within the current session

Warning: Agent Teams is experimental. Test with non-critical work first and monitor teammate coordination for unexpected behavior.


Plugin Subagent Security

Plugin-provided subagents have restricted frontmatter capabilities for security. The following fields are not allowed in plugin subagent definitions:

  • hooks - Cannot define lifecycle hooks
  • mcpServers - Cannot configure MCP servers
  • permissionMode - Cannot override permission settings

This prevents plugins from escalating privileges or executing arbitrary commands through subagent hooks.


Architecture

High-Level Architecture

Subagent Lifecycle


Context Management

Key Points

  • Each subagent gets a fresh context window without the main conversation history
  • Only the relevant context is passed to the subagent for their specific task
  • Results are distilled back to the main agent
  • This prevents context token exhaustion on long projects

Performance Considerations

  • Context efficiency - Agents preserve main context, enabling longer sessions
  • Latency - Subagents start with clean slate and may add latency gathering initial context

Key Behaviors

  • No nested spawning - Subagents cannot spawn other subagents
  • Background permissions - Background subagents auto-deny any permissions that are not pre-approved
  • Backgrounding - Press Ctrl+B to background a currently running task
  • Transcripts - Subagent transcripts are stored at ~/.claude/projects/{project}/{sessionId}/subagents/agent-{agentId}.jsonl
  • Auto-compaction - Subagent context auto-compacts at ~95% capacity (override with CLAUDE_AUTOCOMPACT_PCT_OVERRIDE environment variable)

When to Use Subagents

ScenarioUse SubagentWhy
Complex feature with many stepsYesSeparate concerns, prevent context pollution
Quick code reviewNoUnnecessary overhead
Parallel task executionYesEach subagent has own context
Specialized expertise neededYesCustom system prompts
Long-running analysisYesPrevents main context exhaustion
Single taskNoAdds latency unnecessarily

Best Practices

Design Principles

Do:

  • Start with Claude-generated agents - Generate initial subagent with Claude, then iterate to customize
  • Design focused subagents - Single, clear responsibilities rather than one doing everything
  • Write detailed prompts - Include specific instructions, examples, and constraints
  • Limit tool access - Grant only necessary tools for the subagent’s purpose
  • Version control - Check project subagents into version control for team collaboration

Don’t:

  • Create overlapping subagents with same roles
  • Give subagents unnecessary tool access
  • Use subagents for simple, single-step tasks
  • Mix concerns in one subagent’s prompt
  • Forget to pass necessary context

System Prompt Best Practices

  1. Be Specific About Role

    You are an expert code reviewer specializing in [specific areas]
  2. Define Priorities Clearly

    Review priorities (in order): 1. Security Issues 2. Performance Problems 3. Code Quality
  3. Specify Output Format

    For each issue provide: Severity, Category, Location, Description, Fix, Impact
  4. Include Action Steps

    When invoked: 1. Run git diff to see recent changes 2. Focus on modified files 3. Begin review immediately

Tool Access Strategy

  1. Start Restrictive: Begin with only essential tools
  2. Expand Only When Needed: Add tools as requirements demand
  3. Read-Only When Possible: Use Read/Grep for analysis agents
  4. Sandboxed Execution: Limit Bash commands to specific patterns

Example Subagents in This Folder

This folder contains ready-to-use example subagents:

1. Code Reviewer (code-reviewer.md)

Purpose: Comprehensive code quality and maintainability analysis

Tools: Read, Grep, Glob, Bash

Specialization:

  • Security vulnerability detection
  • Performance optimization identification
  • Code maintainability assessment
  • Test coverage analysis

Use When: You need automated code reviews with focus on quality and security


2. Test Engineer (test-engineer.md)

Purpose: Test strategy, coverage analysis, and automated testing

Tools: Read, Write, Bash, Grep

Specialization:

  • Unit test creation
  • Integration test design
  • Edge case identification
  • Coverage analysis (>80% target)

Use When: You need comprehensive test suite creation or coverage analysis


3. Documentation Writer (documentation-writer.md)

Purpose: Technical documentation, API docs, and user guides

Tools: Read, Write, Grep

Specialization:

  • API endpoint documentation
  • User guide creation
  • Architecture documentation
  • Code comment improvement

Use When: You need to create or update project documentation


4. Secure Reviewer (secure-reviewer.md)

Purpose: Security-focused code review with minimal permissions

Tools: Read, Grep

Specialization:

  • Security vulnerability detection
  • Authentication/authorization issues
  • Data exposure risks
  • Injection attack identification

Use When: You need security audits without modification capabilities


5. Implementation Agent (implementation-agent.md)

Purpose: Full implementation capabilities for feature development

Tools: Read, Write, Edit, Bash, Grep, Glob

Specialization:

  • Feature implementation
  • Code generation
  • Build and test execution
  • Codebase modification

Use When: You need a subagent to implement features end-to-end


6. Debugger (debugger.md)

Purpose: Debugging specialist for errors, test failures, and unexpected behavior

Tools: Read, Edit, Bash, Grep, Glob

Specialization:

  • Root cause analysis
  • Error investigation
  • Test failure resolution
  • Minimal fix implementation

Use When: You encounter bugs, errors, or unexpected behavior


7. Data Scientist (data-scientist.md)

Purpose: Data analysis expert for SQL queries and data insights

Tools: Bash, Read, Write

Specialization:

  • SQL query optimization
  • BigQuery operations
  • Data analysis and visualization
  • Statistical insights

Use When: You need data analysis, SQL queries, or BigQuery operations


Installation Instructions

/agents

Then:

  1. Select ‘Create New Agent’
  2. Choose project-level or user-level
  3. Describe your subagent in detail
  4. Select tools to grant access (or leave blank to inherit all)
  5. Save and use

Method 2: Copy to Project

Copy the agent files to your project’s .claude/agents/ directory:

# Navigate to your project cd /path/to/your/project # Create agents directory if it doesn't exist mkdir -p .claude/agents # Copy all agent files from this folder cp /path/to/04-subagents/*.md .claude/agents/ # Remove the README (not needed in .claude/agents) rm .claude/agents/README.md

Method 3: Copy to User Directory

For agents available in all your projects:

# Create user agents directory mkdir -p ~/.claude/agents # Copy agents cp /path/to/04-subagents/code-reviewer.md ~/.claude/agents/ cp /path/to/04-subagents/debugger.md ~/.claude/agents/ # ... copy others as needed

Verification

After installation, verify the agents are recognized:

/agents

You should see your installed agents listed alongside the built-in ones.


File Structure

project/ ├── .claude/ │ └── agents/ │ ├── code-reviewer.md │ ├── test-engineer.md │ ├── documentation-writer.md │ ├── secure-reviewer.md │ ├── implementation-agent.md │ ├── debugger.md │ └── data-scientist.md └── ...

  • Slash Commands - Quick user-invoked shortcuts
  • Memory - Persistent cross-session context
  • Skills - Reusable autonomous capabilities
  • MCP Protocol - Real-time external data access
  • Hooks - Event-driven shell command automation
  • Plugins - Bundled extension packages

Comparison with Other Features

FeatureUser-InvokedAuto-InvokedPersistentExternal AccessIsolated Context
Slash CommandsYesNoNoNoNo
SubagentsYesYesNoNoYes
MemoryAutoAutoYesNoNo
MCPAutoYesNoYesNo
SkillsYesYesNoNoNo

Integration Pattern


Additional Resources


Last updated: March 2026

This guide covers complete subagent configuration, delegation patterns, and best practices for Claude Code.

Last updated on