2026-07-17
Claude Agent SDK (Formerly Claude Code SDK): Build and Host a Persistent Agent
Use the renamed Claude Agent SDK to build a bounded Python or TypeScript agent, then add sessions, storage, isolation, observability, and safe hosting.
Short answer: the product people still search for as the “Claude Code Agent SDK” is now officially called the Claude Agent SDK. It lets a Python or TypeScript application run the same agent loop, context management, and built-in tools that power Claude Code. You supply the task, working directory, tool policy, session rules, and surrounding application.
A useful first deployment is not an unrestricted autonomous developer. Start with one bounded job, a throwaway workspace, a short turn limit, and only the tools that job needs. Stream every event, retain the final result and cost data, and make external mutations somebody else's decision until the workflow has earned trust.
This guide builds that foundation, then shows what changes when the process must stay reachable after the original request: durable sessions, storage, isolation, credentials, telemetry, routing, and recovery.
Contents
- Use the current name and packages
- Know what the SDK provides
- Choose a bounded first job
- Install and authenticate
- Run a small Python agent
- Treat permissions as code
- Consume the event stream
- Choose a session lifecycle
- Persist the right state
- Build a real security boundary
- Add production operations
- Decide whether to host it yourself
The Claude Code SDK was renamed
Anthropic's current documentation and repositories use Claude Agent SDK. Older examples may refer to Claude Code SDK, import older option types, or install obsolete package names. The migration included naming changes such as ClaudeCodeOptions becoming ClaudeAgentOptions, alongside changes to settings isolation and programmatic agent features.
| What you may encounter | Use now |
|---|---|
| Claude Code SDK | Claude Agent SDK |
| Python package from an old tutorial | claude-agent-sdk |
| Current TypeScript package | @anthropic-ai/claude-agent-sdk |
ClaudeCodeOptions | ClaudeAgentOptions |
That is more than cosmetic housekeeping. Searching the old phrase can lead to code whose permission behavior, package path, or bundled CLI assumptions no longer match the release you install. Pin the SDK version, read its changelog before minor upgrades, and keep the package version and the bundled Claude Code binary version visible in your build record.
What the SDK gives you—and what it does not
The SDK is a programmable agent harness. It supplies an agent loop and built-in tools for files, code search, terminal commands, edits, web access, and other Claude Code capabilities. It can use hooks, MCP servers, subagents, sessions, and custom tools. Python offers the simple query() interface plus ClaudeSDKClient for an open bidirectional conversation. TypeScript exposes an async query object and streaming controls.
It does not become a hosted service merely because the loop is long-running. Your application still owns request authentication, queueing, tenant routing, workspace preparation, transcript retention, artifact storage, retries, cancellation, telemetry, and incident response. The model may choose actions; the surrounding system decides which actions are possible.
If you only want a specialist to inspect part of a repository inside one interactive Claude Code session, a Claude Code subagent is smaller and cheaper to operate. Use the SDK when you need to embed the loop in software, handle requests from another system, or control the session lifecycle programmatically.
Pick one first job with a stopping rule
“Maintain our repository” is a poor first contract. It has no finish line and mixes investigation, editing, release authority, and product judgment. Choose something a reviewer can verify in minutes.
A good starter job is a dependency-risk brief: inspect the lockfile and package manifests, find direct dependencies with a specified license or version pattern, and return paths plus a suggested verification command. It needs read and search access, but no edit tool, network credential, or deployment token. The output can be checked against the repository.
Write the contract before the prompt:
- one input location and one output schema;
- an explicit maximum number of turns;
- the allowed and forbidden tool categories;
- a list of conditions that must stop the run;
- the person or service allowed to approve a mutation;
- the evidence needed to call the task complete.
A persistent process should still perform finite jobs. “Always on” describes availability, not permission to work forever.
Install the current package and keep auth outside the prompt
For Python, Anthropic currently documents Python 3.10 or later. Create a virtual environment and install the SDK there:
python3 -m venv .venv
source .venv/bin/activate
pip install claude-agent-sdk
For TypeScript, use Node.js 18 or later and install the scoped package:
npm install @anthropic-ai/claude-agent-sdk
Both current SDK packages bundle a native Claude Code binary for supported platforms, so a separate Claude Code installation is not normally required. The binary is tied to the package release; update the SDK deliberately rather than replacing an invisible global CLI underneath a pinned application.
Set ANTHROPIC_API_KEY through your process environment or secret manager. Never paste it into a prompt, source file, transcript, or workspace note. For a production container, the stronger pattern is to keep sampling and tool credentials outside the agent's security boundary and inject them at a trusted proxy.
Run a bounded Python agent
This example asks for a read-only repository map. It caps the number of agent turns, chooses a working directory explicitly, and blocks mutation tools. Notice that allowed_tools pre-approves tools; it is not the complete deny list.
import asyncio
from claude_agent_sdk import (
ClaudeAgentOptions,
ResultMessage,
query,
)
async def main() -> None:
options = ClaudeAgentOptions(
cwd="/work/repository",
allowed_tools=["Read", "Glob", "Grep"],
disallowed_tools=["Write", "Edit", "Bash"],
max_turns=8,
)
prompt = """
Map the authentication request path.
Return the entry handler, verifier, session writer, and direct tests.
Cite a file path and symbol for every claim. Do not modify files.
Stop and report the missing input if generated routes are unavailable.
"""
async for message in query(prompt=prompt, options=options):
# Send structured events to your logger or client here.
if isinstance(message, ResultMessage):
print(message.result)
asyncio.run(main())
Run it against a disposable checkout that contains no unrelated credentials. Verify three things: the result cites real symbols, denied tools remain unavailable, and the process exits when it reaches the turn cap or final result. A successful answer is not enough if the surrounding controls were never exercised.
Treat tool permissions as executable policy
A common mistake is assuming allowed_tools removes every unlisted tool. Anthropic's current Python README says it is a permission allowlist: those tools are auto-approved, while other tools fall through to the configured permission mode and callback. Use disallowed_tools when a tool must be unavailable.
Keep three layers separate:
- Prompt contract: explains the task and expected behavior.
- SDK permission policy: approves, denies, or intercepts tool calls.
- Runtime boundary: limits filesystem, network, credentials, CPU, memory, and processes even if the first two layers fail.
Hooks are useful for deterministic checks and audit events. A PreToolUse hook can reject a command or path before execution; a PostToolUse hook can record a file change. Do not turn a hook into a giant security parser. The container, proxy, and mounted filesystem should make broad damage impossible without depending on model compliance or one callback.
Consume the stream, not only the final sentence
The SDK returns an asynchronous stream of messages. Production code should treat that stream as the run record. Capture the initialization event and session ID, tool requests and results, assistant messages, final result, error status, token usage, cost, duration, and cancellation reason. Preserve structured fields instead of flattening everything into a chat transcript.
A practical event pipeline separates three audiences:
- the user sees concise progress and the final artifact;
- the operator sees tool timing, retries, policy decisions, and resource use;
- the auditor sees immutable evidence with sensitive fields redacted.
Define terminal outcomes explicitly: completed, rejected by policy, cancelled, timed out by your supervisor, exhausted turn budget, failed tool, or infrastructure failure. A process that stopped producing output is not “still thinking” forever. The hosting documentation notes there is no top-level session timeout, so your application must own an outer deadline or watchdog in addition to maxTurns.
Choose a session lifecycle before choosing infrastructure
Anthropic's hosting guide describes four useful patterns. The right one depends on how users return to the work, not on which cloud vendor has the best demo.
| Pattern | Best for | Main obligation |
|---|---|---|
| Ephemeral | One request, one disposable container | Export the result before destruction |
| Long-running | Chat, inbound events, or continuous service | Route each live session to its process and monitor memory |
| Hybrid | Sessions that sleep between interactions | Hydrate transcripts and workspace state safely |
| Multi-agent container | Closely collaborating SDK processes | Separate working directories and tenant settings |
Start ephemeral unless the product genuinely requires continuity. It is easier to reason about a clean workspace and finite process than a months-old session that has accumulated files, memory, and assumptions. Move to hybrid or long-running only after you can state exactly what must survive and how it is recovered.
Persist transcripts, memory, and artifacts separately
By default, session transcripts, Claude memory files, and working-directory artifacts live on local disk. A container restart, scale-down, or reschedule can erase them. The official SessionStore interface addresses transcript mirroring across hosts, but it does not persist CLAUDE.md files or general workspace artifacts.
Design three storage paths instead of one vague “agent memory” bucket:
- Transcript store: session messages required for resume or audit.
- Workspace store: files, patches, reports, and generated artifacts with ownership and retention rules.
- Durable knowledge: reviewed facts and instructions that should influence future work.
Make hydration observable. Record the session ID, store version, workspace snapshot, code revision, SDK version, and policy version used for each run. Alert on transcript mirror failures when resumption matters. A resumed transcript paired with the wrong repository revision can be more misleading than starting clean.
Put the agent inside a boundary, not beside your secrets
An agent reads untrusted repositories, webpages, issue text, and tool output. Any of those sources can contain instructions that try to redirect its behavior. Prompt wording helps, but it cannot replace isolation.
For a serious deployment, combine:
- a non-root container or stronger sandbox with CPU, memory, process, and filesystem limits;
- a dedicated working directory containing only the required files;
- default-deny outbound networking with an allowlisted egress proxy;
- credentials injected by services outside the agent boundary;
- an authenticated gateway in front of the application;
- separate configuration directories and settings for every tenant.
In a shared container, disable filesystem settings sources when they are not deliberately supplied, point CLAUDE_CONFIG_DIR at a tenant-specific location, use a tenant-specific working directory, and control auto-memory. Otherwise one tenant's local configuration can quietly influence another tenant's session.
Add the boring production machinery
The agent loop is the interesting part; the queue and watchdog are what keep it useful. Before accepting unattended requests, add these controls:
- Admission: authenticate the caller, validate input size, and reject overlapping work for the same workspace.
- Supervision: enforce wall-clock, turn, token, and cost ceilings outside the model loop.
- Cancellation: propagate user cancellation to the running process and any child tools.
- Telemetry: export tool timing, failures, tokens, costs, queue delay, and terminal outcomes.
- Recovery: retry only idempotent stages and preserve resumable artifacts.
- Review: require evidence and approval before publishing, merging, sending, or deploying.
The SDK can inherit OpenTelemetry configuration for traces, metrics, and logs. Keep prompt and tool payload capture off unless you have a documented need and redaction policy. Operational visibility should not become a second secret archive.
Capacity planning starts with measurement. Each live session has a subprocess and memory footprint. Measure peak RSS on a representative long run, reserve host overhead, and route a live session consistently to the container that owns its process. Wide subagent fan-outs can hit API limits; batch work instead of dispatching every possible child at once.
Self-host the SDK or use a persistent outer runtime?
Self-host the Claude Agent SDK when its programmable loop is the product: you need custom application logic, a specific session model, tight integration with internal tools, and engineering capacity for isolation, routing, storage, and operations.
Use a persistent agent platform when the main requirement is operational reach—scheduled tasks, chat channels, browser state, files, terminal access, and reliable delivery—rather than building that control plane from scratch. GolemWorkers can provide the always-available outer worker while a Claude SDK process remains one bounded tool inside its workflow. The outer runtime still needs scoped credentials and explicit release boundaries.
Do not confuse persistence with one giant session. A durable worker can start a clean SDK job for each repository task, retain the approved artifacts, and discard the risky execution environment afterward. That pattern often gives users continuity without carrying every old tool result into the next decision.
Production checklist
- The code uses current Claude Agent SDK package and type names.
- The SDK and bundled CLI versions are pinned and visible.
- Every job has a finite scope, output contract, and stop conditions.
- Mutation tools are disallowed unless the workflow explicitly owns edits.
- The working directory contains no unrelated credentials or tenant data.
- A runtime boundary limits filesystem, network, CPU, memory, and processes.
- Secrets are supplied by a manager or proxy, never by prompt text.
- The event stream records session ID, tool outcomes, cost, and terminal state.
- An outer supervisor enforces wall-clock and budget limits.
- Transcript, workspace artifacts, and durable knowledge have separate storage rules.
- Resume binds to the correct user, workspace, code revision, and policy version.
- External actions require the level of human approval their impact deserves.
Bottom line
The search term “Claude Code Agent SDK” points to a real capability under a newer name. The Claude Agent SDK turns Claude Code's agent loop into a Python or TypeScript building block. That gives you powerful tools quickly, but it does not supply the operational boundary around them.
Build the smallest useful job first. Deny tools you do not need. Stream and classify every outcome. Choose a session lifecycle before choosing a host. Store transcripts, files, and reviewed memory deliberately. Then place the process inside isolation with narrow network and credential paths. A persistent agent is dependable because its boundaries persist, not because its conversation never ends.
Primary sources
- Anthropic: Agent SDK overview — packages, built-in tools, hooks, permissions, sessions, and core examples.
- Anthropic: Hosting the Agent SDK — session patterns, persistence, resources, routing, telemetry, and tenant isolation.
- Anthropic: Securely deploying AI agents — isolation, network controls, credential proxies, and filesystem hardening.
- Anthropic: Claude Agent SDK for Python — installation, interfaces, permission semantics, and migration notes.
- Anthropic: Claude Agent SDK for TypeScript — current package and rename notice.