Claude Agent SDK

Claude Code, as a library.

An agent loop you can call from your own code. You hand it a prompt; it reads files, runs commands, edits code, and searches the web — until the task is done. Here's what it is, why it exists, and how to know whether it's the right tool for you.

Python · TSTwo SDKs
Built-inTools & loop
Your infraRuns in-process

What it actually is

The Claude Agent SDK is Claude Code packaged as a library for Python and TypeScript. You give it a prompt, and it runs the full agent loop for you — Claude decides what to do, calls tools, sees the results, and keeps going until the work is finished.

The point: you don't build the tools or the loop. Reading files, running Bash, editing code, web search — it's all built in and ready on the first call.

async for message in query(
    prompt="Find and fix the bug in auth.py",
    options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"]),
):
    print(message)  # Claude reads the file, finds the bug, edits it

The problem it solves

To make Claude do things — not just chat — you normally write a manual loop: send prompt → Claude asks to use a tool → you execute it → send the result back → repeat. That's the raw API / Client SDK path, and you build all the plumbing yourself.

The Agent SDK hands you that plumbing for free, plus everything that makes Claude Code good at real work: built-in tools, subagents, hooks, permissions, sessions, MCP, and automatic context management so long tasks don't blow the context window.

What you get out of the box

🧰

Built-in tools

Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch — nothing to implement.

🤖

Subagents

Spawn specialized agents for focused subtasks; they report back with results.

🪝

Hooks

Run your own code at lifecycle points — log, validate, block, or transform behavior.

🔒

Permissions

Whitelist safe tools, block dangerous ones, or require approval for sensitive actions.

🧵

Sessions

Persistent context across exchanges. Resume later or fork to explore alternatives.

🔌

MCP

Connect databases, browsers, and APIs through the Model Context Protocol.

Which Claude tool should you use?

OptionRuns whereBest for
Claude Code CLIYour terminalInteractive dev, one-off tasks
Client SDK (raw API)Your processPlain text generation — you wire up any tools
Agent SDKYour process & infraAutonomous agents that work on your files & services
Managed AgentsAnthropic infraProduction agents without running your own sandbox

The decision, in four rules

Just generating text, no autonomous actions
→ Client SDK
Coding by hand, interactively
→ Claude Code CLI
An agent that reads, edits & runs things on your machine
→ Agent SDK
Same, but let Anthropic run the sandbox & scaling
→ Managed Agents

Common path: prototype with the Agent SDK locally, then graduate to Managed Agents for production if you'd rather not run the infrastructure yourself.

Get started in three steps

1

Install

npm i @anthropic-ai/claude-agent-sdk or pip install claude-agent-sdk (Python 3.10+).

2

Set your key

export ANTHROPIC_API_KEY=… from the Console. Bedrock, Vertex & Azure also supported.

3

Run an agent

Call query() with a prompt and allowed_tools — that's a working agent.

// TypeScript — bundles the Claude Code binary, nothing else to install
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Find all TODO comments and create a summary",
  options: { allowedTools: ["Read", "Glob", "Grep"] }
})) {
  if ("result" in message) console.log(message.result);
}

Is this even an agent job?

Reach for the Agent SDK only when all three are true. Miss one, and a single API call or a plain script will be cheaper, faster, and more predictable.

01

Steps aren't known ahead

The work depends on what it discovers along the way — no fixed recipe.

02

It explores real state

Files, command output, a database, an API — and reacts to what it finds.

03

Tool use is the point

The value is in doing, not in generating a block of text.

Where it fits in the real world

ScenarioWhy an agent — not a script or one API call
CI failure triage botOn a red build it reads the logs, greps the repo, finds the cause, opens a fix PR. Different path every time.
Dependency & framework upgrades"Bump this major version." It edits, runs tests, fixes breakage, iterates — reasoning a codemod can't.
On-call / ops copilotPager fires → it pulls logs, runs read-only diagnostics, drafts the next runbook step. Keep it read-only at the gateway.
DB investigation"Why is this endpoint slow?" It inspects the query, checks indexes, drafts a migration against the real schema.
Support ticket → codeIt navigates the actual codebase to find the responsible module and proposes a precise patch, not a generic reply.
Product feature: "do it for me"Give your users an agent that acts over your app's data & tools via MCP; your API layer is the auth/quota boundary.

The common shape: an agent works on your files, infra, and services across many unknown steps. That's exactly what the SDK gives you — and what a raw API call does not.

Where not to use it

One input, one transform

Summarize · classify · extract · rewrite a single thing → a plain Claude API call.

A fixed pipeline

No decisions to make → a normal script beats an agent every time.

High volume, latency-sensitive

Agents are slower and pricier per run — wrong for thousands of requests a minute.

Fully deterministic output

If you need the same result every time, don't hand it to a reasoning loop.

What it costs

The Agent SDK bills exactly like the Claude API — you pay per token for the model you choose. An agent costs more than a single call because the loop re-sends the growing context and generates tool calls each turn. Prices below are US dollars per million tokens.

ModelContext InputOutput Cache readCache write
Claude Fable 5 most capable1M$10.00$50.00~$1.00$12.50
Claude Opus 4.8 default1M$5.00$25.00~$0.50$6.25
Claude Sonnet 5 balanced1M$3.00$15.00~$0.30$3.75
Claude Haiku 4.5 fast & cheap200K$1.00$5.00~$0.10$1.25
Cache read ≈ 0.1× input — repeat context is ~90% cheaper Cache write = 1.25× input (5-min TTL; 2× for 1-hour) Batch API = 50% off, async Sonnet 5 intro: $2 / $10 through 2026-08-31

Feel the scale. In this POC, one trivial "create a file and read it back" task on Opus 4.8 cost about $0.17 — fine for a PR bot that fires occasionally, wrong for 10,000 requests a minute. Levers to cut it: prompt caching for shared context, a cheaper model (Haiku/Sonnet) for simple steps, and the Batch API for non-urgent work.

Who reaches for it — and who shouldn't

✓ A good fit
  • Product & platform engineers automating their own codebase — CI fixers, dependency upgrades, migrations.
  • DevTools / internal-tools teams shipping agents that act on company systems and repos.
  • SaaS builders embedding a "do-it-for-me" agent over their own data & tools via MCP.
  • Ops / SRE building on-call copilots that read logs and run read-only diagnostics.
  • Startups & solo devs prototyping agentic features fast, on their own infra.
✗ Better served elsewhere
  • Need one text answer? Summarize · classify · extract → the Client SDK (Messages API).
  • High volume, latency-critical? Thousands of calls a minute → a plain API call, not an agent loop.
  • Don't want to run infra? Prefer a hosted sandbox & session store → Managed Agents.
  • No-code / non-technical? The SDK is a developer library — reach for a finished product.
  • Fully deterministic output? Same result every time → ordinary code beats a reasoning loop.

A reference architecture

React app
Human surface — intent in, live timeline out
Hono middleware
Gateway — auth, quotas, logging & the policy boundary
Agent SDK query()
The loop — reasons, calls built-in tools, observes

The integration layer is where an agentic app earns its keep: it's the one place to enforce what an autonomous agent is allowed to do — the tool allow-list, the sandbox, the auth. A permission guard there (not just a working directory) is the real security boundary.

Under the hood — the real code

Not pseudocode. This is the actual source running in the reference POC: a Hono API that streams the agent loop, the canUseTool guard that jails it to a sandbox, and the browser-side client that reads the stream. Click a tab.

index.ts — Hono middleware pipeline + the SSE endpoint that runs query() guard.ts — the sandbox & tool-allow-list boundary api.ts — SSE-over-fetch, because EventSource can't POST

Go deeper

Built as a field note · Back to the Field Library · Content summarized from the official Claude Agent SDK docs