Claude Code Sub-Agents: Orchestrating Complex Tasks 2026
By Learnia Team
Claude Code Sub-Agents: Orchestrating Complex Tasks 2026
This article is written in English. Our training modules are available in multiple languages.
Sub-agents are Claude Code's way of dividing and conquering. Instead of one agent doing everything sequentially, spawn multiple specialized agents to work in parallel—each focused on a specific subtask with its own context and tools.
Table of Contents
- →What Are Sub-Agents?
- →Why Use Sub-Agents?
- →Agent Types and Permissions
- →Spawning Sub-Agents
- →Orchestration Patterns
- →Real-World Examples
- →Troubleshooting
- →Related Articles
- →Key Takeaways
Go Beyond Prompts — Build AI Systems
What Are Sub-Agents?
Sub-agents are isolated Claude instances spawned from your main session. Each sub-agent:
- →Has its own context window
- →Runs specific tools with specific permissions
- →Reports back to the orchestrating agent
- →Can work in parallel with other sub-agents
Sub-Agent Architecture:
Main Agent ("Refactor authentication across codebase")
↓ Spawns parallel agents ↓
- →Explore Agent → Analyzes
src/ - →Explore Agent → Analyzes
lib/ - →Explore Agent → Analyzes
tests/
↓ Results flow back ↓
Main Agent synthesizes findings
Why Use Sub-Agents?
Without Sub-Agents
Large tasks consume your context quickly:
> Analyze all React components for accessibility issues
Analyzing src/components/Button.tsx...
Analyzing src/components/Modal.tsx...
Analyzing src/components/Form.tsx...
[... 50 more files ...]
⚠️ Context limit approaching. Some files may be truncated.
With Sub-Agents
Divide work across isolated contexts:
> Analyze all React components for accessibility issues
Spawning sub-agents:
- Agent 1: Analyzing src/components/ui/*
- Agent 2: Analyzing src/components/forms/*
- Agent 3: Analyzing src/components/layout/*
[Agents working in parallel...]
All agents complete. Synthesizing findings:
Found 12 accessibility issues across 47 components.
Each agent has full context for its slice of work.
Built-in Agent Types
Claude Code includes several built-in agents:
Explore Agent
Fast, read-only codebase exploration:
> Use the Explore agent to understand the authentication system
[Explore Agent]
Analyzing authentication...
Auth System Summary:
- JWT-based authentication in src/auth/
- Session management in src/session/
- OAuth providers in src/auth/providers/
- Middleware: src/middleware/auth.ts
Key files:
- src/auth/jwt.ts (token generation)
- src/auth/verify.ts (token validation)
- src/middleware/auth.ts (route protection)
[Agent complete]
Explore is read-only—it can't modify files, reducing risk for autonomous exploration.
Plan Agent
Architecture and planning focused:
> Use the Plan agent to design a caching layer
[Plan Agent]
Designing caching solution...
Recommended Architecture:
1. Cache Layer: Redis for distributed caching
2. Cache Keys: Based on endpoint + params hash
3. TTL Strategy: 5min for listings, 1hr for static
4. Invalidation: Event-driven via message queue
Implementation Steps:
1. Set up Redis connection (src/cache/client.ts)
2. Create cache middleware (src/middleware/cache.ts)
3. Add cache decorators for services
4. Implement invalidation handlers
[Agent complete]
Plan focuses on analysis and design without making changes.
General-Purpose Agent
The default agent with full capabilities:
> Create a sub-agent to implement the user profile feature
[General Agent]
Implementing user profile...
Created:
- src/components/UserProfile.tsx
- src/api/profile.ts
- src/types/profile.ts
- tests/profile.test.ts
[Agent complete]
General-purpose agents can read, write, and execute commands.
Managing Agents
View Available Agents
> /agents
Interactive menu:
Available Agents:
Built-in:
[1] explore - Fast read-only exploration
[2] plan - Architecture and planning
[3] general-purpose - Full capabilities
Custom:
[4] security-audit - Security-focused analysis
[5] docs-generator - Documentation creation
[c] Create agent [e] Edit agent [d] Delete agent
[Esc] Exit
Create Custom Agent
Define specialized agents for your workflow:
> /agents
[c] Create agent
Name: security-audit
Description: Security-focused code analysis
Allowed tools: Read, grep_search, semantic_search
System prompt: You are a security expert. Analyze code for vulnerabilities,
exposed secrets, injection risks, and security best practices.
Be thorough and report all findings with severity levels.
Spawning Sub-Agents
In Conversation
Ask Claude to spawn agents naturally:
> Use sub-agents to analyze each module in parallel
Spawning agents for each module:
- Module 1: src/auth (Explore agent)
- Module 2: src/api (Explore agent)
- Module 3: src/components (Explore agent)
- Module 4: src/utils (Explore agent)
[All agents working...]
Explicit Agent Request
Specify which agent type to use:
> Have the Explore agent map all database queries in the codebase
[Explore Agent]
Mapping database queries...
Parallel Execution
> Run these tasks in parallel with sub-agents:
1. Find all TODO comments
2. Check for deprecated API usage
3. Identify unused exports
Spawning 3 parallel agents...
Agent 1 (TODOs): Found 23 TODO comments
Agent 2 (Deprecated): Found 5 deprecated API calls
Agent 3 (Unused): Found 12 unused exports
All agents complete.
Agent Configuration
Custom Agent Definition
Create agents in settings:
// .claude/settings.json
{
"agents": {
"security-scan": {
"description": "Security vulnerability scanner",
"model": "claude-sonnet",
"allowedTools": ["Read", "grep_search", "Bash(grep:*)"],
"systemPrompt": "You are a security expert. Scan for vulnerabilities, exposed credentials, and security anti-patterns."
},
"docs-writer": {
"description": "Documentation generator",
"model": "claude-sonnet",
"allowedTools": ["Read", "Write(docs/**)"],
"systemPrompt": "You are a technical writer. Generate clear, comprehensive documentation."
},
"test-creator": {
"description": "Test generation specialist",
"model": "claude-sonnet",
"allowedTools": ["Read", "Write(**/*.test.*)", "Bash(npm:test)"],
"systemPrompt": "You are a testing expert. Create comprehensive test suites with good coverage."
}
}
}
Agent Properties
| Property | Description |
|---|---|
description | What the agent does |
model | Claude model to use |
allowedTools | Tools the agent can access |
deniedTools | Tools explicitly blocked |
systemPrompt | Instructions for the agent |
maxTokens | Output token limit |
temperature | Response randomness (0-1) |
Sub-Agent Communication
Result Aggregation
Sub-agents report back to the main agent:
Main: Analyze each microservice for API inconsistencies
Sub-agent 1 (user-service):
- 3 inconsistent response formats
- Missing error codes on 2 endpoints
Sub-agent 2 (order-service):
- Consistent patterns ✓
- 1 deprecated endpoint in use
Sub-agent 3 (payment-service):
- 2 inconsistent date formats
- Non-standard status codes
Main: Synthesizing findings...
Context Passing
The main agent provides context to sub-agents:
Main: I need to refactor error handling. First, have Explore
agents map current error patterns in each service.
Context passed to sub-agents:
- Project uses TypeScript
- Current error patterns to look for
- Reporting format expected
Sub-agents receive targeted context, not the entire conversation.
Real-World Patterns
Pattern 1: Codebase Exploration
Map a large unfamiliar codebase:
> Use Explore agents to understand this codebase structure
[Spawning Explore agents...]
Agent 1: Core architecture (src/core)
Agent 2: API layer (src/api)
Agent 3: UI components (src/components)
Agent 4: Utilities (src/utils)
Agent 5: Configuration (config, *.config.*)
[Synthesizing...]
Codebase Overview:
- Framework: Next.js 14 with App Router
- State: Zustand + React Query
- API: tRPC with Prisma ORM
- Auth: NextAuth.js with JWT
- Testing: Vitest + Playwright
Key architectural patterns:
- Feature-based folder structure
- Server/client component separation
- Centralized error handling in src/core/errors
Pattern 2: Parallel Refactoring
Refactor multiple files simultaneously:
> Refactor all API routes to use the new error handling pattern
[Creating refactoring agents...]
Agent 1: src/api/users/* (5 files)
Agent 2: src/api/products/* (8 files)
Agent 3: src/api/orders/* (6 files)
Agent 4: src/api/auth/* (4 files)
[Agents working in parallel...]
Progress:
- Agent 1: ████████░░ 80% (4/5 files)
- Agent 2: ██████░░░░ 60% (5/8 files)
- Agent 3: ████████░░ 67% (4/6 files)
- Agent 4: ██████████ 100% (4/4 files)
[All agents complete]
Summary:
- 23 files refactored
- 89 error handlers updated
- 12 type definitions added
Pattern 3: Test Generation
Generate tests across the codebase:
> Create comprehensive tests for all services
[Spawning test-creator agents...]
Agent 1: UserService tests
Agent 2: OrderService tests
Agent 3: PaymentService tests
Agent 4: NotificationService tests
[Agents working...]
Created test files:
- tests/services/user.test.ts (15 tests)
- tests/services/order.test.ts (22 tests)
- tests/services/payment.test.ts (18 tests)
- tests/services/notification.test.ts (12 tests)
Total: 67 tests covering 94% of service methods
Pattern 4: Documentation Sprint
Generate docs in parallel:
> Document all public APIs using docs-writer agents
[Spawning docs-writer agents...]
Agent 1: REST API documentation
Agent 2: GraphQL schema docs
Agent 3: SDK reference
Agent 4: Getting started guide
[Agents working...]
Generated:
- docs/api/rest.md (45 endpoints)
- docs/api/graphql.md (complete schema)
- docs/sdk/reference.md (all public methods)
- docs/getting-started.md (quickstart guide)
Pattern 5: Security Audit
Comprehensive security scan:
> Run a security audit using security-scan agents
[Spawning security-scan agents...]
Agent 1: Dependency vulnerabilities
Agent 2: Code security patterns
Agent 3: Configuration review
Agent 4: Authentication audit
[Scanning...]
Security Report:
CRITICAL (2):
- Exposed API key in src/config/legacy.ts
- SQL injection risk in src/api/search.ts
HIGH (5):
- 3 npm packages with known vulnerabilities
- Missing rate limiting on auth endpoints
- Weak password validation
MEDIUM (12):
- Various XSS prevention gaps
- Missing CSRF tokens
- Overly permissive CORS
Full report: .claude/reports/security-audit.md
Agent Limits & Best Practices
Context Management
Each sub-agent has its own context limit:
- →Main agent: 200k tokens
- →Sub-agent 1: 200k tokens (isolated)
- →Sub-agent 2: 200k tokens (isolated)
- →Sub-agent 3: 200k tokens (isolated)
Total effective context: 800k tokens for the same task.
Best Practices
1. Scope agents narrowly
# Good: Specific scope
"Analyze authentication files in src/auth"
# Bad: Too broad
"Analyze everything in src"
2. Use appropriate agent types
# Read-only task → Explore agent
# Planning task → Plan agent
# Implementation → General agent
3. Limit parallel agents
# Good: 3-5 parallel agents
# Risky: 20 parallel agents (harder to coordinate)
4. Provide clear deliverables
"Report back with:
- List of issues found
- Severity for each
- File and line number
- Suggested fix"
5. Validate agent output
Main agent should verify sub-agent results
before taking action based on them.
Agents in Automation
Headless Agent Spawning
In automated scripts:
claude --print -p "Use Explore agents to map the codebase structure"
CI/CD Integration
# .github/workflows/analysis.yml
- name: Run parallel analysis
run: |
claude --dangerously-skip-permissions -p \
"Use sub-agents to analyze: 1) test coverage 2) type safety 3) lint issues"
See Claude Code GitHub Actions: AI-Powered CI/CD Automation.
SDK Usage
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const response = await client.messages.create({
model: "claude-sonnet-4-20250514",
max_tokens: 8096,
messages: [{
role: "user",
content: "Use sub-agents to analyze each module in parallel"
}]
});
See Headless & Programmatic Claude Code: SDK & Automation.
Integration with Other Features
Agents + Hooks
Hooks apply to sub-agent actions too:
{
"hooks": {
"PreToolUse": [{
"matcher": "*",
"command": "python .claude/hooks/validate.py"
}]
}
}
All sub-agent tool calls go through your hooks.
See Claude Code Hooks: Automate Your Development Workflow.
Agents + MCP
Sub-agents can use MCP tools:
{
"agents": {
"github-helper": {
"allowedTools": ["mcp__github__*", "Read"],
"systemPrompt": "You help with GitHub operations."
}
}
}
See Model Context Protocol (MCP) for Claude Code: Complete Guide.
Agents + Custom Commands
Commands can specify agent usage:
<!-- .claude/commands/audit.md -->
---
description: Full codebase audit
---
Run a comprehensive audit using sub-agents:
1. Spawn Explore agents to map the codebase
2. Spawn security-scan agents for vulnerabilities
3. Spawn a Plan agent to prioritize findings
4. Synthesize into a final report
See Custom Slash Commands in Claude Code: Build Your Own.
Debugging Agents
Verbose Mode
claude --verbose
Shows agent lifecycle:
[AGENT] Spawning Explore agent for src/auth
[AGENT] Context: 2,340 tokens
[AGENT] Tools: Read, grep_search
[AGENT] Started: abc123
[AGENT] abc123: Reading src/auth/jwt.ts
[AGENT] abc123: Complete (4.2s)
[AGENT] Result: 1,200 tokens
Agent Logs
Sub-agents write to session logs:
> /export
Session exported with:
- Main agent conversation
- Sub-agent transcripts
- Tool execution history
Common Issues
Agent hanging:
- →Check for infinite loops in task
- →Verify tool permissions
- →Try smaller scope
Inconsistent results:
- →Add more specific instructions
- →Use lower temperature
- →Verify context passed correctly
Out of context:
- →Reduce scope per agent
- →Use more agents with smaller slices
- →Enable compaction
Related Articles
Expand your Claude Code agent knowledge:
- →Claude Code GitHub Actions - Automate workflows with AI-powered CI/CD
- →Claude Code SDK Headless Mode - Programmatic automation patterns
- →Claude Code Installation and Setup - Get started with configuration
- →Claude Code Slash Commands Reference - Complete command guide
- →Claude Code vs Copilot vs Cursor 2026 - Feature comparison
Key Takeaways
- →
Divide and conquer: Sub-agents let you tackle large tasks by splitting work.
- →
Choose the right agent: Explore for reading, Plan for design, General for changes.
- →
Isolated contexts: Each sub-agent has its own context window.
- →
Parallel execution: Multiple agents can work simultaneously.
- →
Control with permissions: Limit what each agent type can do.
Master Agent Orchestration
Sub-agents are powerful, but orchestrating them effectively requires understanding agent patterns and control flows.
In our Module 6 — Autonomous Agents, you'll learn:
- →Agent architecture fundamentals
- →Orchestration patterns
- →Error handling and recovery
- →Building reliable agent workflows
→ Explore Module 6: Autonomous Agents
Last updated: January 2026. Covers Claude Code sub-agents with Claude Sonnet 4.5 and the latest multi-agent orchestration features.
Module 6 — AI Agents & ReAct
Create autonomous agents that reason and take actions.
→Related Articles
ClawdBot Skills Platform: Build, Share & Deploy Custom AI Agent Skills with ClawHub (2026)
Gemini 3.1 Pro: Complete Guide to Google's Most Advanced Reasoning Model (2026)
Lyria 3: Complete Guide to Google's AI Music Generation — Prompts, SynthID & Creative Workflows (2026)
FAQ
What are Claude Code sub-agents?+
Sub-agents are isolated Claude instances spawned from your main session. Each has its own context window, runs specific tools with controlled permissions, and reports back to the orchestrating agent for synthesis.
What types of sub-agents does Claude Code support?+
Claude Code supports three main agent types: Explore agents for reading and analyzing code, Plan agents for design and architecture decisions, and General agents for making actual code changes.
How do Claude Code sub-agents handle context limits?+
Each sub-agent has its own context window, preventing large tasks from consuming all context. Work is divided into smaller scopes, and compaction can be enabled for very large analyses.
Can Claude Code sub-agents run in parallel?+
Yes, multiple sub-agents can execute simultaneously. For example, separate explore agents can analyze different directories concurrently, with results synthesized by the main orchestrating agent.
How do I control sub-agent permissions in Claude Code?+
Use the permissions parameter when spawning agents. Explore agents default to read-only, Plan agents can read and analyze, and General agents can make changes—each with configurable tool access.