Overview
Subagents are separate agent instances your main agent can spawn for focused
subtasks. Use them to isolate context, run analyses in parallel, and apply
specialized instructions without bloating the main prompt. The Agent SDK
recommends defining them programmatically with the agents option.
Define subagents programmatically
Each subagent is an AgentDefinition with a description (when to use it),
prompt (its behavior), optional tools, and optional model. Include Agent
in allowedTools so invocations auto-approve.
for await (const message of query({
prompt: "Review the authentication module for security issues",
options: {
allowedTools: ["Read", "Grep", "Glob", "Agent"],
agents: {
"code-reviewer": {
description: "Expert code review specialist. Use for quality and security reviews.",
prompt: "You are a code review specialist...",
tools: ["Read", "Grep", "Glob"],
model: "sonnet",
},
},
},
})) {
if ("result" in message) console.log(message.result);
}
AgentDefinition also supports disallowedTools, skills, mcpServers,
maxTurns, effort, background, and permissionMode.
Why subagents
- Context isolation: each subagent runs in a fresh conversation; only its
final message returns to the parent.
- Parallelization: independent subagents run concurrently.
- Specialization: tailored system prompts and knowledge per subagent.
- Tool restriction: limit a subagent to specific tools to reduce risk.
What a subagent inherits
A subagent receives its own system prompt, the Agent tool's prompt string,
project CLAUDE.md (via settingSources), and inherited tool definitions. It does
not receive the parent's conversation history, system prompt, or preloaded
skills (unless listed in skills). Put any file paths or context it needs into
the prompt.
Invoke and detect
Claude invokes subagents automatically based on description, or you can name one
explicitly ("Use the code-reviewer agent to..."). Subagents run via the Agent
tool; detect them by tool_use blocks named Agent (older SDKs used Task), and
messages from inside a subagent carry parent_tool_use_id.
Resume
When a subagent completes, the Agent tool result includes agentId: <id>.
Capture the session_id and agentId, then resume with resume: sessionId and
reference the agent id in the prompt to continue with full context.
Scale up
For runs coordinating dozens to hundreds of agents, use the Workflow tool
(TypeScript SDK), which moves orchestration into a script outside the conversation
context.
Source