Claude Agent SDKclaude-agent-sdk 0.2.157 · Python 3.10+
Dashboard
0%

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

python
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)
python
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.

Exampleshop_desk.py, the new branch inside ShopModel.reply
    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]})]}
Exampleshop_desk.py, the new branch inside use
        elif name == "Agent":
            text, failed = await self.subagent(args, call), False
Exampleshop_desk.py, a new method
    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.

Exampleshop_desk.py, the new first lines of say
        # 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"):
            return

Two runs, one forwarding option apart

Example
await watch("Ask the order-checker about A17", quiet)
Example
await watch("Ask the order-checker about A17", loud)
  • Both runs show the Agent call, the subagent's tool call and its result, and the same final answer.
  • Only the second carries the subagent's own sentence, the extra assistant line in the middle.
  • The answer reached the parent either way. The subagent's last message is the Agent call's result, with or without the option.

Telling the subagent's messages apart

Example
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__)

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 receivesIt does not receive
Its own prompt, and the text of the Agent callThe parent's conversation history and tool results
Project CLAUDE.md, when the project source is loadedThe parent's system prompt
Tool definitions, or the subset tools namesSkill 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, Grep and Glob.
Watch out. The only thing crossing from parent to subagent is the Agent call's prompt text, so file paths, error messages and decisions the subagent needs have to be in it. A subagent that starts without them starts blind.
Try it yourself
  • Remove tools from the definition and ask again. Which tools does it get?
  • Define a second agent, refund-helper, with only the refund tool.
  • Print ShopDesk(loud).setup after a run and find forwardSubagentText.
PreviousPlugins

Every expert started right here.