Claude Code Subagents: How to Create and Use Specialized AI Agents
Most AI coding sessions degrade after an hour because file reads, search results, and test output flood the context window. Claude Code subagents fix this by running side tasks in isolated context, each with a custom system prompt, scoped tool access, and independent model selection. Creating, configuring, and deploying subagents takes a few minutes and the payoff in context quality is immediate.
Why Context Saturation Breaks AI Coding Sessions
73% of engineering teams now use AI coding tools daily, up from 18% two years ago, according to a 2026 developer adoption survey of 15,000 respondents. But quantity of adoption has not solved the biggest practical problem: context window saturation. A single multi-hour session on a production codebase can push a 200K-token window to two-thirds capacity, at which point the AI starts missing earlier instructions or fabricating function signatures that were correct three prompts ago.
The problem is not the model. It is signal-to-noise ratio. Every file read, every grep result, every test log consumes tokens that crowd out the instructions and code that actually matter.
Claude Code subagents solve this by delegating side work to isolated AI workers. Each subagent gets its own context window, its own system prompt, its own tool access list, and its own permission mode. It does its work independently, and only the final summary returns to the parent conversation. All the intermediate noise stays inside the subagent and never touches your main session.
Claude Code ships with three built-in subagent types:
- Explore: a read-only agent running on Haiku, optimized for codebase search. It cannot write or edit files.
- Plan: a research agent used during plan mode to gather context before presenting a strategy. Also read-only.
- General-purpose: a full-capability agent that inherits the main conversation's model and tools for complex, multi-step tasks.
Beyond these built-ins, you can create custom subagents for any workflow: code review, database queries, test execution, documentation generation, or domain-specific analysis. The open-source awesome-claude-code-subagents repository on GitHub catalogues over 150 definitions across 10 categories, from language specialists to infrastructure automation.
A non-fork subagent's initial context contains only its own system prompt, the delegation message from Claude, CLAUDE.md files from the project, and any preloaded skills. It does not see the parent conversation history, previously loaded files, or earlier tool calls. This isolation is the point: the subagent arrives fresh, does focused work, and returns a clean result.
How to Create Your First Custom Subagent
Subagents are Markdown files with YAML frontmatter on top and a system prompt below. Store them in one of two locations:
- Project scope (
.claude/agents/): available only in the current project. Check these into version control so your team can use and improve them. - User scope (
~/.claude/agents/): available in every project on your machine. Good for personal workflows like a code reviewer you use everywhere.
When both scopes define a subagent with the same name, the project-level definition takes priority. Organization administrators can also deploy managed subagents that override both.
Using the /agents Command
The fastest way to create a subagent is the interactive /agents command inside Claude Code:
- Run
/agentsto open the management interface - Switch to the Library tab and select Create new agent
- Choose Personal (user scope) or Project (project scope)
- Select Generate with Claude and describe what you want: "A code reviewer that checks for security vulnerabilities and performance issues"
- Choose which tools the subagent can access
- Pick a model: Haiku for speed, Sonnet for balance, Opus for deep reasoning
- Optionally enable persistent memory so the subagent learns across sessions
- Save and the subagent is available immediately
Writing a Subagent File by Hand
For full control, create a Markdown file directly. Here is a code reviewer subagent:
---
name: code-reviewer
description: Reviews code for quality and best practices. Use proactively after code changes.
tools: Read, Grep, Glob, Bash
model: sonnet
---
You are a senior code reviewer. When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Check for bugs, security issues, and style problems
Organize feedback by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)
Save this as .claude/agents/code-reviewer.md and restart your session. Subagents created through the /agents interface activate immediately without a restart. Claude will automatically delegate code review tasks to this subagent when the task description matches.
The description field is critical. Claude reads it to decide when to delegate. Writing "Use proactively after code changes" tells Claude to reach for this subagent without being asked. A vague description like "helps with code" means Claude will rarely choose it.
CLI-Defined Subagents for Quick Testing
For one-off experiments, define subagents inline when launching Claude Code without creating files:
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer. Use proactively after code changes.",
"prompt": "You are a senior code reviewer. Focus on quality and security.",
"tools": ["Read", "Grep", "Glob", "Bash"],
"model": "sonnet"
}
}'
CLI-defined subagents exist only for that session. Use them to prototype behavior before committing to a file.
Configuring Tools, Models, and Permissions
Only name and description are required in the frontmatter. The optional fields are where subagents become powerful.
Tool Restrictions
By default, a subagent inherits every tool available in the main conversation. You can restrict this with two fields:
- tools (allowlist): only these specific tools are available. Everything else is blocked.
- disallowedTools (denylist): these tools are removed from the inherited set. Everything else stays.
A read-only researcher needs only Read, Grep, Glob, Bash. A database query agent might get only Bash paired with a PreToolUse hook that validates each command is a SELECT statement before execution.
For MCP server tools, you can grant or deny at the server level. Adding mcp__github to disallowedTools removes every tool from the GitHub MCP server while keeping all other tools intact. Adding mcp__* to disallowedTools removes every MCP tool from any server.
You can also control which subagents a subagent itself can spawn. Adding Agent(worker, researcher) to the tools list means only those two types can be delegated to. Omitting Agent entirely prevents the subagent from spawning any children.
Model Routing for Cost Control
The model field accepts haiku, sonnet, opus, fable, a full model ID like claude-opus-4-8, or inherit (the default). Model routing is one of the most practical reasons to use subagents: run routine tasks on cheaper, faster models while keeping the main conversation on a more capable one.
Set model: haiku on an Explore-style subagent that searches for files and returns paths. Set model: sonnet on a code reviewer that needs to reason about patterns. Keep the default inherit on a fixer that needs the same reasoning depth as your main session.
The CLAUDE_CODE_SUBAGENT_MODEL environment variable routes all subagents to a specific model unless they explicitly override it. Resolution order: environment variable, then per-invocation parameter, then frontmatter, then main conversation model.
Permission Modes
The permissionMode field controls how the subagent handles approval prompts:
- default: standard permission checking
- acceptEdits: auto-accept file edits in the working directory
- auto: a background classifier reviews commands automatically
- plan: read-only exploration mode
- dontAsk: auto-deny prompts (explicitly allowed tools still work)
- bypassPermissions: skip all permission prompts (use with extreme caution)
If the parent session uses bypassPermissions or acceptEdits, that takes precedence and the subagent cannot override it.
Additional Frontmatter Options
Several other fields round out the configuration surface. The effort field (low, medium, high, xhigh, max) controls reasoning depth. The maxTurns field limits how many agentic loops the subagent can run before stopping. Setting isolation: worktree gives the subagent its own temporary git worktree for file modifications, useful when parallel subagents would otherwise conflict on the same files. The skills field preloads specific skill content into the subagent's context at startup, giving it domain knowledge without consuming turns on skill discovery.
Give your subagent output a persistent home
Fast.io workspaces store, index, and share the files your Claude Code subagents produce, through an MCP-ready endpoint. Starts with a 14-day free trial.
Production Patterns for Subagent Workflows
Several patterns from the official documentation and community examples work well in production codebases.
Parallel Research
When you need to understand several parts of a codebase at once, spawn subagents for each area:
Research the authentication, database, and API modules
in parallel using separate subagents
Each subagent explores its area in its own context window. Claude synthesizes the findings when all three return. This works best when the research paths do not depend on each other.
Chained Subagents
For multi-step workflows, subagents run in sequence. Each one completes its task and returns results to Claude, which passes relevant context to the next:
Use the code-reviewer subagent to find performance issues,
then use the optimizer subagent to fix them
The reviewer identifies problems. The optimizer receives those specific findings and applies fixes. Neither subagent needs the full context of the other's work.
Nested Subagents
As of Claude Code v2.1.172, subagents can spawn their own subagents up to 5 levels deep. A reviewer subagent might dispatch a verifier for each finding, keeping all intermediate output out of your main conversation entirely. Only the top-level summary returns to you.
To prevent a subagent from spawning children, omit Agent from its tools list or add it to disallowedTools.
Forking the Conversation
A fork is a special subagent that inherits the entire conversation history instead of starting fresh. Use it when a named subagent would need too much background, or when you want to try several approaches in parallel from the same starting point:
/fork draft unit tests for the parser changes so far
The fork runs in the background while you continue working. Because it shares the parent's system prompt and tool definitions, it reuses the prompt cache, making it cheaper than a fresh subagent for context-heavy tasks.
When to Use Subagents vs. the Main Conversation
Use the main conversation when the task needs frequent back-and-forth, when multiple phases share significant context, or when latency matters. Subagents start fresh and need time to gather context, so quick targeted changes are faster in the main session.
Use subagents when the task produces verbose output you do not need in your main context, when you want to enforce tool restrictions, or when the work is self-contained and can return a summary. For reusable prompts that should run in the main conversation rather than in isolation, consider Skills instead. For a quick question about something already in your context, use /btw, which sees your full history but has no tool access and does not pollute your context with its answer.
Persistent Memory and Artifact Storage
Subagents start fresh by default. Every invocation creates a new instance with no memory of previous sessions. The memory field changes this by giving a subagent a persistent directory that survives across conversations.
Memory Scopes
Three scopes control where the memory lives:
- user (
~/.claude/agent-memory/<name>/): learnings apply across all projects. Good for a code reviewer that accumulates general best practices. - project (
.claude/agent-memory/<name>/): knowledge is project-specific and shareable via version control. This is the recommended default. - local (
.claude/agent-memory-local/<name>/): project-specific but excluded from version control. Use for sensitive or machine-specific notes.
When memory is enabled, the subagent's system prompt automatically includes instructions for reading and writing to the memory directory. Read, Write, and Edit tools are enabled regardless of the tools field so the subagent can manage its files.
A practical pattern: ask the subagent to check its memory before starting ("Review this PR, and check your memory for patterns you have seen before") and update it after finishing ("Save what you learned to your memory"). Over time, this builds institutional knowledge that makes the subagent more effective with each invocation.
Where Subagent Output Goes
Subagents produce artifacts that often need to outlive the coding session: generated documentation, analysis reports, migration scripts, configuration files. Local filesystems work for individual developers, but teams need shared, persistent storage with search and access control.
You have several options. S3 buckets handle raw artifact archival well. Google Drive works for teams already in the Google ecosystem. A shared Git repository gives you version-controlled outputs.
For teams building with AI agents, Fast.io workspaces provide a purpose-built layer. Agents can push output to a shared workspace via the Fast.io MCP server or API. When Intelligence Mode is enabled, files are automatically indexed for semantic search, so team members can query subagent output with natural language instead of digging through directories. The ownership transfer feature lets an agent build a workspace and hand it to a human reviewer while keeping admin access for future updates.
Every org starts with a 14-day free trial, with storage, monthly credits, and workspaces scaled to each plan.
Frequently Asked Questions
What are Claude Code subagents?
Claude Code subagents are specialized AI workers that run in their own context window with a custom system prompt, specific tool access, and independent permissions. When Claude encounters a task that matches a subagent's description, it delegates to that subagent, which works independently and returns only its results. This keeps intermediate output like file reads, search results, and test logs out of the main conversation.
How do I create a custom subagent in Claude Code?
Create a Markdown file with YAML frontmatter in either .claude/agents/ (project scope) or ~/.claude/agents/ (user scope). The frontmatter needs a name and description at minimum, with optional fields for tools, model, permissionMode, memory, and hooks. You can also run the /agents command inside Claude Code for a guided setup that generates the system prompt for you.
Can Claude Code subagents use different AI models?
Yes. The model field in a subagent's frontmatter accepts haiku, sonnet, opus, fable, a full model ID like claude-opus-4-8, or inherit (which uses the main conversation's model). You can also set the CLAUDE_CODE_SUBAGENT_MODEL environment variable to route all subagents to a specific model by default. This lets you run routine tasks on cheaper models while keeping complex work on more capable ones.
How do subagents preserve context in Claude Code?
Each subagent runs in its own isolated context window. The main conversation delegates a task description, and the subagent works independently without consuming the parent's context. When the subagent finishes, only its summary returns to the main conversation. All intermediate tool calls, file reads, and search results stay inside the subagent's context.
What is the difference between a subagent and a fork in Claude Code?
A subagent starts fresh with its own system prompt and no conversation history. A fork inherits the entire conversation so far, including system prompt, tools, model, and message history. Forks are useful when a named subagent would need too much background context, or when you want to try several approaches from the same starting point. Forks also reuse the parent's prompt cache, making them cheaper for context-heavy tasks.
Can Claude Code subagents spawn other subagents?
Yes, as of Claude Code v2.1.172, subagents can spawn their own subagents up to 5 levels deep. This is useful when a delegated task splits into parallel subtasks. To prevent nesting, omit Agent from the subagent's tools list or add it to disallowedTools.
How does persistent memory work for Claude Code subagents?
Set the memory field in the subagent's frontmatter to user, project, or local. This gives the subagent a persistent directory where it stores learnings across conversations. User scope persists across all projects, project scope is shareable via version control, and local scope stays on your machine. The subagent's system prompt automatically includes instructions for managing its memory directory.
Related Resources
Give your subagent output a persistent home
Fast.io workspaces store, index, and share the files your Claude Code subagents produce, through an MCP-ready endpoint. Starts with a 14-day free trial.