# Subagents Subagents are specialized AI instances that Claude delegates tasks to. Each runs in its own context window with custom system prompt, specific tool access, and independent permissions. ## Key Characteristics - **Isolated context**: Each subagent has its own context window - **Custom system prompt**: Tailored instructions for specific tasks - **Tool restrictions**: Can limit which tools the subagent can use - **Parallel execution**: Multiple subagents can run simultaneously - **Concurrency limit**: ~10 concurrent subagents (additional tasks queue) ## Built-in Subagents | Subagent | Purpose | Model | Tool Access | |----------|---------|-------|-------------| | **Explore** | Read-only codebase searches | Haiku | Read, Grep, Glob | | **Plan** | Research and planning | Sonnet | Full | | **General-purpose** | Full capability tasks | Sonnet | Full | ## Creating Custom Subagents Place subagent definitions in `.claude/agents/`: ```markdown # .claude/agents/security-reviewer.md --- name: security-reviewer description: Security-focused code reviewer. Use for PRs touching auth or sensitive data. tools: Read, Grep, Glob, Bash model: sonnet permissionMode: default --- You are a senior security engineer reviewing code for vulnerabilities. When invoked: 1. Run git diff to identify changed files 2. Focus on authentication, authorization, input validation, and data handling 3. Check for OWASP Top 10 vulnerabilities 4. Report findings with severity ratings ``` ## Subagent Frontmatter | Field | Required | Description | |-------|----------|-------------| | `name` | Yes | Identifier for the subagent | | `description` | Yes | When to use this subagent (triggers delegation) | | `tools` | No | Comma-separated allowlist of tools | | `disallowedTools` | No | Comma-separated denylist | | `model` | No | `haiku`, `sonnet`, or `opus` | | `permissionMode` | No | How permission prompts behave | ## Parallel Subagent Invocation Prompt Claude to delegate to multiple subagents: ```yaml - uses: anthropics/claude-code-action@v1 with: prompt: | Review PR #${{ github.event.pull_request.number }}. Delegate to 3 parallel subagents: 1. **Security Agent**: OWASP Top 10, input validation, auth checks 2. **Performance Agent**: N+1 queries, memory leaks, blocking calls, bundle size 3. **Style Agent**: Naming conventions, documentation, test coverage Focus ONLY on changed files: git diff --name-only origin/main...HEAD After all complete: - Consolidate findings by severity (Critical/High/Medium/Low) - Post inline comments on specific lines - Provide summary with approval recommendation ``` ## Explicit Parallel Tasks Request specific number of parallel agents: ```yaml prompt: | Explore this codebase using 4 parallel tasks. Each subagent should: - Agent 1: Analyze src/api/ for endpoint patterns - Agent 2: Analyze src/auth/ for security issues - Agent 3: Analyze tests/ for coverage gaps - Agent 4: Analyze docs/ for outdated content ``` ## Critical Limitation: MCP Tools **MCP tools are NOT available in background subagents.** If your workflow relies on MCP servers (GitHub, Jira, Linear, etc.), run those operations in the foreground: ```yaml prompt: | **CRITICAL: Keep all MCP operations in the foreground. Do NOT delegate to subagents.** For issues labeled 'jira-linked': - Fetch acceptance criteria from the linked Jira ticket - Comment the criteria on the GitHub issue ``` ## Security Reviewer Example ```markdown # .claude/agents/security-reviewer.md --- name: security-reviewer description: Security-focused reviewer for auth, tokens, and sensitive data tools: Read, Grep, Glob, Bash model: sonnet permissionMode: default --- You are a senior security engineer. When invoked: 1. Run `git diff --name-only origin/main...HEAD` to identify changed files 2. For each file, check for: - SQL injection (raw queries, string concatenation) - XSS vulnerabilities (unescaped output, innerHTML) - Authentication/authorization bypasses - Hardcoded secrets or credentials - Insecure deserialization - Missing input validation - SSRF vectors 3. Rate findings: CRITICAL | HIGH | MEDIUM | LOW 4. Include specific line numbers and remediation advice ``` ## Performance Reviewer Example ```markdown # .claude/agents/performance-reviewer.md --- name: performance-reviewer description: Performance-focused reviewer for database queries, memory, and bundle size tools: Read, Grep, Glob, Bash model: sonnet --- You are a performance engineer. When invoked: 1. Identify changed files with `git diff --name-only origin/main...HEAD` 2. Check for: - N+1 query patterns - Missing database indexes - Memory leaks (unclosed resources, growing collections) - Blocking I/O in async contexts - Bundle size impacts (large imports, missing tree shaking) - Unnecessary re-renders (React) 3. Provide specific recommendations with line numbers ``` ## Documentation Reviewer Example ```markdown # .claude/agents/docs-reviewer.md --- name: docs-reviewer description: Documentation reviewer for API docs, comments, and README accuracy tools: Read, Grep, Glob model: haiku --- You are a technical writer. When invoked: 1. Check documentation accuracy against code changes 2. Verify: - JSDoc/TSDoc comments match function signatures - README examples are runnable - API documentation reflects current endpoints - Changelog is updated for significant changes 3. Suggest specific documentation updates ``` ## Subagent Coordination Patterns ### Wolf Pack Pattern Multiple specialized reviewers attacking a PR from different angles: ```yaml prompt: | Deploy the wolf pack review pattern: - Security wolf: Hunt for vulnerabilities - Performance wolf: Track down bottlenecks - Quality wolf: Enforce code standards Each wolf reports findings independently. Consolidate into unified review with severity rankings. ``` ### Exploration Pattern Fan out to explore large codebases: ```yaml prompt: | Explore this monorepo to understand the architecture. Use 4 parallel explorers: - Explorer 1: Map the frontend packages - Explorer 2: Map the backend services - Explorer 3: Map the shared libraries - Explorer 4: Map the infrastructure code Synthesize findings into architecture diagram. ``` ### Divide and Conquer Pattern Split large implementation tasks: ```yaml prompt: | Implement this feature using divide and conquer: - Agent 1: Implement the API layer - Agent 2: Implement the database layer - Agent 3: Implement the frontend components - Agent 4: Write integration tests Coordinate to ensure interfaces match. ```