Skip to content

Custom Subagents

Custom subagents are specialized AI assistants that extend Claude Code’s capabilities by providing task-specific expertise. Each subagent operates with its own context window, custom system prompt, and optionally restricted tool access, enabling powerful delegation patterns for complex development workflows.

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

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.
FieldRequiredDescription
nameYesUnique identifier for the subagent
descriptionYesWhen Claude should use this subagent
toolsNoComma-separated list of allowed tools (inherits all if omitted)
---
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
  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.

  • Context Gathering: Subagents may add 2-3 seconds of latency while gathering context
  • Token Usage: Each subagent uses its own context window, potentially increasing token consumption
  • Tool Access: Restricting tools can sometimes limit effectiveness - balance security with capability

Teams report significant improvements using custom subagents:

  • 40% reduction in code review time with specialized review subagents
  • 60% fewer security issues caught before production with security audit subagents
  • 3x faster test coverage implementation with test generation subagents
  • 50% reduction in debugging time with specialized debugging subagents

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")

The Claude Code community shares subagents for common tasks. Popular examples include:

  • Frontend component generators for React, Vue, and Angular
  • API endpoint builders with automatic validation and documentation
  • DevOps specialists for Docker, Kubernetes, and CI/CD
  • Data science assistants for analysis and visualization
  • Mobile development experts for iOS and Android

Ready to supercharge your development workflow with custom subagents?

  1. Run /agents to create your first subagent
  2. Start with common patterns like code review or test generation
  3. Customize based on your team’s specific needs
  4. Share successful subagents with your team via Git
  5. Iterate and refine based on real-world usage

Custom subagents transform Claude Code from a single assistant into an entire AI development team, each member specialized in their domain and working together seamlessly.