Text of code.claude.com › docs › en › agent-sdk › hosting as Styx crawled it on Nov 20, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

Hosting the Agent SDK - Claude Code Docs

Documentation Index Fetch the complete documentation index at: /docs/llms.txt Use this file to discover all available pages before exploring further. Skip to main content Assistant Responses are generated using AI and may contain mistakes. The Agent SDK spawns and supervises a claude CLI subprocess that owns a shell, a working directory, and session files on disk. Hosting it is not like hosting a stateless API wrapper.

Every running agent is a long-lived process tied to local state, which shapes how you allocate resources, persist sessions, and scale across tenants. This page covers self-hosting on your own infrastructure. For deployable Dockerfiles and Kubernetes manifests, see the hosting cookbook . If you don’t need to run the agent loop itself on your own infrastructure, consider Managed Agents instead. Anthropic hosts the agent loop, and your application sends events and receives streamed results through the client SDKs or the REST API.

Tool execution runs in an Anthropic-managed cloud sandbox or a self-hosted sandbox on your own infrastructure. The subprocess model Every hosting decision on this page follows from how the SDK runs the agent. When your code calls query() , the SDK spawns a separate claude CLI process and talks to it over stdio. That subprocess owns the shell, the working directory, and the JSONL session transcripts on local disk. One agent session maps to one subprocess.

Running N concurrent sessions takes N subprocesses, each with its own process tree and transcript file. By default they all inherit your application’s working directory. When sessions need separate working directories, pass a distinct cwd in the options of each session’s query() call: import { query } from "@anthropic-ai/claude-agent-sdk" ; for await ( const message of query ({ prompt: "Summarize the files in this directory" , options: { cwd: "/work/session-a" }, })) { console . log ( message ); } import asyncio from claude_agent_sdk import ClaudeAgentOptions, query async def main (): async for message in query( prompt = "Summarize the files in this directory" , options = ClaudeAgentOptions( cwd = "/work/session-a" ), ): print (message) asyncio.run(main()) The TypeScript examples on this page use top-level await , so save them as .mts files or set "type": "module" in package.json .

State that lives on local disk Three kinds of agent state live on the container’s filesystem by default. None of them survive a container restart, a scale-down, or a move to a different node. State Default location Session transcripts ~/.claude/projects/ , or the projects/ directory under CLAUDE_CONFIG_DIR if set CLAUDE.md memory files ~/.claude/CLAUDE.md for the user tier and the session’s working directory for the project tier Working-directory artifacts The session’s working directory To persist transcripts across hosts, configure a SessionStore adapter .

Memory files and other working-directory artifacts need their own storage strategy, such as a mounted volume or an object-store sync. For how sessions, resumption, and forking work at the API level, see Sessions . Choose a session pattern These four patterns cover session lifecycle: how long a container lives relative to the sessions it serves. For where the container runs, the hosting cookbook has deployable code for local Docker, Modal, and Kubernetes.

Choose a session pattern here and a deployment target from the cookbook. Ephemeral sessions Create a container for each user task and destroy it when the task completes. Best for one-off tasks. The user may still interact with the AI while the task is completing, but once completed the container is destroyed. Example workloads include bug investigation and fix, invoice and receipt extraction, document translation, and media transformation.

The container runs a one-shot entrypoint that reads the task from the TASK_PROMPT environment variable, calls the SDK, and exits. import { query } from "@anthropic-ai/claude-agent-sdk" ; const prompt = process . env . TASK_PROMPT ! ; for await ( const message of query ({ prompt , options: { maxTurns: 20 } })) { console . log ( message ); } import asyncio import os from claude_agent_sdk import ClaudeAgentOptions, query async def main (): async for message in query( prompt = os.environ[ "TASK_PROMPT" ], options = ClaudeAgentOptions( max_turns = 20 ), ): print (message) asyncio.run(main()) The script prints each message as it arrives, including a result message whose subtype is success when the task completes within the turn limit.

If the task hits the 20-turn limit instead, the result message’s subtype is error_max_turns and the query() call raises an error after yielding it, so wrap the loop in a try block if the container needs to exit cleanly. See Handle the result for the error subtypes. Long-running sessions Run persistent container instances, often hosting multiple SDK processes per container, to serve ongoing work. Best for agents that take autonomous action, serve content, or handle high-volume message streams.

Example workloads include an email agent that triages and responds to incoming mail, a site builder that hosts a per-user editable site through container ports, and a chat bot that handles continuous traffic from a platform like Slack. The container exposes an HTTP or WebSocket endpoint and maps each active session to a long-lived query and the subprocess behind it. The calls that keep sessions open and warm differ between the SDKs: TypeScript : use streamInput() to add turns to an active session.

Call startup() to pre-warm subprocesses ahead of incoming traffic. If you don’t know a session’s working directory until its first request arrives, pre-warm with prewarm() instead. Python : use ClaudeSDKClient to hold a session open across turns. Size the container so it can hold the maximum number of concurrent sessions in memory. Hybrid sessions Ephemeral containers that hydrate from a SessionStore on startup and persist updates back.

Best for sessions that span many interactions but sit idle between them. The container spins down during idle periods and spins back up when the user returns. Example workloads include a personal project manager with intermittent check-ins, deep research that pauses and resumes over hours, and a customer support agent that loads ticket history across interactions. Tune your provider’s idle timeout to how frequently you expect users to return.

Shutting a container down without a SessionStore configured loses the transcript with it, so the store is required for this pattern, not optional. The pattern hinges on resuming a session by ID with a shared store attached: import { query , type SessionStore } from "@anthropic-ai/claude-agent-sdk" ; declare const userInput : string ; declare const sessionId : string ; // looked up from your database by user declare const sessionStore : SessionStore ; // an object store, key-value store, database, or your own adapter for await ( const message of query ({ prompt: userInput , options: { resume: sessionId , sessionStore }, })) { // ... } from claude_agent_sdk import query, ClaudeAgentOptions, SessionStore import asyncio user_input: str = ... session_id: str = ... # looked up from your database by user session_store: SessionStore = ... # an object store, key-value store, database, or your own adapter async def main (): async for message in query( prompt = user_input, options = ClaudeAgentOptions( resume = session_id, session_store = session_store, ), ): ... asyncio.run(main()) Multi-agent container Run multiple SDK subprocesses inside one container.

Best for agents that must collaborate closely, for example multi-agent simulations where the agents interact with each other in a shared environment. Give each agent its own working directory so they do not overwrite each other’s files, and isolate settings loading so per-agent CLAUDE.md files do not leak across agents. See Multi-tenant isolation for the specific options. Provision the container Container-

The rest of this page is on the live site.