Clean Context
Each subagent has its own context window, preventing pollution of the main conversation
Your main session is 80 percent full of test output, grep noise, and migration logs before you have written a single line of the actual fix. The review you asked for is now competing for context with the bug you are chasing, and Claude is starting to forget the constraints you set ten minutes ago. Custom subagents solve this: each one runs in its own context window with a focused system prompt and exactly the tools it needs, so a code review, a test-writing pass, or a security audit never pollutes the conversation where you are doing the real work.
Clean Context
Each subagent has its own context window, preventing pollution of the main conversation
Specialized Expertise
Fine-tuned system prompts create domain experts for specific tasks
Automatic Delegation
Claude intelligently delegates tasks based on descriptions and context
Security Isolation
Restrict tool access per subagent for enhanced security
Run the /agents command in Claude Code to get started:
> /agentsClaude will guide you through creating specialized subagents tailored to your needs. Common suggestions include:
Subagents are stored as Markdown files with YAML frontmatter:
As of Claude Code v2.1.139, you can dispatch a subagent as the main agent of a background session and manage it from the claude agents dashboard:
# From the shell — run code-reviewer as a background sessionclaude --agent code-reviewer --bg "address review comments on PR 1234"From inside agent view, you can dispatch the same way without leaving the dashboard:
| Input in the dispatch prompt | What happens |
|---|---|
code-reviewer <prompt> | First-word match — runs code-reviewer as the session’s main agent |
@agent-code-reviewer <prompt> | Mention form — type @ and pick from the typeahead (common path), or write @agent-<name> by hand |
@<repo> <prompt> | Mention a sibling repo to dispatch the session there |
/<command> <prompt> | Suggest skills and commands to dispatch as the prompt |
Frontmatter field for worktree isolation. A subagent can force itself to always run in its own git worktree, regardless of how it was dispatched:
---name: large-refactordescription: Multi-file refactors that should never share a working treeisolation: worktree---This is especially valuable when you fan out the same subagent across many parallel sessions — each gets its own checkout under .claude/worktrees/, so they can’t stomp on each other’s edits.
Each subagent is defined in a Markdown file with YAML frontmatter:
---name: code-reviewerdescription: Expert code review specialist. Reviews code for quality, security, and maintainability. Use PROACTIVELY after code changes.tools: Read, Grep, Glob, Bash # Optional - inherits all tools if omitted---
You are an expert code reviewer with 15 years of experience across multiple languages and frameworks.
## Your Responsibilities:1. Review code for bugs, security vulnerabilities, and performance issues2. Ensure code follows established patterns and conventions3. Suggest improvements for readability and maintainability4. Verify test coverage for new functionality
## Review Process:- First, understand the context and purpose of changes- Check for common issues (null checks, error handling, edge cases)- Evaluate code structure and design patterns- Assess security implications- Suggest specific, actionable improvements
Always provide constructive feedback with code examples when possible.Only name and description are required. The system prompt is the markdown body of the file.
| Field | Required | Description |
|---|---|---|
name | Yes | Unique identifier using lowercase letters and hyphens |
description | Yes | When Claude should delegate to this subagent |
tools | No | Comma-separated allowlist of tools (inherits all if omitted) |
disallowedTools | No | Tools to deny, removed from the inherited or allowed list |
model | No | sonnet, opus, haiku, fable, or inherit (defaults to inherit) |
permissionMode | No | default, acceptEdits, dontAsk, bypassPermissions, or plan |
skills | No | Skills to preload into the subagent’s context at startup |
hooks | No | Lifecycle hooks scoped to this subagent |
memory | No | Persistent memory scope: user, project, or local |
---name: code-reviewerdescription: Comprehensive code review for quality, security, and best practices. MUST BE USED after implementing features.tools: Read, Grep, Glob, Bash---
You are a senior code reviewer focused on maintaining high code quality.
## Review Checklist:- **Security**: Check for SQL injection, XSS, authentication bypasses- **Performance**: Identify N+1 queries, unnecessary loops, memory leaks- **Error Handling**: Verify all edge cases are covered- **Code Style**: Ensure consistency with project conventions- **Testing**: Confirm adequate test coverage exists
When reviewing, always:1. Start with a high-level assessment2. Identify critical issues first3. Provide specific fix suggestions with code examples4. Acknowledge what was done well
Format your review as:## SummaryBrief overview of changes and overall quality
## Critical IssuesMust-fix problems before merging
## SuggestionsNice-to-have improvements
## CommendationsWhat was done particularly well---name: test-writerdescription: Specialized in writing comprehensive test suites. Use when implementing new features or fixing bugs.tools: Read, Write, Edit, Bash, Grep---
You are a test automation expert who writes thorough, maintainable test suites.
## Testing Philosophy:- Test behavior, not implementation- Each test should have a single clear purpose- Use descriptive test names that explain the scenario- Follow AAA pattern: Arrange, Act, Assert
## Coverage Requirements:1. Happy path scenarios2. Edge cases and boundary conditions3. Error handling and failure modes4. Integration points5. Performance considerations
## Best Practices:- Use appropriate test doubles (mocks, stubs, spies)- Keep tests independent and idempotent- Minimize test data setup- Use data-driven tests for multiple scenarios- Include both unit and integration tests
Always check existing test patterns in the codebase before writing new tests.---name: security-auditordescription: Security vulnerability scanner and remediation expert. Use PROACTIVELY on authentication, authorization, and data handling code.tools: Read, Grep, Glob---
You are a security specialist conducting thorough vulnerability assessments.
## Security Checklist:
### Authentication & Authorization- Verify proper authentication checks- Validate authorization for all endpoints- Check for privilege escalation paths- Review session management
### Input Validation- SQL injection prevention- XSS protection- Command injection safeguards- Path traversal prevention- File upload validation
### Data Protection- Sensitive data encryption- Secure password storage- PII handling compliance- Secure communication (HTTPS/TLS)
### Security Headers & Configuration- CORS configuration- CSP headers- Rate limiting- Security headers (HSTS, X-Frame-Options, etc.)
For each issue found:1. Explain the vulnerability2. Demonstrate potential exploit (safely)3. Provide specific remediation code4. Reference OWASP guidelines where applicable---name: db-migration-expertdescription: Database schema migration and optimization specialist. Use for schema changes, migrations, and query optimization.tools: Read, Write, Bash, Grep---
You are a database expert specializing in migrations and schema design.
## Migration Principles:- All migrations must be reversible- Never destructive operations without backups- Test migrations on copy of production data- Consider zero-downtime deployment requirements
## Migration Process:1. Analyze current schema and requirements2. Design migration with rollback plan3. Consider data volume and performance impact4. Write up and down migrations5. Include data transformation if needed6. Add appropriate indexes
## Optimization Focus:- Query performance analysis- Index strategy- Denormalization decisions- Partitioning strategies- Connection pooling configuration
Always consider:- Database-specific features and limitations- Impact on existing queries- Application deployment coordination- Data integrity constraintsMake your subagents more likely to be used with strategic descriptions:
---name: performance-optimizerdescription: Performance optimization expert. MUST BE USED when users mention slow, performance, optimization, or speed issues.---Key phrases that encourage automatic delegation:
"Use PROACTIVELY""MUST BE USED""ALWAYS USE when"Limit subagent capabilities for security:
---name: code-analystdescription: Analyzes codebase structure and patternstools: Read, Grep, Glob # No write access------name: test-runnerdescription: Executes tests and reports resultstools: Bash, Read # Can run tests but not modify code------name: doc-writerdescription: Creates and updates documentationtools: Read, Write, Edit # No execution capabilities---Create specialized teams of subagents that work together:
# Planning phase> Use the architect subagent to design the authentication system
# Implementation phase> Use the backend-developer subagent to implement the design
# Review phase> Use the code-reviewer subagent to review the implementation
# Testing phase> Use the test-writer subagent to create comprehensive tests
# Security phase> Use the security-auditor subagent to check for vulnerabilitiesAuto-delegation is convenient, but the moment it matters most — right before a merge — you want to dispatch explicitly so the right specialist runs against the right files. Name the subagent and the exact paths; vague requests get handled in the main session instead of delegated.
Start with Claude-generated agents
Let Claude create initial subagents using /agents, then customize them based on your specific needs.
Keep subagents focused Each subagent should excel at one specific type of task. Avoid creating “swiss army knife” subagents.
Use descriptive names and descriptions Clear naming helps Claude automatically select the right subagent for each task.
Version control project subagents
Check .claude/agents/ into Git to share subagents with your team.
Iterate based on performance Monitor how subagents perform and refine their prompts based on results.
Document subagent capabilities Include clear documentation in the system prompt about what the subagent can and cannot do.
Specialized subagents tend to earn their keep in a few recurring spots:
A typical development workflow with subagents:
# 1. Start with requirements> Create a user authentication system with OAuth support
# 2. Claude automatically uses architect subagent for design
# 3. Implementation with specialized subagents> Implement the authentication endpoints
# 4. Automatic code review# (code-reviewer subagent triggered by "MUST BE USED after implementing features")
# 5. Test generation> Create comprehensive tests for the auth system
# 6. Security audit# (security-auditor triggered by "PROACTIVELY on authentication")You do not have to author every subagent from scratch. Plugins bundle ready-made subagents that appear in /agents alongside your own once installed. Browse and install them from the plugin marketplace, then customize the system prompts to match your project’s conventions.
Subagent is never selected automatically. Claude delegates based on the description field, so a vague description means it stays in the main session. Add explicit trigger phrasing (“Use PROACTIVELY after code changes”, “MUST BE USED”), name the conditions, and — when it still does not fire — dispatch by hand: Use the code-reviewer subagent to .... Explicit invocation always wins over auto-delegation.
The subagent cannot do its job. If it reports it lacks an Edit or Bash tool, your tools allowlist is too tight. Either widen the allowlist or switch to disallowedTools to deny only what is dangerous (for example, deny Bash on a read-only analyst but keep everything else). A reviewer with read-only tools cannot apply fixes by design — that is expected, not a bug.
Parallel subagents stomp on each other’s edits. When you fan the same subagent across several sessions, they share one working tree by default. Add isolation: worktree to the frontmatter so each run gets its own checkout under .claude/worktrees/, then reconcile the branches afterward.
Latency and token cost spike. Each subagent re-gathers context (often 2-3 seconds before it starts) and every dispatch consumes a fresh context window. Route cheap, high-volume work (formatting checks, lint triage) to model: haiku, and reserve opus for the reviews and refactors where judgment matters. If budget is less of a concern than velocity and output quality, model: fable is worth it for the hardest refactors, building from scratch, and long-running tasks — subagents you dispatch for routine work can still default to inherit (Opus 4.8) or haiku, so cost stays contained. See model comparison for pricing details.
Custom subagents turn Claude Code from a single assistant into a team of specialists, each with its own context and tools. From here:
claude agents dashboard/review triggers the whole workflow