Company OAsAll ProblemsOA CalendarInterview ExperiencesPremium
OAHelper

Built by students, for students - practice company-specific OAs, DSA sheets, and real interview experiences to land your dream role.

© 2026 OAHelper.in·Terms·Privacy·Refunds·Trust & Safety·Contact·
Ready to crack your next OA?

Practice company-specific questions trusted by thousands of students across India.

Start PracticingGo Premium
OA Practice·DSA·Placements

Disclaimer: OAHelper is an independent educational platform. We (oahelper.in) do not own the images or questions shown. Content is uploaded by users.

Module 03

Claude Agent SDK

  • LangGraph Stateful Graphs
  • AutoGen Actor Model
  • CrewAI Role-Based Crews
  • OpenAI Agents SDK
  • Claude Agent SDK
  • Agno and Mastra
On this page

This week

  • LangGraph Stateful Graphs
  • AutoGen Actor Model
  • CrewAI Role-Based Crews
  • OpenAI Agents SDK
  • Claude Agent SDK
  • Agno and Mastra

In plain words

You are organising the college fest. You cannot hold every detail yourself, so you hand sound to Rahul and food to Sneha, and they each report back one line. The Claude Agent SDK is that idea as a library: built-in tools, lifecycle hooks, saved sessions, and subagents that do bulky work in their own context and return only a short answer.

How it flows

  1. 1Parent gets task→
  2. 2Spawn subagents→
  3. 3Hooks check tools→
  4. 4Subagents return results→
  5. 5Session saved

A tiny example

Python
register("pre_tool", allow_check)

def subagent(task, big_text):
    # runs in its OWN context
    return run_tool("summarise", big_text)

for task in tasks:
    short = subagent(task, load_logs(task))
    append(session_id, short)   # parent stores one line only

Notice the parent never stores the big text — only the one-line result each subagent hands back.


What you will learn

  • The difference between a plain model API and a full agent harness you can import.
  • What subagents are, and the two reasons you spawn them.
  • How hooks and a session store keep an agent honest across restarts.
  • When to self-host the harness and when to let someone else host it.

The problem, simply

Think about your college fest. You are the organiser and there are twenty things to do — auditorium, passes, sound, sponsors, food. Do all twenty yourself and by evening you have forgotten who paid the ₹5,000 advance.

So you give sound to Rahul, food to Sneha, sponsors to Karthik. Each keeps the messy details in their own head and comes back with one line: "Sound booked, ₹8,000." Your head stays clear.

Now the software version. A raw model API gives you one question and one answer. A real agent needs to run tools, remember old conversations, check risky actions, and split big work into pieces.

You can build all that yourself. Or you can import a library that already ships it. That library is what we are studying today.

The idea

Two different SDKs, one confusing name

Anthropic ships two things and students mix them up in interviews.

The Client SDK (the plain anthropic package) is the raw Messages API. Send messages, get a reply. You write the loop, execute the tools, store the state.

The Claude Agent SDK is the harness itself, packaged as a library — basically the Claude Code loop that you import into your own program. Built-in tools, MCP server connections, lifecycle hooks, subagent spawning, session storage.

IMP

Note: A "harness" just means the code around the model — the loop, the tools, the memory, the safety checks. The model is the engine; the harness is the rest of the car.

IMPRemember: Client SDK gives you the loop to write. Agent SDK gives you the loop already written.

What comes in the box

The Agent SDK ships more than ten tools out of the box — read a file, write a file, run a shell command, grep, glob, fetch a page. Your own tools plug in through the same tool-schema interface, so a custom tool looks no different from a built-in one.

Subagents, and why they exist

A subagent is a child agent with its own context window. The parent gives it a task, it works, and only the final result comes back.

There are exactly two reasons to use one.

One, parallelisation. "Find the test file for each of these 20 modules" is 20 independent little tasks. Run them together instead of one after another.

Two, context isolation. This is the real trick. Suppose Priya's agent must scan a 4,000-line log file to find one error. If the parent reads the file, those 4,000 lines sit in its context forever. Instead the parent spawns a subagent, which reads everything in its own context and returns one sentence: "Line 2,187, database timeout."

That is exactly Rahul and the sound booking. He handled the mess; you got one line.

  1. 1Parent gets task→
  2. 2Spawns subagents→
  3. 3Each works alone→
  4. 4Results come back→
  5. 5Parent answers

The Python SDK also lets you look inside: list_subagents() tells you which children exist, and get_subagent_messages() shows what a child actually did — useful when a subagent returns something odd.

The session store

Agents restart, servers get redeployed, users close the tab and come back after lunch. So the conversation must live somewhere outside memory.

The session store has five methods, and interviewers do ask for them:

  • append(session_id, message) — add one turn.
  • load(session_id) — bring the conversation back.
  • list_sessions() — see everything stored.
  • delete(session_id) — remove it, and this cascades to the subagent sessions under it.
  • list_subkeys(session_id) — list the subagent keys hanging off that session.

There is also a CLI flag --session-mirror, which copies the transcript to an external file while it streams — handy when the process dies before you can read anything.

Hooks

A hook is a function the harness calls at a fixed moment. Register it once, and it fires every time.

  • PreToolUse and PostToolUse — check or log every tool call. This is where you block a delete you do not like.
  • SessionStart and SessionEnd — set up and clean up.
  • UserPromptSubmit — touch the user's message before the model sees it.
  • PreCompact — runs just before the context gets compressed.
  • Stop — cleanup when the agent finishes.
  • Notification — side-channel alerts.
  1. 1User prompt→
  2. 2PreToolUse check→
  3. 3Tool runs→
  4. 4PostToolUse log→
  5. 5Session saved

Seeing one trace across two processes

The SDK starts the Claude Code CLI as a subprocess. Normally that breaks tracing in half — one trace for your code, another for the subprocess.

Not here. Any OpenTelemetry span open in your code is passed into the subprocess using W3C trace context headers — simply an agreed format for saying "this work belongs to that parent trace." So the whole multi-process run shows up as one trace in your dashboard.

Hosted instead of self-hosted

Claude Managed Agents is the hosted version. Anthropic runs the infrastructure and you get long-running async work, built-in prompt caching and built-in compaction without writing any of it.

The trade is simple: less control, much smaller ops burden. Self-host when you need to shape the loop yourself; go managed when you mostly want work to run reliably for hours.

Build it

Python
"""A tiny toy version of an agent harness: tools, hooks, subagents, session store."""

# ---- Tools -------------------------------------------------------------
TOOLS = {
    "word_count": lambda text: str(len(text.split())),
    "shout": lambda text: text.upper(),
}

# ---- Hooks -------------------------------------------------------------
HOOKS = {"pre_tool": [], "post_tool": []}

def register(event, fn):
    HOOKS[event].append(fn)

def run_tool(name, arg):
    for h in HOOKS["pre_tool"]:
        if h(name, arg) is False:          # a hook can veto the call
            return "BLOCKED by hook"
    fn = TOOLS[name]
    result = fn(arg)
    for h in HOOKS["post_tool"]:
        h(name, result)
    return result

# ---- Session store -----------------------------------------------------
SESSIONS = {}                               # session_id -> list of turns

def append(sid, msg):
    SESSIONS.setdefault(sid, []).append(msg)

def load(sid):
    return SESSIONS.get(sid, [])

def list_subkeys(sid):
    return [k for k in SESSIONS if k.startswith(sid + ":")]

# ---- Subagent: its own context, only the result comes back -------------
def subagent(parent_sid, child_name, big_text, tool):
    child_sid = parent_sid + ":" + child_name
    append(child_sid, big_text)              # the mess stays in the child
    return run_tool(tool, big_text)

# ---- Demo --------------------------------------------------------------
register("pre_tool", lambda n, a: n in TOOLS)
register("post_tool", lambda n, r: print(f"  [hook] {n} returned {len(r)} chars"))

parent = "sess_priya"
append(parent, "User: summarise these three log chunks")

chunks = ["error at line 12 " * 20, "all clear " * 30, "timeout db " * 25]
for i, chunk in enumerate(chunks):
    out = subagent(parent, f"worker{i}", chunk, "word_count")
    append(parent, f"worker{i} says: {out} words")   # one short line only

print("Parent turns:", load(parent))
print("Subagent keys:", list_subkeys(parent))
print("Parent context size:", sum(len(t) for t in load(parent)), "chars")
print("Child context size:", sum(len(t) for k in list_subkeys(parent) for t in load(k)), "chars")

Look at the last two printed lines. The children hold hundreds of characters of raw log text; the parent holds a few short sentences. That gap is context isolation — the whole reason subagents exist. Notice too that the hook fires on every tool call without any tool knowing about it.

Where you will see this

  • Claude Code itself — the SDK is that same harness, exposed for your own tools.
  • Cursor and similar coding assistants, which fan out subagents to search a big repo without filling the main context.
  • Customer-support bots that reload a chat from three days ago — that is the session store working.
  • Internal company agents where a PreToolUse hook blocks any command touching the production database.
  • Nightly report generation and bulk cleanup jobs — exactly the managed-hosting case.

Common mistakes

  • Spawning a subagent for every tiny task. A hundred subagents for a hundred one-line jobs means overhead costs more than the work. Batch them.
  • Hook creep. Every team adds "just one small hook", and later startup is slow and nobody knows what runs. Review hooks every few months.
  • Session bloat. Sessions pile up and storage grows. Use list_sessions with an expiry policy.
  • Deleting a parent session without cascading. Subagent sessions become orphans that nobody reads or removes.
  • Thinking the harness makes the agent correct. It only handles plumbing. A bad prompt is still bad, just with nicer logs.

If they ask in an interview

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

A: The Client SDK is the raw Messages API — you write the loop, execute tools and manage state yourself. The Agent SDK ships that loop pre-built: built-in tools, MCP connections, hooks, subagents and a session store. Pick the Client SDK when you want full control over the loop shape.

Q: Why would you spawn a subagent instead of just doing the work in the main agent?

A: Two reasons. Parallelisation, so independent tasks run together. And context isolation — the subagent reads the bulky material in its own context and returns a short result, so the parent's budget stays free for reasoning.

Q: How do you get one end-to-end trace when the SDK runs the CLI as a subprocess?

A: The active OpenTelemetry span is propagated into the subprocess using W3C trace context headers. Both processes then report under the same trace ID, so your backend shows one trace instead of two halves.

Try these

  1. Add a PreToolUse hook to the toy code that allows a tool at most five calls per session. Print a message when it blocks one.
  2. Batch twenty tasks into four subagents of five each. Print parent context size for one-per-task versus batched, and compare.
  3. Add delete(sid) and make it cascade — deleting the parent must remove every subagent key under it. Check list_subkeys is empty after.
  4. Print the subagent keys as an indented tree, then nest a subagent inside a subagent and see what three levels look like.

Words, simply

WordMeaning in simple words
HarnessThe code around the model: loop, tools, memory, checks
Agent SDKClaude Code's harness shipped as a library you can import
Client SDKThe plain model API; you write the loop yourself
SubagentA child agent with its own context; only its result comes back
Session storeWhere conversations are saved so they survive a restart
HookA function the harness calls at a fixed moment, like before a tool runs
W3C trace contextAn agreed format for linking work across processes into one trace
Managed AgentsThe hosted version — Anthropic runs the infrastructure for you

Quick recap

  • The Agent SDK is a harness in a box: built-in tools, MCP, hooks, subagents, session store — the Client SDK is just the raw API.
  • Subagents exist for two reasons only: run things in parallel, and keep bulky work out of the parent's context.
  • Hooks give you cross-cutting control, the session store gives you memory across restarts, and managed hosting trades control for far less ops work.

Check what you learned

1 / 7. What is the difference between the Anthropic Client SDK and the Claude Agent SDK?
1/7
PreviousOpenAI Agents SDKNextAgno and Mastra

On this page