agents parameter.
Overview
You can create subagents in three ways:- Programmatically: use the
agentsparameter in yourquery()options (TypeScript, Python) - Filesystem-based: define agents as markdown files in
.claude/agents/directories (see defining subagents as files) - Built-in general-purpose: Claude can invoke the built-in
general-purposesubagent at any time via the Agent tool without you defining anything
description field. Write clear descriptions that explain when the subagent should be used, and Claude will automatically delegate appropriate tasks. You can also explicitly request a subagent by name in your prompt (for example, “Use the code-reviewer agent to…”).
Benefits of using subagents
Context isolation
Each subagent runs in its own fresh conversation. Intermediate tool calls and results stay inside the subagent; only its final message returns to the parent. See What subagents inherit for exactly what’s in the subagent’s context. Example: aresearch-assistant subagent can explore dozens of files without any of that content accumulating in the main conversation. The parent receives a concise summary, not every file the subagent read.
Parallelization
Multiple subagents can run concurrently, so independent subtasks finish in the time of the slowest one rather than the sum of all of them. Example: during a code review, you can runstyle-checker, security-scanner, and test-coverage subagents simultaneously instead of sequentially.
Specialized instructions and knowledge
Each subagent can have tailored system prompts with specific expertise, best practices, and constraints. Example: adatabase-migration subagent can have detailed knowledge about SQL best practices, rollback strategies, and data integrity checks that would be unnecessary noise in the main agent’s instructions.
Tool restrictions
Subagents can be limited to specific tools, reducing the risk of unintended actions. Example: adoc-reviewer subagent might only have access to Read and Grep tools, ensuring it can analyze but never accidentally modify your documentation files.
Creating subagents
Programmatic definition (recommended)
Define subagents directly in your code using theagents parameter. This example creates two subagents: a code reviewer with read-only access and a test runner that can execute commands. Claude invokes subagents through the Agent tool, so include Agent in allowedTools to auto-approve subagent invocations without a permission prompt.
AgentDefinition configuration
| Field | Type | Required | Description |
|---|---|---|---|
description | string | Yes | Natural language description of when to use this agent |
prompt | string | Yes | The agent’s system prompt defining its role and behavior |
tools | string[] | No | Array of allowed tool names. If omitted, inherits all tools |
disallowedTools | string[] | No | Array of tool names to remove from the agent’s tool set |
model | string | No | Model override for this agent. Accepts an alias such as 'fable', 'opus', 'sonnet', 'haiku', 'inherit', or a full model ID. Defaults to main model if omitted |
skills | string[] | No | List of skill names to preload into the agent’s context at startup. Unlisted skills remain invocable through the Skill tool |
memory | 'user' | 'project' | 'local' | No | Memory source for this agent |
mcpServers | (string | object)[] | No | MCP servers available to this agent, by name or inline config |
initialPrompt | string | No | Auto-submitted as the first user turn when this agent runs as the main thread agent. Ignored when the agent is invoked as a subagent |
maxTurns | number | No | Maximum number of agentic turns before the agent stops |
background | boolean | No | Run this agent as a non-blocking background task when invoked |
effort | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | number | No | Reasoning effort level for this agent |
permissionMode | PermissionMode | No | Permission mode for tool execution within this agent |
AgentDefinition reference for details.
As of Claude Code v2.1.172, subagents can spawn their own subagents. A background subagent five levels below the main agent cannot spawn further subagents; foreground subagents can spawn at any depth. To prevent a subagent from spawning others, omit
Agent from its tools array or add it to disallowedTools. See nested subagents for the full depth rules.Filesystem-based definition (alternative)
You can also define subagents as markdown files in.claude/agents/ directories. See the Claude Code subagents documentation for details on this approach. Programmatically defined agents take precedence over filesystem-based agents with the same name.
Even without defining custom subagents, Claude can spawn the built-in
general-purpose subagent. This is useful for delegating research or exploration tasks without creating specialized agents. Include Agent in allowedTools so these invocations auto-approve without a permission prompt.What subagents inherit
A subagent’s context window starts fresh (no parent conversation) but isn’t empty. The only channel from parent to subagent is the Agent tool’s prompt string, so include any file paths, error messages, or decisions the subagent needs directly in that prompt.| The subagent receives | The subagent does not receive |
|---|---|
Its own system prompt (AgentDefinition.prompt) and the Agent tool’s prompt | The parent’s conversation history or tool results |
Project CLAUDE.md (loaded via settingSources) | Preloaded skill content, unless listed in AgentDefinition.skills |
Tool definitions (inherited from parent, or the subset in tools) | The parent’s system prompt |
The parent receives the subagent’s final message verbatim as the Agent tool result, but may summarize it in its own response. To preserve subagent output verbatim in the user-facing response, include an instruction to do so in the prompt or
systemPrompt option you pass to the main query() call.Invoking subagents
Automatic invocation
Claude automatically decides when to invoke subagents based on the task and each subagent’sdescription. For example, if you define a performance-optimizer subagent with the description “Performance optimization specialist for query tuning”, Claude will invoke it when your prompt mentions optimizing queries.
Write clear, specific descriptions so Claude can match tasks to the right subagent.
Explicit invocation
To guarantee Claude uses a specific subagent, mention it by name in your prompt:Dynamic agent configuration
You can create agent definitions dynamically based on runtime conditions. This example creates a security reviewer with different strictness levels, using a more powerful model for strict reviews.Detecting subagent invocation
Subagents are invoked via the Agent tool. To detect when a subagent is invoked, check fortool_use blocks where name is "Agent". Messages from within a subagent’s context include a parent_tool_use_id field.
The tool name was renamed from
"Task" to "Agent" in Claude Code v2.1.63. Current SDK releases emit "Agent" in tool_use blocks but still use "Task" in the system:init tools list and in result.permission_denials[].tool_name. Checking both values in block.name ensures compatibility across SDK versions.message.content. In TypeScript, SDKAssistantMessage wraps the Claude API message, so content is accessed via message.message.content.
This example iterates through streamed messages, logging when a subagent is invoked and when subsequent messages originate from within that subagent’s execution context.
Resuming subagents
Subagents can be resumed to continue where they left off. Resumed subagents retain their full conversation history, including all previous tool calls, results, and reasoning. The subagent picks up exactly where it stopped rather than starting fresh. When a subagent completes, the Agent tool result includes a text block containingagentId: <id>. The built-in Explore and Plan agents are one-shot and do not return an agentId, so use a custom agent or general-purpose when you need to resume. To resume a subagent programmatically:
- Capture the session ID: Extract
session_idfrom messages during the first query - Extract the agent ID: Parse
agentIdfrom the Agent tool result text - Resume the session: Pass
resume: sessionIdin the second query’s options, and include the agent ID in your prompt
You must resume the same session to access the subagent’s transcript. Each
query() call starts a new session by default, so pass resume: sessionId to continue in the same session.When using a custom agent, pass the same agent definition in the agents parameter for both queries.endpoint-finder agent. The first query runs it and captures the session ID and agent ID from the Agent tool result, then the second query resumes the session to ask a follow-up question that requires context from the first analysis.
- Main conversation compaction: When the main conversation compacts, subagent transcripts are unaffected. They’re stored in separate files.
- Session persistence: Subagent transcripts persist within their session. You can resume a subagent after restarting Claude Code by resuming the same session.
- Automatic cleanup: Transcripts are cleaned up based on the
cleanupPeriodDayssetting (default: 30 days).
Tool restrictions
Subagents can have restricted tool access via thetools field:
- Omit the field: agent inherits all available tools (default)
- Specify tools: agent can only use listed tools
Common tool combinations
| Use case | Tools | Description |
|---|---|---|
| Read-only analysis | Read, Grep, Glob | Can examine code but not modify or execute |
| Test execution | Bash, Read, Grep | Can run commands and analyze output |
| Code modification | Read, Edit, Write, Grep, Glob | Full read/write access without command execution |
| Full access | All tools | Inherits all tools from parent (omit tools field) |
Scale up with dynamic workflows
Subagents work well for a few delegated tasks per turn. For runs that coordinate dozens to hundreds of agents, use theWorkflow tool, which moves the orchestration into a script the runtime executes outside the conversation context. See dynamic workflows for how workflows differ from turn-by-turn subagent delegation.
The Workflow tool is available in the TypeScript Agent SDK v0.3.149 and later. Include Workflow in allowedTools to auto-approve workflow runs. The tool input and output schemas are listed in the TypeScript reference.
Troubleshooting
Claude not delegating to subagents
If Claude completes tasks directly instead of delegating to your subagent:- Check Agent invocations are approved: include
AgentinallowedToolsto auto-approve subagent calls. Without it, Agent invocations fall through to yourcanUseToolcallback or, indontAskmode, are denied - Use explicit prompting: mention the subagent by name in your prompt (for example, “Use the code-reviewer agent to…”)
- Write a clear description: explain exactly when the subagent should be used so Claude can match tasks appropriately
Filesystem-based agents not loading
Agents defined in.claude/agents/ are loaded at startup only. If you create a new agent file while Claude Code is running, restart the session to load it.
Windows: long prompt failures
On Windows, subagents with very long prompts may fail due to command line length limits (8191 chars). Keep prompts concise or use filesystem-based agents for complex instructions.Related documentation
- Claude Code subagents: comprehensive subagent documentation including filesystem-based definitions
- Dynamic workflows: orchestrate many subagents from a script for jobs too large for one conversation
- SDK overview: getting started with the Claude Agent SDK