Claude Code Sub-Agents Best Practices
What Are Subagents?
Subagents are specialized AI assistants that run in their own context window with a custom system prompt, specific tool access, and independent permissions. When Claude encounters a matching task, it delegates to the subagent, which works independently and returns results.
[!IMPORTANT] Subagents cannot spawn other subagents. If you need nested delegation, chain subagents from the main conversation or use Skills instead. For parallel agents that communicate with each other, use Agent Teams instead.
Why Use Subagents?
| Benefit | Description |
|---|---|
| Preserve context | Keep exploration/investigation out of your main conversation |
| Enforce constraints | Limit which tools a subagent can use |
| Reuse configs | User-level subagents work across all projects |
| Specialize behavior | Focused system prompts for specific domains |
| Control costs | Route tasks to cheaper models like Haiku |
Built-In Subagents
Claude Code includes these built-in subagents:
| Agent | Model | Tools | Purpose |
|---|---|---|---|
| Explore | Haiku (fast) | Read-only | File discovery, code search, codebase exploration |
| Plan | Inherits | Read-only | Codebase research for planning mode |
| General-purpose | Inherits | All tools | Complex research, multi-step operations |
| Bash | Inherits | Bash | Running terminal commands in separate context |
| Claude Code Guide | Haiku | — | Answering questions about Claude Code features |
When to Use Subagents vs Main Conversation
Use the main conversation when:
- •The task needs frequent back-and-forth or iterative refinement
- •Multiple phases share significant context (planning → implementation → testing)
- •You're making a quick, targeted change
- •Latency matters — subagents start fresh and may need time to gather context
Use subagents when:
- •The task produces verbose output you don't need in your main context
- •You want to enforce specific tool restrictions or permissions
- •The work is self-contained and can return a summary
- •You need parallel research on independent topics
Use Agent Teams instead when:
- •Workers need to communicate with each other directly
- •You need sustained parallelism exceeding your context window
- •Complex work requiring discussion and collaboration between agents
- •Cross-layer coordination (frontend, backend, tests)
Creating Custom Subagents
File Format
Subagent files use YAML frontmatter + Markdown body for the system prompt:
--- name: code-reviewer description: Reviews code for quality and best practices tools: Read, Glob, Grep, Bash model: sonnet --- You are a code reviewer. When invoked, analyze the code and provide specific, actionable feedback on quality, security, and best practices.
Supported Frontmatter Fields
| Field | Required | Description |
|---|---|---|
name | Yes | Unique identifier (lowercase + hyphens) |
description | Yes | When Claude should delegate to this subagent |
tools | No | Allowlisted tools (inherits all if omitted) |
disallowedTools | No | Tools to deny from inherited list |
model | No | sonnet, opus, haiku, or inherit (default: inherit) |
permissionMode | No | default, acceptEdits, delegate, dontAsk, bypassPermissions, plan |
maxTurns | No | Maximum agentic turns before stopping |
skills | No | Skills to preload into subagent context at startup |
mcpServers | No | MCP servers available to this subagent |
hooks | No | Lifecycle hooks scoped to this subagent |
memory | No | Persistent memory scope: user, project, or local |
Scope and Priority
| Location | Scope | Priority |
|---|---|---|
--agents CLI flag | Current session only | 1 (highest) |
.claude/agents/ | Current project | 2 |
~/.claude/agents/ | All your projects | 3 |
Plugin's agents/ directory | Where plugin is enabled | 4 (lowest) |
[!TIP] Project subagents (
.claude/agents/) should be checked into version control so your team can share and improve them collaboratively.
Best Practices
1. Design Focused Subagents
Each subagent should excel at one specific task. Don't create Swiss-army-knife agents — instead, chain specialized ones.
2. Write Detailed Descriptions
Claude uses the description field to decide when to delegate. Include:
- •What the subagent does
- •When it should be used
- •Add "use proactively" to encourage automatic delegation
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.
3. Limit Tool Access (Principle of Least Privilege)
Grant only necessary permissions:
# Read-only reviewer tools: Read, Grep, Glob, Bash disallowedTools: Write, Edit # Debugging agent that needs edit access tools: Read, Edit, Bash, Grep, Glob
4. Use Persistent Memory for Learning Across Sessions
memory: user # Recommended default scope
| Scope | Location | Best For |
|---|---|---|
user | ~/.claude/agent-memory/<name>/ | Learnings across all projects |
project | .claude/agent-memory/<name>/ | Project-specific, shareable via VCS |
local | .claude/agent-memory-local/<name>/ | Project-specific, not in VCS |
Include memory instructions in the subagent prompt:
Update your agent memory as you discover codepaths, patterns, library locations, and key architectural decisions. This builds up institutional knowledge across conversations.
5. Use Hooks for Conditional Validation
When you need finer control than the tools field provides:
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
6. Preload Skills for Domain Knowledge
skills: - api-conventions - error-handling-patterns
[!NOTE] Subagents don't inherit skills from the parent conversation. You must list them explicitly.
Common Patterns
Isolate High-Volume Operations
Use a subagent to run the test suite and report only the failing tests with their error messages
Run Parallel Research
Research the authentication, database, and API modules in parallel using separate subagents
Chain Subagents for Multi-Step Workflows
Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them
Foreground vs Background Execution
- •Foreground: Blocks main conversation, permission prompts pass through to you
- •Background: Runs concurrently, pre-approves permissions, auto-denies unapproved tools
- •Press Ctrl+B to background a running task
- •Ask Claude to "run this in the background"
Resume a Subagent
Continue that code review and now analyze the authorization logic
Resumed subagents retain their full conversation history.
Example Subagent Templates
Code Reviewer (Read-Only)
--- name: code-reviewer description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code. tools: Read, Grep, Glob, Bash model: inherit --- You are a senior code reviewer ensuring high standards of code quality and security. When invoked: 1. Run git diff to see recent changes 2. Focus on modified files 3. Begin review immediately Review checklist: - Code is clear and readable - Functions and variables are well-named - No duplicated code - Proper error handling - No exposed secrets or API keys - Input validation implemented - Good test coverage - Performance considerations addressed Provide feedback organized by priority: - Critical issues (must fix) - Warnings (should fix) - Suggestions (consider improving) Include specific examples of how to fix issues.
Debugger (Read + Edit)
--- name: debugger description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues. tools: Read, Edit, Bash, Grep, Glob --- You are an expert debugger specializing in root cause analysis. When invoked: 1. Capture error message and stack trace 2. Identify reproduction steps 3. Isolate the failure location 4. Implement minimal fix 5. Verify solution works Focus on fixing the underlying issue, not the symptoms.
Database Query Validator (Hook-Protected)
---
name: db-reader
description: Execute read-only database queries. Use when analyzing data or generating reports.
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
---
You are a database analyst with read-only access. Execute SELECT queries
to answer questions about the data. You cannot modify data.
CLI-Defined (Ephemeral Session)
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer. Use proactively after code changes.",
"prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
"tools": ["Read", "Grep", "Glob", "Bash"],
"model": "sonnet"
}
}'
Quick Reference: Key Commands
| Action | Command |
|---|---|
| Manage subagents interactively | /agents |
| Request specific subagent | Use the <name> subagent to... |
| Background a running subagent | Ctrl+B |
| Disable background tasks | CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1 |
| Disable specific subagent | permissions.deny: ["Task(agent-name)"] |