Claude Code Sub-Agents

Multi-agent orchestration: spawn parallel worker agents, isolate work in git worktrees, and run specialized sub-agents concurrently.

What are sub-agents?

Sub-agents are independent Claude instances that the main (orchestrator) agent spawns via the Agent tool. Each sub-agent runs with its own context window, can call tools, read files, write code, and return a result. They enable true parallel execution — instead of working sequentially through a 10-file refactor, an orchestrator can dispatch 10 sub-agents simultaneously and collect all results in one pass.

Sub-agents are available in Claude Code's SDK/API layer and in the interactive CLI when Claude uses the Agent tool internally. You can also direct Claude to use them explicitly by describing your task in terms of parallel sub-tasks.

Key insight: The sub-agent has zero memory of the parent conversation. Every prompt must be fully self-contained — file paths, context, expected output format, everything. This is the most common mistake when working with sub-agents.

The Agent Tool

Claude Code orchestrators invoke sub-agents via the Agent tool. Core parameters:

ParameterRequiredDescription
descriptionYes3–5 word summary of what the agent will do (shown in UI)
promptYesFully self-contained task description. No conversation history is passed.
subagent_typeNoWhich specialized agent to use (see types below). Defaults to general-purpose.
run_in_backgroundNoIf true, orchestrator continues immediately; notified on completion.
isolationNo"worktree" — auto-creates a git worktree for the agent to write into.

Example: parallel file analysis

# Orchestrator spawns 3 sub-agents simultaneously (one message, multiple Agent calls):

Agent({
  description: "Analyze auth module",
  subagent_type: "Explore",
  prompt: "Read src/auth/middleware.ts and src/auth/session.ts. Report: what does each file export, what are the key function signatures, and are there any obvious security issues? Under 150 words."
})

Agent({
  description: "Analyze payments module",
  subagent_type: "Explore",
  prompt: "Read src/payments/stripe.ts and src/payments/webhook.ts. Report: what does each file export, what are the key function signatures, and are there any obvious security issues? Under 150 words."
})

Agent({
  description: "Analyze users module",
  subagent_type: "Explore",
  prompt: "Read src/users/model.ts and src/users/service.ts. Report: what does each file export, what are the key function signatures, and are there any obvious security issues? Under 150 words."
})

Specialized Agent Types

Explore Fast read-only search agent. Finds files by pattern, greps for symbols, answers "where is X defined." Reads excerpts — do NOT use for full code review or cross-file consistency checks.
Plan Software architect agent. Designs implementation plans, identifies critical files, considers architectural trade-offs. Returns step-by-step plans. Cannot write files.
claude (general-purpose) All-tools catch-all. Use when the task involves writing code, editing files, running commands, or anything not covered by a specialized type.

Custom agent types can be registered in a project's agent configuration. Third-party skill packs may also add agent types (e.g., code-reviewer, security-auditor).

Foreground vs Background Execution

Foreground (default)

The orchestrator blocks until the sub-agent returns. Use this whenever you need the result before proceeding — research agents whose findings inform next steps, or any agent whose output you'll immediately act on.

Background (run_in_background: true)

The orchestrator continues immediately; you are auto-notified when the agent completes. Use background when you have genuinely independent work to do in parallel — writing new code while a test-runner agent validates existing code, for example.

Do NOT poll background agents. If you start an agent with run_in_background: true, wait for the automatic completion notification. Polling loops waste tokens and add latency.
# Background agent — orchestrator continues while this runs
Agent({
  description: "Run full test suite",
  run_in_background: true,
  prompt: "Run 'npm test' and report: total tests, failures, and any error messages. Under 100 words."
})

# Orchestrator now continues writing new feature code...
# Will be notified when test agent completes.

Worktree Isolation

Pass isolation: "worktree" to have Claude Code automatically create a temporary git worktree for the sub-agent. This gives the agent its own branch and directory — changes won't conflict with your main working tree or other sub-agents.

# Two agents write to separate files simultaneously, safely isolated
Agent({
  description: "Add user auth tests",
  isolation: "worktree",
  prompt: "In this repo, add unit tests for src/auth/middleware.ts. Create tests/auth/middleware.test.ts with at least 5 test cases covering: valid JWT, expired JWT, missing token, malformed token, and role-based access. Use the existing test patterns from tests/users/model.test.ts."
})

Agent({
  description: "Add payments tests",
  isolation: "worktree",
  prompt: "In this repo, add unit tests for src/payments/stripe.ts. Create tests/payments/stripe.test.ts with at least 5 test cases. Use the existing test patterns from tests/users/model.test.ts."
})

Writing Effective Sub-Agent Prompts

The sub-agent starts cold — no history, no context from the parent session. Terse prompts produce shallow results.

What to always include

What to never do

Common Orchestration Patterns

Fan-out / fan-in

Orchestrator dispatches multiple parallel sub-agents, waits for all to return, then synthesizes results. Best for: parallel file analysis, multi-repo tasks, batch code generation.

# Step 1: Fan-out (all 3 run in parallel)
results = [
  Agent({description:"Audit auth", prompt:"..."}),
  Agent({description:"Audit payments", prompt:"..."}),
  Agent({description:"Audit users", prompt:"..."})
]

# Step 2: Orchestrator synthesizes results and decides next action
# Step 3: Fan-out again with write agents if changes needed

Research then implement

An Explore agent finds the right files first. The orchestrator reads the result, identifies what to change, then sends specific write instructions to a claude agent. Avoids the write agent scanning the entire repo.

Design then build

A Plan agent designs the architecture and returns a step-by-step plan. The orchestrator reviews it (and possibly asks the user to confirm), then dispatches build agents per the plan.

Independent background work

Start a test-runner or lint agent in the background while continuing to write code. Merge the test results when they arrive.

Cost Considerations

Each sub-agent is a full Claude API call with its own context. Costs multiply with agent count. Tips to keep costs down:

FAQ

Do sub-agents have access to the same tools as the main agent?

Specialized types have restricted tool sets (Explore is read-only; Plan cannot write files). General-purpose claude agents have access to all tools. Tool permissions from your Claude Code settings still apply.

Can I use sub-agents in the interactive Claude Code CLI?

Claude Code's orchestrator uses the Agent tool internally when it decides to delegate work. In some contexts you can directly instruct Claude to use it. Sub-agents are most commonly used when building automated pipelines with Claude Code SDK.

How do I debug a sub-agent that returns a bad result?

The most common cause is an under-specified prompt. Add more context, file paths, and constraints. If the agent is calling wrong tools, use a more specific subagent_type. If results look like hallucinations, the agent likely couldn't find the files — add explicit paths and verify they exist before dispatching.

How many sub-agents can run in parallel?

No hard limit is enforced in the framework. In practice, 3–8 parallel agents is efficient; beyond that you're likely waiting on the slowest agent anyway. Rate limits on your API tier apply per-request, so very wide fan-outs may hit throttling.

What happens if a sub-agent fails or times out?

The Agent tool call returns an error result to the orchestrator. The orchestrator should check the result and either retry with a different prompt, try a simpler approach, or surface the error to the user. Don't silently ignore failed sub-agent calls.

Are sub-agents the same as Claude Code worktrees?

Related but different. Worktrees are a git feature that lets you check out multiple branches simultaneously — useful for running parallel Claude Code sessions manually. Sub-agents with isolation: "worktree" use git worktrees under the hood to isolate automated agent work, but the agent-spawning itself is a separate concept.

Related Guides

More Claude Code Tools

⚡ Using Claude Code? 30 power prompts that 2× your output · £5 £3 first 10Get PDF £3 →