## Highlights
## Content
Custom subagents in Claude Code are specialized AI assistants that can be invoked to handle specific types of tasks. They enable more efficient problem-solving by providing task-specific configurations with customized system prompts, tools and a separate context window.
## What Are Subagents?
Subagents are pre-configured AI personalities that Claude Code can delegate tasks to. Each subagent:
- Has a specific purpose and expertise area
- Uses its own context window separate from the main conversation
- Can be configured with specific tools it’s allowed to use
- Includes a custom system prompt that guides its behavior
When Claude Code encounters a task that matches a subagent’s expertise, it can delegate that task to the specialized subagent, which works independently and returns results.
## Key Benefits
## Quick Start
To create your first subagent:
## Subagent Configuration
| Field | Required | Description |
| ---------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name` | Yes | Unique identifier using lowercase letters and hyphens |
| `description` | Yes | Natural language description of the subagent’s purpose |
| `tools` | No | Comma-separated list of specific tools. If omitted, inherits all tools from the main thread |
| `model` | No | Model to use for this subagent. Can be a model alias (`sonnet`, `opus`, `haiku`) or `'inherit'` to use the main conversation’s model. If omitted, defaults to the [configured subagent model](https://code.claude.com/docs/en/model-config) |
| `permissionMode` | No | Permission mode for the subagent. Valid values: `default`, `acceptEdits`, `bypassPermissions`, `plan`, `ignore`. Controls how the subagent handles permission requests |
| `skills` | No | Comma-separated list of skill names to auto-load when the subagent starts. Skills are loaded into the subagent’s context automatically |
### File Locations
Subagents are stored as Markdown files with YAML frontmatter in two possible locations:When subagent names conflict, project-level subagents take precedence over user-level subagents.
### Plugin Agents
[Plugins](https://code.claude.com/docs/en/plugins) can provide custom subagents that integrate seamlessly with Claude Code. Plugin agents work identically to user-defined agents and appear in the `/agents` interface.**Plugin agent locations**: plugins include agents in their `agents/` directory (or custom paths specified in the plugin manifest).**Using plugin agents**:
- Plugin agents appear in `/agents` alongside your custom agents
- Can be invoked explicitly: “Use the code-reviewer agent from the security-plugin”
- Can be invoked automatically by Claude when appropriate
- Can be managed (viewed, inspected) through `/agents` interface
See the [plugin components reference](https://code.claude.com/docs/en/plugins-reference#agents) for details on creating plugin agents.
### CLI-based Configuration
You can also define subagents dynamically using the `--agents` CLI flag, which accepts a JSON object:**Priority**: CLI-defined subagents have lower priority than project-level subagents but higher priority than user-level subagents.**Use case**: This approach is useful for:
- Quick testing of subagent configurations
- Session-specific subagents that don’t need to be saved
- Automation scripts that need custom subagents
- Sharing subagent definitions in documentation or scripts
For detailed information about the JSON format and all available options, see the [CLI reference documentation](https://code.claude.com/docs/en/cli-reference#agents-flag-format).
### File Format
Each subagent is defined in a Markdown file with this structure:
#### Configuration Fields
### Model Selection
The `model` field allows you to control which [AI model](https://code.claude.com/docs/en/model-config) the subagent uses:
- **Model alias**: Use one of the available aliases: `sonnet`, `opus`, or `haiku`
- **`'inherit'`**: Use the same model as the main conversation (useful for consistency)
- **Omitted**: If not specified, uses the default model configured for subagents (`sonnet`)
Using `'inherit'` is particularly useful when you want your subagents to adapt to the model choice of the main conversation, ensuring consistent capabilities and response style throughout your session.
### Available Tools
Subagents can be granted access to any of Claude Code’s internal tools. See the [tools documentation](https://code.claude.com/docs/en/settings#tools-available-to-claude) for a complete list of available tools.You have two options for configuring tools:
- **Omit the `tools` field** to inherit all tools from the main thread (default), including MCP tools
- **Specify individual tools** as a comma-separated list for more granular control (can be edited manually or via `/agents`)
**MCP Tools**: Subagents can access MCP tools from configured MCP servers. When the `tools` field is omitted, subagents inherit all MCP tools available to the main thread.
## Managing Subagents
The `/agents` command provides a comprehensive interface for subagent management:
```sh
/agents
```
This opens an interactive menu where you can:
- View all available subagents (built-in, user, and project)
- Create new subagents with guided setup
- Edit existing custom subagents, including their tool access
- Delete custom subagents
- See which subagents are active when duplicates exist
- **Manage tool permissions** with a complete list of available tools
### Direct File Management
You can also manage subagents by working directly with their files:
Subagents created by manually adding files will be loaded the next time you start a Claude Code session. To create and use a subagent immediately without restarting, use the `/agents` command instead.
## Using Subagents Effectively
### Automatic Delegation
Claude Code proactively delegates tasks based on:
- The task description in your request
- The `description` field in subagent configurations
- Current context and available tools
To encourage more proactive subagent use, include phrases like “use PROACTIVELY” or “MUST BE USED” in your `description` field.
### Explicit Invocation
Request a specific subagent by mentioning it in your command:
## Built-in Subagents
Claude Code includes built-in subagents that are available out of the box:
### General-purpose Subagent
The general-purpose subagent is a capable agent for complex, multi-step tasks that require both exploration and action. Unlike the Explore subagent, it can modify files and execute a wider range of operations.**Key characteristics:**
- **Model**: Uses Sonnet for more capable reasoning
- **Tools**: Has access to all tools
- **Mode**: Can read and write files, execute commands, make changes
- **Purpose**: Complex research tasks, multi-step operations, code modifications
**When Claude uses it:**Claude delegates to the general-purpose subagent when:
- The task requires both exploration and modification
- Complex reasoning is needed to interpret search results
- Multiple strategies may be needed if initial searches fail
- The task has multiple steps that depend on each other
**Example scenario:**
### Plan Subagent
The Plan subagent is a specialized built-in agent designed for use during plan mode. When Claude is operating in plan mode (non-execution mode), it uses the Plan subagent to conduct research and gather information about your codebase before presenting a plan.**Key characteristics:**
- **Model**: Uses Sonnet for more capable analysis
- **Tools**: Has access to Read, Glob, Grep, and Bash tools for codebase exploration
- **Purpose**: Searches files, analyzes code structure, and gathers context
- **Automatic invocation**: Claude automatically uses this agent when in plan mode and needs to research the codebase
**How it works:**When you’re in plan mode and Claude needs to understand your codebase to create a plan, it delegates research tasks to the Plan subagent. This prevents infinite nesting of agents (subagents cannot spawn other subagents) while still allowing Claude to gather the necessary context.**Example scenario:**
The Plan subagent is only used in plan mode. In normal execution mode, Claude uses the general-purpose agent or other custom subagents you’ve created.
### Explore Subagent
The Explore subagent is a fast, lightweight agent optimized for searching and analyzing codebases. It operates in strict read-only mode and is designed for rapid file discovery and code exploration.**Key characteristics:**
- **Model**: Uses Haiku for fast, low-latency searches
- **Mode**: Strictly read-only - cannot create, modify, or delete files
- **Tools available**: - Glob - File pattern matching - Grep - Content searching with regular expressions - Read - Reading file contents - Bash - Read-only commands only (ls, git status, git log, git diff, find, cat, head, tail)
**When Claude uses it:**Claude will delegate to the Explore subagent when it needs to search or understand a codebase but doesn’t need to make changes. This is more efficient than the main agent running multiple search commands directly, as content found during the exploration process doesn’t bloat the main conversation.**Thoroughness levels:**When invoking the Explore subagent, Claude specifies a thoroughness level:
- **Quick** - Fast searches with minimal exploration. Good for targeted lookups.
- **Medium** - Moderate exploration. Balances speed and thoroughness.
- **Very thorough** - Comprehensive analysis across multiple locations and naming conventions. Used when the target might be in unexpected places.
**Example scenarios:**
## Example Subagents
### Code Reviewer
```sh
---
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
```sh
---
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
Debugging process:
- Analyze error messages and logs
- Check recent code changes
- Form and test hypotheses
- Add strategic debug logging
- Inspect variable states
For each issue, provide:
- Root cause explanation
- Evidence supporting the diagnosis
- Specific code fix
- Testing approach
- Prevention recommendations
Focus on fixing the underlying issue, not the symptoms.
```
### Data Scientist
```sh
---
name: data-scientist
description: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries.
tools: Bash, Read, Write
model: sonnet
---
You are a data scientist specializing in SQL and BigQuery analysis.
When invoked:
1. Understand the data analysis requirement
2. Write efficient SQL queries
3. Use BigQuery command line tools (bq) when appropriate
4. Analyze and summarize results
5. Present findings clearly
Key practices:
- Write optimized SQL queries with proper filters
- Use appropriate aggregations and joins
- Include comments explaining complex logic
- Format results for readability
- Provide data-driven recommendations
For each analysis:
- Explain the query approach
- Document any assumptions
- Highlight key findings
- Suggest next steps based on data
Always ensure queries are efficient and cost-effective.
```
## Best Practices
- **Start with Claude-generated agents**: We highly recommend generating your initial subagent with Claude and then iterating on it to make it personally yours. This approach gives you the best results - a solid foundation that you can customize to your specific needs.
- **Design focused subagents**: Create subagents with single, clear responsibilities rather than trying to make one subagent do everything. This improves performance and makes subagents more predictable.
- **Write detailed prompts**: Include specific instructions, examples, and constraints in your system prompts. The more guidance you provide, the better the subagent will perform.
- **Limit tool access**: Only grant tools that are necessary for the subagent’s purpose. This improves security and helps the subagent focus on relevant actions.
- **Version control**: Check project subagents into version control so your team can benefit from and improve them collaboratively.
## Advanced Usage
### Chaining Subagents
For complex workflows, you can chain multiple subagents:
### Dynamic Subagent Selection
Claude Code intelligently selects subagents based on context. Make your `description` fields specific and action-oriented for best results.
### Resumable Subagents
Subagents can be resumed to continue previous conversations, which is particularly useful for long-running research or analysis tasks that need to be continued across multiple invocations.**How it works:**
- Each subagent execution is assigned a unique `agentId`
- The agent’s conversation is stored in a separate transcript file: `agent-{agentId}.jsonl`
- You can resume a previous agent by providing its `agentId` via the `resume` parameter
- When resumed, the agent continues with full context from its previous conversation
**Example workflow:**Initial invocation:Resume the agent:**Use cases:**
- **Long-running research**: Break down large codebase analysis into multiple sessions
- **Iterative refinement**: Continue refining a subagent’s work without losing context
- **Multi-step workflows**: Have a subagent work on related tasks sequentially while maintaining context
**Technical details:**
- Agent transcripts are stored in your project directory
- Recording is disabled during resume to avoid duplicating messages
- Both synchronous and asynchronous agents can be resumed
- The `resume` parameter accepts the agent ID from a previous execution
**Programmatic usage:**If you’re using the Agent SDK or interacting with the AgentTool directly, you can pass the `resume` parameter:
Keep track of agent IDs for tasks you may want to resume later. Claude Code displays the agent ID when a subagent completes its work.
## Performance Considerations
- **Context efficiency**: Agents help preserve main context, enabling longer overall sessions
- **Latency**: Subagents start off with a clean slate each time they are invoked and may add latency as they gather context that they require to do their job effectively.
- [Plugins](https://code.claude.com/docs/en/plugins) - Extend Claude Code with custom agents through plugins
- [Slash commands](https://code.claude.com/docs/en/slash-commands) - Learn about other built-in commands
- [Settings](https://code.claude.com/docs/en/settings) - Configure Claude Code behavior
- [Hooks](https://code.claude.com/docs/en/hooks) - Automate workflows with event handlers
[Plugins](https://code.claude.com/docs/en/plugins)