Subagents are specialized AI assistants in Claude Code that handle specific tasks in isolated context windows. Each gets its own system prompt, tool access, and permissions. When Claude encounters a matching task, it delegates to the subagent, which works independently and returns results.

Why Subagents Matter

Single agents exhaust context windows on complex, multi-stage tasks. Subagents solve this:

  • Each specialist gets its own dedicated context
  • Verbose output stays isolated from main conversation
  • Tool access can be restricted per agent
  • Multiple agents run in parallel

Built-in Subagents

AgentModelToolsPurpose
ExploreHaikuRead-onlyFast codebase search and analysis
PlanInheritsRead-onlyResearch during plan mode
general-purposeInheritsAll toolsComplex multi-step tasks
BashInheritsTerminalRunning commands separately
Claude Code GuideHaikuAllAnswer feature questions

Explore runs cheap and fast (Haiku). Use it for codebase exploration rather than burning Sonnet tokens on file reads.

Creating Custom Subagents

Two methods:

Interactive: /agents → Create new agent → User-level or Project-level → Generate with Claude

Manual: Create markdown file in:

  • ~/.claude/agents/ (user-level, all projects)
  • .claude/agents/ (project-level, version controlled)

Frontmatter Configuration

---
name: code-reviewer
description: Expert code review. Use proactively after code changes.
tools: Read, Grep, Glob, Bash
disallowedTools: Write, Edit
model: sonnet
permissionMode: default
skills: some-skill-name
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "./scripts/validate.sh"
---
 
Your system prompt in Markdown...
FieldRequiredPurpose
nameYesLowercase with hyphens, unique identifier
descriptionYesWhen Claude should delegate (trigger phrase)
toolsNoAllowed tools (comma-separated)
disallowedToolsNoTools to deny
modelNosonnet, opus, haiku, inherit
permissionModeNoPermission handling mode
skillsNoSkills to load
hooksNoLifecycle hooks

Permission Modes

ModeBehavior
defaultStandard permission prompts
acceptEditsAuto-accept file edits
dontAskAuto-deny permission prompts
bypassPermissionsSkip all permission checks
planRead-only exploration mode

Tool Categories

Read-only (reviewers, auditors):

Read, Grep, Glob

Research (analysts):

Read, Grep, Glob, WebFetch, WebSearch

Code writers (developers):

Read, Write, Edit, Bash, Glob, Grep

Example Subagents

Code Reviewer (Read-only)

---
name: code-reviewer
description: Expert code review. Use proactively after code changes.
tools: Read, Grep, Glob, Bash
model: inherit
---
 
You are a senior code reviewer. Analyze code for:
- Clarity and readability
- Duplicate code
- Error handling
- Security (no secrets)
- Input validation
- Test coverage
- Performance
 
Provide feedback by priority: Critical, Warnings, Suggestions.

Debugger (Read-write)

---
name: debugger
description: Fix errors and test failures
tools: Read, Edit, Bash, Grep, Glob
---
 
You are an expert debugger. When invoked:
1. Capture error and stack trace
2. Identify reproduction steps
3. Isolate failure location
4. Implement minimal fix
5. Verify solution works
 
Provide root cause, evidence, fix, and prevention recommendations.

DB Reader (Restricted)

---
name: db-reader
description: Read-only database queries
tools: Bash
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "./scripts/validate-readonly-query.sh"
---
 
You run read-only SQL queries. Never INSERT, UPDATE, DELETE, or DROP.

Parallelization Patterns

Subagents shine for parallel work:

Fan-Out: Launch multiple subagents for independent tasks

Explore the codebase using 4 tasks in parallel.
Each agent should explore different directories.

Pipeline: Chain subagents where output feeds input

Use code-reviewer to find issues, then optimizer to fix them.

Map-Reduce: Split large task, aggregate results

Review auth, database, and API modules in parallel using separate subagents.
Summarize findings when all complete.

Task Tool vs Subagents

Different execution models:

AspectTask ToolCustom Subagents
PersistenceEphemeral workersReusable specialists
ContextFresh each timeCan be resumed
DefinitionCLI parametersMarkdown files
Best forParallel searchPersistent expertise

The Task tool spawns temporary contractors. Subagents are team members you’ve trained.

Key Constraints

  • No nesting: Subagents cannot spawn other subagents
  • No skill inheritance: Subagents don’t inherit parent skills
  • Fresh context: Each invocation starts fresh (unless resumed)
  • No MCP in background: Background subagents can’t access MCP tools
  • Transcript persistence: Subagent transcripts stored separately, ~30 day cleanup

When to Use Subagents

Use subagents when:

  • Task produces verbose output
  • Need specific tool restrictions
  • Self-contained work with summary return
  • Want to preserve main context
  • Running parallel operations

Use main conversation when:

  • Frequent back-and-forth needed
  • Multiple phases share context
  • Quick, targeted changes
  • Latency-sensitive tasks

Cost Considerations

Subagent chains increase token usage significantly. On Claude Pro/Max, you’ll hit usage caps faster. Trade-off: dramatically increased output and velocity at higher consumption.

Use Haiku model for read-only subagents to reduce costs:

model: haiku

Managing Subagents

/agents            # Interactive management
/agents list       # View all available
/agents create     # Create new
/agents edit       # Edit existing

Disable specific subagents in settings:

{
  "permissions": {
    "deny": ["Task(Explore)", "Task(custom-agent)"]
  }
}

Sources