Claude Code Subagents

A practical guide to Claude Code subagents: when to use them, how to create custom agents, tool permissions, context isolation, background tasks, memory, hooks, and team rollout.

Claude Code subagents are specialized workers that handle a focused task in their own context and return a summary to the main conversation. They are useful when a side task would flood your main session with search results, logs, test output, or file exploration that you do not need to keep in the main thread.

Last checked on May 24, 2026. Claude Code supports built-in subagents, custom user and project subagents, plugin-provided agents, CLI-defined agents, foreground/background execution, session-wide --agent, subagent memory, tool restrictions, hooks, and experimental forked subagents. Treat subagents as a workflow primitive, not as a reason to split every task.

Quick Answer

Use a subagent when a task is self-contained, can be delegated with a clear prompt, and should return a concise result. Good examples are code review, test failure triage, log analysis, documentation research, security checks, or independent research across several modules. Keep the main conversation for tasks that require frequent back-and-forth, shared context across planning and implementation, or fast targeted edits.

The most important rule: a normal subagent starts with a fresh context. It does not automatically see your conversation history, earlier tool results, or files already read by the main session. If the subagent needs a path, error message, decision, or constraint, include it in the delegation prompt or in the subagent definition.

Subagents vs Other Claude Code Mechanisms

Subagents solve context isolation and role specialization. They are not a replacement for every customization surface.

NeedBetter mechanism
Keep long research output out of the main threadSubagent
Reuse a role with its own prompt and tool limitsCustom subagent
Run several independent investigations in parallelSubagents or agent view
Create a reusable prompt that runs in the main contextSkill or slash command
Store project-wide instructionsCLAUDE.md or project rules
Enforce permissions before tool callsPermission rules and hooks
Coordinate many workers with shared task stateAgent teams
Avoid file conflicts between parallel coding sessionsWorktrees

If you only need a short reusable instruction, create a skill or slash command. If you need a worker with its own role, context, tools, and model choice, create a subagent.

Built-In, Custom, Plugin, And CLI Agents

Claude Code can use multiple kinds of subagents:

Agent typeWhere it comes fromBest use
Built-in agentsClaude Code itselfExplore, plan, or general-purpose delegation without extra setup.
User subagents~/.claude/agents/Personal agents you want across projects.
Project subagents.claude/agents/Team-shared agents for one repository.
Plugin agentsInstalled plugin agents/ foldersDistributed workflow integrations.
CLI-defined agentsclaude --agents ...Temporary agents for tests, scripts, or automation.
Managed agentsOrganization managed settingsEnterprise-controlled agents and policy.

For a team repository, prefer .claude/agents/ after the workflow is stable enough to share. For personal experimentation, start in ~/.claude/agents/ or use /agents.

Create And Manage Agents

The recommended interactive path is the /agents command. It opens the agent management interface where you can view built-in, user, project, and plugin agents, create a new agent, edit tool access, delete custom agents, and see which agent is active when duplicates exist.

Manual creation is also simple. Put a Markdown file in .claude/agents/ for a project agent:

---
name: code-reviewer
description: Review recent changes for correctness, security, maintainability, and test coverage. Use proactively after code edits.
tools: Read, Grep, Glob, Bash
model: inherit
---

You are a senior code reviewer. Review the current diff first, then inspect only the files needed to verify the change.

Report findings by severity:

1. Blocking bugs or security risks.
2. Regressions or missing tests.
3. Maintainability suggestions.

Do not edit files. Return file paths, line references, and concrete fixes.

Subagent files are loaded at session start. If you add or edit files directly on disk while Claude Code is already running, restart the session. Agents created through /agents are available immediately.

Frontmatter Fields That Matter

Every subagent needs a clear identity and delegation description. Treat the description field as search intent for Claude. Claude uses it to decide when the agent should run.

FieldRequiredPractical guidance
nameYesUse lowercase letters and hyphens, such as code-reviewer.
descriptionYesExplain when to delegate. Include "use proactively" only when the agent really should run without being asked.
Markdown body or promptYesThe agent system prompt. Be explicit about workflow, output format, and limits.
toolsNoOmit to inherit tools, or list a narrow set such as Read, Grep, Glob.
disallowedToolsNoRemove risky tools from an inherited set.
modelNoUse when the role needs a different model from the main session.
permissionModeNoUseful for narrow local workflows, but do not rely on it to bypass parent policy.
mcpServersNoGive the agent specific MCP access when needed.
hooksNoRun hooks only while that subagent is active.
skillsNoPreload skill content into the agent context at startup.
memoryNoGive the agent persistent memory with user, project, or local scope.
backgroundNoHint whether the agent can run concurrently.
colorNoUI identification. Helpful when several agents run at once.

Keep names unique. If two files within one scope declare the same name, Claude Code may keep one and discard another without a useful warning.

How To Invoke A Subagent

There are three common patterns.

Natural Language

Name the agent in your prompt and let Claude decide whether to delegate:

Use the test-runner subagent to run the failing test suite and report only the failing cases.

This is the softest form. It usually works when the agent description is clear.

Agent Mention

Use an agent mention when you want a specific subagent for one task. The full request still goes through the main conversation, but the mention controls which agent Claude invokes.

@"code-reviewer (agent)" review the auth changes in the current diff.

You can also type the agent name manually when needed. Plugin-provided agents may use scoped names.

Session-Wide Agent

Use --agent when the whole session should run as that agent:

claude --agent code-reviewer

You can also make a project default in .claude/settings.json:

{
  "agent": "code-reviewer"
}

Be careful with session-wide agents. The subagent system prompt replaces the default Claude Code system prompt for that session, while normal memory loading still applies. Use this for deliberate modes, not casual one-off tasks.

Foreground And Background Subagents

Subagents can run in the foreground or background.

ModeBehaviorBest use
ForegroundBlocks the main conversation until complete. Permission prompts surface to you.Reviews or fixes that need interactive approvals.
BackgroundRuns while you continue working. Tool calls that would require new permission are auto-denied.Long read-only research, logs, documentation lookup, or test analysis.

You can ask Claude to run a task in the background, or press Ctrl+B to background a running task. If background behavior is not desired, set CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1.

Background is not a magic speed boost. Running several agents multiplies token usage and can create competing edits if they touch the same files. Use read-only tools or worktree isolation when tasks might overlap.

What A Subagent Sees

A normal subagent starts fresh. Its context contains the agent prompt, the task message Claude writes when delegating, basic environment details, and configured project memory sources. It does not inherit the full parent conversation history or previous tool results.

Context itemNormal subagent behavior
Parent conversation historyNot included.
Files already read by the main sessionNot included.
Agent system promptIncluded from the agent definition.
Delegation task messageIncluded, written by Claude from your request.
CLAUDE.md and memoryLoaded for most custom agents. Built-in Explore and Plan skip some memory and git context.
Git statusIncluded when available unless disabled.
Preloaded skillsIncluded only when listed in the skills field.
Tool resultsOnly from the subagent's own work.

This is why delegation prompts must be concrete. Bad: "review the thing we discussed earlier." Better: "review the current diff for src/auth/session.ts and src/auth/callback.ts; focus on token refresh, redirect handling, and missing tests."

Tool Permissions And Safety

Limit tool access by default. A code reviewer usually needs Read, Grep, Glob, and maybe Bash for git diff or tests. It usually does not need Edit or Write. A debugger may need Edit, but only if its job includes fixing the bug.

RoleSuggested toolsAvoid at first
Code reviewerRead, Grep, Glob, BashEdit, Write
Test runnerRead, Bash, Grep, GlobBroad write access
Documentation researcherRead, Grep, Glob, WebFetch if availableRepo write tools
Security reviewerRead, Grep, Glob, BashAutomatic fixes
Migration implementerRead, Edit, Bash, Grep, GlobDeploy tools
Database analystBash with hook guardrailsWrite SQL

For sensitive workflows, combine subagent tools with permission rules and hooks. Tool lists narrow what an agent can do; permissions and hooks enforce policy around what should happen.

Memory, Skills, Hooks, And MCP

Subagents can become more capable when they load the right supporting context.

FeatureUse it whenCaution
skillsThe agent should start with domain instructions or reusable workflow knowledge.Preloaded skills add context cost.
memoryThe agent should remember recurring project patterns across sessions.Keep memory curated and avoid secrets.
hooksThe agent needs lifecycle checks while active.Hooks run code, so keep them auditable.
mcpServersThe agent needs specialized external tools.Grant the smallest MCP surface needed.

Project-scoped memory is often the best default for team agents because it can be versioned and improved with the repository. Use local memory for private machine-specific learning. Use user memory for patterns that apply across many repositories.

Practical Agent Roles

Start with roles that have clear inputs and outputs.

Code Reviewer

Purpose: inspect recent changes without editing. Output should be findings by severity, with file and line references.

Best prompt rule: "Do not summarize the whole diff. Report only actionable issues."

Test Triage Agent

Purpose: run or inspect tests, reduce noisy output, and return failing test names, error messages, likely root cause, and recommended next command.

Good delegation:

Use the test-triage subagent to run the auth test suite. Return only failing tests, root-cause hypotheses, and the smallest next verification command.

Documentation Researcher

Purpose: inspect docs, changelogs, or official sources and summarize what changed. This is especially useful for Claude Code topics because docs change quickly.

Security Reviewer

Purpose: inspect a change for secrets, broad permissions, unsafe shell usage, exposed tokens, risky MCP writes, or insufficient validation. Keep it read-only by default.

Release Checklist Agent

Purpose: check status, changelog, environment variables, migrations, and smoke tests. It can be very valuable, but it should not deploy unless the team intentionally grants that tool access.

Team Rollout Pattern

Do not start by creating ten agents. Create one agent for one repeated pain.

  1. Observe the workflow: identify tasks that produce noisy output or require a stable checklist.
  2. Write a narrow role: one purpose, one output format, one tool set.
  3. Run manually: invoke the agent by name for a few real tasks.
  4. Tighten description: improve when Claude should delegate.
  5. Limit tools: remove edit or write access unless the role needs it.
  6. Document in CLAUDE.md: explain when the team should use the agent.
  7. Commit project agents: only after the behavior is predictable.

This keeps subagents useful instead of turning them into a confusing automation layer.

Common Mistakes

MistakeWhy it hurtsBetter approach
Creating agents before the workflow is provenYou freeze the wrong process.Run manually first, then promote repeated roles.
Vague descriptionsClaude cannot delegate reliably.Say exactly when to use the agent.
Giving every agent all toolsMore risk and less focus.Grant the narrowest useful tools.
Expecting the parent context to be visibleNormal subagents start fresh.Pass paths, errors, and decisions explicitly.
Returning huge reportsThe main thread gets polluted anyway.Require concise summaries and evidence.
Letting multiple agents edit the same filesMerge conflicts and duplicated work.Use read-only agents or worktrees.
Using background agents for permission-heavy workBackground agents auto-deny prompts.Use foreground for interactive approvals.
Not restarting after manual file editsClaude may not load new agent definitions.Restart the session or create through /agents.

A Starter Project Agent Set

For a Claude Code knowledge-base project, a small useful set is:

AgentPurposeTools
content-reviewerCheck pages for thin content, unclear claims, missing internal links, and outdated sources.Read, Grep, Glob
source-checkerVerify whether Claude Code claims still match official docs.Read, Grep, Glob, WebFetch if available
frontend-qaInspect rendered pages, layout regressions, dark mode, and mobile overflow.Read, Bash
seo-structure-reviewerCheck title, description, H2 flow, FAQ intent, and related-page links.Read, Grep, Glob

Do not enable all of them at once. Start with content-reviewer or source-checker, because those directly support search traffic quality.

Official Sources