Get Started

The Harness as a Library, Subagents and Session Store

A harness you can import: built-in tools, subagents for context isolation, hooks, W3C trace propagation, session persistence. The Claude Agent SDK is the reference example, the library form of the Claude Code harness, and Claude Managed Agents is the hosted alternative for long-running async work.

75 minutesLearn + BuildPython (stdlib)Free lesson

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 (appendloadlist_sessionsdeletelist_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

A raw LLM API gets you one round-trip. A production agent needs tool execution, MCP servers, lifecycle hooks, subagent spawning, session persistence, trace propagation. Claude Agent SDK ships this shape as a library, the same harness Claude Code uses, exposed for custom agents.

The Concept

Client SDK vs Agent SDK

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

Built-in tools

The SDK ships 10+ tools out of the box: file read/write, shell, grep, glob, web fetch, more. Custom tools register via the standard tool-schema interface.

Subagents

Two purposes documented by Anthropic:

  1. Parallelization. Run independent work concurrently. "Find the test file for each of these 20 modules" is 20 parallel subagent tasks.
  2. Context isolation. Subagents use their own context window; only results return to the orchestrator. The orchestrator's budget is preserved.

Python SDK recent additions: list_subagents()get_subagent_messages() for reading subagent transcripts.

Session store

Protocol parity with TypeScript:

  • append(session_id, message)add a turn.
  • load(session_id)restore conversation.
  • list_sessions()enumerate.
  • delete(session_id)with cascade to subagent sessions.
  • list_subkeys(session_id)list subagent keys.

--session-mirror (CLI flag) mirrors the transcript to an external file as it streams, for debugging.

Hooks

Lifecycle hooks you can register:

  • PreToolUsePostToolUsegate or audit tool calls.
  • SessionStartSessionEndset up and tear down.
  • UserPromptSubmitact on user input before the model sees it.
  • PreCompactrun before context compaction.
  • Stopcleanup on agent exit.
  • Notificationside-channel alerts.

Hooks are how pro-workflow (Phase 14 curriculum reference) and similar systems add cross-cutting behavior.

W3C trace context

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

Claude Managed Agents

The hosted alternative (beta header managed-agents-2026-04-01). Long-running async work, built-in prompt caching, built-in compaction. Trade control for managed infrastructure.

Where this pattern goes wrong

  • Subagent over-spawn. Spawning 100 subagents for 100 tiny tasks. Overhead dominates. Batch instead.
  • Hook creep. Every team adds hooks; startup time balloons. Review hooks quarterly.
  • Session bloat. Sessions accumulate; size grows. Use list_sessions + expiry policy.

Build It

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

  • ToolToolRegistry with built-in read_filewrite_filelist_dir.
  • Subagentprivate context, isolated run, results returned.
  • SessionStoreappend, load, list, delete, list_subkeys.
  • Hookspre_tool_usepost_tool_usesession_startsession_end.
  • A demo: main agent spawns 3 subagents in parallel (each isolated), aggregates results, persists session.

Run it:

Code
python3 code/main.py

The trace shows subagent context isolation (orchestrator context size stays bounded), hook execution, and session persistence.

Use It

  • 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) for OpenAI-first counterparts.
  • LangGraph + custom tools if you want the graph-shaped state machine instead.

Ship It

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

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

Check what you learned

7 questions. Answer each one to see why.

Question 1 of 70 correct

What is the difference between the Anthropic Client SDK and the Claude Agent SDK?

The full code

Every file for this lesson. Copy it, run it, then change it.

main.py
"""Claude Agent SDK harness shape in stdlib.

Built-in tools, subagents with isolated context, lifecycle hooks, session store.
Demonstrates how spawning subagents keeps the orchestrator's context bounded.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Callable


@dataclass
class Tool:
    name: str
    description: str
    fn: Callable[..., str]


class ToolRegistry:
    def __init__(self) -> None:
        self._tools: dict[str, Tool] = {}

    def register(self, tool: Tool) -> None:
        self._tools[tool.name] = tool

    def get(self, name: str) -> Tool | None:
        return self._tools.get(name)

    def names(self) -> list[str]:
        return sorted(self._tools)


@dataclass
class Hooks:
    pre_tool_use: list[Callable[[str, dict[str, Any]], None]] = field(default_factory=list)
    post_tool_use: list[Callable[[str, str], None]] = field(default_factory=list)
    session_start: list[Callable[[str], None]] = field(default_factory=list)
    session_end: list[Callable[[str], None]] = field(default_factory=list)


@dataclass
class Turn:
    role: str
    content: str


class SessionStore:
    def __init__(self) -> None:
        self._sessions: dict[str, list[Turn]] = {}
        self._subkeys: dict[str, list[str]] = {}

    def append(self, session_id: str, turn: Turn) -> None:
        self._sessions.setdefault(session_id, []).append(turn)

    def load(self, session_id: str) -> list[Turn]:
        return list(self._sessions.get(session_id, []))

    def list_sessions(self) -> list[str]:
        return sorted(self._sessions)

    def delete(self, session_id: str) -> None:
        self._sessions.pop(session_id, None)
        for sub in self._subkeys.get(session_id, []):
            self._sessions.pop(sub, None)
        self._subkeys.pop(session_id, None)

    def list_subkeys(self, session_id: str) -> list[str]:
        return list(self._subkeys.get(session_id, []))

    def link_sub(self, parent: str, sub: str) -> None:
        self._subkeys.setdefault(parent, []).append(sub)


@dataclass
class AgentRun:
    session_id: str
    context_tokens: int = 0
    tool_calls: list[tuple[str, dict[str, Any], str]] = field(default_factory=list)
    output: str = ""


class Harness:
    def __init__(self, tools: ToolRegistry, hooks: Hooks,
                 store: SessionStore) -> None:
        self.tools = tools
        self.hooks = hooks
        self.store = store
        self._sub_counter = 0

    def _dispatch(self, tool_name: str, args: dict[str, Any]) -> str:
        for hook in self.hooks.pre_tool_use:
            hook(tool_name, args)
        tool = self.tools.get(tool_name)
        if tool is None:
            result = f"error: unknown tool {tool_name!r}"
        else:
            try:
                result = tool.fn(**args)
            except Exception as e:
                result = f"error: {type(e).__name__}: {e}"
        for hook in self.hooks.post_tool_use:
            hook(tool_name, result)
        return result

    def run_agent(self, session_id: str, prompt: str,
                  tool_calls: list[tuple[str, dict[str, Any]]],
                  parent_session: str | None = None) -> AgentRun:
        for hook in self.hooks.session_start:
            hook(session_id)
        if parent_session is not None:
            self.store.link_sub(parent_session, session_id)

        run = AgentRun(session_id=session_id)
        self.store.append(session_id, Turn("user", prompt))
        run.context_tokens += len(prompt.split())

        for tool_name, args in tool_calls:
            result = self._dispatch(tool_name, args)
            run.tool_calls.append((tool_name, args, result))
            self.store.append(session_id, Turn("tool", f"{tool_name}: {result}"))
            run.context_tokens += len(result.split())

        output = f"processed {len(tool_calls)} tools; session={session_id}"
        run.output = output
        self.store.append(session_id, Turn("assistant", output))
        run.context_tokens += len(output.split())

        for hook in self.hooks.session_end:
            hook(session_id)
        return run

    def spawn_subagents(self, parent_session: str,
                        tasks: list[tuple[str, list[tuple[str, dict[str, Any]]]]]
                        ) -> list[AgentRun]:
        runs: list[AgentRun] = []
        for prompt, tool_calls in tasks:
            self._sub_counter += 1
            sub_session = f"{parent_session}.sub{self._sub_counter:02d}"
            run = self.run_agent(sub_session, prompt, tool_calls,
                                 parent_session=parent_session)
            runs.append(run)
        return runs


def _read_file_demo(path: str) -> str:
    return f"[content of {path}: 42 lines]"


def _list_dir_demo(path: str) -> str:
    return f"[{path}: 7 files]"


def main() -> None:
    print("=" * 70)
    print("CLAUDE AGENT SDK SHAPE — Phase 14, Lesson 17")
    print("=" * 70)

    tools = ToolRegistry()
    tools.register(Tool("read_file", "read a file", _read_file_demo))
    tools.register(Tool("list_dir", "list a directory", _list_dir_demo))

    hook_log: list[str] = []
    hooks = Hooks(
        pre_tool_use=[
            lambda n, a: hook_log.append(f"pre[{n}]: {a}")
        ],
        post_tool_use=[
            lambda n, r: hook_log.append(f"post[{n}]: {r[:30]}")
        ],
        session_start=[lambda s: hook_log.append(f"session_start[{s}]")],
        session_end=[lambda s: hook_log.append(f"session_end[{s}]")],
    )

    store = SessionStore()
    harness = Harness(tools, hooks, store)

    parent = "session_main"
    print("\norchestrator starts")
    orchestrator_run = harness.run_agent(
        parent,
        "review these three modules",
        [("list_dir", {"path": "/project"})],
    )
    print(f"  orchestrator context tokens: {orchestrator_run.context_tokens}")

    print("\nspawn three subagents (context isolation)")
    sub_runs = harness.spawn_subagents(parent, [
        ("review module a", [("read_file", {"path": "a.py"})]),
        ("review module b", [("read_file", {"path": "b.py"})]),
        ("review module c", [("read_file", {"path": "c.py"})]),
    ])
    for run in sub_runs:
        print(f"  sub {run.session_id}  tokens={run.context_tokens}  "
              f"tool_calls={len(run.tool_calls)}")
    print(f"  orchestrator context tokens remain: "
          f"{orchestrator_run.context_tokens}")

    print("\nsession store")
    for sid in store.list_sessions():
        print(f"  {sid}  turns={len(store.load(sid))}")
    print(f"  subkeys of {parent}: {store.list_subkeys(parent)}")

    print("\nhooks fired")
    for line in hook_log[:10]:
        print(f"  {line}")
    print(f"  ... {len(hook_log)} hook events total")

    print("\ndelete parent (cascades to subs)")
    store.delete(parent)
    print(f"  remaining sessions: {store.list_sessions()}")

    print()
    print("subagent results return to orchestrator; orchestrator context is preserved.")


if __name__ == "__main__":
    main()