13 min
How to run Claude Code safely in a Claude Agent SDK sandbox with Blaxel
Learn what the Claude Agent SDK sandbox covers and where it stops. Connect Claude agents to a remote Blaxel microVM through MCP and run tools off your host.

The Claude Agent SDK gives Claude real tools on a real machine. It can edit files and run shell commands for you. Anthropic's security docs warn that an approved Bash command "can still write anywhere your user account can." Permission prompts reduce that risk, but your laptop or server still bears the consequences of any mistake.
A Claude Agent SDK sandbox moves that execution off your machine. Blaxel runs each sandbox as an isolated microVM that starts in under a second. An idle sandbox drops to standby and resumes in under 25ms with its files intact. Your agent gets a disposable computer, and your own environment stays out of reach.
This tutorial covers current Python and TypeScript samples for connecting a Claude agent to a Blaxel sandbox.
Key takeaways
- Each
query()call spawns aclaudeCLI process that owns the shell, so a prompt-injected model reaches whatever it can. - The SDK's
sandboxoption wraps shell commands only. Python also runs unsandboxed with a warning unless you setfailIfUnavailable. - With
tools: []and sandbox-onlyallowedTools, every file write and process launch runs in a microVM. - Blaxel sandboxes drop to standby after about 15 seconds of network inactivity and resume in under 25ms with files intact.
Quick steps to sandbox a Claude agent on Blaxel
Six steps take a Claude agent from a fresh install to a sandboxed run. Steps 1 to 5 move tool execution to Blaxel. Step 6 covers any Bash you keep local, as the SDK sandbox section explains.
| Step | What you do | Command or setting |
|---|---|---|
| 1 | Install the SDKs | npm pkg set type=module, then npm install @anthropic-ai/claude-agent-sdk @blaxel/core |
| 2 | Log in to Blaxel | bl login |
| 3 | Create a sandbox | SandboxInstance.createIfNotExists() from @blaxel/core |
| 4 | Point the agent at the sandbox MCP server | mcpServers entry with ${sandbox.metadata.url}/mcp and a Bearer Authorization header |
| 5 | Remove local built-in tools and allow the sandbox tools | tools: [] and allowedTools: ["mcp__sandbox__*"] |
| 6 | If you keep local Bash, sandbox it | sandbox: { enabled: true, failIfUnavailable: true } |
Why Claude Agent SDK agents need a sandbox
Each query() call spawns a separate claude CLI process. The claude process owns the shell and the working directory, per the Agent SDK hosting guide. The subprocess also keeps session transcripts on local disk. Whatever that shell can touch, a prompt-injected model can touch too.
Anthropic recommends running the SDK application inside an isolation boundary. Its secure deployment guide compares four options:
| Technology | Isolation strength | Performance overhead | Complexity |
|---|---|---|---|
| Sandbox runtime | Good (secure defaults) | Very low | Low |
| Containers (Docker) | Setup dependent | Low | Medium |
| gVisor | Excellent (with correct setup) | Medium/High | Medium |
| VMs (Firecracker, QEMU) | Excellent (with correct setup) | High | Medium/High |
gVisor and VMs score highest for isolation, which matters most for agents running AI-generated code. Containers share the host kernel, so a kernel exploit can reach every workload on the machine.
Every Blaxel sandbox runs in its own microVM with no shared kernel. Blaxel runs that VM layer as managed infrastructure, so you don't build or operate it yourself.
How to sandbox the Claude Agent SDK itself
The SDK ships a programmatic sandbox option for shell commands. In TypeScript, SandboxSettings has enabled, autoAllowBashIfSandboxed, and failIfUnavailable keys, per the Agent SDK TypeScript reference.
TypeScript
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Run the test suite and summarize failures.",
options: {
sandbox: {
enabled: true,
autoAllowBashIfSandboxed: true,
failIfUnavailable: true, // TypeScript default is already true
},
},
})) {
console.log(message);
}
In Python, ClaudeAgentOptions takes these settings through a sandbox parameter, which defaults to None, per the Python reference. Python doesn't declare failIfUnavailable as a field, but the SDK forwards it.
Python
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
options = ClaudeAgentOptions(
sandbox={
"enabled": True,
"autoAllowBashIfSandboxed": True,
"failIfUnavailable": True, # Python default is to run unsandboxed with a warning
"network": {"allowLocalBinding": True},
},
)
async def main():
async for message in query(prompt="Run the test suite.", options=options):
print(message)
asyncio.run(main())
The TypeScript example targets @anthropic-ai/claude-agent-sdk 0.3.317 on npm. The Python example targets claude-agent-sdk 0.2.177 on PyPI. The SDK requires Python 3.10+ or Node.js 18.14+.
Several behaviors decide whether this sandbox protects you:
- Fail-open in Python: If the sandbox can't start, Python runs commands unsandboxed and prints a warning to stderr. With
failIfUnavailableset,query()yields aResultMessagewithsubtype="error_during_execution"and then raises. Wrap the loop intryto catch the exception. - Platform support: The sandbox runs on macOS, Linux, and WSL2 (Windows Subsystem for Linux 2). On native Windows, Claude Code runs commands unsandboxed. On Linux, the sandbox also depends on
bubblewrapandsocat. - WebFetch gap: Network settings apply to sandboxed Bash commands. The settings don't restrict WebFetch, which uses permission rules instead.
- Escape hatches: The model can set
dangerouslyDisableSandboxin tool input. The SDK then sends that command to yourcanUseTool(TypeScript) orcan_use_tool(Python) callback. Commands listed inexcludedCommandsalways run outside the sandbox, with no request from the model. - Socket access: Allowing
/var/run/docker.sockthroughallowUnixSocketsgrants full host access through the Docker API. - Permission bypass: With
bypassPermissionsandallowUnsandboxedCommandsboth on, the model runs unsandboxed commands with no approval prompt.
Together, these limits mean the SDK sandbox is a guardrail for shell commands on the host you already trust. To keep agent-generated code off that host, move tool execution to a remote sandbox.
Give Claude tools that run in a remote sandbox
Each Blaxel sandbox exposes an MCP server that lets agents operate the sandbox through tool calls. The server's tools handle file and process operations. When the agent has only these tools, every file write or process launch lands in the microVM.
Tasks that need shared files can use Agent Drive, which is in private preview. It mounts one filesystem that multiple sandboxes share across agent sessions.
How to connect a Claude agent to a Blaxel sandbox
Quick steps 1 to 5 fall into three stages, from an empty project to an agent whose tools run remotely. The TypeScript path follows Blaxel's Claude Agent SDK tutorial.
1. Install the SDKs and log in
You need an Anthropic API key, a Blaxel account, and the Blaxel CLI. Install the Claude Agent SDK and the Blaxel TypeScript SDK in one command. Python users install claude-agent-sdk and blaxel from PyPI instead.
The TypeScript samples assume @blaxel/core 0.3.34 on npm. The Python sample assumes blaxel 0.4.22 on PyPI.
Shell
npm pkg set type=module # the TS samples use top-level await
npm install @anthropic-ai/claude-agent-sdk @blaxel/core
# Python: pip install claude-agent-sdk blaxel
bl login
export ANTHROPIC_API_KEY=... # Agent SDK model calls
export BL_WORKSPACE=... # Blaxel workspace
export BL_API_KEY=... # Blaxel API key, used in the MCP header
For most installs, the Claude Agent SDK bundles a native Claude Code binary pinned to the SDK version. You don't install Claude Code separately. Updating the SDK updates the bundled binary.
The Blaxel CLI (bl) handles authentication for the Blaxel SDK. Install it by following the CLI reference. Then run bl setup to add the Blaxel skills for coding agents like Claude Code. In this pattern, the agent process runs on your machine or server. The SDK's runtime minimums apply there.
The sandbox image's versions matter only if you run the SDK inside the sandbox. Per the templates page, blaxel/base-image ships Node.js 22 and Python 3.12. The blaxel/claude-code image ships Node.js 24. Both clear the SDK minimums.
2. Create a sandbox
Create the sandbox with a name, an image, memory, and a region.
TypeScript
import { SandboxInstance } from "@blaxel/core";
// Reuses the sandbox with this name, or creates it
const sandbox = await SandboxInstance.createIfNotExists({
name: "my-sandbox",
image: "blaxel/base-image:latest", // Node.js 22 and Python 3.12
memory: 4096, // in MB
region: "us-pdx-1",
});
// The streamable HTTP MCP server listens at <metadata.url>/mcp
const mcpUrl = `${sandbox.metadata.url}/mcp`;
The MCP endpoint is the sandbox's base URL from metadata.url, plus /mcp. Give each user or task its own sandbox. A shared sandbox lets one session's files and processes leak into another's, which defeats the isolation you just set up. Pick the region closest to the host running your agent to cut round-trip time on every tool call. If creation times out, use the isCreationTimeoutError helper from @blaxel/core to detect the error.
3. Wire the sandbox MCP server into query()
Register the sandbox's /mcp URL as an MCP server, and send your Blaxel API key in the Authorization header. Then pass tools: [] to remove every built-in tool, so Claude can't fall back to your host.
TypeScript
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Create hello.py in the sandbox, run it, and report the output.",
options: {
mcpServers: {
sandbox: {
type: "http", // McpHttpServerConfig
url: mcpUrl,
headers: { Authorization: `Bearer ${process.env.BL_API_KEY}` },
},
},
tools: [], // no built-in tools run on your host
allowedTools: ["mcp__sandbox__*"],
maxTurns: 10,
},
})) {
console.log(message);
}
The Python version creates the sandbox and passes the same options in snake_case.
Python
import asyncio
import os
from blaxel.core import SandboxInstance
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
sandbox = await SandboxInstance.create_if_not_exists({
"name": "my-sandbox",
"image": "blaxel/base-image:latest", # Node.js 22 and Python 3.12
"memory": 4096,
"region": "us-pdx-1",
})
options = ClaudeAgentOptions(
mcp_servers={
"sandbox": {
"type": "http",
"url": f"{sandbox.metadata.url}/mcp",
"headers": {"Authorization": f"Bearer {os.environ['BL_API_KEY']}"},
}
},
tools=[], # no built-in tools run on your host
allowed_tools=["mcp__sandbox__*"],
max_turns=10,
)
async for message in query(
prompt="Create hello.py in the sandbox, run it, and report the output.",
options=options,
):
print(message)
asyncio.run(main())
These notes use the TypeScript names. allowedTools auto-approves the listed tools. Unlisted tools fall through to permissionMode and your canUseTool callback. An allow rule approves a call before it reaches that callback.
Put any per-call checks in a PreToolUse hook instead. To confirm remote execution, check that hello.py exists in the sandbox. Your local directory should have no copy. maxTurns caps runaway loops. The result message carries a session_id you can store and pass to resume later.
4. Keep sandbox state between agent sessions
Coding agents often return to the same repository across sessions. Recloning and reinstalling each time delays the first tool call in every session. Blaxel sandboxes avoid the rebuild by moving between three states:
| State | Memory and processes | Compute cost |
|---|---|---|
| Active | Running | Memory and storage billed |
| Standby | Preserved in a snapshot | No memory charge, snapshot storage billed |
| Deleted | Wiped and not recoverable | None |
A sandbox moves to standby after approximately 15 seconds without active connections. Reconnecting resumes it in under 25ms, with filesystem and processes intact. Blaxel creates new sandboxes in under a second.
For a coding agent, the cloned repo and installed dependencies remain when the user returns. Standby carries no compute charges, and on higher quota tiers it has no time limit. Tier 0 and Tier 1 cap standby at 7 and 30 days, respectively.
Standby has two limits to plan around. External connections, such as database clients, go stale on resume, so reconnect with a health check. Standby also doesn't guarantee durable storage. Put data that must outlive a sandbox in Volumes, which persist through sandbox deletion and re-creation.
What the sandbox does and does not cover
A sandbox narrows what a compromised agent can reach, but some settings can still expose the host. In Anthropic's internal usage, sandboxing cut permission prompts by 84%. Fewer prompts mean longer unattended runs, so the sandbox boundary must stop what a prompt used to catch:
| Area | Scope and guidance |
|---|---|
| File tools, MCP servers, and hooks | The SDK sandbox doesn't wrap them. To put everything behind one boundary, run the whole Claude Code process inside a remote sandbox. Blaxel's Claude Code tutorial shows this setup. |
| Bypass mode | Always run --dangerously-skip-permissions inside an isolation boundary, per Anthropic's sandbox environments guide. For agent-generated code, use a VM or remote microVM sandbox. On Linux and macOS, Claude Code refuses that flag when run as root, so use a non-root user. |
| Credentials | Code in the sandbox can use any credential stored there. Keep your Anthropic and Blaxel keys on the agent side. Blaxel's proxy secrets injection adds keys to outbound requests so sandbox code never sees them. Proxy secrets injection is in public preview, and Blaxel doesn't yet recommend it for production. |
| Egress | Blaxel's domain filtering, in public preview, restricts outbound traffic to an allowlist. Dedicated egress gateways for static IPs are in private preview. |
Before you ship, take two steps.
- List every credential and network destination your agent touches.
- Remove whatever the task doesn't need.
Run Claude agent tools in microVMs with Blaxel
The SDK sandbox limits what local shell commands can reach. A remote microVM moves generated code and tool calls off your host. Blaxel, the infrastructure foundation for autonomous agents, gives each task a microVM and keeps the cloned repo ready between sessions.
FAQs about Claude Agent SDK sandbox
How do I turn on sandboxing in the Claude Agent SDK?
Pass a sandbox object with enabled: true in the query options. TypeScript fails closed by default. Python runs unsandboxed with a warning unless you set failIfUnavailable. In interactive Claude Code, run /sandbox or set sandbox.enabled in ~/.claude/settings.json instead.
Do Claude Code sandboxes cover MCP servers and file tools?
The built-in sandbox covers only Bash, PowerShell, and Monitor commands and the processes they start. File tools, MCP servers, and hooks run outside it. Run the whole agent process inside a sandbox or VM to cover them.
Is setting IS_SANDBOX=1 enough to sandbox the SDK?
Anthropic doesn't document IS_SANDBOX=1 as a sandboxing control for the SDK, so don't rely on it. Use the documented sandbox option instead.
Is it safe to run Claude Code with --dangerously-skip-permissions?
It's safe only inside an isolation boundary. The flag turns off permission prompts, though a few high-risk actions, such as rm on critical paths, still prompt. With prompts off, the isolation boundary becomes the main protection. Run it as a non-root user in a VM or remote sandbox, never on your main machine.
Related articles

Blaxel News
Securing the open frontier with NVIDIA OpenShell and Blaxel sandboxes
Baseten is a launch partner for the NVIDIA Agent Safety Platform and supports OpenShell in the latest generation of Blaxel Sandboxes.
4 min read

Blaxel News
How to Combine Sandbox Safety with a Decision Layer That Gets the Job Done
Sandboxes let coding agents act safely. Decision layers make sure they act correctly. How Blaxel and Rippletide think about combining both.
5 min read

Blaxel News
Close your laptop. Keep DeepSeek Harness working on Blaxel.
Take your DeepSeek Harness task to a private Blaxel host and let it keep working. Review the patch, then return the files and conversation to your computer.
4 min read