Claude Code

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

ScenarioWhy use a subagent?
Broad code explorationLarge Grep/Read outputs stay out of the main session
Specialized reviewsA fixed prompt and read-only tools keep reviews consistent
Parallel researchInvestigate directions independently and summarize in the main session
Restricting high-risk toolsLimit capabilities with tools, disallowedTools, and permissionMode
Cost controlAssign 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.

SubagentTools and modelTypical use
ExploreRead-only tools; inherits the main model, capped at Opus on the Claude APISearch and understand codebases; locate files quickly
PlanRead-only tools; inherits the main modelResearch before producing a plan in plan mode
general-purposeUsually all tools; inherits the main modelComplex multi-step tasks requiring exploration and changes
statusline-setupSonnetConfigure /statusline
claude-code-guideHaikuAnswer 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:

RequirementMethod
Disable a particular built-in subagentAdd Agent(Explore) to permissions deny
Prevent all subagent delegationDeny the Agent tool
Disable only Explore / PlanSet CLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS=1
Remove all built-in types in non-interactive or SDK useSet 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.

1

Choose a scope

Use .claude/agents/ for project agents and ~/.claude/agents/ for personal agents shared across projects.

2

Write the agent file

.claude/agents/code-reviewer.md
---
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.
3

Invoke explicitly

Use the code-reviewer subagent to review my recent changes

You 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.

LocationScopePrecedence
Managed settingsOrganizationHighest
--agents CLI JSONCurrent session2
.claude/agents/Current project3
~/.claude/agents/All personal projects4
Plugin agents/Projects using the pluginLowest

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 frontmatter name determines identity, not the filename or subdirectory.
  • Avoid duplicate name values within one scope; /doctor can 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, and permissionMode.

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.

FieldPurpose
nameUnique identifier, preferably lowercase letters and hyphens; supplied as agent_type in hooks
descriptionTells Claude when to delegate; specific descriptions improve automatic selection
toolsTool allowlist; inherits available parent tools when omitted
disallowedToolsRemoves tools from the inherited or specified set
modelinherit, sonnet, opus, haiku, fable, or a full model ID; defaults to inherit
permissionModedefault, acceptEdits, auto, dontAsk, bypassPermissions, or plan
maxTurnsLimits agentic turns
skillsPreloads full skill content at startup
mcpServersConnects or references MCP servers for this subagent only
hooksHooks that run only during this subagent's lifecycle
memoryPersistent memory scope: user, project, or local
backgroundAlways runs in the background when true
effortOverrides session effort; supported values depend on the model
isolationRuns in a temporary git worktree when set to worktree
colorDisplay color in panels and transcripts
initialPromptFirst 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:

  1. CLAUDE_CODE_SUBAGENT_MODEL
  2. Model parameter supplied for this invocation
  3. Agent frontmatter model
  4. 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:

PatternMeaning
mcp__githubAll 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.

ModeBehavior
defaultStandard permission checks and prompts
acceptEditsAutomatically accepts edits within the working directory and common file commands
autoUses a background classifier for commands and writes to protected directories
dontAskAutomatically denies requests that would require a prompt
bypassPermissionsSkips most permission prompts
planRead-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:

.claude/settings.json
{
  "hooks": {
    "SubagentStart": [
      {
        "matcher": "db-reader",
        "hooks": [{ "type": "command", "command": "./scripts/setup-db.sh" }]
      }
    ],
    "SubagentStop": [
      {
        "hooks": [{ "type": "command", "command": "./scripts/cleanup-db.sh" }]
      }
    ]
  }
}

#Invocation methods

MethodUsageSuitable for
Automatic delegationSpecify triggers clearly in descriptionEveryday use without explicit selection
Natural languageUse the code-reviewer subagent...Occasional explicit selection
@ mention@"code-reviewer (agent)" ...Requiring a particular agent
--agentclaude --agent code-reviewerRunning the entire session as this agent
Settings{ "agent": "code-reviewer" }A default project agent
--agentsSupply JSON at startupTemporary 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.

ModeBehavior
Foreground subagentThe main session waits; permission prompts are forwarded immediately
Background subagentYou 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.md and memory hierarchy, except for Explore / 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 far

Forks suit parallel directions within the same context, such as drafting tests, comparing implementations, or investigating a side branch. Differences from named subagents:

ComparisonForkNamed subagent
ContextInherits the complete main sessionFresh context with the task description
System prompt and toolsSame as the main sessionFrom the agent definition
ModelSame as the main sessionFrom model or inherited
Prompt cacheCan reuse the main session prefixSeparate cache

Set CLAUDE_CODE_FORK_SUBAGENT=1 to explicitly enable forks, or 0 to disable them. A fork cannot spawn another fork.

#Best practices

PracticeReason
Give each agent one category of taskEasier description matching and more consistent output
Make review agents read-only by defaultPrevent incidental changes during review
Commit project agents to version controlShare review and implementation rules across the team
Delegate long logs, tests, and searchesKeep the main context focused
Add hooks for high-risk capabilitiesTool restrictions limit tools; hooks can inspect individual commands
Use worktrees for parallel editsPrevent 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.