Building Subagents in Claude Code: Complete Tutorial
Claude Code can spawn subagents—specialized mini-agents that execute tasks in parallel while you continue working. This tutorial shows you how to create custom subagents, when to use them, and patt...
Building Subagents in Claude Code: Complete Tutorial
Claude Code can spawn subagents—specialized mini-agents that execute tasks in parallel while you continue working. This tutorial shows you how to create custom subagents, when to use them, and patterns for effective multi-agent workflows.
How subagents work, creating custom subagent definitions, choosing the right model, and practical patterns for code review, testing, and research workflows.
What Are Subagents?
Subagents are lightweight Claude instances with their own:
- Context window — Isolated from the main agent
- System prompt — Specialized for specific tasks
- Tool permissions — Controlled access to capabilities
- Model selection — Independent model choice
When you ask Claude to spawn a subagent, it creates a fresh instance that works independently. This prevents context pollution and enables parallel execution.
Key Characteristics
| Aspect | Main Agent | Subagent |
|--------|------------|----------|
| Context | Shared across session | Fresh, isolated |
| Persistence | Throughout session | Task-scoped |
| Nesting | Can spawn subagents | Cannot spawn subagents |
| Tools | Full access | Configurable per agent |
---
Built-in Subagents
Claude Code includes two built-in subagents:
Explore Subagent
Fast, lightweight agent for codebase exploration:
- Read-only mode (can't modify files)
- Optimized for file discovery and search
- Uses bash commands:
ls,find,cat,git log,git diff
Invoke with:
``
Use the explore subagent to find all authentication-related files
`
Plan Subagent
Activates automatically in plan mode:
- Researches codebase before creating plans
- Explores architecture and patterns
- Gathers context for implementation planning
You don't invoke this directly—it runs automatically when you enter plan mode with complex tasks.
---
Creating Custom Subagents
Custom subagents are defined as Markdown files with YAML frontmatter.
File Locations
| Location | Scope | Priority |
|----------|-------|----------|
|
.claude/agents/*.md | Project-specific | Higher (overrides global) |
|
~/.claude/agents/*.md | Global (all projects) | Lower |
Subagent Structure
`markdown
---
name: code-reviewer
description: Reviews code changes for quality, security, and best practices
model: sonnet
tools:
- Read
- Glob
- Grep
- Bash
permissionMode: bypassPermissions
---
You are a senior code reviewer. Your role is to review code changes and provide actionable feedback.
Review Criteria
- Code Quality
- Clear, readable code
- Appropriate naming
- DRY principles applied
- Security
- No hardcoded secrets
- Input validation
- SQL injection prevention
- Performance
- Efficient algorithms
- No unnecessary loops
- Proper async handling
Output Format
Structure your review as:
- Summary (1-2 sentences)
- Issues Found (if any)
- Suggestions for Improvement
- What's Done Well
`
Frontmatter Fields
| Field | Required | Description |
|-------|----------|-------------|
|
name | Yes | Identifier for invocation |
|
description | Yes | When to use this agent |
|
model | No | sonnet, opus, or inherit |
|
tools | No | List of allowed tools (defaults to all) |
|
permissionMode | No | Permission handling mode |
|
skills | No | Skills available to the agent |
---
Model Selection
Choose the right model for each subagent:
Sonnet (Default)
`yaml
model: sonnet
`
- Fast and cost-effective
- Good for routine tasks
- Code review, file exploration, testing
Opus
`yaml
model: opus
`
- Maximum reasoning capability
- Complex analysis tasks
- Architecture decisions, security audits
Inherit
`yaml
model: inherit
`
- Uses whatever model the main agent uses
- Consistent behavior across the session
Use Sonnet for most subagents. Reserve Opus for tasks requiring deep reasoning. Each subagent uses its own token quota.
---
Practical Subagent Examples
Code Reviewer
`markdown
---
name: code-reviewer
description: Reviews code for quality, security, and best practices
model: sonnet
tools:
- Read
- Glob
- Grep
---
You are a thorough code reviewer. Review the specified files and provide constructive feedback.
Focus on:
- Logic errors and edge cases
- Security vulnerabilities
- Performance issues
- Code style consistency
- Test coverage gaps
Be specific. Reference line numbers. Suggest concrete fixes.
`
Test Runner
`markdown
---
name: test-runner
description: Runs tests and analyzes failures
model: sonnet
tools:
- Bash
- Read
- Glob
---
You are a test execution specialist. Run the specified tests and analyze results.
When tests fail:
- Identify the failure pattern
- Locate the relevant source code
- Explain why the test failed
- Suggest a fix
Report:
- Total tests run
- Pass/fail counts
- Failure analysis for each failed test
`
Security Auditor
`markdown
---
name: security-auditor
description: Audits code for security vulnerabilities
model: opus
tools:
- Read
- Glob
- Grep
---
You are a security researcher auditing code for vulnerabilities.
Check for:
- Injection vulnerabilities (SQL, XSS, command)
- Authentication/authorization flaws
- Sensitive data exposure
- Insecure dependencies
- Cryptographic issues
Classify findings by severity (Critical, High, Medium, Low).
Provide remediation guidance for each issue.
`
Documentation Generator
`markdown
---
name: doc-generator
description: Generates documentation from code
model: sonnet
tools:
- Read
- Glob
- Write
---
You are a technical writer. Generate clear, comprehensive documentation.
For functions/methods:
- Purpose and use cases
- Parameters with types
- Return values
- Usage examples
- Edge cases
Write in a clear, concise style. Include code examples.
`
Dependency Analyzer
`markdown
---
name: dep-analyzer
description: Analyzes project dependencies for issues
model: sonnet
tools:
- Read
- Bash
- Glob
---
You analyze project dependencies for:
- Outdated packages
- Security vulnerabilities
- Unused dependencies
- Version conflicts
- License compliance
Report findings with severity and recommended actions.
`
---
Invoking Subagents
Automatic Delegation
Claude analyzes your request and picks the right subagent:
`
Review the authentication module for security issues
`
If you have a
security-auditor subagent, Claude may automatically delegate to it.
Explicit Invocation
Request a specific subagent:
`
Use the code-reviewer subagent to review the changes in the last commit
`
Multiple Parallel Subagents
Request parallel execution:
`
Use 3 subagents to review each of the modified files in parallel
`
Or be specific:
`
Create a subagent for each file in src/components that needs TypeScript migration
`
---
Patterns for Effective Use
Pattern 1: Parallel Research
When exploring a codebase, spawn multiple research agents:
`
I need to understand the authentication system. Use subagents to:
- Find all auth-related files
- Document the auth flow
- List all API endpoints requiring auth
- Check for security issues
`
Each subagent works independently, then results consolidate.
Pattern 2: Review Pipeline
Chain subagents for thorough review:
`
For the changes in this PR:
- Use code-reviewer to check code quality
- Use security-auditor to check for vulnerabilities
- Use test-runner to verify tests pass
`
Pattern 3: Bulk Operations
Process multiple files in parallel:
`
Use a subagent for each React component in src/components
to add TypeScript types
`
When multiple subagents might modify the same files, use research-only subagents or carefully coordinate write operations.
Pattern 4: Specialized Expertise
Create focused subagents for specific technologies:
`markdown
---
name: react-expert
description: React and frontend architecture specialist
---
You are a React expert. Focus on:
- Component design patterns
- State management
- Performance optimization
- Hook usage best practices
- Testing strategies
`
Then invoke for React-specific work:
`
Use the react-expert subagent to review the new dashboard component
`
---
Context Sharing
Subagents have isolated context. To share information:
Write to Files
Have subagents write findings to files:
`markdown
Write your analysis to .claude/analysis/auth-review.md
`
The main agent or other subagents can then read these files.
Return Summaries
Subagent results return to the main agent automatically. Structure outputs for easy consumption:
`markdown
Output Format
Always structure your response as:
Summary
[Brief overview]
Findings
[Detailed analysis]
Recommendations
[Actionable next steps]
`
---
Best Practices
Each subagent should have one clear responsibility. Avoid "swiss army knife" subagents that do everything.
Sonnet for routine tasks (reviews, testing, exploration). Opus for complex reasoning (security audits, architecture).
Only grant tools the subagent needs. A reviewer doesn't need Write access.
Your subagent's system prompt is its instruction manual. Be specific about expectations.
Research subagents should explore without modifying. This enables safe parallel execution.
---
Subagents with CAS
Combine subagents with CAS for powerful workflows:
Context-Aware Review
`
Before reviewing, check CAS for our coding standards:
cas_search: "coding standards this project"
Then use code-reviewer to check if the PR follows these standards.
`
Task-Scoped Subagents
`
Start the authentication task:
cas_task_start: "Implement user authentication"
Use subagents to research:
- Our existing auth patterns
- Similar implementations
- Security requirements
Add findings to task notes:
cas_task_notes: "Research complete - see findings..."
`
---
Troubleshooting
Subagent Not Found
Symptom: "Unknown subagent: my-agent"
Fix:
- Check file exists at
.claude/agents/my-agent.md
Verify YAML frontmatter is valid
Restart Claude Code after adding new subagents
Subagent Not Using Expected Model
Symptom: Subagent seems to use different model
Fix:
- Explicit set
model: in frontmatter
Check for typos ( sonnet not sonnett)
Permission Denied
Symptom: Subagent can't perform certain actions
Fix:
- Add required tools to
tools: list
Check permissionMode setting
Context Not Shared
Symptom: Subagent doesn't know about previous work
Fix:
- This is by design—subagents have isolated context
- Pass context explicitly in the task prompt
- Have subagents write to shared files
---
Conclusion
Subagents are a powerful feature for scaling your AI-assisted development. By creating specialized agents with focused responsibilities, you can:
- Parallelize research and analysis
- Maintain clean context separation
- Apply expert reviews consistently
- Automate complex workflows
Start with the built-in Explore subagent to understand the pattern, then create custom subagents for your team's specific needs.
Create your first custom subagent: a code-reviewer in
.claude/agents/code-reviewer.md`. Then try: "Use the code-reviewer subagent to review the last commit."
---