Skip to content
Lesson 7 of 14

Subagents — Task Delegation

10 min read

What Are Subagents

Subagents are specialized AI agents that Claude Code can spawn to handle specific tasks independently. Instead of doing everything in a single conversation thread, Claude can delegate work to one or more subagents that operate in parallel, each focused on a narrow objective. When a subagent finishes, it reports its findings back to the main session.

This is how senior engineers work in practice. You do not do everything yourself -- you delegate research to one team member, testing to another, and documentation to a third, then synthesize the results. Subagents bring this same pattern to AI-assisted development.

The key benefits are parallelism, isolation, and context protection. Subagents can explore risky approaches without polluting your main conversation's context. They can research multiple topics simultaneously. And they keep your main session's context window focused on the primary task rather than filling it with exploratory dead ends.

Built-In Agent Types

Claude Code ships with several built-in agent types optimized for common tasks:

General-purpose agent -- The default agent type. It has access to the same tools as the main session and can handle any task you would give to Claude directly.

Explore agent -- Optimized for codebase exploration. It reads files, searches through code, and builds an understanding of project structure without making any changes. Use this when you need Claude to research a question about your codebase without risking accidental modifications.

Plan agent -- Creates detailed implementation plans. It analyzes requirements, reviews existing code, and produces step-by-step plans with file changes, new files, and commands to run. Use this before starting complex tasks to get a roadmap.

Code-reviewer agent -- Specialized for code review. It examines diffs, checks for bugs and security issues, evaluates test coverage, and produces structured review feedback.

Additional built-in agents may be available depending on your Claude Code version. Run a session and ask Claude what agents are available to see the current list.

When to Use Subagents

Subagents shine in specific scenarios:

Parallel research. You need to understand three different approaches to implementing a feature. Instead of researching them sequentially in your main session, spawn three subagents and let them explore in parallel. You get results faster and keep your main context clean.

claude
> I need to add real-time notifications to our app. Research three approaches in parallel:
> 1. WebSocket implementation with Socket.io
> 2. Server-Sent Events with native browser APIs
> 3. A polling-based approach with long polling
> For each, analyze the trade-offs for our Next.js + PostgreSQL stack.

Claude will delegate each research track to a separate subagent, then synthesize the findings.

Isolated exploration. You want Claude to try a risky refactoring approach but do not want to mess up your main session if it goes wrong. A subagent can explore the approach in isolation, and you only apply the results if they look good.

Protecting main context. Your main session is deep into a complex task and the context window is filling up. Instead of risking context loss by adding more exploratory work, delegate side questions to subagents. They use their own context windows, leaving yours intact.

Specialized tasks. Some tasks benefit from focused attention. Code review, documentation generation, and test writing are all tasks where a dedicated agent with clear instructions produces better results than squeezing them into a busy main session.

The Agent Tool

Under the hood, Claude uses the Agent tool to launch subagents. You do not need to invoke this tool directly -- Claude decides when to use it based on your request. However, understanding how it works helps you write better prompts.

When Claude launches a subagent, it provides:

  • A specific prompt describing the task
  • A set of allowed tools (which may be a subset of the main session's tools)
  • Any relevant context from the current conversation

The subagent runs independently, using its own context window and making its own tool calls. When it finishes, it returns a summary of its work to the main session.

You can influence subagent behavior through your prompts. If you ask Claude to "research this carefully and report back with code examples," the subagent will be more thorough than if you say "quickly check if this is feasible."

Creating Custom Subagents

For recurring delegation patterns, you can define custom agents as markdown files in the .claude/agents/ directory:

<!-- File: .claude/agents/test-writer.md -->
---
name: Test Writer
description: Writes comprehensive unit and integration tests for TypeScript code. Specializes in Vitest with React Testing Library.
tools:
  - Read
  - Write
  - Bash
  - Glob
  - Grep
---

## Instructions

When writing tests, follow these rules:

### Setup
- Use Vitest as the test runner
- Use React Testing Library for component tests
- Use MSW (Mock Service Worker) for API mocking
- Place test files in __tests__/ directories next to the source

### Test Structure
- Group related tests with describe blocks
- Use clear test names: "should [expected behavior] when [condition]"
- Follow the Arrange-Act-Assert pattern
- Test both happy paths and error cases

### Coverage Requirements
- Every exported function must have at least one test
- Edge cases: null inputs, empty arrays, boundary values
- Async functions: test both resolved and rejected states
- Components: test rendering, user interactions, and accessibility

### Output
- Create the test file with all tests
- Run the tests to verify they pass
- Report coverage summary

Now when you ask Claude to write tests, it can delegate to this specialized agent that knows your exact testing conventions, tools, and requirements.

Agent Anatomy: Frontmatter Fields

Custom agent files support these frontmatter fields:

---
name: Agent Name              # Display name
description: What this agent does  # Used for matching tasks to agents
tools:                        # Allowed tools (restrict for safety)
  - Read
  - Write
  - Bash
  - Glob
  - Grep
---

The tools list is important for safety. A documentation agent does not need the Bash tool. An exploration agent does not need the Write tool. Restricting tools to what the agent actually needs prevents accidental modifications and reduces risk.

Another Example: Documentation Agent

<!-- File: .claude/agents/doc-writer.md -->
---
name: Documentation Writer
description: Generates and updates project documentation including API references, guides, and inline code comments.
tools:
  - Read
  - Write
  - Glob
  - Grep
---

## Instructions

When generating documentation:

### Process
1. Read the source code thoroughly before writing anything
2. Identify all public APIs, exported functions, and interfaces
3. Generate documentation that matches the existing style in the project
4. Update any related documentation files (README, API docs, etc.)

### Standards
- Use JSDoc for TypeScript/JavaScript
- Include parameter descriptions, return types, and examples
- Add @throws annotations for functions that can throw
- Keep descriptions concise but complete
- Every code example must be valid and runnable

### Do NOT
- Modify any source code (only documentation and comments)
- Generate documentation for private/internal functions
- Add documentation that duplicates what TypeScript types already express

Notice this agent does not have the Bash tool. It can only read and write files, which is all it needs for documentation work. This constraint prevents it from accidentally running commands while it focuses on its writing task.

Agent Teams

For complex projects that benefit from multi-agent collaboration, Claude Code supports agent teams. When enabled, multiple agents can work together on different aspects of a task, coordinating through the main session.

Enable agent teams with the environment variable:

export CLAUDE_AGENT_TEAMS=1
claude

With agent teams active, Claude can orchestrate workflows like: one agent researches the database schema, another reviews the existing API code, a third drafts the new endpoint, and the main session synthesizes everything into a final implementation.

This feature is most useful for large, multi-step tasks where different aspects require different specializations.

Worktree Isolation

For maximum safety, subagents can run in isolated git worktrees. A worktree is a separate working directory that shares the same git history but has its own file state. Changes made in a worktree do not affect your main working directory until you explicitly merge them.

claude
> Create a new feature branch in a worktree and implement the user profile API endpoint.
> Do not modify my current working directory.

Claude creates a worktree, runs the subagent inside it, and reports back. If you like the result, you merge the worktree branch. If not, you delete it with no impact on your main branch.

This is especially valuable for experimental work where you want to try something without any risk to your current state.

Background Agents

Some subagent tasks take a long time -- running a full test suite, performing a comprehensive code audit, or generating documentation for an entire project. For these cases, you can ask Claude to run the agent in the background:

claude
> Run a comprehensive security audit of the entire codebase in the background.
> I will continue working on the auth refactoring while that runs.

The background agent works independently while you continue your main task. When it finishes, you receive a notification with the results.

When NOT to Use Subagents

Subagents add overhead. Each one consumes tokens, takes time to start up, and requires Claude to synthesize the results. For simple, direct tasks, using the main session is faster and cheaper.

Do not use subagents for:

  • Simple file reads. If you just need to see what is in a file, ask directly.
  • Directed searches. If you know where to look, point Claude there instead of spawning an explorer.
  • Trivial edits. Changing a variable name or fixing a typo does not need a dedicated agent.
  • Sequential tasks. If step 2 depends on step 1, running them in separate agents wastes time because they cannot parallelize.

The rule of thumb: if the task takes fewer than 3-4 tool calls to complete, do it in the main session. If it requires significant exploration, could benefit from parallelism, or needs isolation from your main work, use a subagent.

Best Practices

Give agents clear, specific prompts. Instead of "look at the codebase," try "analyze the authentication flow starting from src/auth/login.ts, trace the token validation logic through all middleware layers, and identify any paths where an expired token could bypass validation." Specificity produces dramatically better results from subagents.

Use tool restrictions to enforce safety boundaries. An exploration agent should not have Write access. A documentation agent should not have Bash access. Match tools to the task.

Review subagent results before acting on them. Subagents are powerful but not infallible. When a subagent reports findings or proposes changes, review them in the main session before committing anything.

Try this exercise: create a custom test-writer agent and a custom doc-writer agent for your project. Give each one the minimum set of tools it needs. Then start a Claude Code session and ask Claude to write tests for a complex function and generate documentation for a module, simultaneously. Observe how Claude delegates to both agents in parallel and synthesizes the results. Compare the quality of the output against what you get when asking the main session to do both tasks sequentially.