← Blog
Engineering

Claude Agent SDK sandbox: run each task in its own workspace

Yura Dubinin
Yura Dubinin

A Claude Agent SDK sandbox is the environment where the SDK's agent process, tools and working files run. The SDK starts a Claude CLI subprocess. Giving that process a separate VM or container lets you define which files and credentials it can reach and what happens when the task ends. Setting a working directory alone does not create that boundary. Anthropic hosting guide

Use one workspace per task for independent jobs. For a session that spans several requests, retain the workspace or persist the state needed to resume. Keep authentication, task ownership and scheduling in a coordinator outside the agent's machine.

We build Lizard. This guide uses Lizard Sandboxes for a small setup example and compares the hosting choices. We checked the APIs and commands on 4 November 2026. The new SDK example was reviewed against documentation; it has not been run against Anthropic in a cloud sandbox.

What must the host provide?

The Agent SDK needs a runtime, a CLI subprocess, a working directory and access to the model service. The subprocess can also start tools that use more memory, CPU and disk than the SDK itself. Size the workspace for the task: reading a few files differs from building a repository or driving a browser.

RequirementDecision to make
Process lifetimeCan the agent outlive the inbound HTTP request?
FilesWhich input, transcript and output files must survive?
ToolsWhich tools can run, and which need approval?
CredentialsWhich service can each credential reach?
NetworkWhich hosts must the task contact?
RecoveryHow will the coordinator detect a failed or interrupted run?

Local directories separate application state, but processes with the same operating-system access can still reach other directories. For unrelated users, use a boundary that matches that risk. Anthropic's secure deployment guide discusses isolation and credentials.

Choose a hosting target

Lizard Sandboxes provide Firecracker microVMs with their own kernels, ready templates, command execution and file transfer. They suit CPU tasks that fit the fixed machine sizes. Lizard does not offer sandbox GPU instances or arbitrary Dockerfile-based sandbox templates. Lizard Sandboxes

E2B provides Linux sandboxes, templates and code-execution APIs. Daytona offers workspace tools and several runtime classes. Modal supports elastic CPU resources and GPU workflows, with runtime-specific constraints. A Docker or Kubernetes deployment gives you control over your own infrastructure, while you handle capacity, isolation and cleanup. E2B, Daytona, Modal

The SDK can run on a host with the needed runtime and subprocess support; it does not require one particular sandbox vendor. Check dependencies, network access, shutdown behavior and memory under your own workload.

Start with a small read-only SDK task

This example reads a local project file and asks Claude for a summary. It exposes only the Read, Glob and Grep tools to the agent. It does not need unrestricted Bash execution or permission bypass.

You need a Lizard project and signed-in Lizard CLI, plus an Anthropic API key for model calls. Lizard compute and Anthropic usage have separate billing. Install the CLI using the current instructions.

1. Create a Small workspace

Replace the project placeholder, then copy the returned sandbox ID into SB:

lizard sandbox create --project YOUR_PROJECT_ID \
  --template claude --size small --timeout 3600000 --json
SB=YOUR_SANDBOX_ID
lizard sandbox exec "$SB" -- mkdir -p /workspace/agent

The explicit lifetime is one hour. The CLI default is five minutes, and running commands does not reset that deadline. Set a deadline appropriate to the job and save outputs before it expires. Sandbox CLI

2. Save the SDK runner locally

Create summarize.mjs with this code:

import { query } from '@anthropic-ai/claude-agent-sdk';

if (!process.env.ANTHROPIC_API_KEY) {
  throw new Error('Set ANTHROPIC_API_KEY inside the task environment');
}

let completed = false;
for await (const message of query({
  prompt: 'Read README.md and summarize the project in two sentences.',
  options: {
    cwd: '/workspace/agent',
    settingSources: [],
    tools: ['Read', 'Glob', 'Grep'],
    allowedTools: ['Read', 'Glob', 'Grep'],
    permissionMode: 'dontAsk',
    maxTurns: 6,
  },
})) {
  if (message.type !== 'result') continue;
  if (message.subtype !== 'success' || message.is_error) {
    throw new Error(`Agent failed: ${message.subtype}`);
  }
  completed = true;
  console.log(message.result);
}
if (!completed) throw new Error('Agent ended without a successful result');

tools selects the available built-in tools. allowedTools pre-approves calls; it is not, by itself, a complete tool allowlist. dontAsk denies requests that lack permission. The small turn limit bounds this example's agent loop; it does not cap total cloud spend. Agent SDK reference

Create a small README.md beside the script, then upload both files:

lizard sandbox files put "$SB" ./summarize.mjs /workspace/agent/summarize.mjs
lizard sandbox files put "$SB" ./README.md /workspace/agent/README.md
lizard sandbox shell "$SB"

3. Install and run inside the workspace

In the sandbox's Bash shell:

cd /workspace/agent
npm init -y
npm install --save-exact @anthropic-ai/claude-agent-sdk
read -rsp 'Anthropic API key: ' ANTHROPIC_API_KEY
export ANTHROPIC_API_KEY
node summarize.mjs
unset ANTHROPIC_API_KEY

The expected result is a short summary printed to stdout and a zero exit status. A missing credential, denied operation or exhausted turn limit should produce a failed run. Keep the generated lockfile and use npm ci when you turn the example into a repeatable environment.

The prompt avoids putting the key in shell history. The key still exists inside the agent's environment while the task runs. For a service that executes untrusted work, consider an outbound proxy that injects credentials outside the sandbox. SDK authentication and hosting

4. Export what you need, then pause

Exit the sandbox shell and retrieve any output files through lizard sandbox files get. Once the result is saved:

lizard sandbox pause "$SB"

Confirm the final state is paused. A successful pause ends compute charges and keeps the workspace state; Persistent Volumes storage has separate billing. This example's local disk does not become durable storage merely because its path starts with /workspace. Persistence, Persistent Volumes

Add production behavior around the runner

Put each request in a task record before starting an agent. Store the owner, sandbox ID, status, deadline and output location. Stream progress through the coordinator and retain the final result independently of the client connection.

Handle cancellation and cleanup in separate paths. A client disconnect need not cancel useful work; a cancelled task should not keep a hidden machine running. Retry cleanup after transient failures and reconcile task records with actual sandbox states.

For sessions, save the session ID and the required transcript and file state. A database row containing only the ID cannot recreate missing workspace files. Anthropic documents session storage separately from working-directory artifacts. Sessions, hosting state

Keep reusable template state free of user credentials and private task files. Restore that clean state for each unrelated task. Do not let one user's paused machine become another user's workspace without a proven reset.

What does the workspace cost?

Lizard Small costs $0.0162 per running hour. One hundred aggregate running hours use $1.62 of compute; a new Pro account still has a $19 monthly minimum with $19 of included usage. Model calls, Persistent Volumes and other resources need their own budget. Lizard pricing

Pro supports 20 Small sandboxes at once and 400 new starts per day, with minute and hourly start limits too. Pro 5x costs $99 with $99 of usage and supports up to 110 Small sandboxes; Pro 20x costs $499 with $499 of usage and supports up to 600. Higher concurrency does not mean each task finishes at the same speed. Current limits

Measure full runtime, including package installation, model waits and output transfer. If you pause a workspace between requests, the coordinator must remain outside it: a paused process cannot receive the request that wakes itself.

Is the Claude Agent SDK's working directory a sandbox? No. cwd chooses where the process works. Use operating-system controls or a separate container or VM to define access beyond that directory.

Can I start with Claude Code instead of writing an SDK service? Yes. For a single coding task, the Claude Code sandbox guide shows the shorter CLI workflow. Use the SDK when your application needs to manage agent messages, tool policy and session behavior in code.

Build with AI. Ship with Lizard.

You don't need a platform team to go live. Your whole cloud, one CLI command away.

Services
—
Add-ons
—
Deployments
—
Sandbox starts
—

We use cookies for essential site functionality and analytics. See our Cookie Policy.