Claude Agent SDK: How to Build Production AI Agents
Learn how to take the Claude Agent SDK from prototype to production with sandboxing, durable sessions, permissions, observability, approvals, and recovery.
One call to the Claude Agent SDK can create a local Claude CLI subprocess with its own working directory, session files, tools, and child processes. Anthropic's official hosting guide makes the operational implication clear: this is not a stateless API wrapper. Every active session is a workload you must isolate, persist, limit, observe, and eventually terminate.
The Claude Agent SDK gives Python and TypeScript applications the agent loop behind Claude Code: tools, sessions, permissions, hooks, subagents, and MCP connections. That is a capable runtime. It is not a complete production system.
This guide shows the SDK-specific architecture around that runtime: how to operate its subprocess, working directory, sessions, hooks, permissions, and MCP tools with durable state, observability, and human approval.
The production rule: treat the Claude Agent SDK as the reasoning and execution harness. Treat everything around it as an application and operations problem.
What is the Claude Agent SDK?
The Claude Agent SDK is Anthropic's library for embedding Claude Code's agent loop inside an application you operate. The official Agent SDK overview documents Python and TypeScript support, built-in tools, session management, hooks, permissions, subagents, skills, and MCP.
That definition matters because three adjacent products are easy to confuse.
| Product | What it gives you | What you still own |
|---|---|---|
| Claude Agent SDK | An agent harness with a tool loop, sessions, permissions, hooks, and subagents | Hosting, isolation, authorization, persistence, monitoring, recovery |
| Anthropic client SDK | Lower-level access to the Messages API | Planning loop, tool execution, state, and all production controls |
| Claude Code | An interactive coding product and CLI | It is not your application's control plane |
| Managed agent hosting | A hosted execution option from Anthropic | Application policy, identity, business authorization, and operator workflows |
The Agent SDK was formerly described as the Claude Code SDK. Use the current name in new systems, but expect the older term in repositories and search results.
What comes built in
A Claude Agent SDK application can:
- inspect files and search a working directory
- call allowed tools and shell commands
- keep and resume a session
- intercept lifecycle events with hooks
- delegate bounded work to subagents
- connect tools and data through MCP
- stream intermediate messages and final results
Those primitives save months of harness work. They do not decide who may issue a refund, which tenant owns a record, how a failed job resumes, or when a human must approve a side effect.
For a broader map of orchestration libraries, use our AI agent frameworks guide. This article stays at a different altitude: operating one specific SDK safely in production.
The four-layer production architecture
A reliable Claude agent is easier to reason about when you separate four responsibilities.
| Layer | Owns | Failure if omitted |
|---|---|---|
| 1. Claude Agent SDK | reasoning loop, context, tools, sessions, hooks | You rebuild the agent harness |
| 2. Execution environment | process, filesystem, network, resource isolation | One run can reach data or systems it should not |
| 3. Application control plane | identity, queues, tenant routing, budgets, lifecycle | Runs duplicate, disappear, or cross boundaries |
| 4. Operations and governance | traces, approvals, audits, intervention, evaluation | Nobody can safely supervise or explain the work |
1. The request and control plane
Do not let an HTTP request directly start an unbounded agent and wait. Put an application-owned control plane in front:
- Authenticate the actor.
- Resolve the tenant and policy.
- Create an idempotent run record.
- Place the task on a queue.
- Allocate a worker with explicit limits.
- Stream status events to the product.
- Persist the result and terminal state.
The run registry should know whether a task is queued, working, waiting for approval, completed, canceled, or failed. That state belongs to your application, not to a chat transcript.
2. The SDK worker is not a stateless wrapper
Anthropic's hosting guide explains that the SDK communicates with a Claude CLI subprocess. The process has a working directory, local files, child processes, and session state.
That has practical consequences:
- Ten concurrent sessions can mean ten active process trees.
- A worker restart can remove local artifacts that were never persisted.
- Cancellation must terminate descendants, not only the parent request.
- Health checks must cover the process and the job state.
- Capacity planning needs CPU, memory, disk, token, and subprocess limits.
A serverless function can still be part of the ingress layer. It is rarely the whole execution environment for a long-running, tool-using agent.
3. Sandbox every run
SDK permissions are useful, but they are application behavior. They are not an operating-system security boundary.
Give each run or tenant:
- an isolated working directory
- a container or stronger sandbox
- a read-only base image where practical
- CPU, memory, process, and wall-clock limits
- short-lived credentials
- outbound network allowlists
- restricted filesystem mounts
- controlled artifact export
- cleanup after termination
Treat documents, websites, repository content, and MCP responses as untrusted input. A prompt injection inside a support ticket should not gain more authority than the employee who submitted it.
The OWASP guidance for LLM applications is a useful threat-model baseline.
Building Effective AI AgentsDiscover how Anthropic approaches the development of reliable AI agents. Learn about our research on agent capabilities, safety considerations, and technical framework for building trustworthy AI.4. Add an operations layer around the runtime
A production trace must reconstruct:
- what request started the run
- which identity and tenant authorized it
- what context the model received
- which tools it requested
- which calls were approved, blocked, or executed
- what each call returned
- how many turns, tokens, and dollars it consumed
- why it stopped
- what artifact or side effect it produced
This is where Rerun fits. Rerun is not another framework and it does not replace the Claude Agent SDK. It is a framework-agnostic operations layer for watching runs, retaining logs, routing approvals, and keeping a human in control. It does not provide the SDK's reasoning loop, and it should not be treated as the sandbox boundary.
A Claude Agent SDK run trace, from request to approval
A trace should follow the SDK's real lifecycle, not reduce the run to one model response. This representative event sequence is the operational artifact we use to design the surrounding system.
| Sequence | SDK or application event | Control recorded | Operator question answered |
|---|---|---|---|
| 1 | Application accepts task | actor, tenant, idempotency key | Who asked for this work? |
| 2 | Worker starts Claude subprocess | worker ID, SDK version, working directory | Where is it running? |
| 3 | SDK requests a tool | tool name, validated arguments, session ID | What is Claude trying to do? |
| 4 | Pre-tool hook evaluates policy | allow, block, or approval-required decision | Which rule applied? |
| 5 | Run pauses for a human | proposed side effect, evidence, expiry | What exactly am I approving? |
| 6 | Tool executes after approval | external receipt, duration, redacted result | Did the action happen once? |
| 7 | SDK verifies outcome | test, read-after-write result, artifact hash | Is the completion claim supported? |
| 8 | Worker stops and cleans up | stop reason, descendants terminated, artifacts persisted | Can the run be audited or recovered? |
This sequence creates a durable boundary between what Claude proposes and what the application authorizes. A generic model transcript cannot answer these questions.
The implementation can emit structured events from hooks and application code:
def audit_tool_request(run, tool_name, tool_input, decision):
emit_event({
"event": "tool_policy_decision",
"run_id": run.id,
"session_id": run.session_id,
"tool": tool_name,
"input_hash": stable_hash(tool_input),
"decision": decision.status,
"policy_version": decision.policy_version,
"requires_approval": decision.requires_approval,
})Keep secrets and raw personal data out of telemetry. Store references or hashes when the full payload is not required for an audit.
Build a bounded Claude Agent SDK task
A production guide still needs a minimal reference point. The exact API can change, so verify package names and options against the current Python reference before deployment.
The important design choices are stable: a specific working directory, a small tool allowlist, a turn limit, streaming result handling, and explicit failure states.
import asyncio
from claude_agent_sdk import ClaudeAgentOptions, query
async def run_review():
options = ClaudeAgentOptions(
cwd="/workspaces/review-4f31",
allowed_tools=["Read", "Glob", "Grep"],
max_turns=12,
permission_mode="default",
)
async for message in query(
prompt=(
"Review the staged change. Do not edit files. "
"Return findings with file paths and evidence."
),
options=options,
):
persist_event(message)
asyncio.run(run_review())This is deliberately read-only. A first production task should prove that identity, isolation, traces, cancellation, and recovery work before it receives write access.
Give business tools narrow contracts
Do not expose a generic "run SQL" tool when the job only needs to fetch one account. Do not expose "send email" when the desired first step is "create draft."
A good tool contract is:
- small and explicitly named
- schema validated
- scoped to the current actor and tenant
- bounded by a timeout
- idempotent where possible
- clear about side effects
- safe to retry, or marked as non-retryable
Here is a useful agent brief for a consequential workflow. It separates reversible preparation from an irreversible action.
{
"goal": "Prepare an overdue-invoice follow-up",
"allowed_actions": [
"read_invoice",
"read_customer_contact",
"create_email_draft"
],
"forbidden_actions": [
"send_email",
"change_invoice",
"issue_refund"
],
"verification": [
"invoice_is_still_overdue",
"recipient_matches_customer_record",
"draft_mentions_correct_amount"
],
"approval_required_for": [
"send_email",
"apply_credit",
"issue_refund"
],
"limits": {
"max_turns": 10,
"max_runtime_seconds": 180
}
}MCP expands capability and the trust boundary
MCP gives the Claude Agent SDK a standard way to reach tools and data. It does not make those tools safe by default.
For each MCP server, decide:
- how credentials are supplied
- which tenant and actor they represent
- which tools are exposed
- which arguments are permitted
- which outputs need validation
- which actions require approval
- how access is revoked after a run
Connect the smallest useful surface. "The server supports 40 tools" is not a reason to expose all 40.
Design a loop that can prove its work
Anthropic's practical pattern is simple: gather context, take action, verify results. Production systems should make every stage inspectable.
Gather only the context the task needs
Let the agent search a bounded workspace instead of copying an entire repository or knowledge base into the prompt. Keep tenant filters outside the model. If retrieval can return another customer's data, prompt wording will not repair the boundary.
Separate:
- session transcript
- application state
- files and artifacts
- project instructions
- long-term memory
- audit events
A session identifier is not a backup strategy. Persist each type according to its recovery needs.
Verify before claiming completion
A model saying "done" is not evidence. Require deterministic checks such as:
- schema validation
- tests and linters
- read-after-write verification
- policy evaluation
- artifact scanning
- expected-state comparison
- receipts from external systems
An LLM judge can add a useful signal. It should not be the only gate for money movement, deletion, access changes, or customer communication.
Use subagents selectively
Subagents help when research or analysis can run independently. They also multiply context, tool calls, cost, and failure paths.
Set explicit limits on:
- delegation depth
- fan-out
- accessible tools
- per-agent budgets
- total run time
- how evidence returns to the parent
More agents are not automatically a better architecture. One bounded loop with strong tools often beats a swarm nobody can debug.
Choose a session and hosting model
| Model | Best for | Main benefit | Main risk |
|---|---|---|---|
| Ephemeral | bounded one-off jobs | clean isolation and teardown | cold starts and state hydration |
| Long-running | interactive or continuous work | low latency and warm context | idle cost and restart complexity |
| Hybrid | intermittent resumable work | balance of cost and continuity | careful persistence and versioning |
| Multi-agent container | tightly related advanced workloads | shared local resources | leakage, contention, correlated failure |
Ephemeral sessions
Start a clean sandbox per task, hydrate required data, run, persist artifacts, and destroy the environment. This is the safest default for jobs that complete in minutes.
Long-running sessions
Keep the process warm for interactive products or continuous agents. Define maximum sessions per worker, heartbeat behavior, drain procedures, and restart recovery.
Hybrid sessions
Persist before shutdown, then hydrate and resume by session ID. Test recovery across SDK upgrades. Session transcripts, filesystem artifacts, and memory files may need different stores.
For framework-neutral cloud patterns, our guide to deploying AI agents goes deeper than this SDK-specific article should.
Secure consequential actions at three levels
Least privilege needs three independent layers.
- SDK permissions: which tools the agent may request.
- Application authorization: whether this actor and tenant may perform the action.
- Infrastructure controls: what the process can reach even if other checks fail.
If all three reduce to "the prompt says not to," there is no meaningful boundary.
Use hooks as enforcement and instrumentation points
The official hooks documentation describes lifecycle interception around tool use, permissions, sessions, and stopping.
Useful patterns include:
- check policy before a tool call
- redact or classify tool output
- emit a structured audit event
- pause for approval
- validate completion
- clean up resources at session end
Business-critical authorization must fail closed outside the model. If the policy service is unavailable, a payment tool should stop, not improvise.
Make approval a durable state
A human approval is not a Slack message that the agent ignores after a timeout. It is a blocking state transition.
| Action | Default policy | Evidence shown to approver |
|---|---|---|
| Read an allowed record | automatic | record ID, tenant, reason |
| Create a draft | automatic with logging | draft and source data |
| Send an external message | approval for new workflows | recipient, full content, sources |
| Modify production data | approval | diff, owner, rollback plan |
| Issue refund or payment | mandatory approval | amount, policy, account, evidence |
| Delete data or change access | mandatory approval | scope, impact, recovery path |
Rerun can hold a run in a waiting-for-human state, show the proposed action and its context, then resume after approval. The application still owns the underlying business authorization.
Observability, budgets, and recovery
Traditional service metrics are necessary but insufficient. Track at least:
- success rate by task type
- deterministic verification pass rate
- human intervention rate
- tool error rate
- retries and duplicate prevention
- turns and tool calls per run
- tokens and cost per successful task
- median and P95 duration
- queue wait time
- cancellation and timeout rate
Version prompts, tool schemas, policies, models, and SDK dependencies. Without versions, a regression has no useful before-and-after boundary.
Plan for failure before scaling
| Failure | Detection | Recovery |
|---|---|---|
| Worker exits | heartbeat and missing lease | reclaim job from durable checkpoint |
| Tool times out | typed timeout event | retry only if safe and idempotent |
| Approval expires | approval-state SLA | escalate or cancel, never auto-approve |
| Session cannot resume | hydration test fails | start a reviewed recovery run |
| Model loops | turn, time, and budget limits | stop with evidence and partial artifacts |
| Duplicate delivery | idempotency collision | return existing run state |
| Unsafe request | policy rejection | log reason and require human handling |
A replay should not blindly repeat side effects. Store external receipts and idempotency keys so recovery can distinguish "not attempted" from "completed but response lost."

AI Agent Testing: How to Build a Test Harness for Reliable Agents
Learn how to test AI agents that actually work: golden datasets, LLM-as-a-judge, trajectory evals, and the runtime governance that turns testing into reliability.
Why this is not a Zapier, Make, or n8n flowchart
Deterministic workflow tools are excellent when the path is known: trigger, validate, transform, send. Use them for that.
The Claude Agent SDK is useful when software must inspect an environment, form a plan, choose tools, and revise its approach based on results. That flexibility adds variable paths, latency, cost, and operational risk.
A flowchart stops where its designer stopped drawing. An agent keeps choosing. That is why the agent needs stronger runtime controls, not fewer.
A sensible system can wrap one agentic step in a deterministic workflow. Do not use an autonomous agent when an ordinary function or queue worker will do.
Why this is not just a chatbot
A chatbot primarily exchanges messages. A production agent can maintain task state, inspect systems, execute tools, create artifacts, pause for approval, verify changes, and resume later.
The distinction is agency and side effects, not the presence of a chat window. A polished conversation does not make a system operationally ready.
If you need the broader conceptual boundary, AI agent vs chatbot covers it without duplicating this production guide.
Production readiness checklist
Architecture
Security
Reliability and operations
Evaluation
The practical production standard
The Claude Agent SDK gives you a strong agent runtime without forcing you to rebuild the loop behind Claude Code. The production advantage comes from what you put around it.
Start with one bounded, read-only task. Isolate it. Persist its state. Record every tool call. Add deterministic verification. Then introduce side effects behind approvals.
Rerun sits outside the reasoning loop, where operators need it: live run visibility, audit trails, costs, approvals, and intervention across frameworks.
The goal is not maximum autonomy. It is useful autonomy that remains observable, interruptible, and accountable.
Frequently asked questions
What is the Claude Agent SDK?
The Claude Agent SDK is Anthropic's Python and TypeScript library for embedding Claude Code's agent loop, tools, sessions, permissions, hooks, subagents, and MCP connections inside an application you operate.
Is the Claude Agent SDK the same as the Anthropic API SDK?
No. The Agent SDK provides an agent harness and tool loop. The Anthropic client SDK gives lower-level API access, so your application owns more of the planning, tool execution, and state management.
Does the Claude Agent SDK run in the cloud?
It runs wherever you host the application and its Claude subprocess. You can operate it in containers, virtual machines, or another suitable environment, while Anthropic also offers managed hosting options.
Does the Claude Agent SDK support Python and TypeScript?
Yes. Anthropic provides official SDKs and reference documentation for both Python and TypeScript.
Can the Claude Agent SDK use MCP servers?
Yes. MCP can connect the agent to external tools and data, but your application must still enforce authentication, tenant scope, authorization, validation, and approvals.
How do you persist Claude Agent SDK sessions?
Persist the session identifier and transcript using the supported session mechanisms, then store working-directory artifacts, application state, memory files, and audit events separately according to their recovery needs.
Is the Claude Agent SDK production-ready?
It provides capable production building blocks, but production readiness depends on the surrounding isolation, persistence, authorization, observability, budget controls, recovery procedures, and human approval paths.
When should I use a workflow tool instead of an AI agent?
Use deterministic automation when every step and branch can be specified in advance. Use an agent when the task requires contextual planning, tool selection, iteration, and verification in a changing environment.
Written by
Clément Janssens


