NEW: Claude Code Security — research preview →

Subagents

Delegate tasks to isolated agents — parallel execution, specialized roles, and persistent memory

NEWRead time: 11 min

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

ProblemSolution
Long sessions accumulate irrelevant contextDelegate to a subagent with a clean slate
Some tasks need different tools or permissionsScope tools per subagent
Multiple independent tasks can run in parallelSpawn several subagents simultaneously
Specialized workflows need domain-specific behaviorDefine 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

TypeOptimized forTools available
ExploreRead-only file discovery and codebase searchRead-only (Write and Edit denied)
PlanCodebase research during plan modeRead-only (Write and Edit denied)
general-purposeComplex multi-step tasks needing exploration and actionAll tools available to subagents
statusline-setupRuns when you use /statusline (Sonnet)Limited
claude-code-guideAnswers 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:

PriorityLocationScope
1 (highest)Managed settingsOrganization-wide
2--agents CLI flagCurrent session only
3.claude/agents/<name>.mdCurrent project
4~/.claude/agents/<name>.mdAll your projects
5 (lowest)A plugin's agents/ directoryWhere 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-reviewer runs 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.

FieldPurpose
nameUnique identifier (no :, can't start with -)
descriptionWhen Claude should delegate to this agent
toolsAllowlist of tools (comma-separated or YAML list). Inherits all subagent tools if omitted
disallowedToolsDenylist, applied before tools
modelsonnet, opus, haiku, fable, a full model ID, or inherit
effortlow, medium, high, xhigh, max (available levels depend on the model)
permissionModedefault, acceptEdits, auto, dontAsk, bypassPermissions, plan
maxTurnsMax agentic turns before the subagent stops
skillsSkills to preload into the agent at startup
mcpServersMCP servers scoped to this agent
hooksLifecycle hooks scoped to this agent
memoryPersistent memory scope: user, project, or local
backgroundtrue always runs the agent in the background
isolationworktree runs the agent in a temporary git worktree
colorUI 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 numbers

The 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

ModeBehavior
ForegroundBlocks the main conversation; permission prompts pass straight through to you
BackgroundRuns 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 Agent from its tools or add it to disallowedTools.

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
---
ScopeStorage pathUse 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:

  1. The task matches a subagent's description
  2. A skill has context: fork set
  3. You explicitly ask Claude to delegate (or @-mention an agent)
  4. /batch is used

The result comes back as a summary in your main conversation. You can ask for more detail or iterate from there.


  • Skills — context: fork and agent frontmatter
  • Hooks — Lifecycle events that apply to subagents
  • Plugins — Distribute custom agents as plugins
  • Agent Teams — Orchestrating parallel agent workflows