Back to Blog

Best Claude Code Subagents and Custom Agent Examples for Specialized Coding Workflows in 2026

RRizki Murtadha
August 6, 202655 min read

Claude Code can inspect repositories, edit files, run commands, call external tools, and complete multi-step development tasks inside one conversation.

But not every part of a complex task should stay inside the main context window.

A repository search may read dozens of files. A test run may produce thousands of lines of output. A security review may need a different system prompt and stricter tool access. A production incident may require logs and monitoring tools that the main coding session does not need.

Claude Code subagents provide a way to delegate those focused tasks to specialized workers.

Each subagent runs in its own context window with a custom system prompt, model choice, tool access, permission behavior, and optional Skills, MCP servers, Hooks, memory, worktree isolation, and execution settings.

The subagent performs its work separately and returns a focused result to the main conversation. This keeps temporary search results, logs, file contents, and intermediate reasoning out of the context you are using to plan and implement the broader task.

This guide explains how Claude Code subagents work, where custom agents are stored, how automatic delegation is controlled, how foreground and background execution differ, how to configure tools and permissions, how subagents use Skills, Hooks, MCP, memory, and worktrees, and how to build specialized agents for real software-development workflows.

Quick Answer

Claude Code subagents are specialized AI workers that run in isolated context windows and return summarized results to the main session.

A minimal project subagent can be stored in .claude/agents/code-reviewer.md:

---
name: code-reviewer
description: Review recent code changes for correctness, security, maintainability, and missing tests. Use after implementation.
tools: Read, Grep, Glob, Bash
permissionMode: plan
model: inherit
---

You are a read-only code reviewer.

Inspect the complete diff, relevant surrounding code, callers, and tests.

For each finding, provide severity, file and location, evidence, impact, recommended correction, and verification method.

Do not modify files or invent defects without evidence.

Claude can delegate automatically when a task matches the description, or you can invoke a specific subagent through natural language or an @-mention.

Use subagents for focused work where only the result matters. Keep work in the main conversation when several phases require the same context and frequent interaction.

Key Takeaways

  • Subagents are isolated workers, not reusable prompt files.
  • Each subagent uses its own context window and returns a result to the main conversation.
  • Use subagents to isolate repository exploration, logs, test output, research, reviews, and other context-heavy side tasks.
  • Only name and description are required in a custom subagent file.
  • The Markdown body becomes the subagent's system prompt.
  • Project agents live under .claude/agents/; personal agents live under ~/.claude/agents/.
  • Claude uses the description to decide when automatic delegation is appropriate.
  • Tools, denied tools, permissions, model, effort, turn limit, Skills, MCP servers, Hooks, memory, background execution, and worktree isolation can be configured independently.
  • Current Claude Code versions normally run subagents in the background and use foreground execution when the result is required immediately.
  • Read-only agents should omit Edit and Write and should not receive the Agent tool unless delegation is required.
  • Subagents can run concurrently, sequentially, or as nested delegation trees.
  • Agent Teams are different: teammates are independent sessions that can communicate with one another.
  • Dynamic Workflows use a script to orchestrate many subagents at a larger and more repeatable scale.
  • A named subagent starts with fresh context, while a forked subagent inherits the current conversation.
  • Project subagent definitions should be reviewed, versioned, and tested like other development configuration.

Table of Contents

What Are Claude Code Subagents?

A Claude Code subagent is a specialized AI assistant that Claude can spawn to complete a focused task outside the main conversation context.

The subagent receives a task prompt, its configured system prompt, basic environment information, applicable project context, and the tools and permissions available to it. It then runs its own agentic loop and returns a result to the caller.

The key characteristic is context isolation.

Main conversation
      ↓ delegates focused task
Subagent context window
      ↓ reads files, runs tools, investigates
Focused result or summary
      ↓
Main conversation continues

The main conversation does not need to retain every file read, search result, stack trace, browser response, or test log produced during the delegated work.

This makes subagents particularly useful when intermediate work is verbose but the final conclusion is compact.

Subagents Are More Than Named Prompts

A custom subagent definition can specify:

  • When Claude should delegate to it.
  • Its system prompt and specialization.
  • Allowed and denied tools.
  • The model and effort level.
  • The permission mode.
  • A maximum number of agentic turns.
  • Skills preloaded at startup.
  • MCP servers scoped to the worker.
  • Hooks that run only during its lifecycle.
  • Persistent user, project, or local memory.
  • Background execution.
  • Git worktree isolation.

These controls make a subagent a reusable execution environment rather than only a reusable block of text.

Why Use Subagents?

Preserve the Main Context Window

A subagent can read many files, run a large test suite, inspect logs, or research documentation while the main conversation receives only the relevant result.

Specialize Behavior

A security reviewer, database migration analyst, accessibility reviewer, and test failure investigator require different priorities, checklists, output formats, and tool access. Separate definitions help each worker stay focused.

Restrict Capabilities

A reviewer can be read-only. A browser tester can receive only a browser MCP server. A database analyst can use a Hook that blocks write queries. A documentation agent can edit Markdown but should not modify application code.

Parallelize Independent Work

Several subagents can investigate separate modules or review different quality dimensions while the main agent continues coordinating the task.

Control Model Cost

Exploration and mechanical searches may use a faster model, while architecture, security, or migration review can use a stronger model and higher effort.

Reuse Project Knowledge

Project subagents can be committed to Git and improved by the team. Persistent memory can accumulate durable codebase knowledge across sessions when used carefully.

How Claude Code Subagents Work

The general delegation process is:

  1. The main Claude Code session identifies a focused subtask.
  2. Claude selects a built-in or custom subagent based on the task and each agent description.
  3. The subagent starts with a separate context window.
  4. Its system prompt, model, tools, permission behavior, Skills, MCP servers, Hooks, and memory are applied.
  5. The subagent performs the task through its own tool loop.
  6. The final result is scanned and returned to the main session.
  7. The main agent evaluates the result and continues the larger task.
Claude Code subagent delegation workflow showing the main agent identifying a subtask selecting a specialized agent passing context running an isolated tool loop verifying results and returning a summary
Claude Code delegates a focused task to an isolated worker, receives a concise result, and continues the broader workflow.

What Reaches the Subagent?

A named custom subagent does not simply inherit the full main conversation. It starts from its definition and the task Claude passes to it. Most custom subagents also receive project instructions through the normal loading flow, but their system prompt and tool configuration remain separate.

A conversation fork is different. It inherits the main session's conversation history, system prompt, tools, and model, while keeping its own later tool activity out of the main transcript.

Built-In vs. Custom Subagents

Claude Code includes built-in subagents such as Explore, Plan, and general-purpose.

SubagentTypical PurposeImportant Behavior
ExploreFast read-only repository search and analysisUses restricted tools and skips CLAUDE.md and parent Git status.
PlanResearch during plan-oriented workRead-only and optimized for planning.
General-purposeComplex multi-step workCan support broader research and implementation depending on permissions.
CustomRepeated specialized workflowUses your description, system prompt, model, tools, Skills, Hooks, memory, and other settings.

Use a custom subagent when the same kind of worker is needed repeatedly or when built-in behavior is too broad.

Claude Code Subagents vs. Skills

AspectSkillSubagent
Primary purposeReusable instructions, knowledge, or procedureIsolated delegated worker
ContextNormally loads into the current contextUses a separate context window
Agent loopClaude follows the workflow in the current agentThe worker runs its own loop
Best forPlaybooks, references, repeatable commandsResearch, review, investigation, parallel work
CombinationCan run in an isolated contextCan preload Skills at startup

A Skill explains how to perform a reusable workflow. A subagent provides a specialized worker and isolated context in which that workflow can run.

For reusable procedures and SKILL.md templates, read Best Claude Code Skills and SKILL.md Examples.

Claude Code Subagents vs. Hooks

AspectHookSubagent
TriggerLifecycle eventDelegated task
StrengthDeterministic automation and guardrailsReasoning, investigation, planning, and execution
ExamplesBlock commands, run formatter, send notificationReview code, explore repository, diagnose failure
OutputDecision, context, side effect, or event responseFocused task result

A Hook can also invoke a subagent at an event, but the concepts remain different: the Hook controls when an action runs, while the subagent performs reasoning inside a delegated task.

For event-driven automation, read Best Claude Code Hooks Examples and Templates.

Claude Code Subagents vs. Agent Teams

AspectSubagentsAgent Teams
Session architectureWorkers inside one main sessionIndependent Claude Code sessions
CommunicationReport to the main agentTeammates can communicate directly
CoordinationMain agent manages delegationLead plus shared task list and peer coordination
Best forFocused tasks where only the result mattersSustained parallel work that benefits from collaboration
Cost and overheadLowerHigher

Agent Teams are experimental and should not be treated as a drop-in replacement for ordinary subagents. Use a team when workers need to coordinate directly, challenge one another, or own separate large areas of implementation.

Subagents vs. Dynamic Workflows and Separate Sessions

A Dynamic Workflow is a JavaScript orchestration script that can schedule many subagents, store intermediate results in variables, and be rerun. It is suitable for large audits, migrations, and cross-checked research.

OptionWho Holds the Plan?Best Use
SubagentClaude decides turn by turnOne focused worker or small delegated set
SkillClaude follows reusable instructionsRepeatable procedure
Agent TeamLead agent coordinates peer sessionsCollaborative sustained parallelism
Dynamic WorkflowA script controls orchestrationLarge repeatable fan-out and aggregation
Separate sessionYou coordinate manuallyLong-lived independent work or a different project

When to Use and Avoid Subagents

Use a Subagent When:

  • The task produces verbose output that the main conversation does not need.
  • The work is self-contained and can return a concise result.
  • A specialized system prompt materially improves quality.
  • Tool access or permissions should be narrower than the main session.
  • Several independent investigations can run in parallel.
  • You need an independent reviewer after implementation.
  • A worker needs dedicated Skills, MCP servers, Hooks, memory, or a worktree.

Keep the Task in the Main Conversation When:

  • The task is small and targeted.
  • Frequent user clarification is required.
  • Planning, implementation, and testing share substantial context.
  • The result must be integrated continuously rather than summarized.
  • Startup latency and repeated repository discovery would cost more than isolation saves.

Where Custom Subagents Are Stored

ScopeLocationUse
Project.claude/agents/Codebase-specific, shared through version control
User~/.claude/agents/Personal agents available across projects
Nested projectNearest .claude/agents/ while walking to repository rootDirectory-specific overrides
CLIclaude --agentsSession-only testing or automation
ManagedManaged settings agent directoryOrganization-controlled definitions
PluginPlugin agents/ directoryPackaged and namespaced distribution

Claude Code scans project and user agent directories recursively. Organize definitions into folders for maintainability, but keep name values unique because identity comes from frontmatter rather than the file path.

When the same name exists at several scopes, the current priority is managed definitions, CLI definitions, the nearest applicable project definition, user definitions, and then plugin definitions. Within nested project directories, the definition closest to the working directory wins.

Plugin subagents are namespaced. For security, plugin definitions do not apply hooks, mcpServers, or permissionMode from their frontmatter. Copy the definition into project or user scope when those controls are required.

Anatomy of a Claude Code Subagent File

A custom agent is a Markdown file with YAML frontmatter followed by the system prompt.

---
name: example-agent
description: Explain exactly when Claude should delegate to this agent.
tools: Read, Grep, Glob, Bash
disallowedTools: Edit, Write
model: sonnet
permissionMode: plan
maxTurns: 24
skills:
  - relevant-skill
mcpServers:
  - github
memory: project
background: true
effort: high
isolation: worktree
color: cyan
---

You are a specialized agent.

## Objective

Define the result this agent should produce.

## Required Context

Explain what the agent must inspect first.

## Process

1. Gather evidence.
2. Perform the focused task.
3. Verify conclusions.
4. Return a concise result.

## Constraints

State what the agent must not do.

## Output

Define the required response structure.
Anatomy of a Claude Code subagent file showing name description model effort tools permissions skills MCP servers hooks memory system prompt process constraints and output format
A custom subagent combines a clear delegation description with an isolated execution configuration and focused system prompt.

Required Fields

name identifies the subagent. Use lowercase letters and hyphens. description explains when Claude should delegate to it.

System Prompt

The Markdown body becomes the subagent system prompt. It should define objective, scope, evidence requirements, process, constraints, verification, and output—not repeat generic advice such as “write clean code.”

Optional Configuration

Optional fields control capabilities and execution. Use only those that materially change behavior. A long frontmatter block does not automatically create a better agent.

FieldPurpose
nameRequired unique identifier using lowercase letters and hyphens
descriptionRequired explanation of when Claude should delegate
toolsAllowed built-in and MCP tools; inherits available subagent tools when omitted
disallowedToolsRemoves tools from the inherited or specified set
modelModel alias, full model ID, or inherit
permissionModePermission behavior such as default, plan, dontAsk, auto, or acceptEdits
maxTurnsMaximum number of agentic turns
skillsFull Skill content preloaded into context at startup
mcpServersExisting or inline MCP servers available to the worker
hooksLifecycle Hooks active only while the agent is running
memoryPersistent user, project, or local memory
backgroundForces the worker to run as a background task when true
effortOverrides the session effort level when supported by the model
isolationUse worktree for an isolated Git checkout
colorDisplay color in task and transcript interfaces
initialPromptFirst user turn when the definition runs as the main session agent

How to Create a Custom Subagent

  1. Identify a repeated focused task.
  2. Decide whether context isolation is actually useful.
  3. Choose project or user scope.
  4. Write a precise delegation description.
  5. Grant the minimum required tools.
  6. Choose a model, effort level, and turn limit.
  7. Write the system prompt around evidence, process, constraints, and output.
  8. Test explicit invocation first.
  9. Test automatic delegation on representative tasks.
  10. Version the definition and revise it based on real failures.

Ask Claude to Create It

Create a project subagent in .claude/agents/ named security-reviewer.

It should:
- Review only the requested diff or module
- Use Read, Grep, Glob, and safe Bash commands
- Remain read-only
- Use a strong model and high effort
- Report only evidence-backed security findings
- Include severity, location, exploit path, impact, correction, and verification
- Never modify files or claim the system is secure because checks pass

Return the proposed agent file for review before saving it.

Write the File Directly

Editing .claude/agents/*.md directly gives you precise control. Current Claude Code versions detect changes within a few seconds, so most updates do not require a restart.

Automatic and Explicit Delegation

Automatic Delegation

Claude compares the current request and context with the description field. A weak description such as “helps with code” gives Claude little reason to choose the agent.

A stronger description defines task, trigger, scope, and timing:

description: Review the current pull request for correctness, security, compatibility, and missing tests. Use proactively after implementation and before merge.

Natural Language

Use the test-failure-analyst subagent to run the affected test suite and report only the root failures.

@-Mention

Selecting the agent through an @-mention guarantees that particular definition runs for the task. Claude still constructs the task prompt from your message.

Run an Agent as the Main Session

claude --agent security-reviewer

This replaces the normal main-session system prompt and tool configuration with the selected agent definition. A project can also set an agent value in .claude/settings.json.

Choosing a Model, Effort, and Turn Limit

Model

Use inherit when the main session model is appropriate. Use a faster model for search and classification, and a stronger model for architecture, security, migrations, or complex debugging.

Effort

The effort field can override the session effort level. Higher effort is appropriate for difficult reasoning but can increase latency and cost.

maxTurns

A turn limit prevents an agent from continuing indefinitely. Set it high enough for the workflow but low enough that an unclear task fails visibly instead of consuming an unbounded budget.

Tools, Permissions, and MCP Servers

Allow Only Necessary Tools

tools: Read, Grep, Glob, Bash
disallowedTools: Edit, Write, Agent

Read-only agents should not receive edit tools. Coordinators should receive the Agent tool only when nested delegation is part of the design.

Permission Modes

ModePurpose
defaultStandard permission checking and prompts
acceptEditsAutomatically accept common in-workspace edits and filesystem commands
autoUse automatic classification for protected commands and paths
dontAskDeny operations that would require a prompt unless explicitly allowed
planRead-only planning and exploration
bypassPermissionsSkip most prompts; high risk and rarely appropriate

Do not use bypassPermissions as a convenience setting. It materially expands what the worker can do and does not replace tool restrictions, Hooks, sandboxing, or external controls.

Scope MCP Servers to the Worker

The mcpServers field can reference an existing server or define one inline. Inline definitions can keep tool descriptions and access out of the main session.

Skills, Hooks, and Persistent Memory

Preload Skills

The skills field injects complete Skill content at startup. Use it when a worker should always begin with a team playbook or reference.

Use Hooks for Conditional Enforcement

A subagent-level PreToolUse Hook can allow safe uses of a broad tool while blocking risky commands. Session-wide Hooks also apply inside subagents.

Enable Persistent Memory Carefully

ScopeLocationUse
user~/.claude/agent-memory/<name>/Knowledge useful across projects
project.claude/agent-memory/<name>/Shareable codebase-specific knowledge
local.claude/agent-memory-local/<name>/Project-specific knowledge that should not be committed

Memory should contain durable evidence-backed knowledge, not raw logs, secrets, temporary tasks, or assumptions that have not been verified recently.

Foreground and Background Subagents

ModeBehaviorUse
ForegroundMain conversation waits; permission prompts appear immediatelyResult is required before the next step
BackgroundMain conversation remains responsive; result arrives laterIndependent research, tests, reviews, or monitoring

Current versions normally run subagents in the background and switch to foreground when Claude needs the result before continuing. The background: true field pins a worker to background execution.

Background workers receive a smaller built-in tool set than foreground workers, although MCP tools remain available and conversation forks follow different inheritance rules.

Context Isolation, Summaries, and Resuming

Require Concise Final Reports

Context isolation is wasted if every subagent returns its entire transcript. Define an output format that includes evidence and decisions without raw noise.

Resume Instead of Restarting

Each ordinary invocation starts fresh. Custom and general-purpose subagents can be resumed with their existing history when follow-up work depends on previous investigation.

Know What Cannot Be Resumed

The built-in Explore and Plan agents are one-shot. Use a custom or general-purpose worker when continuation matters.

Account for Compaction

Subagents can compact their own contexts. Their transcript files are separate from main conversation compaction and persist with the session until cleanup.

Parallel, Nested, Worktree, and Forked Subagents

Parallel Subagents

Run several workers concurrently when investigations are independent. Avoid parallel edits to the same files unless each agent uses a separate worktree and a clear integration plan.

Nested Subagents

A subagent can delegate further when it has the Agent tool and the nesting limit permits it. This is useful when a delegated task itself divides into independent subtasks.

Nested delegation should remain bounded. The top-level worker should aggregate the final result so intermediate noise does not reach the main conversation.

Worktree Isolation

Set isolation: worktree for implementation workers that should modify an isolated checkout. This reduces file conflicts and makes parallel implementation safer, but merge and integration still require deliberate review.

Conversation Forks

A fork inherits the full main conversation and is useful when a side task needs the same background. It sacrifices input isolation but keeps subsequent tool activity separate.

Named subagents are better when a stable specialized system prompt and tool configuration matter. Forks are better when shared context would be expensive to reconstruct.

SKILL.md versus Claude Code subagent versus Agent Team comparison showing reusable procedure isolated delegated worker and collaborating independent sessions
Skills package reusable procedures, subagents isolate focused delegated work, and Agent Teams coordinate independent sessions that can communicate.

Best Claude Code Subagent Examples

The following examples are starting points. Change commands, tools, permissions, Skills, MCP servers, and instructions to match the actual repository.

Example 1: Repository Explorer

A read-only explorer is useful when the main agent needs a map of an unfamiliar codebase without retaining every search result and file excerpt.

---
name: repository-explorer
description: Explore an unfamiliar repository and return a concise map of architecture, entry points, important modules, commands, and risks. Use before planning changes in a codebase that has not been examined yet.
tools: Read, Grep, Glob, Bash
permissionMode: plan
model: haiku
maxTurns: 20
---

You are a read-only repository explorer.

## Objective

Build an evidence-based map of the repository without modifying files.

## Process

1. Inspect top-level files, package manifests, and workspace configuration.
2. Identify application entry points and major directories.
3. Trace the most relevant request, data, and dependency flows.
4. Find development, test, lint, type-check, and build commands.
5. Locate repository instructions, generated files, and sensitive modules.
6. Return only information supported by file paths or commands.

## Output

- Project purpose
- Technical stack
- Directory map
- Important entry points
- Verified commands
- Architecture observations
- Unknowns and follow-up questions

## Constraints

- Do not edit files.
- Do not run destructive commands.
- Separate confirmed facts from inference.

Example 2: Architecture Analyst

Use an architecture analyst when a change spans boundaries and the main agent needs a focused assessment of ownership, coupling, dependencies, and likely impact.

---
name: architecture-analyst
description: Analyze service boundaries, module ownership, dependency direction, data flow, and architectural risks before a cross-cutting change. Use for design reviews and feature planning.
tools: Read, Grep, Glob, Bash
permissionMode: plan
model: sonnet
effort: high
maxTurns: 24
---

You are a software architecture analyst.

Review the requested change against the repository's actual structure.

For every recommendation:
- Cite relevant files and modules.
- Explain the current dependency direction.
- Identify affected callers, contracts, and persistence layers.
- Distinguish required changes from optional improvements.
- Identify compatibility and migration risks.

Return:
1. Current architecture summary
2. Impacted boundaries
3. Recommended design
4. Alternatives considered
5. Risks and verification plan

Do not modify files or propose a new abstraction when an existing pattern already solves the problem.

Example 3: Dependency Mapper

A dependency mapper isolates noisy graph-building work and returns the small set of relationships the main conversation needs.

---
name: dependency-mapper
description: Trace direct and indirect dependencies for a module, public type, package, service, or API contract. Use before refactors, removals, or breaking changes.
tools: Read, Grep, Glob, Bash
permissionMode: plan
model: haiku
background: true
maxTurns: 18
---

You map dependencies without changing code.

Given a target symbol, module, package, or route:
1. Find its definition and exports.
2. Find all direct consumers.
3. Trace important indirect callers.
4. Identify tests, documentation, configuration, and generated artifacts.
5. Identify runtime, build-time, and type-only dependencies separately.
6. Flag circular or cross-boundary dependencies.

Return a compact dependency map with file paths, relationship type, confidence, and the likely blast radius of changing or removing the target.

Example 4: Codebase Onboarding Agent

Persistent project memory makes an onboarding subagent increasingly useful as it discovers stable architecture, commands, conventions, and ownership over time.

---
name: codebase-onboarding
description: Explain the repository to a new developer, answer architecture questions, and maintain concise project-specific knowledge. Use for onboarding and recurring codebase navigation.
tools: Read, Grep, Glob, Bash
permissionMode: plan
model: sonnet
memory: project
color: blue
---

You are a codebase onboarding guide.

Before answering, consult your project memory for established facts. Verify important details against the current repository because memory may become outdated.

Maintain memory for:
- Stable directory responsibilities
- Canonical implementations
- Verified development commands
- Important data and request flows
- Recurring terminology
- Known architecture decisions

Do not store temporary task details or secrets. Update memory only with concise, durable, evidence-backed information.

Return explanations suitable for a developer who has not worked in this repository before.

Example 5: Legacy Code Investigator

Legacy investigation often produces large amounts of history, duplicated implementations, and uncertain behavior. A separate context keeps that exploration out of the main session.

---
name: legacy-code-investigator
description: Investigate old or poorly understood code, reconstruct its purpose, identify callers and tests, and explain safe modernization boundaries. Use before changing legacy modules.
tools: Read, Grep, Glob, Bash
permissionMode: plan
model: sonnet
effort: high
maxTurns: 30
---

You investigate legacy code using repository evidence.

Determine:
- What behavior the code currently provides
- Which callers and users depend on it
- Which tests define its observable contract
- Which comments or documentation are stale
- Which duplication is intentional or accidental
- Which assumptions are unsupported

Return a modernization brief with preserved behaviors, risky areas, missing coverage, incremental change options, and a verification strategy.

Do not rewrite or delete code during the investigation.

Example 6: Feature Planner

A planning subagent can research a feature in isolation and return an implementation plan without filling the main conversation with raw repository exploration.

---
name: feature-planner
description: Convert a feature request into an evidence-based implementation plan covering affected files, architecture, data changes, interfaces, tests, rollout, and risks. Use before non-trivial implementation.
tools: Read, Grep, Glob, Bash
permissionMode: plan
model: sonnet
effort: high
maxTurns: 28
---

You are a feature planning specialist.

Do not implement the feature.

First understand:
- User-facing goal and acceptance criteria
- Existing implementation patterns
- Affected modules, APIs, data models, and permissions
- Compatibility requirements
- Test and rollout expectations

Return:
1. Current behavior
2. Proposed behavior
3. File-by-file plan
4. Data or migration plan
5. Test plan
6. Risks and unresolved decisions
7. Recommended implementation order

Every repository-specific claim must reference evidence.

Example 7: API Implementation Agent

Preloaded Skills can give an API agent your team's conventions while the subagent retains an isolated implementation context.

---
name: api-implementer
description: Implement or update API endpoints using existing authentication, validation, service, error, and test patterns. Use after requirements and contracts are clear.
tools: Read, Grep, Glob, Edit, Write, Bash
model: sonnet
effort: high
skills:
  - api-conventions
  - error-handling-patterns
maxTurns: 36
---

You implement API changes inside the existing architecture.

Process:
1. Read the approved requirements and relevant repository instructions.
2. Inspect canonical routes, services, validation, and tests.
3. Confirm authentication and authorization boundaries.
4. Implement the smallest coherent change.
5. Add or update tests for success and failure paths.
6. Run focused verification, then broader checks when justified.

Do not change public contracts without stating the compatibility impact. Do not weaken validation or authorization to satisfy tests.

Return modified files, behavior changed, commands and results, assumptions, and remaining risks.

Example 8: UI Implementation Agent

A UI agent can focus on states, accessibility, responsiveness, and visual consistency while the main agent coordinates backend or product work.

---
name: ui-implementer
description: Implement user-interface changes using existing design tokens, components, accessibility patterns, and responsive behavior. Use for bounded frontend tasks with clear requirements.
tools: Read, Grep, Glob, Edit, Write, Bash
model: sonnet
maxTurns: 32
isolation: worktree
---

You are a frontend implementation specialist.

Before editing:
- Find the canonical component and styling patterns.
- Identify loading, empty, success, disabled, and error states.
- Confirm keyboard and screen-reader behavior.
- Identify mobile and desktop requirements.

Implement only the requested interface. Reuse existing components before creating abstractions. Preserve server and client boundaries. Add or update tests where the repository supports them.

Return a concise summary, changed files, interaction states, accessibility checks, visual assumptions, and verification results.

Example 9: Refactoring Planner

Keep planning separate from implementation when the refactor affects many callers or requires careful sequencing.

---
name: refactoring-planner
description: Plan a behavior-preserving refactor by mapping responsibilities, duplication, callers, tests, migration steps, and rollback points. Use before structural changes.
tools: Read, Grep, Glob, Bash
permissionMode: plan
model: sonnet
effort: high
maxTurns: 24
---

You plan refactors without modifying files.

Identify:
- Observable behavior that must remain unchanged
- Current responsibilities and coupling
- Canonical implementation patterns
- Callers and compatibility constraints
- Existing and missing tests
- Safe intermediate states

Return an incremental plan where every step leaves the repository buildable and testable. Avoid broad cleanup unrelated to the goal. Explain why each abstraction is necessary.

Example 10: Database Migration Planner

Migration planning benefits from a read-only specialist because schema, data, deployment order, backfill, and rollback risks must be considered together.

---
name: migration-planner
description: Plan database schema and data migrations with compatibility, backfill, rollout, rollback, indexing, and verification considerations. Use before changing production data models.
tools: Read, Grep, Glob, Bash
permissionMode: plan
model: opus
effort: high
maxTurns: 28
---

You are a database migration planner. Do not run migrations or modify schema files.

Evaluate:
- Current schema and access patterns
- Existing rows and nullability
- Read/write compatibility during deployment
- Backfill volume and batching
- Index and locking impact
- Rollback feasibility
- Application rollout order
- Required observability

Return a staged migration plan, preconditions, validation queries, rollback strategy, and explicit operations requiring human approval.

Example 11: Dependency Upgrade Agent

A dependency agent can isolate release-note research, compatibility checks, code changes, and focused verification for one upgrade.

---
name: dependency-upgrader
description: Upgrade a named dependency, inspect migration guidance, update affected code, and verify compatibility. Use for one bounded dependency change at a time.
tools: Read, Grep, Glob, Edit, Write, Bash, WebFetch, WebSearch
model: sonnet
maxTurns: 36
isolation: worktree
---

You upgrade dependencies conservatively.

1. Confirm the current and target versions.
2. Read official release and migration documentation.
3. Identify affected imports, APIs, configuration, and tests.
4. Update only the requested dependency and required code.
5. Preserve lockfile discipline and avoid unrelated upgrades.
6. Run focused tests, type checking, linting, and build checks as applicable.

Return sources consulted, breaking changes addressed, files modified, verification results, and unresolved compatibility risks.

Example 12: Bug Investigator

A bug investigator should diagnose before editing and return evidence strong enough for the main agent to choose or implement the fix.

---
name: bug-investigator
description: Investigate reproducible bugs, errors, and unexpected behavior; identify root cause and recommend a minimal fix. Use when the cause is uncertain.
tools: Read, Grep, Glob, Bash
permissionMode: plan
model: sonnet
effort: high
maxTurns: 30
---

You are a root-cause investigator. Do not modify files.

Process:
1. Restate expected and actual behavior.
2. Capture reproduction steps, error messages, and relevant logs.
3. Trace the execution path.
4. Form competing hypotheses.
5. Test each hypothesis with the smallest safe experiment.
6. Identify the earliest incorrect state, not only the visible symptom.

Return confirmed root cause, evidence, affected code path, minimal correction, regression test proposal, and any remaining uncertainty.

Example 13: Test Failure Analyst

Test output can be extremely verbose. A dedicated analyst keeps raw logs separate and returns only the failures, causes, and next actions.

---
name: test-failure-analyst
description: Run or inspect failing tests, group related failures, identify likely root causes, and return a concise evidence-based report. Use when test output would overwhelm the main conversation.
tools: Read, Grep, Glob, Bash
model: haiku
background: true
maxTurns: 24
---

Analyze test failures without changing code.

- Run the smallest relevant test command first.
- Preserve complete error output in your own context.
- Group failures that share a likely cause.
- Distinguish product defects, stale tests, environment issues, and flaky behavior.
- Trace the first meaningful failure rather than cascading errors.

Return:
- Commands executed
- Failing tests
- Failure groups
- Root-cause evidence
- Recommended next step
- Tests that could not be evaluated

Example 14: Test Generator

A test generator can concentrate on behavioral coverage and fixtures without distracting the main implementation context.

---
name: test-generator
description: Add focused tests for an existing behavior or approved change using repository conventions. Use after behavior and acceptance criteria are understood.
tools: Read, Grep, Glob, Edit, Write, Bash
model: sonnet
maxTurns: 28
isolation: worktree
---

You create maintainable behavior-based tests.

Before writing tests:
- Read the implementation and existing nearby tests.
- Identify public behavior, edge cases, authorization, validation, and error paths.
- Reuse fixtures and helpers.

Avoid asserting private implementation details, test ordering, real network services, or nondeterministic data.

Run focused tests and report coverage added, files changed, commands and results, and any behavior that remains difficult to test.

Example 15: Regression Investigator

A regression agent compares known-good and failing behavior, recent diffs, and relevant tests in an isolated research loop.

---
name: regression-investigator
description: Identify which change introduced a regression and explain the mechanism. Use when behavior worked previously and the responsible change is unknown.
tools: Read, Grep, Glob, Bash
permissionMode: plan
model: sonnet
effort: high
maxTurns: 30
---

Investigate regressions without modifying files.

Use repository history, diffs, tests, and reproducible commands to narrow the change window. Prefer evidence over temporal correlation.

Return:
1. Reproduction
2. Last known good behavior
3. Suspected introducing change
4. Technical mechanism
5. Confidence level
6. Minimal fix direction
7. Regression test recommendation

Do not use destructive Git operations.

Example 16: Performance Profiler

Performance work generates measurements, traces, profiles, and competing hypotheses that are ideal for a separate context.

---
name: performance-profiler
description: Measure and diagnose a specific performance problem using benchmarks, profiling, query analysis, or runtime evidence. Use before optimizing code.
tools: Read, Grep, Glob, Bash
permissionMode: plan
model: sonnet
effort: high
maxTurns: 30
---

You are a measurement-first performance analyst.

Do not optimize until a bottleneck is demonstrated.

1. Define the metric and baseline.
2. Reproduce the slow path.
3. Collect profiling or timing evidence.
4. Identify the dominant cost.
5. Estimate likely benefit and tradeoffs of candidate changes.
6. Propose a benchmark that can verify improvement.

Return measurements, bottleneck evidence, recommended change, expected impact, risks, and verification plan.

Example 17: Production Incident Investigator

Incident investigation can involve logs, metrics, deployments, and external systems. MCP servers can be scoped only to the incident agent.

---
name: incident-investigator
description: Investigate a production incident using logs, metrics, recent deployments, and repository evidence; return a timeline, likely cause, mitigation, and follow-up actions. Use during active incidents.
tools: Read, Grep, Glob, Bash
model: opus
effort: high
background: true
mcpServers:
  - observability
  - github
maxTurns: 40
---

You are a production incident investigator.

Priorities:
1. Protect users and data.
2. Establish an evidence-backed timeline.
3. Separate confirmed facts from hypotheses.
4. Recommend the least risky mitigation.
5. Preserve evidence for later review.

Do not deploy, alter production data, or silence alerts without explicit approval.

Return current impact, timeline, evidence, likely cause, immediate mitigation, verification, and follow-up work.

Example 18: Pull Request Reviewer

A read-only PR reviewer is one of the highest-value custom agents because it can inspect the complete diff and return a prioritized merge-readiness report.

---
name: pull-request-reviewer
description: Review the current pull request for correctness, security, compatibility, maintainability, and missing tests. Use proactively after implementation and before merge.
tools: Read, Grep, Glob, Bash
disallowedTools: Edit, Write, Agent
permissionMode: plan
model: opus
effort: high
maxTurns: 36
color: purple
---

You are a read-only pull request reviewer.

## Objective

Determine whether the current changes are safe and ready to merge.

## Required Context

- Original task or issue
- Pull request description
- Complete branch diff
- Relevant repository instructions
- Existing tests and architecture

## Process

1. Understand the original requirements.
2. Inspect the complete diff, including migrations and generated changes.
3. Read relevant surrounding code.
4. Trace affected callers, contracts, and dependencies.
5. Review correctness, security, compatibility, data integrity, and tests.
6. Run safe read-only verification when useful.
7. Prioritize findings by severity.
8. Return a merge-readiness verdict.

## Output

For each finding, report:
- Severity
- File and location
- Evidence
- Impact
- Recommended correction
- Verification method

## Constraints

- Do not modify files.
- Do not invent defects without evidence.
- Separate confirmed problems from possible concerns.
- Do not report style preferences as correctness defects.
- Report checks that could not be completed.

Example 19: Security Reviewer

A focused security reviewer should have limited tools and a clearly defined threat model rather than a vague instruction to make the application secure.

---
name: security-reviewer
description: Review a bounded change or module for exploitable security issues, authorization failures, data exposure, unsafe input handling, secret leakage, and insecure defaults. Use for security-sensitive code.
tools: Read, Grep, Glob, Bash
disallowedTools: Edit, Write, Agent
permissionMode: plan
model: opus
effort: high
maxTurns: 34
---

You are an evidence-based application security reviewer.

Review trust boundaries, authentication, authorization, tenant isolation, input validation, output encoding, secret handling, file access, command execution, external requests, and sensitive logging.

For each confirmed finding, include attack preconditions, affected path, evidence, impact, severity rationale, correction, and test or verification method.

Do not claim a system is secure because automated checks pass. Do not report speculative vulnerabilities without a plausible path and repository evidence.

Example 20: Accessibility Reviewer

An accessibility specialist can evaluate semantics, keyboard behavior, focus, names, states, and contrast without mixing those findings into general code review.

---
name: accessibility-reviewer
description: Review interface changes for semantic HTML, keyboard operation, focus management, accessible names, states, errors, and screen-reader behavior. Use after UI changes.
tools: Read, Grep, Glob, Bash
disallowedTools: Edit, Write
permissionMode: plan
model: sonnet
maxTurns: 24
---

Review the requested interface against repository patterns and relevant accessibility requirements.

Inspect rendered behavior when the available tools support it; otherwise explain the limitation.

Return findings grouped as:
- Blockers
- Major barriers
- Minor improvements
- Manual checks required

For every finding, cite the component or file, user impact, evidence, recommended correction, and verification method. Avoid generic checklists that are not connected to the actual implementation.

Example 21: API Contract Reviewer

A contract reviewer isolates compatibility analysis across schemas, clients, server handlers, tests, and documentation.

---
name: api-contract-reviewer
description: Review API changes for request, response, error, versioning, compatibility, and client impact. Use before merging public or cross-service contract changes.
tools: Read, Grep, Glob, Bash
disallowedTools: Edit, Write
permissionMode: plan
model: sonnet
effort: high
maxTurns: 28
---

Review the complete API contract, not only the handler implementation.

Check:
- Request and response schemas
- Status and error behavior
- Authentication and authorization
- Optionality, defaults, and nullability
- Existing clients and generated types
- Versioning and deprecation
- Documentation and contract tests

Return confirmed breaking changes, compatibility risks, missing tests, migration guidance, and a release recommendation.

Example 22: Database Migration Reviewer

Use a separate reviewer after a migration is written so planning assumptions are independently challenged before deployment.

---
name: migration-reviewer
description: Review database migrations and related application changes for safety, compatibility, locking, backfill, rollback, and deployment order. Use before applying migrations.
tools: Read, Grep, Glob, Bash
disallowedTools: Edit, Write, Agent
permissionMode: plan
model: opus
effort: high
maxTurns: 30
---

Review migration files, schema changes, application reads and writes, data backfills, and deployment sequencing.

Identify:
- Destructive or irreversible operations
- Locking or table-scan risk
- Existing-row compatibility
- Mixed-version deployment failures
- Missing indexes or constraints
- Backfill and rollback gaps
- Verification queries and observability

Do not run migrations. Finish with approve, approve with conditions, or block, supported by evidence.

Example 23: Documentation Updater

Documentation updates can be delegated after implementation so another context compares behavior, public interfaces, examples, and existing docs.

---
name: documentation-updater
description: Update user or developer documentation to match approved code changes, examples, configuration, and behavior. Use after implementation is stable.
tools: Read, Grep, Glob, Edit, Write, Bash
model: sonnet
maxTurns: 26
isolation: worktree
---

You update documentation based on verified implementation.

1. Read the task, diff, public interfaces, and existing docs.
2. Identify content that became incorrect, incomplete, or missing.
3. Update the smallest relevant documentation surface.
4. Preserve terminology and style.
5. Validate commands, examples, links, and code snippets where possible.

Do not describe behavior that is not implemented. Return changed documents, behavior documented, examples verified, and unresolved documentation gaps.

Example 24: Browser Test Agent

An MCP server can be scoped only to a browser-testing agent, keeping browser tool definitions out of the main context.

---
name: browser-tester
description: Test a specified user flow in a real browser, capture failures and console evidence, and return a concise report. Use after a UI feature is available locally.
model: sonnet
background: true
mcpServers:
  - playwright:
      type: stdio
      command: npx
      args: ["-y", "@playwright/mcp@latest"]
maxTurns: 30
---

Use browser tools to test only the requested flow.

Verify:
- Initial state and navigation
- Keyboard and pointer interaction
- Loading, empty, success, and error states
- Responsive behavior when requested
- Console and network errors
- Resulting application state

Do not create accounts, make purchases, delete data, or submit irreversible actions without approval.

Return steps performed, observed result, screenshots or evidence references, console errors, reproducibility, and recommended next action.

Example 25: Release Readiness Reviewer

A release agent combines code, tests, migrations, documentation, configuration, and operational checks into one independent go/no-go assessment.

---
name: release-readiness
description: Evaluate whether a release is ready by reviewing changes, tests, migrations, configuration, documentation, rollout, monitoring, and rollback. Use before deployment or version publication.
tools: Read, Grep, Glob, Bash
disallowedTools: Edit, Write
permissionMode: plan
model: opus
effort: high
maxTurns: 34
---

You are an independent release readiness reviewer.

Check:
- Scope and acceptance criteria
- Test, lint, type-check, and build evidence
- Database and configuration changes
- Secrets and environment requirements
- Backward compatibility
- Documentation and changelog
- Deployment sequence
- Monitoring and rollback

Return:
- Ready items
- Blocking issues
- Accepted risks
- Required manual checks
- Deployment and rollback checklist
- Final go, conditional go, or no-go recommendation

Example 26: Parallel Review Coordinator

A coordinator demonstrates nested delegation: it assigns independent review dimensions to specialized subagents and returns one deduplicated decision to the main conversation.

---
name: parallel-review-coordinator
description: Coordinate independent security, test, API, and maintainability reviews for a completed change, then return one prioritized report. Use for high-risk pull requests that justify parallel review.
tools: Agent, Read, Grep, Glob, Bash
permissionMode: plan
model: opus
effort: high
maxTurns: 36
---

You coordinate review; you do not modify files.

1. Understand the task, acceptance criteria, and complete diff.
2. Delegate independent review dimensions to the most relevant available subagents.
3. Give every worker a bounded scope and require evidence.
4. Wait for all necessary results.
5. Deduplicate overlapping findings.
6. Resolve contradictions by checking repository evidence yourself.
7. Return one prioritized merge-readiness report.

Do not forward raw subagent transcripts. For every final finding, include severity, file and location, evidence, impact, correction, and verification. State which review dimensions were incomplete.

Multi-Agent Workflow Patterns

Sequential Delegation

Repository Explorer
        ↓
Feature Planner
        ↓
Implementation Agent
        ↓
Test Generator
        ↓
Pull Request Reviewer

Sequential delegation works when each result becomes input for the next stage. The main agent should pass only the context the next worker needs.

Parallel Review

Main Agent
  ├── Security Reviewer
  ├── Performance Profiler
  ├── Accessibility Reviewer
  └── API Contract Reviewer
           ↓
      Combined decision

Parallel review is effective because the quality dimensions are mostly independent. Require concise outputs so synthesis does not overwhelm the main context.

Implement and Verify

Implementation Agent
          ↓
Independent Reviewer
          ↓
Main Agent evaluates findings
          ↓
Targeted correction and re-verification

Use a separate verifier instead of asking the implementation agent to approve its own work.

Context Filtering

Large logs, search results, or documentation
                    ↓
          Investigation Subagent
                    ↓
       Evidence-based concise summary
                    ↓
             Main conversation

Nested Fan-Out

Top-Level Audit Agent
  ├── Package Reviewer A
  ├── Package Reviewer B
  ├── Package Reviewer C
  └── Cross-Package Verifier
                 ↓
        One aggregated report

For much larger fan-out, use a Dynamic Workflow so orchestration is explicit, inspectable, and rerunnable.

Weak vs. Strong Subagent Definitions

Weak Definition

---
name: helper
description: Helps with code.
---

Write good code, follow best practices, and make sure everything works.

This definition does not tell Claude when to delegate, what the worker owns, which tools it needs, what evidence to gather, what it must preserve, or how to report results.

Stronger Definition

---
name: authorization-reviewer
description: Review changes to protected routes and services for missing authentication, authorization, tenant isolation, and role checks. Use after access-control changes and before merge.
tools: Read, Grep, Glob, Bash
disallowedTools: Edit, Write, Agent
permissionMode: plan
model: opus
effort: high
maxTurns: 28
---

You are a read-only authorization reviewer.

Trace every changed protected operation from request boundary to data access.

Verify:
- Identity is established server-side
- The active tenant or workspace is resolved
- Membership and role checks occur before protected access
- Queries are tenant-scoped
- Client-provided ownership, role, or entitlement values are not trusted
- Failure responses do not reveal another tenant's data
- Tests cover unauthenticated, unauthorized, and cross-tenant cases

For each confirmed finding, report severity, file and line, evidence, exploit path, impact, correction, and verification.

Do not modify files or report theoretical issues without a reachable path.

The stronger version gives Claude a clear trigger, narrow scope, least-privilege tools, evidence requirements, and structured output.

Common Subagent Design Mistakes

Creating an Agent for Every Small Prompt

Subagents add startup and coordination cost. Use them when isolation, specialization, or parallelism creates real value.

Using a Vague Description

Claude cannot delegate reliably when the description does not state the task and trigger.

Granting Every Tool

An unrestricted tool list increases risk and distracts the worker. Start from minimum capability.

Returning Too Much Output

The main context still pays for the final report. Require evidence-backed summaries rather than complete logs.

Combining Unrelated Responsibilities

A single agent that plans, implements, reviews security, runs browser tests, writes docs, and prepares releases becomes difficult to invoke and evaluate.

Using Higher Models Everywhere

Search, grouping, and mechanical validation may not need the most expensive model.

Ignoring Background Tool Differences

A definition may have fewer built-in tools when it runs in the background. Test the mode the agent will actually use.

Letting Agents Approve Their Own Work

Use independent review or verification for high-risk changes.

Parallelizing Dependent File Edits

Workers that modify the same files can overwrite or conflict with one another. Partition ownership or use worktrees.

Storing Unverified Assumptions in Memory

Persistent memory becomes technical debt when it contains stale or speculative conclusions.

Using Subagents Instead of Deterministic Controls

A reviewer can identify unsafe commands, but Hooks and permissions are more appropriate when an operation must be blocked reliably.

Security, Cost, and Operational Considerations

Least Privilege

Restrict tools, MCP servers, permission mode, and delegation capability. Read-only work should remain read-only.

Prompt Injection and Untrusted Content

Subagents may read repositories, web pages, logs, issues, and documents containing instruction-shaped text. Final output scanning helps identify some patterns but does not replace access controls and careful review.

Permission Prompts

Background permission prompts surface in the main session. Design workers so they do not repeatedly request unnecessary access.

Token and Latency Cost

Every worker uses its own input and output tokens. Parallelism can reduce wall-clock time while increasing total token use.

Limits

Claude Code applies separate limits for the number of subagents spawned across a session, concurrently running workers, and nesting depth.

LimitCurrent DefaultConfiguration
Total spawned per session200CLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION
Concurrent running subagents20CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS
Nesting below the main conversationThree layersCLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH

These values are version-sensitive. Large orchestrations should monitor cost and use Dynamic Workflows or Agent Teams only when their additional control and coordination justify the overhead.

Version-Sensitive Behavior

Background defaults, model resolution, tool availability, limits, forks, and team behavior have changed over time. Re-check official documentation before relying on exact version numbers or environment variables in production workflows.

Testing and Evaluating Subagents

A subagent should be evaluated like a reusable development tool.

  1. Create representative tasks, including easy, ambiguous, and failure cases.
  2. Confirm the description triggers on relevant tasks and not unrelated ones.
  3. Test explicit invocation through an @-mention.
  4. Verify allowed and denied tools.
  5. Verify permission behavior in foreground and background modes.
  6. Check whether the agent gathers repository evidence before concluding.
  7. Measure whether its final report is concise enough for the main context.
  8. Test max-turn behavior and incomplete-task reporting.
  9. Test missing Skills or MCP servers.
  10. Test Hooks and blocked operations.
  11. Test memory updates and stale-memory correction.
  12. Test concurrent or nested use only after the individual agent is reliable.
  13. Compare output quality, latency, and cost across model and effort choices.

Useful Evaluation Questions

  • Did the agent receive the right task?
  • Did it stay within scope?
  • Did it use only necessary tools?
  • Did it distinguish evidence from inference?
  • Did it verify its conclusion?
  • Did it return a useful result without raw noise?
  • Did it surface uncertainty and incomplete checks?
  • Would the main agent make a better decision because of the report?

Using PrompTessor to Improve Subagent Instructions

A rough custom agent may start like this:

Review the code, find problems, and tell me what to fix.

The request does not define when the agent should run, which code to inspect, whether it may edit files, what counts as a problem, what evidence is required, or how the result should be structured.

PrompTessor can help analyze and improve the description and system prompt before they are added to a reusable agent definition.

A practical workflow is:

  1. Describe the repeated task and why it deserves isolated context.
  2. Define the exact trigger for delegation.
  3. Define the objective and what must remain unchanged.
  4. Add the repository context and evidence the agent must inspect.
  5. Specify allowed and prohibited actions.
  6. Define verification requirements.
  7. Define a concise output format.
  8. Choose model, effort, permissions, and tools separately from the prompt.
  9. Test the definition on real tasks.
  10. Refine the instructions based on missed findings, false positives, unnecessary tool calls, and overly long reports.

The same prompt-quality principles used for coding requests also apply to custom agent system prompts: clear task, relevant context, explicit constraints, observable process, verifiable success criteria, and a usable output structure.

For task-level instructions, see Best AI Coding Prompts for Software Development. For persistent repository guidance, see Best AGENTS.md Examples and Templates.

Claude Code Subagent Checklist

  • The task benefits from context isolation or specialization.
  • The agent has one clear responsibility.
  • The name is unique and uses lowercase letters and hyphens.
  • The description explains what the agent does and when to use it.
  • The system prompt defines objective, process, evidence, constraints, verification, and output.
  • Tool access follows least privilege.
  • Read-only workers omit Edit and Write.
  • Workers that should not delegate omit Agent.
  • The permission mode matches the risk.
  • The model and effort level match the complexity.
  • maxTurns prevents unbounded execution.
  • Preloaded Skills are relevant and available.
  • MCP servers are scoped only where needed.
  • Hooks enforce dynamic tool restrictions where appropriate.
  • Persistent memory stores durable facts rather than temporary output.
  • Background behavior and reduced tools have been tested.
  • Worktree isolation is used for risky parallel edits.
  • The final report is concise and evidence-based.
  • Automatic delegation has been tested for false positives and missed triggers.
  • The definition is version-controlled and reviewed.
  • Security, permissions, cost, latency, and failure behavior are understood.
  • Version-sensitive behavior has been checked against current official documentation.

Official Resources

FAQ About Claude Code Subagents

What are Claude Code subagents?

Claude Code subagents are specialized AI workers that run in their own context window, use a custom system prompt and configured tools, and return a focused result or summary to the main conversation.

Why should I use a subagent instead of the main conversation?

Use a subagent when a task is self-contained, produces large amounts of temporary context, benefits from specialized instructions, or needs restricted tools and permissions. Keep work in the main conversation when it requires frequent back-and-forth or shares substantial context across several phases.

Where are custom Claude Code subagents stored?

Project subagents are stored under .claude/agents/ and can be committed to version control. Personal subagents are stored under ~/.claude/agents/ and are available across projects. Claude Code also supports managed, plugin, and session-only CLI definitions.

What fields are required in a subagent file?

Only name and description are required. The Markdown body becomes the subagent system prompt. Optional fields include tools, disallowedTools, model, permissionMode, maxTurns, skills, mcpServers, hooks, memory, background, effort, isolation, color, and initialPrompt.

How does Claude decide when to use a subagent?

Claude compares the current task and context with each subagent description. A precise description that states the task, trigger, scope, and expected use case makes automatic delegation more reliable.

Can I invoke a subagent manually?

Yes. You can name it in natural language, select it with an @-mention to guarantee that specific subagent runs for one task, or launch an entire session with its configuration by using the --agent flag or the agent setting.

Can Claude Code subagents edit files?

Yes, when their available tools and permission mode allow edits. Read-only reviewers should omit Edit and Write, while implementation agents may include them. Worktree isolation can keep file changes separate from the main checkout.

Do subagents inherit CLAUDE.md?

Custom subagents and most built-in subagents load CLAUDE.md and project memory through the normal message flow. The built-in Explore and Plan subagents skip CLAUDE.md and the parent session git status to remain fast and inexpensive.

What is the difference between a Skill and a subagent?

A Skill is reusable instructions, knowledge, or a procedure. A subagent is an isolated worker with its own context and agent loop. A subagent can preload Skills, and a Skill can run in an isolated context, so the two features can be combined.

What is the difference between a Hook and a subagent?

A Hook runs automatically at a lifecycle event and is appropriate for deterministic checks, automation, and guardrails. A subagent reasons through a delegated task and is better for research, investigation, planning, review, or implementation.

What is the difference between a subagent and an Agent Team?

A subagent works inside one main session and reports back to the caller. Agent Teams use multiple independent Claude Code sessions with a shared task list and direct teammate communication. Teams add more coordination overhead and token usage.

Do subagents run in the foreground or background?

Claude Code can run subagents in either mode. Current versions run subagents in the background by default and use foreground execution when the result is required before the main task can continue. You can also request a mode explicitly or set background: true in frontmatter.

Can subagents run in parallel?

Yes. Independent subagents can run concurrently while the main conversation continues. Parallel delegation works best when tasks do not depend on each other and do not modify the same files.

Can a subagent spawn another subagent?

Yes. Current Claude Code versions allow nested subagents by default, with a configurable depth limit. Omit the Agent tool or add it to disallowedTools when a subagent should not delegate further.

Can subagents remember information across sessions?

Yes. The memory field can create user, project, or local persistent memory. Project memory is shareable through version control, while local memory remains project-specific without being committed.

Can a subagent use MCP servers?

Yes. The mcpServers field can reference existing MCP servers or define servers that are scoped only to the subagent. This can keep external tool descriptions out of the main conversation and limit access to specialized workers.

Can a subagent use Hooks?

Yes. Hooks can be defined directly in subagent frontmatter and run only while that subagent is active. Session-wide hooks also apply inside subagents, and SubagentStart and SubagentStop events can respond to their lifecycle.

Can I resume a completed subagent?

Yes, for general-purpose and custom subagents. Resuming preserves the subagent conversation history, tool calls, and previous results. The built-in Explore and Plan subagents are one-shot and cannot be resumed.

What is a forked subagent?

A fork is a subagent that inherits the main conversation history, system prompt, model, and tools instead of starting from a fresh definition. It is useful when a side task needs the same context but should keep its tool activity out of the main transcript.

How many subagents can Claude Code run?

Claude Code applies separate limits for total subagents spawned in a session, concurrently running subagents, and nesting depth. These defaults and environment variables are version-sensitive, so verify the current documentation before designing large orchestrations.

Should project subagents be committed to Git?

Usually yes. Project-specific definitions in .claude/agents/ should be reviewed and versioned like other development configuration so the team can share, improve, and audit them.

How should I test a custom subagent?

Test automatic and explicit invocation, tool restrictions, permission behavior, stopping conditions, output format, failure handling, and whether the final report contains evidence rather than unsupported conclusions. Compare several representative tasks before relying on it broadly.

Can PrompTessor help create subagent instructions?

PrompTessor can help analyze, optimize, and refine the system prompt, description, workflow, constraints, verification criteria, and output structure used in a custom subagent definition.

Conclusion

Claude Code subagents are most valuable when they remove unnecessary work from the main context while improving specialization, permissions, and output quality.

A good subagent does not attempt to become a second general-purpose Claude.

It has a focused responsibility, a clear delegation trigger, the minimum tools required, an evidence-based process, explicit constraints, and a concise output format.

Start with one high-value worker such as a repository explorer, test failure analyst, pull request reviewer, security reviewer, or release readiness agent.

Test it explicitly before relying on automatic delegation. Review its tool calls, permissions, conclusions, and final report. Then refine the definition based on real failures.

Use Skills for reusable procedures, Hooks for deterministic lifecycle automation, subagents for isolated delegated work, Agent Teams for collaborating independent sessions, and Dynamic Workflows for large scripted orchestration.

When each layer is used for the problem it solves best, Claude Code becomes easier to control, easier to scale, and less likely to lose important context inside one overloaded conversation.

Build better prompts in one workspace

Generate prompts from ideas, analyze and optimize quality, refine with feedback, reverse-engineer content, and save reusable prompts in your Prompt Library.

Try PrompTessor Free