Skip to main content

Python SDK for microsandbox — secure, fast microVM-based sandboxing.

Project description

microsandbox

Lightweight VM sandboxes for Python applications that need hardware-level isolation for AI agents, tools, tests, and untrusted code.

The microsandbox Python package provides async Python bindings to the microsandbox runtime. It creates microVM-backed sandboxes from OCI images or other rootfs sources, then exposes command execution, guest filesystem access, networking, secrets, volumes, metrics, logs, snapshots, and SSH/SFTP through Python-friendly classes and dataclasses.

For the full API reference and longer guides, use the docs site:

Features

  • Hardware VM isolation with a guest Linux kernel
  • Async sandbox lifecycle, execution, filesystem, metrics, and logs APIs
  • OCI image, bind-rootfs, disk-image, and snapshot-based sandboxes
  • Named volumes, bind mounts, tmpfs mounts, and disk-image mounts
  • Network policies, DNS filtering, TLS interception, secrets, and port publishing
  • Rootfs patches before boot
  • Detached sandboxes that can outlive the Python process
  • Typed Python surface with StrEnums, frozen dataclasses, event objects, .pyi stubs, and py.typed

Requirements

  • Python 3.10+
  • Linux with KVM, macOS with Apple Silicon, or Windows with Windows Hypervisor Platform
  • Windows support is currently preview; see the Windows troubleshooting guide for WHP and runtime setup notes.

Supported Platforms

Platform Architecture Notes
macOS ARM64 / Apple Silicon Wheel bundles msb and libkrunfw
Linux x86_64 Wheel bundles msb and libkrunfw
Linux ARM64 Wheel bundles msb and libkrunfw
Windows x86_64, ARM64 Preview; requires WHP

Python wheels bundle the matching msb runtime and libkrunfw library. Source checkouts and unreleased local builds can override runtime paths with MSB_PATH, MSB_LIBKRUNFW_PATH, or microsandbox.set_libkrunfw_path(...).

Installation

pip install microsandbox

Quick Start

import asyncio

from microsandbox import Sandbox


async def main() -> None:
    async with await Sandbox.create("python-readme", image="alpine", replace=True) as sandbox:
        output = await sandbox.shell("echo 'Hello from microsandbox!'")
        print(output.stdout_text.strip())


asyncio.run(main())

async with stops and removes the sandbox when the block exits. Use Sandbox.create(...) without a context manager when you want to control stop(), kill(), or remove() yourself.

Common Examples

These snippets assume you already have a live sandbox: Sandbox.

Command Execution

import sys

output = await sandbox.exec("python3", ["-c", "print(1 + 1)"])
print(output.stdout_text)
print(output.exit_code)

output = await sandbox.shell("echo hello && pwd")
print(output.stdout_text)

output = await sandbox.exec(
    "python3",
    ["script.py"],
    cwd="/app",
    env={"PYTHONPATH": "/app/lib"},
    timeout=30.0,
)

handle = await sandbox.exec_stream("tail", ["-f", "/var/log/app.log"])
async for event in handle:
    match event.event_type:
        case "stdout":
            sys.stdout.buffer.write(event.data)
        case "stderr":
            sys.stderr.buffer.write(event.data)
        case "exited":
            break

Filesystem Operations

fs = sandbox.fs

await fs.write("/tmp/config.json", b'{"debug": true}')
print(await fs.read_text("/tmp/config.json"))

for entry in await fs.list("/etc"):
    print(f"{entry.path} ({entry.kind})")

await fs.copy_from_host("./local-file.txt", "/tmp/file.txt")
await fs.copy_to_host("/tmp/output.txt", "./output.txt")

if await fs.exists("/tmp/config.json"):
    meta = await fs.stat("/tmp/config.json")
    print(f"size: {meta.size}, kind: {meta.kind}")

Named Volumes

from microsandbox import Sandbox, Volume

data = await Volume.create("python-readme-data", quota_mib=100)

writer = await Sandbox.create(
    "python-readme-writer",
    image="alpine",
    volumes={"/data": Volume.named(data.name)},
    replace=True,
)
await writer.shell("echo 'hello' > /data/message.txt")
await writer.stop()

reader = await Sandbox.create(
    "python-readme-reader",
    image="alpine",
    volumes={"/data": Volume.named(data.name, readonly=True)},
    replace=True,
)
output = await reader.shell("cat /data/message.txt")
print(output.stdout_text.strip())
await reader.stop()

Network, DNS, and Ports

from microsandbox import Network, Sandbox
from microsandbox.types import DnsConfig

isolated = await Sandbox.create(
    "python-readme-isolated",
    image="alpine",
    network=Network.none(),
    replace=True,
)

filtered = await Sandbox.create(
    "python-readme-filtered",
    image="alpine",
    network=Network(
        deny_domains=("blocked.example.com",),
        deny_domain_suffixes=(".evil.com",),
        dns=DnsConfig(nameservers=("1.1.1.1:53",)),
    ),
    replace=True,
)

web = await Sandbox.create(
    "python-readme-web",
    image="python",
    ports={8080: 80},
    network=Network.public_only(),
    replace=True,
)

Secrets

Secrets use placeholder substitution. The real value stays on the host and is substituted only for allowed network destinations.

import os

from microsandbox import Sandbox, Secret

sandbox = await Sandbox.create(
    "python-readme-agent",
    image="python",
    secrets=[
        Secret.env(
            "OPENAI_API_KEY",
            value=os.environ["OPENAI_API_KEY"],
            allow_hosts=["api.openai.com"],
        ),
    ],
    replace=True,
)

Rootfs Patches

from microsandbox import Patch, Sandbox

sandbox = await Sandbox.create(
    "python-readme-patched",
    image="alpine",
    patches=[
        Patch.text("/etc/greeting.txt", "Hello!\n"),
        Patch.mkdir("/app", mode=0o755),
        Patch.text("/app/config.json", '{"debug": true}', mode=0o644),
        Patch.append("/etc/hosts", "127.0.0.1 myapp.local\n"),
    ],
    replace=True,
)

Detached Mode

sandbox = await Sandbox.create(
    "python-readme-background",
    image="python",
    detached=True,
    replace=True,
)

handle = await Sandbox.get("python-readme-background")
reconnected = await handle.connect()
output = await reconnected.shell("echo reconnected")
print(output.stdout_text.strip())

Metrics

from microsandbox import MiB, all_sandbox_metrics

metrics = await sandbox.metrics()
print(f"CPU: {metrics.cpu_percent:.1f}%")
print(f"Memory: {metrics.memory_bytes // MiB} MiB")

async for sample in sandbox.metrics_stream(interval=1.0):
    print(f"CPU: {sample.cpu_percent:.1f}%")
    break

for name, sample in (await all_sandbox_metrics()).items():
    print(f"{name}: {sample.cpu_percent:.1f}%")

Typed Errors

Python exports typed errors for the common SDK categories and falls back to MicrosandboxError for unmapped runtime variants. Catch specific errors when you need category-specific handling, and catch MicrosandboxError as the broad SDK base class.

from microsandbox import MicrosandboxError, Sandbox, SandboxAlreadyExistsError

try:
    await Sandbox.create("worker", image="alpine")
except SandboxAlreadyExistsError:
    print("already exists; resume it or pass replace=True")
except MicrosandboxError as exc:
    print(f"microsandbox error: {exc}")

Runtime Setup

Installed wheels bundle the runtime files. The setup helpers are useful for source checkouts, shared runtime installs, and surfacing setup failures at process startup.

from microsandbox import install, is_installed

if not is_installed():
    await install()

More Documentation

Development

From sdk/python:

uv sync --group dev
uv run maturin develop --release
uv run pytest tests
uv run ruff check .

From the repository root, run an example against the SDK project:

uv run --project sdk/python python examples/python/root-oci/main.py

Runtime integration tests require local virtualization support and runtime artifacts:

cd sdk/python
uv run pytest integration/test_create_kwargs.py integration/test_exec.py

License

Apache-2.0

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

microsandbox-0.6.2-cp310-abi3-win_arm64.whl (32.7 MB view details)

Uploaded CPython 3.10+Windows ARM64

microsandbox-0.6.2-cp310-abi3-win_amd64.whl (28.8 MB view details)

Uploaded CPython 3.10+Windows x86-64

microsandbox-0.6.2-cp310-abi3-manylinux_2_28_x86_64.whl (31.3 MB view details)

Uploaded CPython 3.10+manylinux: glibc 2.28+ x86-64

microsandbox-0.6.2-cp310-abi3-manylinux_2_28_aarch64.whl (34.9 MB view details)

Uploaded CPython 3.10+manylinux: glibc 2.28+ ARM64

microsandbox-0.6.2-cp310-abi3-macosx_11_0_arm64.whl (33.1 MB view details)

Uploaded CPython 3.10+macOS 11.0+ ARM64

File details

Details for the file microsandbox-0.6.2-cp310-abi3-win_arm64.whl.

File metadata

  • Download URL: microsandbox-0.6.2-cp310-abi3-win_arm64.whl
  • Upload date:
  • Size: 32.7 MB
  • Tags: CPython 3.10+, Windows ARM64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.26 {"installer":{"name":"uv","version":"0.11.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for microsandbox-0.6.2-cp310-abi3-win_arm64.whl
Algorithm Hash digest
SHA256 0fb613012a281c8c9868bd609fe171ea966edf613059e7b03c5565635f7e4637
MD5 3b8128101b3496c58ce2524eeeb77d76
BLAKE2b-256 ef8c09bfd19f7639963b1048f9445bfa98974fad405bfe48bd24e7a8705f5b1e

See more details on using hashes here.

File details

Details for the file microsandbox-0.6.2-cp310-abi3-win_amd64.whl.

File metadata

  • Download URL: microsandbox-0.6.2-cp310-abi3-win_amd64.whl
  • Upload date:
  • Size: 28.8 MB
  • Tags: CPython 3.10+, Windows x86-64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.26 {"installer":{"name":"uv","version":"0.11.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for microsandbox-0.6.2-cp310-abi3-win_amd64.whl
Algorithm Hash digest
SHA256 282a86e2d8225ec1ee4ff97fa1749610f523a83328135a0ed5f53ba0af466f5a
MD5 04b21883ea9e6221ce2d10fcad9a0592
BLAKE2b-256 2cc9d38db20e2ca9893e8ad3a5cf27c60e141be4e37f2aab767e9ab3bf3a20d3

See more details on using hashes here.

File details

Details for the file microsandbox-0.6.2-cp310-abi3-manylinux_2_28_x86_64.whl.

File metadata

  • Download URL: microsandbox-0.6.2-cp310-abi3-manylinux_2_28_x86_64.whl
  • Upload date:
  • Size: 31.3 MB
  • Tags: CPython 3.10+, manylinux: glibc 2.28+ x86-64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.26 {"installer":{"name":"uv","version":"0.11.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for microsandbox-0.6.2-cp310-abi3-manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 19d712f03bd726dfa06f17c5ce8c55733906212d8f495c8c1cda8c7f50cad611
MD5 90ee732f3062ef534e97e67c33f20c05
BLAKE2b-256 b0ac3a28fd40eaa141b98c65bb8704ef7b114911ce626a62ebf98b07f6c5ea41

See more details on using hashes here.

File details

Details for the file microsandbox-0.6.2-cp310-abi3-manylinux_2_28_aarch64.whl.

File metadata

  • Download URL: microsandbox-0.6.2-cp310-abi3-manylinux_2_28_aarch64.whl
  • Upload date:
  • Size: 34.9 MB
  • Tags: CPython 3.10+, manylinux: glibc 2.28+ ARM64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.26 {"installer":{"name":"uv","version":"0.11.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for microsandbox-0.6.2-cp310-abi3-manylinux_2_28_aarch64.whl
Algorithm Hash digest
SHA256 b09c150ac52de39a08141bd4ed40aed2ead4a17a6d49dcbeaf01d94856f8b99f
MD5 9dd42f2dbcaa756da3aa49d2bb6ba7df
BLAKE2b-256 3e9a258ef202bdc28d3d57e33797e18223f2e8703c37f59d966beb7fade1fa46

See more details on using hashes here.

File details

Details for the file microsandbox-0.6.2-cp310-abi3-macosx_11_0_arm64.whl.

File metadata

  • Download URL: microsandbox-0.6.2-cp310-abi3-macosx_11_0_arm64.whl
  • Upload date:
  • Size: 33.1 MB
  • Tags: CPython 3.10+, macOS 11.0+ ARM64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.26 {"installer":{"name":"uv","version":"0.11.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for microsandbox-0.6.2-cp310-abi3-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 ffe38dc0a1fcf0e653cb2a6f50fa78c4e572f4f6ec2e0111cb7664b3656b02cc
MD5 4a68c624ccc8dfc810a7720382676136
BLAKE2b-256 86b7e8977391cce7b153408ab42598d01866a3fcbf0823a1e5d6572e86b14c61

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page