Subagents and Claude Managed Agents
Why this lesson
Section titled “Why this lesson”Lesson 8 built the loop substrate. Lesson 9 catalogued six canonical patterns. Lesson 10 added Agent Skills (durable instructions) plus Claude Code (one worked harness). This lesson covers two Anthropic-specific primitives that realize patterns 4 (orchestrator-workers) and 6 (autonomous agent) directly. Subagents are how a parent agent spawns focused inner loops, one per subtask, each with its own fresh context, its own optional tool restriction, and (optionally) its own smaller cheaper model. Claude Managed Agents is the Anthropic-hosted harness: instead of building your own loop, sandbox, and tool execution, you POST user events and Anthropic runs the agent.
The capability the lesson builds: pick the right primitive for an agent workload (a single lesson 8 style loop, a Subagent fan-out inside it, or Claude Managed Agents if you would rather not run the harness yourself), define a Subagent and a Managed Agent end to end, and reason about the cost, isolation, and data-retention trade-offs.
Subagents (the focused-inner-loop primitive)
Section titled “Subagents (the focused-inner-loop primitive)”The Anthropic docs frame Subagents this way verbatim: Subagents are separate agent instances that your main agent can spawn to handle focused subtasks. Use them to isolate context, run multiple analyses in parallel, and apply specialized instructions without adding to the main agent's prompt. The mechanism lives in the Claude Agent SDK; the parent agent calls the Agent tool, the SDK spawns a subagent, and the subagent runs an inner lesson 8 style loop until it produces a final message.
The four benefits the docs name are worth memorizing because they map back to lesson 9 directly.
Context isolation. Each subagent runs in its own conversation, which starts fresh unless you choose to fork the current one. Either way, the docs say, intermediate tool calls and results stay inside the subagent, and only its final message returns to the parent. The parent does not see (and does not pay for) the subagent's intermediate work. A research subagent can read forty files; the parent sees a concise summary, not forty file contents.
Parallelization. Multiple subagents can run concurrently. The docs' worked example: during a code review, you can run a style-checker, a security-scanner, and a test-coverage subagent simultaneously, so the review finishes in the time of the slowest check rather than the sum of all three.
Specialized instructions. Each subagent gets its own system prompt. A database-migration subagent can carry detailed SQL-best-practices and rollback-strategy knowledge that would be noise in the main agent's prompt.
Tool restrictions. Each subagent can be limited to a subset of the parent's tools. A doc-reviewer subagent might only have Read and Grep, so it can analyze but never modify your documentation.
How to define a Subagent
Section titled “How to define a Subagent”Three paths, per the docs: programmatic, through the agents option on the SDK's query call (recommended for application code), filesystem-based as markdown files in a .claude/agents/ directory, and the built-in general-purpose subagent that Claude can invoke without any definition.
A programmatic Python definition with two subagents looks like this:
from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition
async for message in query( prompt="Review the authentication module for security issues", options=ClaudeAgentOptions( # Auto-approve these tools, including Agent for subagent invocation allowed_tools=["Read", "Grep", "Glob", "Agent"], agents={ "code-reviewer": AgentDefinition( description="Expert code review specialist. Use for quality, security, and maintainability reviews.", prompt="""You are a code review specialist with expertise in security, performance, and best practices.Be thorough but concise.""", tools=["Read", "Grep", "Glob"], # read-only model="sonnet", # overrides the default model for this subagent ), "test-runner": AgentDefinition( description="Runs and analyzes test suites. Use for test execution and coverage analysis.", prompt="You are a test execution specialist. Run tests; analyze results.", tools=["Bash", "Read", "Grep"], ), }, ),): if hasattr(message, "result"): print(message.result)An agent definition has two required fields: a description, which is the routing signal Claude reads to decide whether to delegate to this subagent, and a prompt, which becomes the subagent's system prompt. Everything else is optional: a tool allowlist (leave it out and the subagent inherits every tool available to subagents), a list of tools to remove, a model choice, an effort level (lesson 3's dial), Agent Skills to preload (lesson 10), MCP servers (lesson 6), a memory source, a permission mode for its tool calls, a cap on its turns, and a flag to run it in the background. The table below gives the exact field names.
| As of November 2026: agent definition field | Required | What it does |
|---|---|---|
description | Yes | When to use this agent; Claude reads it to decide whether to delegate |
prompt | Yes | The subagent's system prompt |
tools | No | Allowed tool names; if omitted, inherits every tool available to subagents |
disallowedTools | No | Tool names to remove from the agent's tool set |
model | No | An alias (fable, opus, sonnet, haiku, inherit) or a full model ID; inherit uses the main model |
effort | No | Reasoning effort: low, medium, high, xhigh, max, or a number |
skills | No | Agent Skills to preload into the subagent's context |
mcpServers | No | MCP servers available to this agent, by name or inline config |
memory | No | Memory source: user, project, or local |
permissionMode | No | Permission mode for tool execution within this agent |
maxTurns | No | Maximum agentic turns before the agent stops |
background | No | Run as a non-blocking background task when invoked |
| Source | Subagents in the SDK (the TypeScript SDK adds a few more fields) |
What Subagents inherit (and do not)
Section titled “What Subagents inherit (and do not)”The docs are explicit about the channel between parent and subagent: The only content you pass 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 (unless it is a fork) | The subagent does NOT receive |
|---|---|
| Its own system prompt + the Agent tool's prompt string | 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 |
One thing to plan around: subagents can nest. A subagent can spawn subagents of its own, up to a configurable depth limit, so one prompt can grow into a tree of agents. A subagent at the bottom layer cannot spawn, so it does its delegated work itself. If one subagent should never delegate, such as a read-only reviewer, leave the Agent tool out of its tool list. You can also cap how many subagents run at once and how much the whole query may spend. Managed Agents, covered next, has its own multiagent setting with its own limits; delegation there is one level deep. The table below lists the defaults for both.
| As of November 2026 | Claude Agent SDK and Claude Code | Claude Managed Agents (multiagent setting) |
|---|---|---|
| Nesting depth | Default 3 layers of subagents below the main agent; set with CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH; 1 turns nesting off | Delegation is one level deep |
| Subagents at once | Default 20, set with CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS | At most 25 child threads at a time, idle ones included |
| Spend cap | max_budget_usd (Python) or maxBudgetUsd (TypeScript); no limit by default | A session budget |
| Notes | Applies to TypeScript SDK v0.3.219 and Python SDK v0.2.127 and later | Configured in the agent's multiagent block |
| Sources | Subagents in the SDK, Claude Code subagents | Multiagent orchestration |
For runs that coordinate dozens to hundreds of agents, the docs point to the Workflow tool, which moves the orchestration into a script the runtime executes outside the conversation context.
How Subagents realize the lesson 9 patterns
Section titled “How Subagents realize the lesson 9 patterns”The mapping is direct. Pattern 4 (orchestrator-workers): the parent loop is the orchestrator; the subagents are the workers; the orchestrator decides what to spawn at runtime based on the input, satisfying the "subtasks not pre-defined" criterion. Pattern 3 (parallelization, sectioning sub-type): multiple subagents run concurrently on independent slices. Pattern 6 (autonomous agent): the parent agent can spawn many subagents over a long run, each focused on a sub-goal, while keeping the main context clean.
One cost angle worth pulling out. Because subagents can run on a smaller model than the parent, the per-subagent model choice is a real cost lever (lesson 3's mix-and-match pattern, now per-subagent), once your evaluation shows the smaller tier holds quality. The docs' worked example builds a security reviewer at query time: strict reviews run on a more capable tier, and balanced reviews on the balanced tier.
Claude Managed Agents (the hosted harness)
Section titled “Claude Managed Agents (the hosted harness)”If Subagents save you from writing the spawn primitive, Claude Managed Agents saves you from writing the entire harness. The docs' verbatim positioning: Pre-built, configurable agent harness that runs in managed infrastructure. Best for long-running tasks and asynchronous work. And: Claude Managed Agents provides the harness and infrastructure for running Claude as an autonomous agent. Instead of building your own agent loop, tool execution, and runtime, you get a fully managed environment where Claude can read files, run commands, browse the web, and run code securely.
The product comparison the docs publish is the cleanest decision framing:
| Messages API (lessons 4-10) | Claude Managed Agents | |
|---|---|---|
| What it is | Direct model prompting access | Pre-built, configurable agent harness that runs in managed infrastructure |
| Best for | Custom agent loops and fine-grained control | Long-running tasks and asynchronous work |
The four core concepts
Section titled “The four core concepts”The docs name four: Agent (the model, system prompt, tools, MCP servers, and Skills), Environment (where sessions run, either an Anthropic-managed cloud sandbox or a self-hosted sandbox on your infrastructure), Session (a running agent instance within an environment, performing a specific task), and Events (the messages exchanged: user turns, tool results, status updates).
How it works
Section titled “How it works”Five steps, per the docs:
- Create an agent. Define the model, system prompt, tools, MCP servers, and Skills. Create the agent once and reference it by ID across sessions.
- Create an environment. Configure the sandbox (cloud or self-hosted).
- Start a session. Launch a session referencing the agent and environment.
- Send events and stream responses. Send user messages as events; Claude autonomously executes tools and streams results back as server-sent events (SSE). Event history is persisted server-side and can be fetched in full.
- Steer or interrupt. Send more user events to guide the agent while it runs, or interrupt it to change direction.
A minimal three-call agent creation in Python looks like this. The SDK sets the required beta header for you; the table at the end of this section names it.
from anthropic import Anthropicclient = Anthropic()
agent = client.beta.agents.create( name="Coding Assistant", model="claude-opus-5-5", system="You are a helpful coding assistant.", tools=[{"type": "agent_toolset_20260401"}], # the full built-in tool set)
environment = client.beta.environments.create( name="quickstart-env", config={ "type": "cloud", "networking": {"type": "limited", "allow_package_managers": True}, },)
session = client.beta.sessions.create( agent=agent.id, environment_id=environment.id, title="Quickstart session",)
# Stream eventswith client.beta.sessions.events.stream(session.id) as stream: client.beta.sessions.events.send( session.id, events=[{"type": "user.message", "content": [{"type": "text", "text": "..."}]}], ) for event in stream: match event.type: case "agent.message": ... case "agent.tool_use": ... case "session.status_idle": breakThe agent toolset tool type turns on the full pre-built set (Bash, file operations, web search, web fetch, and more), and the docs advise giving an agent only the tools it needs. When the agent has nothing more to do, the session sends a status-idle event; you can resume by sending another user event.
When Managed Agents is the right choice
Section titled “When Managed Agents is the right choice”The docs name six signals: long-running execution (tasks that run for minutes or hours with multiple tool calls); cloud infrastructure (secure sandboxes with pre-installed packages and network access); self-hosted execution (sandboxes on infrastructure you control, for compliance or data-residency needs); minimal infrastructure (no agent loop, sandbox, or tool execution layer to build yourself); stateful sessions (persistent filesystems and conversation history across multiple interactions); and scheduled execution (recurring agent runs on a cron schedule).
Limits and data-retention posture
Section titled “Limits and data-retention posture”Two real constraints to plan around. Managed Agents is in beta, and every request carries a beta header that the SDK sets for you. MCP tunnels and the dreaming feature inside Managed Agents are in a more limited research preview that requires requesting access.
More important for production decisions: Claude Managed Agents is stateful by design, so conversation history, sandbox state, and outputs are stored server-side. The consequence the docs name directly: Managed Agents is not eligible for Zero Data Retention or HIPAA Business Associate Agreement coverage (the table below shows the status on its date). You retain control of the stored data (you can delete sessions and uploaded files through the API), but if your workload is ZDR-required, you keep the Messages-API path (lessons 4-10 plus a self-built harness or Subagents) until that posture changes.
| As of November 2026 | Claude Managed Agents |
|---|---|
| Status | Beta |
| Beta header (the SDK sets it) | managed-agents-2026-04-01 |
| Endpoints | POST /v1/agents, POST /v1/environments, POST /v1/sessions |
| Built-in tool set type | agent_toolset_20260401 |
| Multiagent setting type | multiagent_20261001 |
| Zero Data Retention | Not eligible |
| HIPAA BAA | Not eligible |
| Research preview (request access) | MCP tunnels, dreaming |
| Sources | Managed Agents overview, Quickstart, Multiagent orchestration |
Decision frame: which primitive
Section titled “Decision frame: which primitive”The clean version, applied per workload:
- A single lesson 8 style loop in your code. When the task fits one agent loop, when you want full control of the harness, when ZDR matters, when latency is dominated by your tool side rather than the loop.
- Subagents (Agent SDK) inside that loop. When you want pattern 4 (orchestrator-workers) or pattern 3 (parallelization) without writing the spawn-and-context-isolation primitive yourself, when per-subagent tool restriction is a real safety win, when running some subtasks on a smaller cheaper model is a real cost win.
- Claude Managed Agents. When the agent runs for minutes or hours, when you do not want to run the sandbox, when stateful sessions are useful, when ZDR is not a constraint. The first call you make creates the agent; the rest is mostly sending events and receiving events.
The three are composable. You can write your own lesson 8 loop that calls Subagents for fan-out, and reach for Managed Agents only on the workloads where the loop or sandbox is the actual constraint. Most production stacks end up with a mix, the same way they end up with a mix of models from lesson 3.
Why this matters when you use Claude
Section titled “Why this matters when you use Claude”The hardest part of running an agent in production is rarely "make the model call." It is the harness around the call: the sandbox, the tool execution, the long-running session state, the multi-step retry policy, the per-step observability. Subagents save you from writing the spawn primitive for patterns 4 and 6 (it is real engineering when you build it yourself, and easy to get wrong on context isolation). Managed Agents saves you from writing the entire harness when you are running long-form asynchronous work and do not want to operate the runtime.
The lesson 12 closer turns whichever path you chose into a shipped production application: cost monitoring on the usage fields, eval-set discipline, the rollout checklist, the data-retention posture that decides between paths.
What you should remember
Section titled “What you should remember”- Subagents (verbatim): separate agent instances that your main agent can spawn to handle focused subtasks. Three creation paths: programmatic (the agents option on the SDK query call), filesystem-based (markdown files in .claude/agents/), or the built-in general-purpose subagent.
- Four Subagent benefits: context isolation (only the final message returns to the parent), parallelization (concurrent subagents), specialized instructions (per-subagent system prompt), and tool restrictions (per-subagent tools whitelist).
- Agent definition essentials: the description routes; the prompt defines behavior; the tool list restricts; the model choice can put a subagent on a smaller, cheaper tier (a per-step instance of lesson 3's mix-and-match); the effort dial applies. Subagents can nest up to a configurable depth limit; leave the Agent tool out of a subagent's tools when it should not delegate.
- Subagents realize the lesson 9 patterns directly: pattern 4 (orchestrator-workers) equals parent loop plus worker subagents; pattern 3 (parallelization, sectioning) equals concurrent subagents; pattern 6 (autonomous agent) equals parent loop spawning many subagents over a long run.
- Beyond dozens to hundreds of subagents: the Workflow tool moves orchestration into a script outside the per-turn context.
- Claude Managed Agents (verbatim): Pre-built, configurable agent harness that runs in managed infrastructure. Best for long-running tasks and asynchronous work. Anthropic provides the agent loop, sandbox, tool execution, and runtime; you POST events and receive SSE events.
- Four core concepts: Agent, Environment, Session, Events. Three endpoints, one each to create an agent, an environment, and a session, plus a beta header that the SDK sets for you.
- Built-in tools via the agent toolset: Bash, file operations, web search and fetch, MCP servers.
- When to choose Managed Agents (six signals): long-running execution; cloud infrastructure; self-hosted execution; minimal infrastructure (no harness to build); stateful sessions; scheduled execution. NOT for ZDR-required workloads (stateful by design; not ZDR or HIPAA BAA eligible).
- Decision frame: A lesson 8 style self-built loop for full control or ZDR; Subagents inside that loop for orchestrator-workers or parallelization or cheaper subagents; Managed Agents for long-running asynchronous work where you skip the harness. The three compose; most production stacks mix them.
A loop in lesson 8. Patterns in lesson 9. Skills and Claude Code in lesson 10. Subagents and Managed Agents here. Lesson 12 ships the result to production.