Skip to main content

Sandcrab Python SDK and MCP server

The sandcrab package provides synchronous and asynchronous clients for Sandcrab's native control API (SandcrabClient, AsyncSandcrabClient), declarative caller-side host-call dispatch (HostCallDispatcher, AsyncHostCallDispatcher), a standard-library JSON-RPC 2.0 stdio MCP server (sandcrab-mcp), and the sandcrab_templates extension used alongside the published OpenSandbox SDK. It requires Python 3.11+ and httpx>=0.28.1,<1.

Run your first session

Run this example on the Linux host where Sandcrab is installed. Use the application account that owns the token from the service setup. In an empty directory, create a virtual environment. Use the PyPI command below for a published version. For a version awaiting publication, give pip the absolute path to sdk/python in the matching checkout in place of sandcrab==0.3.0.

python3 -m venv .venv
.venv/bin/python -m pip install sandcrab==0.3.0

Save this as example.py.

from sandcrab import SandcrabClient

with SandcrabClient(
    endpoint="http://127.0.0.1:9011",
    token_file="/etc/sandcrab-client/token",
    default_profile="default",
) as client:
    with client.open_session() as session:
        session.write_file("src/main.py", "print(6 * 7)\n", parents=True)
        session.exec("python3 src/main.py > answer.txt", check=True)
        print(session.read_text("answer.txt").strip())

Run the example. It prints 42 and closes and forgets the session on exit.

.venv/bin/python example.py

Native client

Connect over a root-owned Unix control socket or a literal loopback HTTP endpoint with a 64-hex service token. Redirects and environment proxies are disabled. When neither socket_path nor endpoint is passed, the client reads SANDCRAB_SOCKET or SANDCRAB_ENDPOINT (plus SANDCRAB_TOKEN_FILE and SANDCRAB_PROFILE), and refuses implicit selection if both transport variables are set.

Exiting with client.open_session() as session: (or async with await client.open_session()) closes and forgets the session unless keep_result=True or auto_close=False is set. run() and session.exec() stream output when on_output is supplied, forget completed records unless keep_result=True, and raise CommandFailedError when check=True and the command does not succeed.

If transport fails after submitting a mutating request (submit_run, open_session, submit_session_command, create_volume), the client raises TransportUncertainError carrying recovery_id and never reposts under a new ID.

Workspace file helpers (write_file, read_file, read_text, mkdir, list_files, search_files, remove_file, diff, snapshot) enforce normalized relative paths, verify ETag digests on complete downloads, and support HTTP byte ranges (byte_range) or 1-based line ranges (offset, limit). import_template() streams plain .tar archives directly and gunzips .tar.gz / .tgz archives on the client before sending bounded application/x-tar bytes.

Caller-owned host calls

HostCallDispatcher and AsyncHostCallDispatcher run handlers in the caller's process while Sandcrab relays opaque bytes; see host calls.

import hashlib, hmac
from sandcrab import HostCallDispatcher, SandcrabClient

dispatcher = HostCallDispatcher()

@dispatcher.on_json("sign-sha256")
def sign_digest(request: dict, context) -> dict:
    digest = request["digest"]
    if digest != expected_digest:
        raise PermissionError("outside build grant")
    sig = hmac.new(signing_key, bytes.fromhex(digest), hashlib.sha256).hexdigest()
    return {"digest": digest, "signature": sig}

with SandcrabClient(socket_path="/run/sandcrab/sandcrab.sock", default_profile="python") as client:
    client.run(["python3", "build_and_sign.py"], dispatcher=dispatcher, check=True)

Each event's requestSha256 and serving epoch are checked before invoking a handler. Dispatchers sharing an InMemoryReplyLedger share the result of overlapping observations of the same (run_id, call_id) and reject changed payloads. With a custom ledger, share one dispatcher to coordinate concurrent calls. For durable external effects, record the reply in the transaction that commits the effect. Any unhandled handler exception cancels the sandbox command and leaves its record retained for inspection.

Stdio MCP server

sandcrab-mcp (or examples/sandcrab-mcp.py) serves MCP 2024-11-05 and 2025-03-26 JSON-RPC 2.0 over stdio using only the Python standard library alongside SandcrabClient:

sandcrab-mcp --endpoint http://127.0.0.1:9011 --token-file /etc/sandcrab-client/token --profile default

Exposed tools are bounded to sandbox execution and workspace-relative files: sandcrab_run, sandcrab_session_open, sandcrab_session_exec, sandcrab_session_close, sandcrab_write_file, sandcrab_read_file, sandcrab_mkdir, sandcrab_list_files, and sandcrab_search_files. File tool payloads are capped at 1 MiB per call; larger files require offset/limit or byte_range. Sessions opened through MCP are closed and forgotten automatically when stdin closes.

Template publication alongside OpenSandbox (sandcrab_templates)

sandcrab_templates remains importable directly (and re-exported from sandcrab) for filesystem capture and immutable publication beside the published OpenSandbox SDK. From a source checkout, install both for the examples below.

python -m pip install ./sdk/python -r evals/sdk/requirements.txt

Create an authenticated TemplateClient with the literal loopback endpoint and service token used by the OpenSandbox connection:

async with TemplateClient("http://127.0.0.1:9011", token) as templates:
    checkpoint = await templates.capture(sandbox.id, "prepared.tar")
    # The builder may now be killed and its client closed.
    template = await templates.publish(checkpoint)
    fresh = await Sandbox.create(checkpoint.image, connection_config=config,
                                 timeout=timedelta(seconds=60),
                                 resource={"cpu": "0.25", "memory": "32Mi"})

Prepare and validate files before capture. checkpoint.image selects a rootfs template in OpenSandbox; workspace captures use native session templateId. The native reference owns freeze semantics, supported metadata, limits and omitted runtime state. Checkpoint.to_dict() and Checkpoint.from_dict() save and load a trusted local receipt; keep it with the captured archive outside the sandbox.

Capture checks the serving epoch, profile, filesystem kind, byte length and SHA-256 before atomically installing a new file without replacing an existing destination (mode 0600 on POSIX). Cancellation closes the response and removes partial staging; capture never publishes a template.

Publication verifies the local archive and sends expectedId to the server. Existing matching objects are reused. After a lost transport reply, the client performs one read to reconcile that ID and never reposts automatically; if absent, PublicationUncertain carries its ID and await templates.reconcile(checkpoint) checks visibility later.

The independent environment example builds, validates, captures, publishes, and starts two independent instances:

python examples/sandcrab-environment.py --base-image PROFILE@sha256:ID \
  --token-file ./client.token --archive ./prepared.tar --receipt ./prepared.json

Compose independently imported layers with await templates.compose([base_id, toolkit_id, workspace_id]); the native recipe contract owns ordering, whiteouts, limits and reference lifetimes. recipe_id(layers) computes the expected ID locally, and examples/sandcrab-recipe.py validates composed layers:

python examples/sandcrab-recipe.py --token-file ./client.token --profile default \
  --validate 'bash /workspace/test.sh' BASE_ID TOOLKIT_ID WORKSPACE_ID

Development

Run the SDK checks from the repository root.

python -m pip install ./sdk/python
python -m unittest discover -s sdk/python/tests -v

Metadata

Release files for sandcrab 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sandcrab 0.3.0
File Size Uploaded Provenance Actions
sandcrab-0.3.0.tar.gz 47.0 kB With provenance Details for sandcrab-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for sandcrab 0.3.0
File Interpreter ABI Platform Actions
sandcrab-0.3.0-py3-none-any.whl Python 3 none any Details for sandcrab-0.3.0-py3-none-any.whl

Total release size: 85.7 kB

Release files / sandcrab-0.3.0.tar.gz

Download URL sandcrab-0.3.0.tar.gz
Size 47.0 kB
Tags Source
SHA-256 checksum
How to use checksums
e8d8802111e13586759dbff2de42b50a67a0bd67f1e51fbe6382111dbe3baf74
BLAKE2b-256 checksum
How to use checksums
898a52ac26ef7e9e1db7f4a4c68ebf2435a30745a0cf783cf151a7217e066369
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

Release files / sandcrab-0.3.0-py3-none-any.whl

Download URL sandcrab-0.3.0-py3-none-any.whl
Size 38.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b2bc67f80700d3adc1567258e47e5b4b8cb3d81f9fcfaf2fdada9a2da9a2c111
BLAKE2b-256 checksum
How to use checksums
b845fe087040a9f9ee415bc8e46305125c642a77905e4bfefba6998287ba08f8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

Security for sandcrab 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for sandcrab-0.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.3.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page