Sub-agent Collaboration Mode

Understanding and using Claude Code's sub-agents β€” parallel exploration, background tasks, isolated execution

Subagent Collaboration Mode

Imagine: you ask Claude to help you refactor a large module, but before refactoring, you need it to first figure out three things β€” what existing API interfaces are there, what the database schema looks like, and what the test coverage is like. In normal mode, Claude can only check these one by one sequentially. But what if it could send out three "clones" to investigate simultaneously?

That's the charm of subagents.

What Are Subagents

Agent Tool Concept

A subagent is a special tool in Claude Code that allows the main session to create independent Claude instances to execute specific tasks. You can think of it as "Claude hired an assistant".

The Claude in the main session is the project manager, responsible for overall coordination. When encountering subtasks that need in-depth investigation, it can launch a subagent to handle them specifically, while continuing to handle other things.

Differences Between Subagents and Main Session

Feature Main Session Subagent
Context Contains full conversation history Independent context window, only contains task description
Lifecycle Persists until you close Claude Code Automatically ends after task completion
Tool Access All authorized tools Can be restricted to specific tool subsets
Execution Mode Interactive dialogue with you Autonomous execution, returns results when done
Context Consumption All operations consume same context Does not consume main session's context
Results Displayed directly Returned to main session as summary

The most critical difference is the independent context window. Subagents have their own context space; their exploration process won't expand the main session's context. Only the final results are passed back to the main session β€” it's like sending someone on a business trip for research; when they return, they just need to give you a report, not replay the entire research process.

Advantages of Independent Context Window

Why is independent context so important? Let me give a practical example:

Suppose you need Claude to analyze a project with 200 files. If you read files one by one in the main session, with each file averaging 200 lines, file content alone would take up 40,000 lines of context. Add Claude's analysis process, and you'll quickly fill up the context.

With subagents, it's different. The subagent reads and analyzes these files in its own context, and only passes back a few hundred lines of analysis report at the end. The main session's context barely increases, and you still have plenty of room to continue subsequent work.

Built-in Subagent Types

Subagents in Claude Code are not actually fixed "types" but are flexibly created by the main session based on task nature. However, in practice, subagents typically assume the following roles:

Explore (Code Search and Exploration)

This is the most common use case for subagents. When Claude needs to understand a certain aspect of a project, it launches an Explore subagent:

Capabilities:

  • Read files (Read)
  • Search code (Grep, Glob)
  • View directory structure
  • Analyze code dependencies

Limitations:

  • Usually only granted read-only tools
  • Cannot modify files
  • Cannot execute commands

Typical Scenarios:

Analyze public interfaces for all services in the src/services/ directory
Find all files that reference UserService
Understand the workflow of the authentication middleware

Plan (Architecture Design and Planning)

Subagents used for formulating plans or design solutions:

Capabilities:

  • All Explore capabilities
  • Web search (documentation, best practices)
  • Generate detailed solution documents

Typical Scenarios:

Design a cache layer architecture
Evaluate feasibility of migrating from REST to GraphQL
Formulate a database sharding strategy

General-Purpose (General-Purpose Tasks)

Subagents that handle specific execution tasks, with full tool access:

Capabilities:

  • Read and write files
  • Execute commands
  • Run tests
  • Install dependencies

Typical Scenarios:

Run the full test suite in the background
Generate API documentation
Execute code formatting

When to Use Subagents

Scenario 1: Code Search and Understanding

When you need Claude to deeply understand an unfamiliar codebase, subagents can efficiently complete the exploration:

I just took over this project. Please help me understand its architecture comprehensively:
1. Use a subagent to analyze the backend directory structure and core modules
2. Use a subagent to analyze the frontend component tree and state management
3. Use a subagent to analyze the database schema and entity relationships
Then synthesize information from all three areas and give me a project architecture overview.

Claude might launch three subagents to execute these tasks in parallel, then aggregate their reports.

Scenario 2: Parallel Research on Multiple Solutions

When you need to compare multiple technical solutions, the parallel capability of subagents is very useful:

I need to choose a message queue for the project. Please research the following solutions separately:
1. Redis Streams β€” check if our existing Redis configuration supports it
2. RabbitMQ β€” evaluate the cost of introducing new dependencies
3. Using PostgreSQL's LISTEN/NOTIFY directly
For each solution, analyze the pros and cons and compatibility with our project.

Scenario 3: Run Long Tasks in the Background

Some tasks take a long time (like running tests, generating documentation). You can put them in a subagent for background execution:

Please run the full test suite in the background while I continue working on other things.
Tell me the results when the tests are done.

Claude will launch a background subagent to execute the tests. You can continue talking with the main session without waiting.

Scenario 4: Isolate High-Risk Operations

When you need to execute potentially risky operations, you can use a subagent for isolation:

Please try the following operations using a subagent:
1. Switch to a temporary branch
2. Try upgrading React to 19.x
3. Run the build and see how many compatibility errors there are
4. Send me the error list
Do not operate on the main branch.

Subagent Practical Tutorial

Example 1: Use Subagents to Understand an Unfamiliar Codebase

Suppose it's your first day on a medium-sized Python project (about 50 source files), and you need to quickly understand its structure.

Your Prompt:

It's my first day on this project. Please help me quickly build an understanding of it.
Use subagents to analyze the following areas in parallel:

1. Project structure and entry points β€” scan directory structure, find main entry, routing definitions, config files
2. Data models β€” analyze all model files and draw entity relationships
3. Business logic β€” analyze the services directory and understand core business workflows
4. External dependencies β€” analyze requirements.txt and actual imports to identify key dependencies

Finally, synthesize all the information into a project overview of no more than 500 words.

Claude's Execution Process:

Claude will create multiple subagents to execute tasks independently. Each subagent explores on its own, then returns results. Throughout the process, you'll see output like:

Launching 4 subagents for parallel analysis...

[Subagent 1] Analyzing project structure...

  - Scanned 52 Python files
  - Found entry point: main.py β†’ FastAPI app
  - Route definitions in routers/ directory (8 routing modules)
  - Config: config.py + .env

[Subagent 2] Analyzing data models...

  - Found 12 SQLAlchemy models
  - Core entities: User, Organization, Project, Task, Comment
  - Key relationships: User ← many-to-many β†’ Organization, Project β†’ has-many β†’ Task

[Subagent 3] Analyzing business logic...

  - 9 service files
  - Core workflows: user management, project management, task assignment, notification system
  - Async task processing using Celery

[Subagent 4] Analyzing external dependencies...

  - 32 direct dependencies
  - Key dependencies: FastAPI, SQLAlchemy, Celery, Redis, Alembic
  - Found 2 unused dependencies (requests, beautifulsoup4)

Finally, Claude synthesizes results from all four subagents and gives you a structured project overview.

Example 2: Launch Multiple Subagents in Parallel to Compare Solutions

You're considering how to implement real-time notifications and want to compare several solutions:

I need to add real-time notification functionality to the project. Please help me evaluate the following three solutions in parallel:

Solution A: WebSocket (using FastAPI's built-in WebSocket support)
Solution B: Server-Sent Events (SSE)
Solution C: Polling

For each solution, please analyze:
1. Compatibility with our existing architecture (check existing code)
2. Implementation complexity (approximately how many files need changes)
3. Performance and scalability
4. Client compatibility

Then give me a comparison table and your recommendation.

Claude's Comparison Results Might Be:

All three subagents have completed analysis. Summary comparison:

| Evaluation Dimension | WebSocket | SSE | Polling |
|----------|-----------|-----|------|
| Architecture Compatibility | Need to add WebSocket routes | Can reuse existing HTTP routes | Fully compatible |
| Implementation Complexity | High (~8 files) | Medium (~4 files) | Low (~2 files) |
| Real-time Capability | Best (full duplex) | Good (server push) | Average (depends on polling interval) |
| Scalability | Needs WebSocket load balancing | Can use CDN | Simplest |
| Celery Integration | Needs additional message bridge | Can directly consume Celery events | Poll database |

**Recommendation**: Considering you're already using Celery + Redis, SSE is the best choice.
It can directly subscribe to Redis channels to get Celery events, with moderate implementation complexity,
and doesn't require additional infrastructure.

Example 3: Run Tests with Background Subagent

You're modifying code and want to know the test results at the same time:

Please run pytest in the background and run the full test suite. I'll continue modifying code. Tell me when it's done.

Claude will launch a background subagent to execute the tests. You can continue talking with Claude and modifying code. When the tests complete, you'll see a result notification:

Background tests completed. Results:

- Total: 247 tests
- Passed: 241
- Failed: 4
- Skipped: 2

Failed tests:
1. test_order_service.py::test_calculate_total_with_discount
   AssertionError: 99.99 != 100.0
2. test_user_service.py::test_create_user_duplicate_email
   IntegrityError: Test database not properly cleaned up
3. ...

Would you like me to analyze these failing tests?

Subagent Configuration

Guide Subagent Behavior Through CLAUDE.md

While you can't directly "configure" subagent parameters, you can use CLAUDE.md to guide Claude on when and how to use subagents:

## Subagent Usage Guidelines

### When to Use Subagents

- Tasks analyzing more than 10 files should use subagents
- When comparing multiple solutions, launch independent subagents for each
- Running tests should be executed in background subagents

### Subagent Task Description Template
When launching subagents, the task description should include:
1. Clear objectives (what to do)
2. Scope limitations (what not to do)
3. Output format (what kind of results to return)

### Subagent Result Handling
Subagent results must include:

- Analysis summary (no more than 200 words)
- Key findings list
- Related file paths
- Potential risks or issues

Understanding Tools Available to Subagents

Which tools a subagent can use depends on authorization from the main session. In practice:

  • Read-only tasks: Usually only granted search tools like Read, Grep, Glob
  • Execution tasks: Granted write tools like Bash, Write, Edit
  • Network tasks: Granted network tools like WebSearch, WebFetch

You can imply tool scope through natural language:

Please use a subagent to analyze (read-only) the relationships of all models in the src/models/ directory.

By adding "read-only" hint, Claude tends to create a subagent with only search and reading capabilities.

Background Execution

Subagents can run in the background without blocking your interaction with the main session. When you say "in the background..." or "asynchronously...", Claude will use the run_in_background parameter:

Please help me with two things in the background:
1. Run the complete lint check
2. Check all dependencies for known security vulnerabilities
I'll continue modifying code and let me know when done.

When a background subagent completes, the system notifies Claude, who then passes the results to you.

Best Practices

1. Give Subagents Clear Task Descriptions

A subagent's context is brand new β€” it doesn't know what you discussed with the main session before. So task descriptions must be self-contained:

Bad Practice:

Use a subagent to check the issue mentioned earlier.

(The subagent doesn't know what "the issue mentioned earlier" is)

Good Practice:

Use a subagent to check whether the process_refund() method in src/services/payment_service.py correctly handles concurrent refund requests.
Need to pay attention to database transaction isolation levels and use of optimistic locking.

2. Use Parallel Subagents to Improve Efficiency

When multiple tasks have no dependencies on each other, let them execute in parallel:

Please execute the following tasks in parallel:
1. [Subagent A] Analyze all API call points in the frontend code
2. [Subagent B] Analyze backend API endpoints and parameter definitions
3. [Subagent C] Check if API documentation is consistent with actual interfaces

After all three tasks are complete, summarize the API inconsistencies.

3. Don't Overuse Subagents

Subagents are not a silver bullet. The following scenarios are more efficient to handle directly in the main session:

  • Simple file viewing: Reading one or two files, just use @ to reference them
  • Simple searches: Searching for one keyword, the main session does it faster
  • Tasks requiring ongoing interaction: Subagents are "one-time", not suitable for tasks requiring multiple rounds of dialogue
  • Serial tasks that depend on previous results: Using subagents would increase complexity

Rule of thumb: If a task can be described in one or two sentences and doesn't require reading a large number of files, do it directly in the main session.

4. Understand Subagent Result Delivery Mechanism

When a subagent completes its task, its results are passed back to the main session in summary form. This means:

  • The original file content read by the subagent will not be fully transmitted back (it's too large)
  • Only the subagent's analysis conclusions and key information will be passed back
  • If you need to see a specific file discovered by the subagent, read it again in the main session yourself
The subagent told me there's an issue on line 127 of payment_service.py.
Please show me lines 120-140 of that file.

5. Use Subagents for "Exploratory" Operations

Not sure if a certain approach is feasible? Use a subagent to experiment, rather than taking risks on the main branch:

Please use a subagent to run an experiment:
1. Create a temporary directory /tmp/experiment
2. Copy src/models/user.py into it
3. Try replacing SQLAlchemy's declarative models with dataclasses
4. See what problems arise

Don't touch any project files.

Advanced: Combining Subagents with Other Features

Subagents + Plan Mode

You can also use subagents in Plan mode. This is a powerful combination β€” use subagents for in-depth research during the planning phase:

(In Plan mode)
Please use subagents to help me research the following questions, then formulate a migration plan based on the research results:
1. List of all current REST API endpoints and their call frequencies
2. Which endpoints already have equivalent GraphQL implementations
3. How much the client code depends on REST APIs

Subagents + MCP Tools

If you've configured MCP servers (like database query tools), subagents can also use them:

Please use a subagent to connect to the database and analyze the following:
1. Data volume for each table
2. Top 10 slow queries
3. Missing indexes
Use the database MCP tool to execute queries.

Subagents + Hooks

You can use Hooks to trigger custom logic when subagents execute specific actions. For example, automatically send notifications when a subagent completes testing:

{
  "hooks": {
    "Notification": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "curl -X POST https://hooks.slack.com/... -d '{\"text\": \"$MESSAGE\"}'"
          }
        ]
      }
    ]
  }
}

FAQ

Q: Can subagents see my conversation history with the main session?

A: No. A subagent's context is brand new and only contains the task description Claude gives it. This is also why task descriptions must be self-contained. However, subagents can read CLAUDE.md, so project-level conventions and agreements do apply to subagents.

Q: Can subagents launch "sub-subagents"?

A: Yes, but nesting too deep is not recommended. Usually one layer of subagent is sufficient.

Q: Can multiple subagents communicate with each other?

A: No, not directly. If you need Subagent B to depend on Subagent A's results, you can only wait for A to complete, then the main session passes the results to B.

Q: Do subagents consume additional API quota?

A: Yes. Subagents use independent context windows, and both input and output of each subagent consume tokens. However, since a subagent's context is usually smaller (only containing specific tasks), total consumption is often less than doing the same work in the main session.

Q: How do I know what a subagent is doing?

A: Claude displays subagent execution status in the main session. You can see which subagents it has launched, what each subagent is doing, and whether it has completed.

πŸš€
Get Started with QCode β€” AI Coding Assistant
Official Claude Code relay, fast and reliable, ready to use
View Pricing Plans β†’ Create Account