title: "Sub-Agents — Claude Code" tested_with: claude-code: "1.0.x" last_updated: 2026-03-21 status: proven difficulty: intermediate prerequisites: [03-prompting-for-agents]

Sub-Agents — Claude Code

The Agent Tool

Claude Code has a built-in mechanism for sub-agents called the Agent tool. When the main agent decides it needs to delegate work, it invokes the Agent tool with a prompt describing what the sub-agent should do. The sub-agent spins up, does its work, and returns a result to the parent.

You do not configure the Agent tool. It is available by default. The main agent decides when to use it based on the task at hand — though you can influence this decision by how you phrase your prompts.

The Agent tool is not a separate binary or service. It is another invocation of Claude within the same Claude Code session, but with its own context window and its own tool access. The sub-agent can read files, search the codebase, run commands, and make edits, just like the parent. What it cannot do is see the parent's conversation history or communicate with other sub-agents directly.

Built-In Sub-Agent Types

Claude Code recognizes several sub-agent patterns, each optimized for a different kind of work.

General-purpose agent. The default. The parent sends a prompt, the sub-agent executes it, and returns the result. No special constraints. This is what you get when you say "use a sub-agent to handle X."

Explore agent. Optimized for research and investigation. An Explore agent reads files, traces through code, searches for patterns, and returns a summary of its findings. It is designed to look without touching — it investigates but does not modify files. Use it when you need to understand something before acting.

Plan agent. Optimized for designing an approach before implementation. A Plan agent analyzes the task, considers the codebase structure, and produces a step-by-step plan. It does not implement the plan itself. The parent can then execute the plan directly or dispatch implementation agents for each step.

These are not hard categories with different underlying models. They are behavioral patterns — the system prompt and instructions given to the sub-agent differ, which shapes its behavior. The Explore agent is told to investigate and report; the Plan agent is told to analyze and design. The underlying capability is the same.

Custom Sub-Agent Types

You can define your own sub-agent types by creating files in the .claude/agents/ directory in your project. Each file defines a sub-agent persona with a specific system prompt, constraints, and behavior.

A custom agent file is a Markdown file that describes the agent's role and instructions. For example, you might create .claude/agents/security-reviewer.md that instructs the sub-agent to review code specifically for security vulnerabilities, or .claude/agents/api-designer.md that focuses on REST API design patterns used by your team.

Custom agents are useful when you have recurring delegation patterns. Instead of writing the same detailed handoff prompt every time you want a security review, you define the agent once and reference it by name.

How to Trigger Sub-Agents

The main agent decides when to use sub-agents based on its assessment of the task. For complex, multi-part tasks, it will often spawn sub-agents without being asked. But you can influence this decision — and sometimes you should.

Explicit prompting. Tell the agent to use sub-agents directly. The agent responds to clear instructions about delegation.

Implicit triggering. Describe a task that naturally decomposes into independent parts. A request like "add comprehensive tests for modules A, B, and C" is a natural candidate for parallel sub-agents, and the agent may choose to use them without prompting.

The most reliable approach is explicit prompting. If you want sub-agents, say so. If you want parallelism, say so. The agent has good judgment about when sub-agents are appropriate, but your explicit instruction removes ambiguity.

Prompting for Sub-Agent Usage

Here are patterns that reliably trigger sub-agent behavior in Claude Code:

Research dispatch:

Use an explore agent to investigate how authentication is implemented
across this codebase. I need to understand the flow from login to
token validation, including any middleware involved.

Parallel implementation:

I need to add input validation to three endpoints: /users, /orders,
and /products. These are independent. Use parallel agents to implement
all three simultaneously. Each should follow the validation pattern
used in /auth/login.

Review dispatch:

I just finished implementing the new caching layer. Dispatch a review
agent to check the implementation for correctness, edge cases, and
consistency with the rest of the codebase.

Planning:

Before we start implementing the new notification system, use a plan
agent to design the approach. It should consider the existing event
system, the database schema, and the API layer.

Multi-step with coordination:

This migration needs three phases:
1. First, use an explore agent to map all usages of the old API
2. Then, use a plan agent to design the migration path
3. Finally, use parallel agents to update each module

Wait for each phase to complete before starting the next.

Notice the pattern in each of these prompts: they specify what kind of work the sub-agent should do, they provide the context the sub-agent needs, and they describe what the result should look like. The prompts are complete enough that the sub-agent can succeed without asking follow-up questions.

The Sub-Agent Lifecycle

Understanding the lifecycle helps you predict behavior and debug issues.

  1. Spawn. The parent decides to use a sub-agent and invokes the Agent tool with a prompt. The prompt describes the task, provides necessary context, and sets expectations for the output.

  2. Initialize. The sub-agent starts with a fresh context window. It receives its system prompt (which may differ based on agent type) and the task prompt from the parent. It does not see the parent's prior conversation.

  3. Execute. The sub-agent works through the task using the same tools available to the parent — file reading, search, bash execution, file editing. It may read many files, run commands, and iterate on its approach.

  4. Return. When the sub-agent completes its task, it returns a result to the parent. This result is a text summary — what it did, what it found, what it changed. The parent receives this as tool output and decides what to do next.

  5. Terminate. The sub-agent's context window is discarded. If you need to continue work that a sub-agent started, you either have the parent do it or spawn a new sub-agent with appropriate context.

Context Passing

What the sub-agent knows and what it does not is the most common source of sub-agent problems.

What the sub-agent gets:

  • Its system prompt (general-purpose, explore, plan, or custom)
  • The task prompt written by the parent
  • Anything it reads from the file system during execution
  • Output from any commands it runs

What the sub-agent does NOT get:

  • The parent's conversation history
  • Results from other sub-agents (unless the parent explicitly includes them in the prompt)
  • The parent's CLAUDE.md context (the sub-agent reads CLAUDE.md itself from disk, but it may not prioritize the same sections)
  • Any mental model the parent has built up over the course of the session

This means the task prompt must be self-contained. If the parent has spent ten messages discussing a specific approach with you, and then dispatches a sub-agent to implement that approach, the sub-agent knows nothing about those ten messages. The parent must distill the relevant decisions into the handoff prompt.

In practice, the parent agent is usually good at writing handoff prompts — it knows what the sub-agent needs. But when you notice a sub-agent producing unexpected results, the first thing to check is whether the handoff prompt contained sufficient context.

Worktree Isolation

When sub-agents need to modify files in parallel, worktree isolation prevents conflicts. A worktree gives each sub-agent its own copy of the working directory, backed by the same git repository.

Worktree isolation matters when:

  • Multiple sub-agents might edit the same file
  • You want clean separation between parallel changes
  • You need the ability to review each sub-agent's changes independently before merging

When a sub-agent runs in a worktree, it operates on a separate checkout. Its file edits do not affect the main working directory or other sub-agents' worktrees. When it finishes, the changes exist as a separate branch or set of modifications that can be merged.

You can prompt for worktree isolation explicitly:

Use worktree-isolated agents to refactor the logging system in
parallel. Agent 1 should handle src/api/, Agent 2 should handle
src/workers/, and Agent 3 should handle src/services/. Each might
need to update shared imports, so keep them isolated.

For tasks where the files are completely independent — for example, adding tests to three modules that share no code — worktree isolation is unnecessary overhead. Use it when there is a real risk of file-level conflict.

Practical Pattern: Research Agent

Use this when you need to understand something before making decisions.

Explore the codebase to find all API endpoints. For each endpoint,
identify:
- The HTTP method and path
- The handler function and its file location
- Any middleware applied
- Whether it has tests

Return a structured summary organized by module.

The explore agent reads route definitions, traces through middleware chains, checks for test files, and returns a comprehensive map. The parent can then use this map to plan further work — identifying untested endpoints, finding inconsistent patterns, or planning a migration.

Practical Pattern: Parallel Implementation

Use this when you have multiple independent implementation tasks.

Add input validation to these three endpoints using the Zod schema
pattern established in src/validation/schemas.ts:

1. POST /api/users - validate email (must be valid format),
   name (required, 1-100 chars), role (must be 'admin' or 'user')
2. POST /api/orders - validate userId (required UUID),
   items (non-empty array), total (positive number)
3. POST /api/products - validate name (required, 1-200 chars),
   price (positive number), category (must be from VALID_CATEGORIES)

Use parallel agents, one per endpoint. Each should add the validation
schema, integrate it into the handler, and add tests for both valid
and invalid inputs.

Each sub-agent gets a clear, self-contained specification. They can all reference the existing Zod schema pattern independently. The parent collects the results and verifies consistency.

Practical Pattern: Review Agent

Use this after implementation to catch issues before committing.

Review the changes I just made to the authentication system.
Specifically check:
- Are there any security issues with the token generation?
- Does the error handling cover all failure cases?
- Are the new functions consistent with the patterns in the rest
  of src/auth/?
- Are there any missing tests?

Be specific about any issues found. Reference exact file paths
and line numbers.

The review agent reads the changed files, compares them against existing patterns, and produces a findings report. This is especially valuable because the review happens in a fresh context — the agent is not anchored by the assumptions that built up during implementation.

Practical Pattern: Plan Agent

Use this before implementation to design the approach.

I need to add a notification system to this application. Users should
receive notifications when:
- An order they placed changes status
- A product on their wishlist goes on sale
- An admin sends a broadcast message

Design an implementation plan. Consider the existing event system in
src/events/, the database schema, and the API patterns used elsewhere.
The plan should cover: data model changes, new API endpoints, event
handlers, and a testing strategy.

The plan agent investigates the existing architecture, identifies integration points, and produces a structured plan. The parent — and you — can review the plan before committing to implementation, catching design issues early.

Effective Sub-Agent Prompts

The quality of the handoff prompt is the single biggest lever on sub-agent performance. Follow these principles:

Be complete. Include everything the sub-agent needs. Do not rely on context it does not have. If there is a relevant decision from earlier in your session, state it explicitly.

Be specific. "Improve the tests" is a bad handoff. "Add edge case tests for the parseDate function covering null input, invalid formats, and timezone boundaries" is a good handoff.

Include constraints. If there are things the sub-agent should not do — do not modify the database schema, do not change the public API, use only the existing test framework — say so in the prompt.

Describe the expected output. "Return a summary of findings" is vague. "Return a list of all endpoints, grouped by module, with the HTTP method, path, and whether tests exist" is precise.

Reference existing patterns. If the sub-agent should follow a pattern that exists in the codebase, point to a specific file: "Follow the pattern in src/validators/user.ts." This gives the sub-agent a concrete example to work from.

Monitoring Sub-Agent Progress

When a sub-agent is running, Claude Code shows its activity in the terminal. You can see which files it reads, which commands it runs, and what edits it makes. This visibility lets you catch problems early — if a sub-agent is reading irrelevant files or going down an unproductive path, the parent will eventually see the result and can try again.

For long-running sub-agent tasks, be patient. Sub-agents go through the same orient-plan-execute cycle as the parent. They read files, think, try things, and iterate. This takes time, especially for exploratory tasks where the sub-agent is mapping unfamiliar territory.

Cost Implications

Each sub-agent uses its own tokens. A task that spawns three sub-agents will use roughly three times the tokens of doing the same work sequentially in the parent — sometimes more, because each sub-agent incurs its own startup overhead (reading files, orienting itself).

The tradeoff is time. Three parallel sub-agents finish in roughly the time of one. If the task is time-sensitive or the work is substantial, the extra token cost is worth it.

For cost-conscious workflows, consider whether sub-agents are necessary for each task. A quick five-line change does not justify the overhead of a sub-agent. A 200-line implementation across three modules does.

You can see token usage in Claude Code's output. Pay attention to this during your early sub-agent experiments to build intuition for what tasks are cost-effective to delegate.

Continuing a Sub-Agent's Work with SendMessage

Sometimes a sub-agent finishes its initial task but you realize follow-up work is needed. Rather than spawning an entirely new sub-agent that must re-orient from scratch, you can use SendMessage to continue a previous sub-agent's conversation.

SendMessage lets the parent send additional instructions to a sub-agent that has already completed a task. The sub-agent retains its context from the first interaction — the files it read, the understanding it built, the changes it made — and can continue where it left off. This avoids the redundant startup cost of a fresh sub-agent re-reading the same files and rebuilding the same understanding.

Use SendMessage when:

  • A sub-agent completed its task but the results need refinement
  • You want to ask follow-up questions about a research agent's findings
  • An implementation sub-agent needs to handle a case it missed

Do not use SendMessage as a substitute for a well-specified initial prompt. If you find yourself sending many follow-up messages to a sub-agent, that usually means the initial handoff prompt was underspecified.