Subagents
A subagent is a separate agent the main one hands a task to, with its own prompt and its own tools. Only its final message comes back.
Last updated: 20 Oct, 2026 · Claude Agent SDK
A plugin can carry subagent files. This lesson defines them in code instead, which is the route the documentation recommends for an SDK application, and shows what the parent sees of the work.
Splitting the work buys three things: each subagent starts with a fresh conversation, so its tool calls do not pile up in the main one; several can run at once; and each can be held to the tools it needs.
Defining one in code
from claude_agent_sdk import AgentDefinition, ClaudeAgentOptions
from shop_tools import shop
from watch import watch
checker = AgentDefinition(
description="Checks the status of orders.", # Claude reads this to decide
prompt="You check orders and report their status in one sentence.",
tools=["mcp__shop__lookup_order"], # no refund tool for this one
)
shared = dict(mcp_servers={"shop": shop}, setting_sources=["project"],
allowed_tools=["mcp__shop__lookup_order"], agents={"order-checker": checker})
quiet = ClaudeAgentOptions(**shared)
loud = ClaudeAgentOptions(**shared, forward_subagent_text=True)from flags import flags
# agents never become a flag: they ride in the initialize request instead
print(flags(quiet))AgentDefinition needs a description, which Claude reads to decide when to use it, and a prompt, its system prompt. tools holds it to a subset. Its optional fields keep their camelCase spelling, disallowedTools and maxTurns among them, because they go on the wire as they are: subagents.
Claude starts one by calling the built-in Agent tool. That name is worth remembering twice over: the init message's tool list still calls it Task, so code that looks for it should match both.
Teaching the desk to run one
shop_desk.py replaces ShopModel.reply with a version that takes the agent names, gains subagent, and replaces use and say.
def reply(self, said, results, tools=(), rules="", skills=(), agents=()):
...
# naming an agent in the message is this stand-in's way of delegating
for name in agents:
if name in said[-1]:
return {"calls": [("Agent", {"subagent_type": name, "prompt": said[-1]})]} elif name == "Agent":
text, failed = await self.subagent(args, call), False async def subagent(self, args, call):
spec = self.setup["agents"][args["subagent_type"]]
# a tool left out of the definition is hidden from this subagent
allowed = spec.get("tools") or list(self.tools)
tools = {name: where for name, where in self.tools.items() if name in allowed}
# a fresh model with only this prompt, so the main conversation stays clean
said, results = [args["prompt"]], []
while "calls" in (step := ShopModel().reply(said, results, tools, spec["prompt"])):
results = [await self.use(name, a, call) for name, a in step["calls"]]
await self.say(step["text"], call)
return step["text"]The definitions arrived in the initialize request, which is why self.setup is where they are read from. subagent builds a fresh model with the Agent call's prompt as its only message, and tags everything it sends with that call's id as parent_tool_use_id.
Keeping a subagent's text out of the stream
By default Claude Code leaves out the text and thinking blocks of a subagent running in the foreground. forward_subagent_text asks for them, and the SDK sends the request as forwardSubagentText in initialize.
# a subagent's own text is left out unless forward_subagent_text asked for it
if parent is not None and not self.setup.get("forwardSubagentText"):
returnTwo runs, one forwarding option apart
await watch("Ask the order-checker about A17", quiet)system init
assistant calls Agent {'subagent_type': 'order-checker', 'prompt': 'Ask the order-checker about A17'}
assistant calls mcp__shop__lookup_order {'order_id': 'A17'}
user result: Order A17 shipped on 3 March.
user result: Order A17 shipped on 3 March.
assistant Order A17 shipped on 3 March.
result success: Order A17 shipped on 3 March.await watch("Ask the order-checker about A17", loud)system init
assistant calls Agent {'subagent_type': 'order-checker', 'prompt': 'Ask the order-checker about A17'}
assistant calls mcp__shop__lookup_order {'order_id': 'A17'}
user result: Order A17 shipped on 3 March.
assistant Order A17 shipped on 3 March.
user result: Order A17 shipped on 3 March.
assistant Order A17 shipped on 3 March.
result success: Order A17 shipped on 3 March.- Both runs show the
Agentcall, the subagent's tool call and its result, and the same final answer. - Only the second carries the subagent's own sentence, the extra
assistantline in the middle. - The answer reached the parent either way. The subagent's last message is the
Agentcall's result, with or without the option.
Telling the subagent's messages apart
from claude_agent_sdk import query
from shop_desk import ShopDesk
async for message in query(prompt="Ask the order-checker about A17", options=loud,
transport=ShopDesk(loud)):
if getattr(message, "parent_tool_use_id", None):
print("inside the subagent:", type(message).__name__)inside the subagent: AssistantMessage inside the subagent: UserMessage inside the subagent: AssistantMessage
Every message produced inside the subagent carries the id of the Agent call that started it. That field is how a user interface shows the delegated work under the call rather than beside it.
What a subagent is given, and what stays behind
| It receives | It does not receive |
|---|---|
Its own prompt, and the text of the Agent call | The parent's conversation history and tool results |
| Project CLAUDE.md, when the project source is loaded | The parent's system prompt |
Tool definitions, or the subset tools names | Skill content, unless the definition's skills field preloads it |
Where delegating is worth it
- A search that reads many files, so the reading never reaches the main conversation.
- Several checks at once, where the slowest one sets the time.
- A task that should never write, held to
Read,GrepandGlob.
Related
- Previous: Plugins
- Next: Structured output
- Reference: Subagents in the SDK
- Remove
toolsfrom the definition and ask again. Which tools does it get? - Define a second agent,
refund-helper, with only the refund tool. - Print
ShopDesk(loud).setupafter a run and findforwardSubagentText.
Every expert started right here.