Subagents
Built-in Claude Code subagents, custom agents, scopes, frontmatter, permissions, models, MCP, hooks, context isolation, and forks.
A subagent is a specialized agent within Claude Code. It handles side tasks that produce substantial search results, logs, file contents, or intermediate reasoning: it works in its own context window and returns only a summary or result to the main session.
Think of a subagent as a configurable temporary colleague: it has its own system prompt, tool scope, permission mode, model selection, and context, while remaining part of the current Claude Code session.
#Suitable tasks
| Scenario | Why use a subagent? |
|---|---|
| Broad code exploration | Large Grep/Read outputs stay out of the main session |
| Specialized reviews | A fixed prompt and read-only tools keep reviews consistent |
| Parallel research | Investigate directions independently and summarize in the main session |
| Restricting high-risk tools | Limit capabilities with tools, disallowedTools, and permissionMode |
| Cost control | Assign a cheaper model alias to exploration agents |
Tasks requiring repeated interaction with you, or depending on the main session history at every step, usually fit the main session better. To reuse prompts or workflows while retaining the main session context, consider Skills.
#Built-in subagents
Claude Code automatically uses built-in subagents when appropriate. They inherit the main session's permissions but have their own tool restrictions.
| Subagent | Tools and model | Typical use |
|---|---|---|
Explore | Read-only tools; inherits the main model, capped at Opus on the Claude API | Search and understand codebases; locate files quickly |
Plan | Read-only tools; inherits the main model | Research before producing a plan in plan mode |
general-purpose | Usually all tools; inherits the main model | Complex multi-step tasks requiring exploration and changes |
statusline-setup | Sonnet | Configure /statusline |
claude-code-guide | Haiku | Answer questions about Claude Code features |
For speed and cost, Explore and Plan do not load CLAUDE.md or the parent session's git status. Other built-in and custom subagents load this context.
Put rules that Explore or Plan must know, such as “do not read the vendor directory,” explicitly in the delegation prompt. Do not rely only on CLAUDE.md.
Common ways to restrict built-in subagents:
| Requirement | Method |
|---|---|
| Disable a particular built-in subagent | Add Agent(Explore) to permissions deny |
| Prevent all subagent delegation | Deny the Agent tool |
Disable only Explore / Plan | Set CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS=1 |
| Remove all built-in types in non-interactive or SDK use | Set CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS=1 |
#Create a custom subagent
A custom subagent is a Markdown file with configuration in YAML frontmatter and its system prompt in the body.
Choose a scope
Use .claude/agents/ for project agents and ~/.claude/agents/ for personal agents shared across projects.
Write the agent file
---
name: code-reviewer
description: Code review specialist. Use proactively after writing or changing code to check quality, security, and maintainability.
tools: Read, Grep, Glob, Bash
model: sonnet
---
You are a senior code reviewer. When invoked, inspect the relevant changes first. Provide reviews and suggestions only; do not edit files.
Group findings by severity: required fixes, recommended fixes, and optional improvements. Give the file location, reason, and suggested fix for each finding.Invoke explicitly
Use the code-reviewer subagent to review my recent changesYou can also select an agent with @ in the input field, for example @"code-reviewer (agent)" Review the authentication changes.
Claude Code watches ~/.claude/agents/ and .claude/agents/ for changes. New or edited files normally take effect within seconds. Restart in two cases: the target agents directory did not exist when the session started, or the session started with --disable-slash-commands.
Starting with v2.1.198, /agents no longer opens the old interactive creation wizard. Ask Claude to generate an agent file, or edit .claude/agents/ / ~/.claude/agents/ directly.
#Scope and precedence
When multiple subagents share a name, Claude Code selects one definition by precedence.
| Location | Scope | Precedence |
|---|---|---|
| Managed settings | Organization | Highest |
--agents CLI JSON | Current session | 2 |
.claude/agents/ | Current project | 3 |
~/.claude/agents/ | All personal projects | 4 |
Plugin agents/ | Projects using the plugin | Lowest |
Additional rules:
- Claude Code searches upward from the working directory for
.claude/agents/; for duplicate names in nested directories, the nearest definition wins. .claude/agents/and~/.claude/agents/are scanned recursively, but the frontmatternamedetermines identity, not the filename or subdirectory.- Avoid duplicate
namevalues within one scope;/doctorcan report some duplicate definitions. - Plugin agent subdirectories become part of the scoped name, for example
my-plugin:review:security. - For security, plugin agents ignore
hooks,mcpServers, andpermissionMode.
Pass JSON through --agents for a temporary session:
claude --agents '{
"safe-reviewer": {
"description": "Read-only code review. Use after code changes.",
"prompt": "You are a read-only code reviewer. Report findings and suggestions without editing files.",
"tools": ["Read", "Grep", "Glob"],
"model": "sonnet"
}
}'#Frontmatter fields
Only name and description are required. The body is the subagent's system prompt.
| Field | Purpose |
|---|---|
name | Unique identifier, preferably lowercase letters and hyphens; supplied as agent_type in hooks |
description | Tells Claude when to delegate; specific descriptions improve automatic selection |
tools | Tool allowlist; inherits available parent tools when omitted |
disallowedTools | Removes tools from the inherited or specified set |
model | inherit, sonnet, opus, haiku, fable, or a full model ID; defaults to inherit |
permissionMode | default, acceptEdits, auto, dontAsk, bypassPermissions, or plan |
maxTurns | Limits agentic turns |
skills | Preloads full skill content at startup |
mcpServers | Connects or references MCP servers for this subagent only |
hooks | Hooks that run only during this subagent's lifecycle |
memory | Persistent memory scope: user, project, or local |
background | Always runs in the background when true |
effort | Overrides session effort; supported values depend on the model |
isolation | Runs in a temporary git worktree when set to worktree |
color | Display color in panels and transcripts |
initialPrompt | First prompt submitted automatically when this agent starts as the main session agent |
bypassPermissions skips most permission prompts and carries significant risk. Explicit ask rules and protections against deleting root/home directories still apply, but this should not be the routine default.
#Model selection
Subagent model selection follows this order:
CLAUDE_CODE_SUBAGENT_MODEL- Model parameter supplied for this invocation
- Agent frontmatter
model - Main session model
Omitting model is equivalent to inherit. If an organization or provider model allowlist rejects a value, Claude Code skips it and falls back to the inherited model.
With Passion8, model aliases and full IDs ultimately depend on models available in the Passion8 console and gateway mappings. Subagents do not configure a separate Base URL; they use the current Claude Code session's connection settings.
#Tool and MCP restrictions
tools is an allowlist and disallowedTools is a denylist. When both are present, denied tools are removed first, then the allowlist is resolved against the remaining tools.
---
name: safe-researcher
description: Read-only research agent for exploring code and logs.
tools: Read, Grep, Glob, Bash
------
name: local-only
description: Inherit all tools except GitHub MCP.
disallowedTools: mcp__github
---MCP tools accept exact tool names or server-level patterns:
| Pattern | Meaning |
|---|---|
mcp__github | All tools from the GitHub server |
mcp__github__* | The same, with an explicit wildcard |
mcp__* | All MCP tools, commonly used in deny rules |
Some tools depend on the main UI or session state and are unavailable to subagents even if listed in tools, including AskUserQuestion, EnterPlanMode, ScheduleWakeup, and WaitForMcpServers.
#Subagent-specific MCP
Declare an MCP server in mcpServers to expose it only to this subagent, keeping tool descriptions out of the main session context.
---
name: browser-tester
description: Verify pages in a real browser.
mcpServers:
- playwright:
type: stdio
command: npx
args: ["-y", "@playwright/mcp@latest"]
- github
---Inline MCP servers connect when the subagent starts and disconnect when it ends. String references reuse a server already configured in the main session. Enterprise MCP policies, --strict-mcp-config, --bare, and other restrictions still apply.
#Permissions and hooks
Subagents inherit the parent's permission context and can override it with permissionMode. The exception is when the parent already uses bypassPermissions, acceptEdits, or auto: the parent mode takes precedence.
| Mode | Behavior |
|---|---|
default | Standard permission checks and prompts |
acceptEdits | Automatically accepts edits within the working directory and common file commands |
auto | Uses a background classifier for commands and writes to protected directories |
dontAsk | Automatically denies requests that would require a prompt |
bypassPermissions | Skips most permission prompts |
plan | Read-only planning |
Define hooks specific to the subagent in its frontmatter:
---
name: db-reader
description: Execute only read-only database queries.
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
---Project-level settings.json can also listen to subagent lifecycle events:
{
"hooks": {
"SubagentStart": [
{
"matcher": "db-reader",
"hooks": [{ "type": "command", "command": "./scripts/setup-db.sh" }]
}
],
"SubagentStop": [
{
"hooks": [{ "type": "command", "command": "./scripts/cleanup-db.sh" }]
}
]
}
}#Invocation methods
| Method | Usage | Suitable for |
|---|---|---|
| Automatic delegation | Specify triggers clearly in description | Everyday use without explicit selection |
| Natural language | Use the code-reviewer subagent... | Occasional explicit selection |
@ mention | @"code-reviewer (agent)" ... | Requiring a particular agent |
--agent | claude --agent code-reviewer | Running the entire session as this agent |
| Settings | { "agent": "code-reviewer" } | A default project agent |
--agents | Supply JSON at startup | Temporary experiments or automation |
--agent makes the main session itself use that agent's system prompt, tool restrictions, and model. It replaces the session's default behavior rather than starting a separate subtask.
#Foreground, background, and resuming
From v2.1.198, subagents generally run in the background by default; Claude puts them in the foreground when it needs the result to continue.
| Mode | Behavior |
|---|---|
| Foreground subagent | The main session waits; permission prompts are forwarded immediately |
| Background subagent | You can keep working; permission prompts appear in the main session and identify the requesting agent |
Explicitly request foreground or background execution, or press Ctrl+B to move a running task to the background. Set CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1 to disable background tasks.
Each invocation normally creates a new subagent instance. Ask Claude to resume an earlier instance to continue it. Resumable agents retain their full history, tool results, and reasoning context. Explore and Plan are one-shot built-ins and do not return resumable agent IDs; use general-purpose or a custom agent when continuity matters.
Subagent transcripts are stored separately from the main session. Compacting the main session does not clear them. cleanupPeriodDays controls retention, defaulting to 30 days.
#Context boundaries
A non-fork subagent starts with a new, independent context. It cannot see the main session's full chat history, previously read files, or previously invoked skills. It normally receives:
- Its own system prompt and basic environment information supplied by Claude Code
- The task description Claude writes for it
- The
CLAUDE.mdand memory hierarchy, except forExplore/Plan - Git status from session startup, except for
Explore/Plan - Full skill content preloaded through
skills
Use a fork when the complete main session context is required.
#Fork the current session
/fork creates a special subagent that inherits the current session's full context, system prompt, tools, model, and history. Its tool calls remain in its own transcript, and only the result returns to the parent.
/fork draft tests for the parser changes so farForks suit parallel directions within the same context, such as drafting tests, comparing implementations, or investigating a side branch. Differences from named subagents:
| Comparison | Fork | Named subagent |
|---|---|---|
| Context | Inherits the complete main session | Fresh context with the task description |
| System prompt and tools | Same as the main session | From the agent definition |
| Model | Same as the main session | From model or inherited |
| Prompt cache | Can reuse the main session prefix | Separate cache |
Set CLAUDE_CODE_FORK_SUBAGENT=1 to explicitly enable forks, or 0 to disable them. A fork cannot spawn another fork.
#Best practices
| Practice | Reason |
|---|---|
| Give each agent one category of task | Easier description matching and more consistent output |
| Make review agents read-only by default | Prevent incidental changes during review |
| Commit project agents to version control | Share review and implementation rules across the team |
| Delegate long logs, tests, and searches | Keep the main context focused |
| Add hooks for high-risk capabilities | Tool restrictions limit tools; hooks can inspect individual commands |
| Use worktrees for parallel edits | Prevent agents from overwriting one another in a shared workspace |
#Official references
Support
Need help?
For setup, billing, or model issues, email us. Check the status page for uptime.
WeChat / QQ support is available at the bottom right.

