Skip to Content

Claude Agent SDK

Give a Claude Agent SDK agent tools that run commands and files in a Sandcovery sandbox instead of on your machine.

The Claude Agent SDK runs Claude Code as a subprocess, and Claude Code's built-in tools, such as Bash, Read, and Write, act on the machine that runs it. This guide turns those tools off and gives the agent three tools that work in one Sandcovery sandbox instead: run a shell command, write a file, and read a file. The sandbox runs on a provider account you connected.

Before you start

  • Create an API key and add at least one provider credential, as the quickstart shows, and set SANDCOVERY_API_KEY.
  • Use Python 3.11 or later, which the sandcovery package supports.
  • Set ANTHROPIC_API_KEY for Claude.

Install the packages

pip install claude-agent-sdk sandcovery

The claude-agent-sdk package includes the Claude Code CLI it runs.

Define the tools and the run

agent.py
import asyncio
from typing import Any

from claude_agent_sdk import (
    ClaudeAgentOptions,
    ClaudeSDKError,
    McpSdkServerConfig,
    ResultMessage,
    create_sdk_mcp_server,
    query,
    tool,
)
from sandcovery import Sandcovery

SANDBOX_TOOLS = ["mcp__sandbox__run_command", "mcp__sandbox__write_file", "mcp__sandbox__read_file"]


def text(value: str) -> dict[str, Any]:
    return {"content": [{"type": "text", "text": value}]}


def sandbox_server(sandcovery: Sandcovery, sandbox_id: str) -> McpSdkServerConfig:
    @tool(
        "run_command",
        "Run a shell command in the sandbox and return its exit code, stdout, and stderr.",
        {"command": str},
    )
    async def run_command(args: dict[str, Any]) -> dict[str, Any]:
        result = await asyncio.to_thread(sandcovery.sandboxes.exec, sandbox_id, args["command"])
        return text(result.model_dump_json())

    @tool(
        "write_file",
        "Write a text file in the sandbox, creating its parent directories.",
        {"path": str, "content": str},
    )
    async def write_file(args: dict[str, Any]) -> dict[str, Any]:
        entry = await asyncio.to_thread(sandcovery.sandboxes.write_file, sandbox_id, args["path"], args["content"])
        return text(entry.model_dump_json())

    @tool("read_file", "Read a UTF-8 text file in the sandbox.", {"path": str})
    async def read_file(args: dict[str, Any]) -> dict[str, Any]:
        content = await asyncio.to_thread(sandcovery.sandboxes.read_file, sandbox_id, args["path"])
        return text(content.decode())

    return create_sdk_mcp_server("sandbox", tools=[run_command, write_file, read_file])


async def run_agent(sandcovery: Sandcovery, prompt: str, *, model: str | None = None) -> str:
    sandbox = sandcovery.sandboxes.create(slug="sandcovery/2x4", ttl_seconds=600)
    try:
        options = ClaudeAgentOptions(
            allowed_tools=SANDBOX_TOOLS,
            max_turns=10,
            mcp_servers={"sandbox": sandbox_server(sandcovery, sandbox.id)},
            model=model,
            setting_sources=[],
            strict_mcp_config=True,
            system_prompt="Answer by running code in your Linux sandbox through your tools.",
            tools=[],
        )
        result: ResultMessage | None = None
        async for message in query(prompt=prompt, options=options):
            if isinstance(message, ResultMessage):
                result = message
        if result is None:
            raise ClaudeSDKError("Claude Code ended without a result.")
        if result.is_error:
            raise ClaudeSDKError("; ".join(result.errors or []) or result.result or result.subtype)
        return result.result or ""
    finally:
        sandcovery.sandboxes.destroy(sandbox.id)
  • sandbox_server serves the three tools from an in-process MCP server named sandbox, so Claude sees them as mcp__sandbox__run_command, mcp__sandbox__write_file, and mcp__sandbox__read_file.
  • tools=[] turns off every built-in tool, so Claude reaches nothing on your machine, and allowed_tools lets the three sandbox tools run without a permission prompt.
  • setting_sources=[] and strict_mcp_config=True keep settings files and other MCP servers on your machine out of the run.
  • Each tool calls the Sandcovery client in a worker thread, so a long command does not block the event loop. run_command returns the exit code, stdout, stderr, and duration as JSON, and a command runs for up to 300 seconds, or for the longest command its provider runs when that is shorter, unless exec gets timeout_seconds.
  • A tool that raises, such as a read of a missing file, sends its error message to Claude instead of ending the run.
  • run_agent creates one sandbox for the run. sandcovery/2x4 starts it on the candidate with the lowest hourly price among the providers that bill by use at 2 vCPU and 4 GiB, and falls back to the next candidate when a create fails.
  • A run that ends on an error, such as a failed model call or reaching max_turns=10, raises ClaudeSDKError with the error Claude Code reported.
  • finally destroys the sandbox after the answer or a failure. If your process exits first, Sandcovery destroys the sandbox when its ttl_seconds ends.
  • With no model, Claude Code runs its default model.

Run the agent

main.py
import asyncio

from sandcovery import Sandcovery

from agent import run_agent

with Sandcovery() as sandcovery:
    print(asyncio.run(run_agent(sandcovery, "Print the first 10 primes with a Python script.")))

Next steps

  • Routing: rank providers by start latency or uptime instead, such as with sandcovery/2x4:fastest.
  • API keys: cap the spend, providers, and concurrency of the key the agent uses.