Menü schliessen
Created: November 25th 2025
Last updated: November 25th 2025
Categories: Artificial intelligence (AI),  IT Knowledge
Author: Aleksandar Pantic

Claude Code Subagents Guide - Build Specialized AI Teams

Tags:  Claude Code

Mastering Claude Code Subagents — Building Specialized AI Teams for Complex Development Tasks

When working with Claude Code, you quickly realize that having a single AI assistant handle everything from architecture planning to bug fixes can become overwhelming. This is where subagents come in — specialized AI assistants that operate independently with their own context windows, tool permissions, and system prompts. Think of subagents as building your own AI development team where each member has specific expertise and responsibilities. This guide explores the architecture, configuration patterns, and advanced techniques for creating powerful subagent workflows that aren't immediately obvious from basic documentation.

What Are Subagents and Why Do They Matter?

Subagents are specialized instances of Claude that can be invoked to handle specific types of tasks. Each subagent operates in its own isolated context window, which provides several critical advantages:

  • Context isolation — Each subagent maintains a separate conversation history, preventing context pollution in your main chat
  • Specialized expertise — Custom system prompts make subagents experts in narrow domains (security audits, database design, API documentation)
  • Tool restrictions — Limit which operations each subagent can perform for security and focus
  • Parallel workflows — Different subagents can handle different aspects of a complex task
  • Reusability — Share battle-tested subagents across projects and teams

Subagent Architecture: How They Actually Work

The Delegation Model

When you're working in Claude Code, the main agent can delegate tasks to subagents in two ways:

  • Automatic delegation — Claude analyzes your request and automatically invokes the appropriate subagent based on the task description and subagent's defined purpose
  • Explicit invocation — You directly request a specific subagent: "Use the security-auditor subagent to review the authentication module"

Context Window Separation

One of the most powerful aspects of subagents is that each operates in its own context window. This means:

Main Agent Context:
- High-level task coordination
- Project overview
- Previous conversations

Subagent Context (Security Auditor):
- Only security-related analysis
- Code snippets relevant to security
- Security best practices and checklists
- No pollution from unrelated discussions

This separation prevents the main agent's context from being consumed by detailed implementation work, allowing it to maintain strategic oversight while subagents handle tactical execution.

The Plan Subagent: A Special Case

Claude Code includes a special built-in subagent called the Plan subagent that only activates in plan mode. When you enable plan mode and Claude needs to research your codebase before creating a plan, it delegates exploration tasks to the Plan subagent. This prevents infinite nesting (subagents cannot spawn other subagents) while still allowing thorough research before planning.

Creating Your First Subagent

File Structure and Location

Subagents are defined as Markdown files with YAML frontmatter. They can be stored in two locations:

# Project-specific subagents (versioned with your repo)
.claude/agents/*.md

# Global subagents (available across all projects)
~/.claude/agents/*.md

When naming conflicts occur, project-specific subagents take precedence over global ones.

Basic Subagent Template

---
name: database-architect
description: Expert database designer specializing in PostgreSQL. Use PROACTIVELY for schema design, optimization, and migration planning. Invoke when creating or modifying database structures.
tools: Read, Grep, Glob, Bash
model: sonnet
---

You are a senior database architect with deep expertise in PostgreSQL, MySQL, and MongoDB. Your role is to design efficient, scalable database schemas and optimize query performance.

## Your Responsibilities

1. **Schema Design**: Create normalized database schemas with proper relationships, indexes, and constraints
2. **Migration Planning**: Design safe, reversible migrations with rollback strategies
3. **Performance Analysis**: Identify slow queries and recommend optimizations
4. **Data Integrity**: Ensure referential integrity, proper constraints, and validation

## Workflow

When invoked, you should:

1. Read existing schema files and migrations
2. Analyze current database structure
3. Identify potential issues or optimization opportunities
4. Propose specific changes with rationale
5. Generate migration files with both up and down methods

## Guidelines

- Always consider data integrity and referential constraints
- Design for scalability from the start
- Include proper indexing strategies
- Document complex queries and optimization decisions
- Use transactions where appropriate
- Consider backup and recovery implications

## Output Format

Provide your recommendations in this format:
- **Issue/Requirement**: Describe what needs to be addressed
- **Proposed Solution**: Specific schema changes or optimizations
- **Migration Code**: Actual SQL or framework-specific migration code
- **Testing Strategy**: How to verify the changes work correctly
- **Rollback Plan**: How to revert if issues arise

Advanced Configuration Patterns

Tool Permission Strategies

One of the most important aspects of subagent design is determining which tools each agent should have access to. Here are common patterns:

Read-Only Analysts

---
name: code-analyzer
description: Static code analysis specialist. Use for architecture review and code quality assessment without making changes.
tools: Read, Grep, Glob
model: sonnet
---

These subagents can explore your codebase but cannot modify anything, making them perfect for audits, reviews, and analysis tasks.

Research and Documentation Agents

---
name: api-documenter
description: Technical documentation specialist. Use after implementing API endpoints to generate comprehensive API documentation.
tools: Read, Grep, Glob, Write
model: sonnet
---

Can read code and write documentation files, but cannot modify source code or execute commands.

Full-Stack Implementation Agents

---
name: feature-implementer
description: Full-stack developer. Use for implementing complete features based on specifications.
tools: Read, Write, Edit, Bash, Grep, Glob
model: sonnet
---

Has broad permissions for implementing features but should be used with careful oversight.

Test Execution Specialists

---
name: test-runner
description: QA specialist for running and debugging tests. Use when test suites need execution or debugging.
tools: Bash, Read, Grep
model: sonnet
---

Can run tests and read results but cannot modify code, ensuring test integrity.

Model Selection Strategy

You can specify which Claude model each subagent uses:

model: sonnet    # Fast, cost-effective for most tasks
model: opus      # Maximum capability for complex reasoning
model: inherit   # Use whatever model the main agent is using

Strategic model selection tip: Use Opus for subagents that require deep reasoning (architecture planning, complex debugging), Sonnet for straightforward implementation tasks, and Haiku for simple, repetitive tasks like linting or formatting.

Real-World Subagent Workflow Patterns

Pattern 1: Sequential Specialist Chain

For complex features, create a chain of specialized subagents that each handle one phase:

User Request → Main Agent Coordinates

1. product-analyst subagent
   - Analyzes requirements
   - Creates user stories
   - Defines acceptance criteria
   → Outputs: specs/feature.md

2. database-architect subagent
   - Designs schema changes
   - Creates migrations
   → Outputs: migrations/*.sql

3. api-designer subagent
   - Designs REST endpoints
   - Defines request/response schemas
   → Outputs: docs/api-spec.yaml

4. feature-implementer subagent
   - Implements backend code
   - Creates controllers and services
   → Outputs: src/**/*.php

5. test-writer subagent
   - Writes unit and integration tests
   - Creates test fixtures
   → Outputs: tests/**/*Test.php

6. documentation-generator subagent
   - Generates API documentation
   - Updates README
   → Outputs: docs/*.md

Pattern 2: Parallel Review and Implementation

While one subagent implements a feature, another can review existing code:

# Session 1: Implementation
"Use feature-implementer to build the user authentication module"

# Session 2: Parallel review
"Use security-auditor to review the current authentication code for vulnerabilities"

Note: True parallelism requires running multiple Claude Code sessions. Within a single session, subagent tool calls execute sequentially.

Pattern 3: Plan-Then-Execute with Verification

This pattern uses multiple subagents to ensure quality:

# Step 1: Planning (read-only)
"Use the laravel-planner subagent to create a detailed implementation plan for the invoice management feature. Output the plan to /docs/invoice-plan.md"

# Step 2: Implementation
"Use the laravel-implementer subagent to implement /docs/invoice-plan.md. Follow the plan exactly and create all specified files."

# Step 3: Testing
"Use the test-automator subagent to run the test suite and fix any failing tests"

# Step 4: Security Review
"Use the security-auditor subagent to review all changes for security issues"

# Step 5: Code Review
"Use the code-reviewer subagent to check code quality, performance, and maintainability"

WordPress Development Subagent Collection

Here are production-ready subagents specifically designed for WordPress plugin and theme development:

WordPress Plugin Architect

---
name: wp-plugin-architect
description: WordPress plugin architecture specialist. Use when creating or restructuring WordPress plugins with OOP principles and best practices.
tools: Read, Write, Edit, Grep, Glob
model: sonnet
---

You are a senior WordPress plugin architect specializing in object-oriented plugin development.

## Core Responsibilities

1. Design plugin architecture using OOP principles
2. Implement proper namespacing and autoloading
3. Create hook-based systems for extensibility
4. Follow WordPress Coding Standards
5. Ensure backward compatibility

## Plugin Structure

Always structure plugins as:

```
plugin-name/
├── plugin-name.php (main file)
├── includes/
│   ├── class-plugin.php (main plugin class)
│   ├── class-autoloader.php
│   ├── class-activator.php
│   ├── class-deactivator.php
│   └── admin/
│       └── class-admin-menu.php
├── assets/
│   ├── css/
│   └── js/
└── languages/
```

## Guidelines

- Use namespaces: `PluginName\Includes`
- Implement singleton pattern for main plugin class
- Use dependency injection where appropriate
- Prefix all hooks with plugin slug
- Sanitize all inputs, escape all outputs
- Use nonces for form submissions
- Enqueue scripts/styles properly
- Make everything translatable

ACF Field Group Builder

---
name: acf-field-builder
description: Advanced Custom Fields specialist. Use when creating or modifying ACF field groups programmatically.
tools: Read, Write, Edit, Grep
model: sonnet
---

You are an ACF (Advanced Custom Fields) expert specializing in programmatic field group creation.

## Your Expertise

1. Creating field groups using `acf_add_local_field_group()`
2. All ACF field types and their configuration options
3. Conditional logic implementation
4. Location rules (post types, taxonomies, user roles, etc.)
5. Field group organization and naming conventions

## Implementation Pattern

Always use this structure:

```php
namespace YourPlugin\ACF;

class FieldGroups {
    public function __construct() {
        add_action('acf/init', [$this, 'register_field_groups']);
    }
    
    public function register_field_groups() {
        if (!function_exists('acf_add_local_field_group')) {
            return;
        }
        
        $this->register_portfolio_fields();
        $this->register_team_fields();
    }
    
    private function register_portfolio_fields() {
        acf_add_local_field_group([
            'key' => 'group_portfolio',
            'title' => 'Portfolio Details',
            'fields' => [
                // Field definitions
            ],
            'location' => [
                [
                    [
                        'param' => 'post_type',
                        'operator' => '==',
                        'value' => 'portfolio',
                    ],
                ],
            ],
        ]);
    }
}
```

## Best Practices

- Use unique, prefixed key values
- Group related fields logically
- Implement conditional logic for complex forms
- Use repeater and flexible content fields effectively
- Consider field group clone functionality for reusable sets

WordPress Security Auditor

---
name: wp-security-auditor
description: WordPress security specialist. Use PROACTIVELY after any code changes to identify security vulnerabilities specific to WordPress.
tools: Read, Grep, Glob
model: sonnet
---

You are a WordPress security expert focused on identifying vulnerabilities and ensuring best practices.

## Security Checklist

When reviewing code, verify:

### Input Validation
- All `$_GET`, `$_POST`, `$_REQUEST` values are sanitized
- File uploads are validated (type, size, extension)
- User input is escaped before database queries

### Output Escaping
- `esc_html()` for HTML content
- `esc_attr()` for HTML attributes
- `esc_url()` for URLs
- `wp_kses()` for allowed HTML
- `esc_js()` for JavaScript strings

### Nonces
- All forms use `wp_nonce_field()`
- All AJAX requests verify nonces with `check_ajax_referer()`
- All URL-based actions use `wp_create_nonce()` and `wp_verify_nonce()`

### Capabilities
- All admin functionality checks `current_user_can()`
- Custom capabilities are properly registered
- Role checks are appropriate for the action

### SQL Security
- Use `$wpdb->prepare()` for all dynamic queries
- Never concatenate user input into SQL
- Sanitize table/column names if dynamic

### File Operations
- Validate file paths to prevent traversal attacks
- Check file permissions
- Use WordPress filesystem API when possible

### AJAX Security
- Verify nonces
- Check capabilities
- Sanitize all inputs
- Return proper JSON responses

## Critical Vulnerabilities to Flag

1. SQL Injection risks
2. XSS vulnerabilities
3. CSRF vulnerabilities
4. Path traversal attempts
5. Privilege escalation possibilities
6. Exposed sensitive data
7. Insecure direct object references

## Output Format

Provide findings as:

**CRITICAL**: [Description] - [Location]
**WARNING**: [Description] - [Location]
**INFO**: [Description] - [Location]

Include code snippets showing the vulnerability and the recommended fix.

Subagent Management Commands

Claude Code provides interactive commands for managing subagents:

# List all available subagents
/agents

# Create a new subagent interactively
/agents create

# Edit an existing subagent
/agents edit security-auditor

# View a subagent's configuration
/agents show database-architect

# Delete a subagent
/agents delete old-agent

Advanced Techniques and Hidden Features

Proactive Invocation Keywords

Use specific keywords in the description field to control when subagents are automatically invoked:

description: Use PROACTIVELY when database schema changes are needed
description: MUST BE USED for all security-related code reviews
description: Invoke IMMEDIATELY after writing or modifying authentication code

These capitalized directives increase the likelihood that Claude will automatically delegate to the appropriate subagent.

Chaining Subagents with Handoff Rules

Design subagents that explicitly hand off to the next specialist:

---
name: spec-writer
description: Requirements and specification writer. Use first for new features.
tools: Read, Write, Grep, Glob
model: sonnet
---

...your system prompt...

## Handoff Protocol

After completing a specification, always recommend:
"The specification is complete in /docs/spec.md. Next, invoke the database-architect subagent to design the schema based on this spec."

Context Management Strategy

Because subagents start with a clean context, they may need to gather information. Optimize this:

## Context Gathering Strategy

1. First, read /docs/ARCHITECTURE.md for system overview
2. Read relevant existing implementations in src/
3. Check for related tests in tests/
4. Review any existing documentation in docs/
5. Only then begin your analysis/implementation

Using Subagents with MCP Servers

Subagents can leverage Model Context Protocol (MCP) servers for extended capabilities:

---
name: deployment-engineer
description: DevOps and deployment specialist with access to cloud infrastructure
tools: Read, Bash, Grep, GitHub, AWS, Kubernetes
model: sonnet
---

When properly configured with MCP servers, this subagent can interact with GitHub, AWS, and Kubernetes directly.

Common Pitfalls and Solutions

Pitfall 1: Overly Broad Tool Permissions

Problem: Giving all subagents access to all tools defeats the purpose of specialization.

Solution: Follow the principle of least privilege. If a subagent only needs to read code, don't give it Write or Bash permissions.

Pitfall 2: Insufficient Context in System Prompts

Problem: Vague system prompts lead to inconsistent behavior.

Solution: Include specific checklists, output formats, and examples directly in the system prompt.

Pitfall 3: Not Versioning Project Subagents

Problem: Team members have different subagent configurations.

Solution: Store project-specific subagents in `.claude/agents/` and commit them to version control.

Pitfall 4: Forgetting Subagent Context Limitations

Problem: Expecting subagents to remember previous conversations.

Solution: Design subagents to be self-sufficient. Include instructions for gathering necessary context at the start of each invocation.

Performance Optimization

Reducing Latency

Subagents add some latency because they start with a clean context. Minimize this by:

  • Using concise system prompts that get to the point quickly
  • Specifying exactly which files or directories to examine
  • Leveraging the Grep and Glob tools for targeted searches instead of reading entire directories

Token Usage Optimization

  • Use Sonnet for routine tasks instead of Opus
  • Create focused subagents that only need to read specific parts of your codebase
  • Use `model: inherit` for subagents that should match the main agent's model choice

Testing and Iterating on Subagents

The Refinement Process

# 1. Create initial subagent
/agents create

# 2. Test it on a real task
"Use the new-subagent to analyze the authentication module"

# 3. Review the results - was the output what you expected?

# 4. Edit and refine
/agents edit new-subagent

# 5. Have Claude help improve it
"Analyze the new-subagent configuration in .claude/agents/new-subagent.md and suggest improvements based on how it performed"

# 6. Test again with the same task
"Use the updated new-subagent to analyze the authentication module again"

Benchmarking Subagent Performance

Create a standard set of tasks for each subagent type and track:

  • Time to complete
  • Quality of output
  • Whether it needed to ask clarifying questions
  • Token usage
  • Whether it invoked itself appropriately (for automatic delegation)

Community Subagent Resources

Several community repositories have emerged with production-ready subagents:

  • VoltAgent/awesome-claude-code-subagents — 100+ specialized subagents organized by domain (frontend, backend, DevOps, data science)
  • wshobson/agents — 85 agents across 63 plugins with multi-agent orchestration patterns
  • valllabh/claude-agents — Enhanced agents with interactive workflows and template-driven outputs

These repositories demonstrate advanced patterns and can serve as starting points for your own custom subagents.

The Future of Subagent Development

The subagent ecosystem is rapidly evolving. Emerging patterns include:

  • Agent Skills — Modular knowledge packages that extend subagent capabilities with progressive disclosure
  • Hooks and Events — Subagents that trigger on specific events (SubagentStart, SubagentStop) for workflow automation
  • Multi-agent orchestration — Coordinator subagents that manage workflows across 7+ specialized subagents
  • Shared agent marketplaces — Community platforms for discovering and sharing battle-tested subagents

Quick Reference: Subagent Configuration

# Minimal subagent
---
name: agent-name
description: When to use this agent
tools: Read, Grep, Glob
---
System prompt goes here.

# Full configuration options
---
name: agent-name                    # Unique identifier
description: Detailed description   # When to invoke (supports PROACTIVELY, MUST BE USED keywords)
tools: Read, Write, Edit, Bash, Grep, Glob, WebFetch, WebSearch  # Specific tools or omit for all
model: sonnet | opus | haiku | inherit  # Which model to use
---

# Your detailed system prompt
# - Define role and expertise
# - List responsibilities
# - Specify workflow and output format
# - Include checklists and guidelines
# - Provide examples

Conclusion

Subagents transform Claude Code from a single AI assistant into an entire specialized development team. By understanding their architecture, properly configuring tool permissions, writing effective system prompts, and implementing workflow patterns like sequential chains and plan-then-execute strategies, you can build reliable, reproducible development pipelines. The key to mastering subagents lies in treating them as domain experts with narrow, well-defined responsibilities rather than general-purpose assistants. Start with a few focused subagents for your most common tasks, refine them through real-world usage, version control them alongside your code, and gradually build a collection of battle-tested specialists that accelerate every aspect of your development workflow.

Additional Resources

To see how we automate complete parts of reviewing and fixing code with the help of claude agents, check out this blog post.