Anthropic Agent SDK: Use Claude Code's Engine in Your App
▶ Watch on YouTube & subscribe to The Stack Underflow
You have built something with Claude Code, watched the agent loop spin, and thought: “I want this running inside my service at 3 a.m. — no terminal, no human, no CLI.” That impulse is exactly the problem the Anthropic Agent SDK solves. It does not replicate Claude Code. It is Claude Code’s engine, repackaged as a library you import and call from Python or TypeScript.
The distinction matters because it changes what you build. When your code drives the loop — not a human typing into a terminal — you need explicit handles on the agent’s lifecycle, tool permissions, and output. The SDK gives you all of those while keeping every building block you already know from the CLI: subagents, skills, hooks, MCP connections, and the same four built-in tools.
The one-sentence version: The Agent SDK is the agent loop, tools, and context management that power Claude Code, handed to you as a library — so your application code drives the same engine the CLI uses, without running the CLI at all.
The layer model: one engine, two entry points
The series has been building a layered picture of how Claude works. The Agent SDK sits at the same layer as Claude Code in that stack — but it is not above it or below it. Both surfaces share one engine. Neither is a thin wrapper; neither is a simplified clone.
┌────────────────────────────────────────┐
│ Claude Code (CLI) │ ← human at the wheel
├────────────────────────────────────────┤
│ Your App via Agent SDK │ ← your code at the wheel
├────────────────────────────────────────┤
│ Agent Loop + Built-in Tools │ ← SHARED ENGINE
├────────────────────────────────────────┤
│ Context / Token Management │
├────────────────────────────────────────┤
│ Claude API (Messages API) │
└────────────────────────────────────────┘
The shared-engine point is load-bearing. When you call the SDK, the same agent loop logic that handles a claude terminal session is what runs your task. You are not sacrificing fidelity for convenience. The only thing you lose is the terminal.
The TypeScript package makes this even more concrete: @anthropic-ai/claude-agent-sdk ships the Claude Code binary as an optional dependency. You do not install the CLI separately. One npm install and the built-in tools are available to your agent in process. The Python equivalent, claude-agent-sdk on PyPI, works the same way through a native binary attachment.
What ships in the box
Out of the box, an SDK-powered agent gets the same built-in tools the CLI exposes to Claude when a developer runs claude interactively:
| Tool | What it does |
|---|---|
Read | Read files from the local filesystem |
Bash | Execute shell commands in a subprocess |
Edit | Apply targeted, diff-style edits to files |
WebSearch | Search the web for current information |
These are not reimplementations. They are the same tool code paths. Your automated agent can read a repository, run a test suite, patch a file, and look up an external API — the same actions Claude Code takes when a developer asks it to.
Beyond the built-in tools, every building block from the CLI is reachable from the SDK:
- Subagents — spawn isolated child agents to handle focused subtasks in parallel. The parent agent delegates; each subagent gets its own context window and reports back. Enable them by including
Agentin yourallowedToolslist. - Skills — reusable capability packages defined by a
SKILL.mdfile. The skill folder format is the same whether the agent is run from the CLI or the SDK; the runtime picks them up identically (docs.anthropic.com, 2026). - Hooks — in-process callbacks that fire at fixed points in the agent lifecycle. In the CLI, hooks are shell commands configured in
settings.json; in the SDK they are callback functions you pass on theoptions.hooksobject. The same six events are available:PreToolUse,PostToolUse,Stop,SessionStart,SessionEnd, andUserPromptSubmit. - MCP connections — the SDK has first-class Model Context Protocol client support. Any MCP server you would connect to in the CLI connects identically here. Custom tools defined as MCP servers plug into the same
allowedToolspattern (modelcontextprotocol.io, 2025-2026).
A minimal working agent
The SDK collapses to three steps: create a client, declare which tools it may use, run the loop on a task. Everything else — the reasoning, the tool calls, the retry logic, the token management — happens inside the engine.
import { ClaudeAgent } from "@anthropic-ai/claude-agent-sdk";
const agent = new ClaudeAgent({
model: "claude-opus-4-8", // current default for agentic work, June 2026
});
const result = await agent.run({
task: "Triage this CI failure and propose a fix: <paste logs here>",
allowedTools: ["Bash", "Read", "Edit"],
});
console.log(result.output);
The loop spins on its own. It reads the logs, runs a diagnostic command, inspects the relevant file, proposes a patch, and returns when done. You supply the task; the SDK supplies the judgment and orchestration. The loop is not a while you write — it is the same loop Claude Code runs, triggered by your agent.run() call.
Lifecycle hooks in practice
Hooks are the most powerful tool for making an agent safe to run headlessly. Because the SDK exposes hooks as in-process callbacks, you can gate, log, or transform any action the agent takes — without touching the core loop.
Task submitted
│
▼
[ UserPromptSubmit hook ] ← sanitise / reject the task upfront
│
▼
Agent loop starts
│
▼
[ PreToolUse hook ] ← approve or block every tool call before it fires
│
▼
Tool executes
│
▼
[ PostToolUse hook ] ← log result, run formatter, push telemetry
│
▼
Loop continues or stops
│
▼
[ Stop / SessionEnd hook ] ← finalise, persist state, notify downstream
A concrete example: put a PreToolUse hook in front of Bash and reject any command that matches a deny-list of destructive patterns. A successful prompt injection — or just an overconfident agent — hits this gate and stops there. The hook runs outside the model’s reasoning, so the model cannot talk its way around it.
| Hook event | Typical use |
|---|---|
PreToolUse | Guardrails, confirmation gates, argument rewriting |
PostToolUse | Auto-formatting, linting, telemetry, logging |
UserPromptSubmit | Input validation, PII scrubbing, task routing |
Stop | Output validation, result caching |
SessionStart / SessionEnd | State initialisation, cleanup, audit logging |
When to reach for the SDK vs. the CLI
The decision comes down to one question: who is at the wheel?
| Scenario | Reach for |
|---|---|
| Developer working interactively in a terminal | Claude Code (CLI) |
| Application, service, or backend worker driving the agent | Agent SDK |
| Automated pipeline — CI/CD, cron job, nightly report | Agent SDK |
| One-off exploratory task with a human in the loop | Claude Code (CLI) |
| Embedded agent inside a product your users interact with | Agent SDK |
| Need programmatic access to all six lifecycle hook events | Agent SDK |
Claude Code is the interactive, human-driven surface. The Agent SDK is the programmatic, machine-driven surface. Same engine — different steering wheel.
Billing: what the June 2026 change means for you
In May 2026, Anthropic announced that Agent SDK and claude -p (headless) usage would move to a separate monthly Agent SDK credit pool distinct from interactive subscription limits, effective June 15, 2026. The stated intent was that automated runs would not eat into the interactive quota.
On June 15, Anthropic paused that change on the day it was scheduled to take effect. As of June 25, 2026, Agent SDK usage on subscription plans (Pro, Max, Team, Enterprise) continues to draw from the same standard subscription limits as interactive usage — no separate pool exists yet. Anthropic’s support documentation reflects this.
The practical advice: watch the Anthropic changelog closely. The billing split is a stated direction, and it may ship in revised form. If your use case involves high-volume headless runs, budget accordingly and check the current docs before you architect around any specific credit model.
Common misconceptions
“The Agent SDK is a thin wrapper around the raw Claude API.” It is not. The raw Messages API is the bottom layer — it handles a single request-response turn and returns a stop_reason like end_turn or tool_use. The Agent SDK is everything above that: the full agent loop, the context management that tracks token budget across turns, the tool orchestration, subagent coordination, hook events, MCP integration, and the built-in tools. These are entirely different abstractions.
“I need to install the Claude Code CLI before using the SDK.” The TypeScript package (@anthropic-ai/claude-agent-sdk) ships the Claude Code binary as an optional dependency. One npm install and you have the built-in tools. No separate CLI install is required.
“The SDK gives me a stripped-down version of Claude Code’s capabilities.” Nothing is removed. Subagents, skills, all six lifecycle hook events, MCP server connections, and the four built-in tools are all present. If the CLI can do it, the SDK exposes it — the surface area is identical. The only difference is who initiates the run.
“I should model-pin to claude-opus-4-8 for everything.” For straightforward or latency-sensitive agentic work, claude-sonnet-4-6 delivers strong performance at lower cost. Reserve claude-opus-4-8 for long-horizon, high-autonomy tasks where the extra reasoning depth pays off. Always pin explicitly — never rely on a default pointer that may change (platform.claude.com/docs/en/about-claude/models/overview, 2026).
Frequently asked questions
Can I use the Agent SDK in Python, or only TypeScript?
Both are fully supported. The Python package (claude-agent-sdk on PyPI) and the TypeScript package (@anthropic-ai/claude-agent-sdk on npm) expose the same agent loop and building blocks. The TypeScript package has the additional convenience of bundling the Claude Code binary as an optional dependency. In Python, SessionStart and SessionEnd hook events come from settings-file shell hooks rather than the options.hooks callback object — a minor implementation detail, same functionality.
Do I have to use the built-in tools, or can I register custom ones?
You can do both. The built-in tools (Bash, Read, Edit, WebSearch) are available when you include their names in allowedTools. You register additional custom tools alongside them — either as direct function definitions or as MCP server connections. The tool call mechanism is identical regardless of source.
How are SDK hooks different from Claude Code CLI hooks?
In the CLI, hooks are shell commands declared in settings.json that the runner forks as subprocesses at lifecycle events. In the SDK, hooks are in-process callback functions you pass to the agent at construction. The events are the same — PreToolUse, PostToolUse, Stop, SessionStart, SessionEnd, UserPromptSubmit — but SDK hooks have direct access to your application’s runtime, state, and libraries, which makes them considerably more powerful for production use.
What is the default model for Agent SDK runs in June 2026?
The authored prompt specifies claude-opus-4-8 as the current default for agentic work, with claude-sonnet-4-6 as the strong cost-efficient alternative. For the hardest long-horizon agentic tasks where access is available, claude-fable-5 is the frontier option. Always pin the model ID explicitly in production — never omit it and rely on a default.
What comes after the Agent SDK in the series? The next tutorial covers managed agents — a mode where Anthropic runs the agent infrastructure on your behalf. With the Agent SDK, you still host and execute the agent process. With managed agents, you hand off the task and Anthropic handles the execution. It is the next step on the autonomy dial, covered in Managed Agents on Anthropic.
Can the Agent SDK connect to MCP servers?
Yes, MCP client support is first-class in the SDK. Define your MCP server connections and include the resulting tools in allowedTools. This is the standard way to give agents access to custom data sources, APIs, and services. See What is MCP? for the protocol-level explanation.
Where this fits in the series
This tutorial is episode 18 of How Claude Actually Works. The series has progressively layered the Claude stack from raw token processing through context management, tool calling, the Claude Code CLI, and its internal building blocks. The Agent SDK is the natural next step: the CLI’s internals becoming a first-class library for code that drives agents without a human at the wheel.
To follow the full arc, the foundational layer lives in The Claude Stack Mental Model. The building blocks the SDK exposes — subagents, skills, hooks, plugins — are covered in Claude Code Skills, Subagents, Hooks, and Plugins Explained. The hooks system specifically is unpacked in Claude Code Hooks Explained. The next episode goes one step further toward hands-off automation: Managed Agents on Anthropic, where Anthropic runs the loop for you.
Browse all tutorials to follow the complete series.
Found this useful? The deep version lives on YouTube — new breakdowns of how AI dev tools actually work, weekly.
Subscribe on YouTube →