TAI BUI
Back to curriculum
BuildPython

Claude Agent SDK: Subagents and Session Store

The Claude Agent SDK is the Claude Code harness packaged as a library: built-in tools, subagents for context isolation, hooks, W3C trace propagation, and a session store. Claude Managed Agents is the hosted alternative for long-running async work.

TIME: ~75 minutesPREREQUISITES: Phase 14 · 01 (Agent Loop), Phase 14 · 06 (Tool Use and Function Calling)

Learning Objectives

  • Explain the difference between the Anthropic Client SDK (raw API) and the Claude Agent SDK (harness shape).
  • Describe subagents — parallelization and context isolation — and when to reach for them.
  • Name the Python SDK's session store surface (`append`, `load`, `list_sessions`, `delete`, `list_subkeys`) and the role of `--session-mirror`.
  • Implement a stdlib harness with built-in tools, subagent spawning with isolated context, lifecycle hooks, and a session store.

The Problem

The Claude Agent SDK is the harness behind Claude Code, exposed as a library so you can build your own agents on it. It handles tool execution, MCP servers, lifecycle hooks, subagent spawning, session persistence, and trace propagation.

You need that because a raw LLM API gives you one round-trip and nothing else. A production agent needs all of the above, and without the SDK you build each piece yourself.

Warm-up0/3
1. In an agent loop, what happens after the model requests a tool call?Warm-up
2. A long agent run keeps appending tool output to its context. What is the most direct problem this causes?Warm-up
3. A web framework lets you register one function that runs before every request handler. What is the main benefit compared with editing each handler?Warm-up
Check: The Problem0/1
1. Why would you choose the Agent SDK over calling the raw Messages API for a production agent?Explain

The Concept

Client SDK vs Agent SDK

The two SDKs sit at different layers:

  • Client SDK (anthropic). The raw Messages API. You own the loop, the tools, and the state.
  • Agent SDK (claude-agent-sdk). The Claude Code loop as a library, with built-in tool execution, MCP connections, hooks, subagent spawning, and a session store.

Pick the Client SDK when you want full control of the loop. Pick the Agent SDK when you want that loop already built.

Built-in tools

The SDK ships with 10+ built-in tools: file read/write, shell, grep, glob, web fetch, and more. Custom tools register through the standard tool-schema interface. The toy harness in Build It implements only three of them (read_file, write_file, list_dir), enough to show the registry pattern.

Subagents

A subagent is a separate agent run, spawned by an orchestrator, with its own context window. Only its result returns to the orchestrator. Anthropic documents two reasons to use one:

  1. Parallelization. Independent work runs concurrently. "Find the test file for each of these 20 modules" becomes 20 parallel subagent tasks.
  2. Context isolation. Because the subagent works in its own window, the orchestrator's context budget stays intact.

The Python SDK recently added list_subagents() and get_subagent_messages() for reading subagent transcripts.

Session store

The session store persists conversations. The Python surface has parity with TypeScript:

  • append(session_id, message) adds a turn.
  • load(session_id) restores a conversation.
  • list_sessions() enumerates sessions.
  • delete(session_id) removes one, cascading to its subagent sessions.
  • list_subkeys(session_id) lists the subagent keys.

The --session-mirror CLI flag mirrors the transcript to an external file as it streams, which is handy for debugging.

Hooks

Hooks are lifecycle callbacks you register to run your own code at fixed points in a run:

  • PreToolUse and PostToolUse gate or audit tool calls.
  • SessionStart and SessionEnd handle setup and teardown.
  • UserPromptSubmit acts on user input before the model sees it.
  • PreCompact runs before context compaction.
  • Stop handles cleanup when the agent exits.
  • Notification sends side-channel alerts.

Hooks are how extensions to the harness add cross-cutting behavior such as auditing, rate limits, and rule enforcement without touching the loop itself.

W3C trace context

OTel spans active on the caller propagate into the CLI subprocess through W3C trace context headers, so the whole multi-process run shows up as one trace in your backend.

Claude Managed Agents

Managed Agents is the hosted alternative, enabled with the beta header managed-agents-2026-04-01. It targets long-running async work and comes with prompt caching and compaction built in. You give up control and get managed infrastructure in return.

Where this pattern goes wrong

  • Subagent over-spawn. Spawning 100 subagents for 100 tiny tasks lets overhead dominate. Batch the tasks instead.
  • Hook creep. Every team adds hooks, and startup time balloons. Review them quarterly.
  • Session bloat. Sessions accumulate and the store grows. Use list_sessions with an expiry policy.
Check: The Concept0/24
1. What is the Claude Agent SDK?Define
2. What is an MCP server in the context of the Agent SDK?Define
3. How many built-in tools does the Agent SDK ship, and what kinds are they?Define
4. What is a subagent?Define
5. What do `list_subagents()` and `get_subagent_messages()` let you do?Define
6. The session store persists conversations. Which of these is NOT part of its surface?Define
7. What does the `--session-mirror` CLI flag do?Define
8. Hooks are lifecycle callbacks that run your code at fixed points in a run. Which of these is NOT one of them?Define
9. What is W3C trace context used for when the Agent SDK launches the CLI subprocess?Define
10. What is Claude Managed Agents?Define
11. What is the difference between the Anthropic Client SDK and the Claude Agent SDK?Explain
12. What are the two documented reasons to use subagents?Explain
13. How does the session store differ from the `--session-mirror` flag?Explain
14. Why register hooks to add auditing or rule enforcement instead of editing the agent loop?Explain
15. What does Claude Managed Agents trade against the self-hosted SDK?Explain
16. What is subagent over-spawn, and when does it happen?Explain
17. What is hook creep, and how does the lesson recommend addressing it?Explain
18. What is session bloat, and how does the lesson recommend addressing it?Explain
19. Agent startup has slowed steadily as each team added its own hooks, and nobody remembers why some exist. Which practice would have prevented this?Analyze
20. An agent spawns one subagent for each of 100 one-line lookups and ends up slower than doing them inline. Which diagnosis fits?Analyze
21. An orchestrator spawns subagents for noisy tasks, yet its context fills as fast as when it did the work itself. Which assumption is most likely wrong?Analyze
22. Your tracing backend shows the caller's spans and the CLI subprocess's spans as two unrelated traces. Which mechanism is not working?Analyze
23. You must block shell commands that delete files and log every tool call for audit, without changing the agent loop. Which design fits?Design
24. An agent must check 100 small config files and you want parallelism without paying per-task overhead 100 times. Which design fits?Design

Build It

code/main.py implements the SDK's shape in stdlib Python:

  • Tool and ToolRegistry, with built-in read_file, write_file, and list_dir.
  • Subagent, which runs with a private context and returns only its results.
  • SessionStore with append, load, list, delete, and list_subkeys.
  • Hooks for pre_tool_use, post_tool_use, session_start, and session_end.
  • A demo where the main agent spawns 3 isolated subagents in parallel, aggregates their results, and persists the session.

Run it:

python3 code/main.py

The trace shows three things: subagent context isolation (the orchestrator's context size stays bounded), hook execution, and session persistence.

Check: Build It0/4
1. In the demo, the orchestrator run reports 11 context tokens before spawning. After the three subagents (12 tokens each) finish, what does `orchestrator_run.context_tokens` show?Apply
2. The demo registers pre/post tool hooks and session start/end hooks, then runs the orchestrator and three subagents, each making one tool call. How many hook events fire in total?Apply
3. After `store.delete("session_main")` in the demo, what does `store.list_sessions()` return?Apply
4. A run dispatches `write_file` through the demo harness, whose registry holds only `read_file` and `list_dir`. What happens?Apply

Use It

Match the tool to the job:

  • Claude Agent SDK for Claude-first products that want the Claude Code harness shape.
  • Claude Managed Agents for hosted, long-running async work.
  • OpenAI Agents SDK (Lesson 16) if you're building OpenAI-first.
  • LangGraph plus custom tools if you'd rather have a graph-shaped state machine.
Check: Use It0/1
1. A Claude-first product must run jobs that last hours with no user watching, and your team does not want to operate the infrastructure. Which choice fits best?Design

Ship It

outputs/skill-claude-agent-scaffold.md scaffolds a Claude Agent SDK app with subagents, hooks, a session store, MCP server attachment, and W3C trace propagation.

Author's Note

Spawn a subagent when you can name what it buys you: work that can run in parallel, or a noisy task whose intermediate output you don't want in the orchestrator's context. If you can't, keep the work in the main agent. Over-spawn is the first failure mode in this lesson for a reason, and batching small tasks is almost always the better default.

Treat hooks and sessions the same way. Both pile up quietly, so give each hook a clear reason to exist and put an expiry policy on sessions from day one rather than after the store gets heavy.

Exercises

  1. Add a subagent spawner that batches 20 tasks into groups of 5 parallel subagents. Measure orchestrator context size vs one-per-task.
  2. Implement a PreToolUse hook that rate-limits write_file calls (5 per minute per session). Trace the behavior.
  3. Wire list_subkeys to render a subagent tree. What does deep nesting look like?
  4. Port the toy to the real claude-agent-sdk Python package. What changes about tool registration?
  5. Read the Claude Managed Agents docs. When would you switch from self-hosted to managed?

Key Terms

TermWhat people sayWhat it actually means
Agent SDK"Claude Code as a library"Harness shape: tools, MCP, hooks, subagents, session store
Subagent"Child agent"Separate context, own budget; results bubble up
Session store"Conversation DB"Persist, load, list, delete turns with subagent cascade
Hook"Lifecycle callback"Pre/post tool, session, prompt submit, compact, stop
W3C trace context"Cross-process trace"Parent span propagates into CLI subprocess
Managed Agents"Hosted harness"Anthropic-hosted long-running async work
--session-mirror"Transcript mirror"Writes session turns to an external file as they stream
MCP server"Tool surface"External tool/resource source attached to the agent

Further Reading

Code

Ships With