13 min
How to run Claude tool use with Blaxel sandboxes
Compare three Claude integration paths on Blaxel: Claude Code, Agent SDK, and Claude Managed Agents. Each runs tool calls inside isolated microVM sandboxes.

Choose among three integration paths. Blaxel supports documented integration paths for Claude tools: Claude Code, the Claude Agent SDK, and Claude Managed Agents. You need a Blaxel workspace and API key, along with the Anthropic credentials required by your chosen path.
Install either Node or Python for the relevant local setup.
In every case, Blaxel runs Claude's file operations and code or shell execution inside microVM-isolated sandboxes instead of on your application server. The paths differ in who controls the agent loop. They also differ in how much you build versus delegate. Anthropic lists Blaxel among the sandbox providers approved for self-hosted Claude Managed Agents execution.
Ways to run Claude tool use on Blaxel
Every Blaxel sandbox exposes a built-in Model Context Protocol (MCP) server over streamable HTTP at {sandbox_url}/mcp. It is authenticated with a Bearer token. That endpoint surfaces 20 tools across four categories: process management, filesystem operations, code search, and code editing. This shared tool surface reduces the custom tool plumbing required when moving among these paths.
Compare the integration paths
- Claude Code + Blaxel sandboxes: Run Anthropic's CLI coding agent inside an agent sandbox. Point it at a separate sandbox holding the target codebase. Best for interactive coding sessions where a developer or agent operates on a hosted project.
- Claude Agent SDK + Blaxel sandboxes: Build a custom agent that uses a sandbox's MCP server as its tool source. Best for custom agent applications where your team defines the tools and manages sessions through its own orchestration logic. More flexibility, more implementation work.
- Claude Managed Agents (CMA) + Blaxel as self-hosted sandbox: Anthropic runs the agent loop while Blaxel runs the code. Best for teams that want managed orchestration, context management, and error recovery. You still control where execution happens.
All paths run on the same primitive: microVM sandboxes with MCP server integration. Claude Code manages its own loop interactively. The Agent SDK hands the loop to your code, and CMA keeps it on Anthropic's infrastructure.
How to run Claude Code in a Blaxel sandbox
Claude Code is Anthropic's CLI-based coding agent. You can run it inside a Blaxel sandbox and connect it to a target codebase over MCP. This setup gives the agent a persistent, isolated environment.
It can write code, run commands, and iterate on a project. Create separate application and agent sandboxes, then wire them together over MCP. Once connected, hand Claude Code a task.
Create the application and Claude Code sandboxes
Log in with bl login and install the SDK. Use npm install @blaxel/core for TypeScript or pip install blaxel for Python. Export your API key as BLAXEL_API_KEY, then create the application and agent sandboxes.
The application sandbox runs the target codebase from the blaxel/nextjs:latest template. The agent sandbox runs from blaxel/claude-code:latest. This image ships with the Claude Code CLI preinstalled.
import { SandboxInstance } from "@blaxel/core";
const appSandbox = await SandboxInstance.createIfNotExists({
name: "nextjs-sandbox",
image: "blaxel/nextjs:latest",
memory: 4096,
region: "us-pdx-1",
});
const claudeSandbox = await SandboxInstance.createIfNotExists({
name: "claude-sandbox",
image: "blaxel/claude-code:latest",
memory: 4096,
region: "us-pdx-1",
envs: [{ name: "BLAXEL_API_KEY", value: process.env.BLAXEL_API_KEY }],
});
console.log(`MCP URL: ${appSandbox.metadata.url}/mcp`);
createIfNotExists is idempotent, so re-running the script reuses existing sandboxes by name. The full tutorial script also starts the app's dev server. It generates a token-gated preview URL for viewing results.
Note the MCP URL it prints. You'll use it in the next step. The application sandbox is the target, and the Claude Code sandbox is the agent.
Connect Claude Code to the target sandbox via MCP
Open a terminal session inside the agent sandbox with bl connect sandbox claude-sandbox. Then register the application sandbox's MCP server:
claude mcp add --transport http sandbox YOUR-SANDBOX-MCP-URL-HERE \
--header "Authorization: Bearer $BLAXEL_API_KEY"
The claude mcp add command accepts repeatable --header flags. Multi-workspace users can add X-Blaxel-Workspace: <WORKSPACE_NAME_OR_ID> as an additional header. Verify the connection with claude mcp list. Confirm the output shows sandbox: .... connected.
By default, the command writes to local scope. This scope covers the current project on that machine only. Passing --scope project writes the server into a .mcp.json file at the project root instead.
From this point, Claude Code operates the application sandbox through the MCP tool surface. That surface covers filesystem tools like fsReadFile, fsWriteFile, and fsListDirectory. It also covers process tools like processExecute and processStop, plus codegen search and edit tools. The agent gets the equivalent of shell access, but every action flows through a structured tool interface. Edits and commands land in the application sandbox, not on your machine.
Execute a coding task and view results
Start the agent by running claude inside the sandbox. Complete the authentication prompts on the initial run. Then give it a task that references the application sandbox. For example, ask it to add a dark mode toggle to the Next.js app in the sandbox. Tell it to verify the build passes.
A task like that typically exercises most of the tool surface. fsListDirectory and fsReadFile map the project and read the components. fsWriteFile writes the edits back. processExecute runs the build or the dev server and returns the output. Each of those calls crosses the MCP connection into the application sandbox.
Open the token-gated preview URL generated during sandbox creation to confirm the change in a browser. If you used the full tutorial script, the development server is already running inside the application sandbox. The toggle then appears without any local build step.
For ongoing work, leave the sandboxes alone when you're done. They return to standby after 15 seconds of network inactivity. Sandboxes resume from standby in under 25ms with full memory state intact. Reconnect later with bl connect sandbox claude-sandbox.
How to use Claude Agent SDK with Blaxel sandboxes
The Claude Agent SDK ships as @anthropic-ai/claude-agent-sdk on npm and claude-agent-sdk on PyPI. It gives you the agent loop as a library. Your team defines the tools and manages sessions through its own orchestration logic. Connecting the SDK to Blaxel sandboxes gives every tool call a microVM-isolated execution environment.
Connect the Claude Agent SDK to a Blaxel sandbox MCP server
For TypeScript, install @anthropic-ai/claude-agent-sdk, @blaxel/core, and express with npm. For Python, run pip install claude-agent-sdk blaxel "fastapi[standard]". Create a sandbox with the Blaxel SDK. Then pass its MCP endpoint to the agent's mcpServers configuration. Use your Blaxel API key as a Bearer token:
const sandbox = await SandboxInstance.createIfNotExists({
name: "my-sandbox",
image: "blaxel/base-image:latest",
memory: 4096,
region: "us-pdx-1",
});
for await (const message of query({
prompt,
options: {
mcpServers: {
sandbox: {
type: "http",
url: `${sandbox.metadata?.url}/mcp`,
headers: { Authorization: `Bearer ${process.env.BLAXEL_API_KEY}` },
},
},
},
})) { /* handle assistant and result messages */ }
Tool discovery is automatic. The SDK reads the manifest from {sandbox_url}/mcp and makes all listed tools available to the agent loop. Each one is namespaced as mcp__sandbox__<tool_name>.
The Claude Agent SDK tutorial has the complete TypeScript and Python implementations. It also includes the HTTP server wrapper. Once connected, every file operation, process command, and code run Claude requests executes inside the sandbox. Because createIfNotExists is idempotent, stateless HTTP handlers can call it on every request without session affinity.
Define custom tools that execute in the sandbox
The default MCP toolset covers files, processes, and code edits, but you can extend it. The SDK's custom tool APIs define in-process tools that run inside your application. TypeScript uses tool() with createSdkMcpServer(). Python uses the @tool decorator with create_sdk_mcp_server().
Claude calls your tool. Your tool function sends a command or script to the sandbox through the Blaxel SDK. The result then flows back into the agent loop.
For agents that write and run code directly, code mode packages this pattern as a deployable MCP server. Deploy a function from the blaxel/code-mode:latest image with an OPENAPI_REFERENCE environment variable. It exposes search and execute. search explores the API spec. execute runs agent-written JavaScript inside a sandbox that calls the real API.
The deployed code-mode function runs inside an auto-scaling sandbox with a 10-minute idle time-to-live (TTL). Unattended workflows therefore need to complete or renew activity within that idle window. The code mode tutorial walks through deployment. It also shows wildcard auto-approval with allowedTools: ["mcp__petstore__*"].
allowedTools auto-approves matching tools. Leave the wildcard out, and every search and execute call remains subject to permission prompts. Those prompts stall an unattended run. The split between search and execute is also why large OpenAPI specs stay manageable. Claude reads the endpoint fragments search returns instead of the whole spec.
Choose between Claude Code and the Agent SDK
Choose Claude Code for interactive coding sessions. In these sessions, a developer or agent works on a single hosted codebase with minimal custom orchestration. Setup is a handful of CLI commands, and Claude manages its own loop.
Developer-facing tools and hosted coding environments belong here. A hosted coding environment that hands each user a live project is the clearest case. The developer types, Claude Code edits and runs the build, and nothing leaves the sandbox pair.
Reach for the Claude Agent SDK when you're building a product around the agent. Custom orchestration logic and multi-tool workflows beyond coding both point to the SDK. So do applications that need programmatic session control.
Data analysis and research workloads usually belong on this side. Automation workloads do too. Its session options include resume and forkSession. The maxTurns option is also available. They exist for exactly this kind of application-level control.
A data-analysis agent is the opposite shape. Your code decides which dataset to load and calls the sandbox to run the data-processing step. It stores the result before deciding what to ask Claude next. That control loop lives in your application, not in a CLI session.
Claude Code is the fast path, and the Agent SDK is the flexible path. Claude Code registers the sandbox MCP endpoint through the CLI, while the Agent SDK places it in mcpServers. The shared execution surface lets you prototype with Claude Code and move to the SDK without replacing the sandbox layer.
How to use Claude Managed Agents with Blaxel as self-hosted execution
Claude Managed Agents keeps the agent loop on Anthropic's side, per Anthropic's managed agents update. The service manages session history and error recovery, including prompt caching. Blaxel is one of the supported sandbox providers alongside Cloudflare, Daytona, Modal, and Vercel.
On the Blaxel side, the architecture consists of an orchestrator and worker. A long-lived orchestrator sandbox listens for session webhooks. It claims work items from Anthropic's work queue. It spawns a short-lived worker microVM per session.
Tool inputs and outputs cross to Anthropic so Claude can plan next steps. Code execution, the filesystem, spawned processes, and network access stay on Blaxel infrastructure.
Set up the orchestrator and workers
- Create a self-hosted environment in the Anthropic Console under Workspace > Environments > New > Self-hosted.
- Generate an environment key and clone the sample orchestrator repository.
- Configure
ANTHROPIC_API_KEY,BL_WORKSPACE,BL_API_KEY, plus the environment ID and key. - Deploy the orchestrator.
- Register the webhook for the
session.status_run_startedevent. - Export
ANTHROPIC_WEBHOOK_SIGNING_KEYfrom the registered webhook. Redeploy so the handler can verify signatures.
During deployment, you deploy a long-lived Blaxel sandbox running a FastAPI webhook server. Its handler verifies the webhook signature and returns a successful response right away. Worker creation happens in the background.
The orchestrator exposes a preview URL that you register with Anthropic. Worker lifetime defaults to two hours. It is configurable via BLAXEL_WORKER_TTL, per the integration guide. Sessions wait in the work queue when no worker is connected rather than failing.
Decide when to use CMA
Choose CMA when you want Anthropic to manage the loop. This management includes prompt caching and session history, with error recovery handled as part of the service. It removes the need for your application to implement the same turn-by-turn orchestration itself, but it does not eliminate operational work on the execution side. Your team must still configure the self-hosted environment, environment credentials, webhook registration, and signing-key verification that connect Anthropic's session lifecycle to Blaxel.
Your team still decides where tool calls run and which image the worker sandboxes boot from. A session can boot with your build toolchain and language runtimes already in place. It can also include private package registries. Anthropic never sees the filesystem those tools operate on. CMA is therefore a strong fit when you want managed session recovery and context handling while retaining control over the worker environment, network access, and code-execution boundary.
CMA offers less orchestration flexibility in exchange for a smaller codebase you have to maintain. It suits teams shipping agent products who would rather not own orchestration themselves. You still operate the long-lived orchestrator, monitor webhook delivery, choose an appropriate worker TTL, and maintain the worker image. Prefer the Agent SDK instead when your application must decide what happens between turns or store intermediate results before the next prompt. It is also preferable when you need direct session control. The relevant options include resume and forkSession; maxTurns is available too.
How to avoid common failures when wiring Claude to Blaxel sandboxes
These failure modes account for most debugging time across the integration paths and include authentication problems as well as runs that hang or silently do nothing.
- Environment variable divergence: Use
BLAXEL_API_KEYconsistently across the Claude Code and Agent SDK paths. Align the names across your scripts before debugging auth failures that are really name mismatches. - Reading MCP status too early: In the Claude Agent SDK, MCP servers connect in the background. The
initmessage can reportstatus: "pending"before the sandbox server is live. Check again on the next message instead of re-registering. From the CLI,claude mcp listreports✔ Connected,! Needs authentication, or✘ Failed to connect. - Blocking on long commands: The sandbox process API caps
waitForCompletionat 100 seconds. Long builds or dependency installs can outrun it. Start the process and poll it withprocessGetorprocessGetLogs. - Worker TTL sizing: Worker lifetime is capped by
BLAXEL_WORKER_TTL. Raise the value before you deploy the orchestrator. Discovering the limit after a session gets cut short costs you the run. - The SDK rename:
ClaudeCodeOptionsis nowClaudeAgentOptions. Older Claude Code SDK examples found through search will not compile against the current package. allowedToolssemantics: A wildcard like["mcp__petstore__*"]auto-approves matching tools without prompting. It does not restrict Claude to only those tools. UsedisallowedToolswhen you need an actual block.
When something breaks, check the environment variable names first. Then check claude mcp list for the CLI path or the init message for the SDK path. Pull processGetLogs output when a command hangs instead of a run failing outright.
How to start running Claude tool use on Blaxel
Run Claude scripts and tool calls inside an isolated virtual machine, especially when the agent touches external web services. Some Claude tool calls execute code, so they need somewhere safe to run. Without an isolated execution environment, those calls run on your application server. They reach your filesystem and network. They can also read environment variables. Isolate Claude Code from sensitive systems, as specified in Anthropic's security guidance. For agents executing AI-generated code, that boundary needs to be hardware-enforced. MicroVM designs such as Firecracker enforce that boundary in hardware. Container runtimes instead share the host kernel.
Blaxel, the perpetual sandbox platform, supports the Claude integration paths described above. Every sandbox gets microVM isolation and its own MCP server. Idle sandboxes sit in standby indefinitely instead of being torn down. A paused session therefore keeps its state without holding compute. On the CMA worker path, outbound requests can also route through Blaxel's proxy for secret injection.
Start with the setup that lets your team validate execution with the least operational change. Claude Code provides the quickest interactive proof of concept. Move to the Agent SDK when product requirements call for application-owned session logic, or use CMA when managed context and recovery justify operating the webhook and worker infrastructure. Read the Blaxel Sandboxes overview or talk to Blaxel about your setup. When you're ready, start building.
FAQ
Which Claude integration path should I use with Blaxel?
If more than one path fits, decide who must own session state, retries, and decisions between turns. Claude Code minimizes setup for human-guided work. The Agent SDK gives your application direct control over session behavior and intermediate results. CMA shifts context and recovery to Anthropic but requires your team to operate the self-hosted environment, signed webhook, orchestrator, and worker configuration.
Does Blaxel support both Claude Agent SDK and Claude Managed Agents?
Yes. Use the Agent SDK when your application should own orchestration. Use Claude Managed Agents when Anthropic should manage the loop. In both cases, Blaxel remains the isolated execution layer. The Agent SDK configures the sandbox endpoint in your application, while CMA uses an orchestrator, signed session webhooks, Anthropic environment credentials, and short-lived worker microVMs.
How does MCP connect Claude to a Blaxel sandbox?
MCP carries Claude's tool requests to the sandbox's built-in server. The sandbox executes each request and returns the result. Authenticate the streamable HTTP endpoint with a Blaxel API key as a Bearer token. For Claude Code, verify registration with claude mcp list; for the Agent SDK, allow for the connection status to remain pending during initial background setup.
Can I use a custom execution environment with Claude and Blaxel?
Yes. Use custom Docker images to run Claude's tool calls in a pre-configured environment. Include the build toolchain and language runtimes your workload requires. Add its dependencies to the image. The resulting sandbox still provides microVM isolation and keeps generated code and shell commands away from your application server, sensitive filesystem, environment variables, and other host resources.
Related articles

Guides
Blaxel + Claude: secure code execution for AI agents
Run Claude Managed Agents with self-hosted sandboxes on Blaxel. Control data residency, network egress, and state persistence.
15 min read

Guides
Volume templates for AI agents: how to start every sandbox from a known-good state
How sandbox volume templates eliminate per-sandbox setup costs, version model weights and dependencies, and speed up fleet startup.
10 min read

Guides
How to run Anthropic tool use code execution with Blaxel
Run Anthropic tool use code execution safely in isolated microVM sandboxes. Learn how to connect Claude Code to a Next.js codebase via MCP using Blaxel.
11 min read