Skip to content

Claude Code Complete Guide

Claude Code Subagent Feature Practical Hands-On Guide [2025 Edition]

Introduction

In our previous article, we provided an overview of the Claude Code subagent feature. In this article, we will explain concrete methods to improve code quality and analysis accuracy using the subagent feature in a practical hands-on format.

Important Note: The subagent feature is not true parallel processing, but a quality improvement tool through structured multi-perspective analysis. Experience the true value of this feature through concrete examples usable in real projects.

Basic Usage

1. Check Available Subagents

# Check available subagents
/agents

This command allows you to view a list of currently available subagents and their respective areas of expertise.

2. Automatic Subagent Delegation

Claude Code automatically delegates work to subagents in appropriate situations.

# Example of automatic delegation for security review
"review my recent code changes for security issues"

# Example of automatic delegation for performance analysis
"analyze performance bottlenecks in my React application"

# Example of automatic delegation for test coverage check
"verify test coverage and suggest improvements"

3. Explicit Subagent Specification

You can explicitly specify a particular subagent to request work.

# Subagent specification using Task tool
Task(
    description="API design review",
    prompt="Review the RESTful API design and generate OpenAPI specifications",
    subagent_type="api-designer"
)

Practical Example 1: Web Application Quality Improvement

Scenario

Execute quality improvements for an e-commerce site simultaneously from multiple perspectives.

Implementation Example

# Parallel quality improvement using multiple specialized agents
"I need to improve my e-commerce website quality. Please use multiple subagents to analyze:
- Security vulnerabilities and best practices
- Performance optimization opportunities  
- Accessibility compliance
- Mobile responsiveness
- SEO optimization"

Expected Processing Flow

graph TD
    A[Main Agent] --> B[Security Audit Agent]
    A --> C[Performance Optimization Agent] 
    A --> D[Accessibility Specialist Agent]
    A --> E[Mobile Responsiveness Agent]
    A --> F[SEO Specialist Agent]

    B --> G[Integrated Report Generation]
    C --> G
    D --> G  
    E --> G
    F --> G

    G --> H[Prioritized Improvement Plan]

Output Examples from Each Agent

Security Audit Agent:

## Security Audit Results
- XSS Vulnerability: Unsanitized input detected at login.js:42
- CSRF Protection: CSRF token not implemented for API endpoints
- Recommendation: Configure Content Security Policy

Performance Optimization Agent:

## Performance Analysis Results
- Image Optimization: Uncompressed images increase load time by 3.2 seconds
- Bundle Size: Unnecessary dependencies add 450KB
- Recommendations: Implement lazy loading, apply code splitting

Practical Example 2: Creating Custom Subagents

Defining Project-Specific Agents

You can create custom agents in the .claude/agents/ directory and share them across your team.

# .claude/agents/vue-specialist.yml
name: "vue-specialist"
description: "Vue.js Specialist Agent"
when_to_use: "When creating, optimizing, or debugging Vue.js components"
tools:
  - file_operations
  - code_analysis  
  - test_runner
system_prompt: |
  You are a Vue.js specialist agent. Please specialize in the following areas:
  - Vue 3 Composition API best practices
  - TypeScript integration
  - Performance optimization
  - Testable design
  - Accessibility compliance

Custom Agent Usage Example

# Component improvement using Vue.js specialist agent
Task(
    description="Vue component optimization",
    prompt="""
    Please improve the following Vue component:
    - Performance optimization
    - Improve TypeScript type safety
    - Accessibility compliance
    - Improve test coverage
    """,
    subagent_type="vue-specialist"
)

Practical Example 3: Large-Scale Refactoring Project

Scenario

Execute gradual modernization of a legacy codebase.

Strategic Approach

# Phase 1: Current State Analysis
"Analyze this legacy codebase and create a modernization roadmap using multiple specialized agents"

# Phase 2: Parallel Refactoring
"Execute modernization plan with parallel refactoring across different modules"

# Phase 3: Quality Assurance
"Verify refactoring results with comprehensive testing and validation"

Specific Agent Allocation

# Agent configuration for analysis phase
modernization_agents = [
    {
        "type": "architecture-analyzer",
        "focus": "Dependency analysis and tech stack evaluation",
        "deliverable": "Architecture improvement proposal"
    },
    {
        "type": "code-quality-auditor", 
        "focus": "Code quality metrics measurement",
        "deliverable": "Quality improvement roadmap"
    },
    {
        "type": "security-assessor",
        "focus": "Security vulnerability assessment", 
        "deliverable": "Security enhancement plan"
    },
    {
        "type": "performance-profiler",
        "focus": "Performance bottleneck identification",
        "deliverable": "Optimization priority list"
    }
]

Execution Flow Optimization

# Efficient parallel execution using BatchTool
batch_tasks = [
    "Refactor authentication module with modern security patterns",
    "Modernize database layer with ORM best practices", 
    "Update frontend components with accessibility standards",
    "Implement comprehensive test suite with high coverage"
]

# Parallel execution configuration
parallelism_level = 4  # Execute 4 tasks simultaneously
queue_management = "auto"  # Automatic queuing

Advanced Utilization Techniques

1. Boomerang Orchestration

An advanced pattern where independent tasks are executed in parallel and results are integrated centrally.

# Multi-perspective API design validation
api_analysis_tasks = [
    Task(subagent_type="api-designer", focus="RESTful design principles"),
    Task(subagent_type="security-expert", focus="Security perspective"), 
    Task(subagent_type="performance-analyst", focus="Performance perspective"),
    Task(subagent_type="documentation-writer", focus="Developer experience")
]

# Result integration and decision making
consolidated_result = orchestrator.merge_and_decide(api_analysis_tasks)

2. Integration with Extended Thinking Mode

# Planning with extended thinking mode
thinking_phase = """
<thinking>
This task is complex and requires analysis from the following perspectives:
1. Database design validity
2. API performance characteristics  
3. Frontend integration complexity
4. Security requirement compliance

Delegate to each specialized agent and derive the optimal solution by integrating results.
</thinking>
"""

# Strategic agent deployment
strategic_deployment = plan_subagent_allocation(thinking_phase)

3. Dynamic Agent Allocation

Dynamically determine the optimal agent configuration based on task complexity.

def determine_agent_strategy(task_complexity, available_resources):
    if task_complexity == "high":
        return {
            "lead_agent": "claude-opus-4",
            "subagents": ["claude-sonnet-4"] * 5,
            "parallelism": 5,
            "strategy": "deep_analysis"
        }
    elif task_complexity == "medium":
        return {
            "lead_agent": "claude-sonnet-4", 
            "subagents": ["claude-sonnet-4"] * 3,
            "parallelism": 3,
            "strategy": "balanced_approach"
        }
    else:
        return {
            "lead_agent": "claude-sonnet-4",
            "subagents": [],
            "parallelism": 1,
            "strategy": "single_agent"
        }

Performance Optimization Best Practices

1. Setting Appropriate Parallelism

# Optimization based on project scale
project_scale_config = {
    "small": {"max_parallel": 3, "queue_size": 10},
    "medium": {"max_parallel": 5, "queue_size": 25}, 
    "large": {"max_parallel": 8, "queue_size": 50},
    "enterprise": {"max_parallel": 10, "queue_size": 100}
}

2. Improving Context Efficiency

# Provide minimal context to each agent
def optimize_context_distribution(main_context, agent_roles):
    optimized_contexts = {}
    for role in agent_roles:
        # Extract only role-relevant information
        relevant_context = extract_relevant_info(main_context, role)
        optimized_contexts[role] = relevant_context
    return optimized_contexts

3. Error Handling and Recovery

# Robust error handling
class SubagentOrchestrator:
    def handle_agent_failure(self, failed_agent, task):
        # Redistribute failed agent's task to other agents
        backup_agents = self.get_backup_agents(failed_agent.type)
        return self.redistribute_task(task, backup_agents)

    def monitor_agent_health(self):
        # Monitor agent health
        for agent in self.active_agents:
            if agent.response_time > threshold:
                self.scale_up_agents(agent.type)

Integration into Actual Development Workflows

1. GitHub Actions Integration

# .github/workflows/claude-code-review.yml
name: Claude Code Multi-Agent Review
on:
  pull_request:
    types: [opened, synchronize]

jobs:
  multi-agent-review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Multi-Agent Code Review
        run: |
          claude-code review \
            --use-subagents \
            --agents "security,performance,accessibility" \
            --output-format "github-comment" \
            ${{ github.event.pull_request.diff_url }}

2. VS Code Integration

// .vscode/settings.json
{
  "claude-code.subagents.enabled": true,
  "claude-code.subagents.autoDelegate": true,
  "claude-code.subagents.preferredAgents": [
    "code-reviewer",
    "test-generator", 
    "documentation-writer"
  ],
  "claude-code.subagents.parallelism": 3
}

3. Project Configuration File

// .claude/config.json
{
  "subagents": {
    "enabled": true,
    "auto_delegation": true,
    "custom_agents_path": ".claude/agents/",
    "default_parallelism": 3,
    "max_parallelism": 8,
    "performance_mode": "balanced",
    "context_optimization": true
  },
  "project_agents": [
    {
      "name": "project-architect",
      "triggers": ["architecture", "design", "structure"],
      "specialization": "system_design"
    },
    {
      "name": "quality-guardian", 
      "triggers": ["test", "quality", "coverage"],
      "specialization": "quality_assurance"
    }
  ]
}

Troubleshooting

Common Issues and Solutions

1. Conflicts Between Agents

# Problem: Multiple agents editing the same file simultaneously
# Solution: Utilize file locking feature
claude-code config set subagents.file_locking true

2. Increased Memory Usage

# Problem: Memory shortage due to large number of subagents
# Solution: Configure dynamic scaling
claude-code config set subagents.dynamic_scaling true
claude-code config set subagents.memory_limit "4GB"

3. Handling API Limitations

# Execution control considering rate limits
class RateLimiter:
    def __init__(self, max_requests_per_minute=60):
        self.max_requests = max_requests_per_minute
        self.request_times = []

    def can_execute(self):
        now = time.time()
        self.request_times = [t for t in self.request_times if now - t < 60]
        return len(self.request_times) < self.max_requests

Conclusion

The Claude Code subagent feature is a powerful tool that fundamentally transforms the development process. By utilizing the practical techniques introduced in this article, you can achieve:

  • 90% improvement in development efficiency: Dramatic speed improvement through parallel processing
  • Quality improvement: Deep analysis by specialized agents
  • Consistency assurance: Quality management with standardized processes
  • Scalability: Flexible response according to project scale

The important thing is to design an appropriate agent configuration suited to your project characteristics and continuously optimize it.

Let's realize next-generation development experience by utilizing the subagent feature!


Tags

ClaudeCode #Subagent #HandsOn #PracticalGuide #DevelopmentEfficiency #ParallelProcessing #MultiAgent #Claude4