Subagents
Delegate tasks to isolated agents — parallel execution, specialized roles, and persistent memory
title: "Subagents" description: "Delegate tasks to isolated agents — parallel execution, specialized roles, and persistent memory" section: "Core" readTime: "11 min" badge: "NEW"
Subagents
Subagents let Claude delegate tasks to isolated agent contexts that run with their own context window, system prompt, tools, and memory. Use them to parallelize work, isolate risky operations, or specialize agents for different roles.
Why Subagents
| Problem | Solution |
|---|---|
| Long sessions accumulate irrelevant context | Delegate to a subagent with a clean slate |
| Some tasks need different tools or permissions | Scope tools per subagent |
| Multiple independent tasks can run in parallel | Spawn several subagents simultaneously |
| Specialized workflows need domain-specific behavior | Define custom agent personas |
Claude spawns subagents with the Agent tool (renamed from Task in v2.1.63; Task(...) references in permission rules still work as aliases).
Built-in Agent Types
| Type | Optimized for | Tools available |
|---|---|---|
Explore | Read-only file discovery and codebase search | Read-only (Write and Edit denied) |
Plan | Codebase research during plan mode | Read-only (Write and Edit denied) |
general-purpose | Complex multi-step tasks needing exploration and action | All tools available to subagents |
statusline-setup | Runs when you use /statusline (Sonnet) | Limited |
claude-code-guide | Answers questions about Claude Code features (Haiku) | Limited |
To disable a built-in, add Agent(Explore) (for example) to permissions.deny, or deny the Agent tool entirely to stop all delegation.
Custom Agents
Define custom subagents as Markdown files with YAML frontmatter. When names collide, the higher-priority location wins:
| Priority | Location | Scope |
|---|---|---|
| 1 (highest) | Managed settings | Organization-wide |
| 2 | --agents CLI flag | Current session only |
| 3 | .claude/agents/<name>.md | Current project |
| 4 | ~/.claude/agents/<name>.md | All your projects |
| 5 (lowest) | A plugin's agents/ directory | Where the plugin is enabled |
---
name: security-reviewer
description: Reviews code for security vulnerabilities. Use when auditing PRs, new API endpoints, or auth flows.
tools: Read, Glob, Grep
model: opus
effort: high
---
You are a security-focused code reviewer. When reviewing code:
1. Check for injection vulnerabilities (SQL, command, path traversal)
2. Verify authentication and authorization on every endpoint
3. Look for hardcoded secrets or API keys
4. Flag insecure dependencies
5. Check input validation at system boundaries
Return findings as: CRITICAL / HIGH / MEDIUM / LOW with file references.Claude delegates to this agent automatically when your request matches its description. You can also invoke it explicitly:
- Natural language: "Use the security-reviewer subagent to check the auth changes"
- @-mention: type
@agent-security-reviewer(or pick it from the@menu) - Whole session:
claude --agent security-reviewerruns the main thread as that agent, or set"agent": "security-reviewer"in.claude/settings.json
Subagents are not slash commands — /security-reviewer won't work. To get a slash command, create a skill with context: fork and agent: security-reviewer (see below).
Frontmatter fields for agents
Only name and description are required. Field names are case-sensitive; unknown fields are silently ignored.
| Field | Purpose |
|---|---|
name | Unique identifier (no :, can't start with -) |
description | When Claude should delegate to this agent |
tools | Allowlist of tools (comma-separated or YAML list). Inherits all subagent tools if omitted |
disallowedTools | Denylist, applied before tools |
model | sonnet, opus, haiku, fable, a full model ID, or inherit |
effort | low, medium, high, xhigh, max (available levels depend on the model) |
permissionMode | default, acceptEdits, auto, dontAsk, bypassPermissions, plan |
maxTurns | Max agentic turns before the subagent stops |
skills | Skills to preload into the agent at startup |
mcpServers | MCP servers scoped to this agent |
hooks | Lifecycle hooks scoped to this agent |
memory | Persistent memory scope: user, project, or local |
background | true always runs the agent in the background |
isolation | worktree runs the agent in a temporary git worktree |
color | UI color: red, blue, green, yellow, purple, orange, pink, cyan |
Use tools, not allowed-tools, in agent files. allowed-tools is a skill field that pre-approves tools — it is ignored in an agent definition, so the agent would silently inherit every tool. permissionMode, mcpServers, and hooks are ignored for plugin-provided agents.
Session-only agents with --agents
Define agents as JSON for a single session — nothing is written to disk. prompt is the system prompt; the other keys match the frontmatter fields:
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer. Use proactively after code changes.",
"prompt": "You are a senior code reviewer. Focus on quality, security, and best practices.",
"tools": ["Read", "Grep", "Glob", "Bash"],
"model": "sonnet"
}
}'Preloading Skills into Subagents
List skills in the skills frontmatter field to inject their full content at subagent startup:
---
name: api-builder
description: Builds REST API endpoints following our conventions
skills:
- api-conventions
- error-handling-patterns
- openapi-docs
---
Build the API endpoint described by the user. Follow the loaded conventions.Unlike regular sessions (where skills load on demand), preloaded skills are fully injected at startup. The subagent has all the context it needs from the first turn.
Run a Skill as a Subagent
Add context: fork to a skill's frontmatter to run it in isolation:
---
name: deep-research
description: Research a topic thoroughly without polluting the main session
context: fork
agent: Explore
---
Research $ARGUMENTS:
1. Find relevant files using Glob and Grep
2. Read and analyze the code
3. Summarize findings with specific file references and line numbersThe skill content becomes the subagent's prompt. The subagent does not see your conversation history, so the instructions must be self-contained. agent picks the subagent type (Explore, Plan, general-purpose, or any custom agent) and defaults to general-purpose. Results are summarized back into your main conversation.
Foreground vs Background
| Mode | Behavior |
|---|---|
| Foreground | Blocks the main conversation; permission prompts pass straight through to you |
| Background | Runs concurrently; permission prompts surface in the main session, naming the asking subagent |
Press Ctrl+B to send a running task to the background, and use /tasks to view and manage background work. Set background: true in an agent's frontmatter to always run it in the background.
Nesting and limits
- Subagents can spawn their own subagents, up to three layers below the main conversation by default (
CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH;"1"turns nesting off). - Up to 20 subagents run concurrently by default (
CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS). - To stop a specific agent from spawning others, omit
Agentfrom itstoolsor add it todisallowedTools.
Resuming a subagent
Each invocation normally starts a fresh instance. Claude can resume a previous subagent — with its full history — by messaging it via the SendMessage tool using its agent ID or name. Explore and Plan are one-shot and cannot be resumed.
Parallel Execution with /batch
The bundled /batch skill orchestrates large-scale changes across a codebase in parallel:
/batch migrate src/ from JavaScript to TypeScript
Claude researches the codebase, decomposes the work into 5 to 30 independent units, and presents a plan. Once you approve, it spawns one background subagent per unit, each in an isolated git worktree. Each subagent implements its unit, runs tests, and publishes its change. Requires a git repository (or a WorktreeCreate hook).
Wall-clock time is roughly that of the slowest unit, but token cost scales with the number of units.
When to use parallel agents:
- Tasks that are truly independent (no shared file writes)
- Time matters more than cost
- Each task is well-defined with clear scope
Subagent Memory
Subagents can maintain their own persistent memory, separate from the main session. Set the memory field to a scope in the agent definition:
---
name: db-specialist
description: Database design and migration specialist
memory: project
---| Scope | Storage path | Use when |
|---|---|---|
user | ~/.claude/agent-memory/<agent-name>/ | Learnings apply across all projects |
project | .claude/agent-memory/<agent-name>/ | Project-specific and version-controlled (recommended default) |
local | .claude/agent-memory-local/<agent-name>/ | Project-specific but not checked in |
With memory enabled, Read/Write/Edit are enabled automatically and the first 200 lines (or 25KB) of the agent's MEMORY.md load into its system prompt. The subagent accumulates knowledge across sessions: table naming conventions it learned, migration patterns that worked, performance optimizations it discovered. The field has no effect when auto memory is turned off.
Delegation Pattern
Claude decides to spawn a subagent when:
- The task matches a subagent's
description - A skill has
context: forkset - You explicitly ask Claude to delegate (or @-mention an agent)
/batchis used
The result comes back as a summary in your main conversation. You can ask for more detail or iterate from there.
Related
- Skills —
context: forkandagentfrontmatter - Hooks — Lifecycle events that apply to subagents
- Plugins — Distribute custom agents as plugins
- Agent Teams — Orchestrating parallel agent workflows