Skip to content

Custom Subagents

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.

  • A working code-reviewer, test-writer, and security-auditor subagent you can drop into any repo
  • The exact frontmatter fields that control a subagent’s model, tools, and isolation
  • Copy-paste prompts for dispatching subagents explicitly when auto-delegation does not fire
  • A recovery playbook for the failure modes that actually bite in practice

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:

Terminal window
> /agents

Claude will guide you through creating specialized subagents tailored to your needs. Common suggestions include:

  • Code Reviewer
  • Test Writer
  • Security Auditor
  • Documentation Generator
  • Performance Optimizer

Subagents are stored as Markdown files with YAML frontmatter:

  • Directory.claude/
    • Directoryagents/ # Project-specific subagents
      • code-reviewer.md
      • test-writer.md
      • security-auditor.md
  • Directory~/.claude/
    • Directoryagents/ # User-level subagents (all projects)
      • debugger.md
      • refactoring-expert.md

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:

Terminal window
# From the shell — run code-reviewer as a background session
claude --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 promptWhat 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-refactor
description: Multi-file refactors that should never share a working tree
isolation: 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-reviewer
description: 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 issues
2. Ensure code follows established patterns and conventions
3. Suggest improvements for readability and maintainability
4. 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.

FieldRequiredDescription
nameYesUnique identifier using lowercase letters and hyphens
descriptionYesWhen Claude should delegate to this subagent
toolsNoComma-separated allowlist of tools (inherits all if omitted)
disallowedToolsNoTools to deny, removed from the inherited or allowed list
modelNosonnet, opus, haiku, fable, or inherit (defaults to inherit)
permissionModeNodefault, acceptEdits, dontAsk, bypassPermissions, or plan
skillsNoSkills to preload into the subagent’s context at startup
hooksNoLifecycle hooks scoped to this subagent
memoryNoPersistent memory scope: user, project, or local
---
name: code-reviewer
description: 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 assessment
2. Identify critical issues first
3. Provide specific fix suggestions with code examples
4. Acknowledge what was done well
Format your review as:
## Summary
Brief overview of changes and overall quality
## Critical Issues
Must-fix problems before merging
## Suggestions
Nice-to-have improvements
## Commendations
What was done particularly well
---
name: test-writer
description: 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 scenarios
2. Edge cases and boundary conditions
3. Error handling and failure modes
4. Integration points
5. 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-auditor
description: 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 vulnerability
2. Demonstrate potential exploit (safely)
3. Provide specific remediation code
4. Reference OWASP guidelines where applicable
---
name: db-migration-expert
description: 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 requirements
2. Design migration with rollback plan
3. Consider data volume and performance impact
4. Write up and down migrations
5. Include data transformation if needed
6. 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 constraints

Make your subagents more likely to be used with strategic descriptions:

---
name: performance-optimizer
description: 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"
  • Specific trigger words in the description

Limit subagent capabilities for security:

---
name: code-analyst
description: Analyzes codebase structure and patterns
tools: Read, Grep, Glob # No write access
---

Create specialized teams of subagents that work together:

Terminal window
# 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 vulnerabilities

Auto-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.

  1. Start with Claude-generated agents Let Claude create initial subagents using /agents, then customize them based on your specific needs.

  2. Keep subagents focused Each subagent should excel at one specific type of task. Avoid creating “swiss army knife” subagents.

  3. Use descriptive names and descriptions Clear naming helps Claude automatically select the right subagent for each task.

  4. Version control project subagents Check .claude/agents/ into Git to share subagents with your team.

  5. Iterate based on performance Monitor how subagents perform and refine their prompts based on results.

  6. 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 dedicated review subagent that runs before every merge, so a fresh context checks the diff for exposed secrets and unparameterized SQL instead of the session that just wrote the code.
  • A security-auditor wired to authentication and data-handling paths via “Use PROACTIVELY”, catching authorization gaps that a general review skims past.
  • A test-writer that reads existing test conventions first, so new suites match the project’s framework and assertion style rather than inventing their own.

A typical development workflow with subagents:

Terminal window
# 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:

  • Agent View — run subagents as background sessions and manage them from the claude agents dashboard
  • Creating Custom Commands — pair subagents with slash commands so a single /review triggers the whole workflow
  • Hooks and Automation — fire subagents automatically on lifecycle events instead of waiting for delegation