How to Integrate microsandbox into an Existing Project: A Complete SDK Guide

Embed hardware-isolated microVMs into any Rust, Python, TypeScript, or Go codebase by adding a single SDK dependency and using the builder API to spawn sandboxes as child processes.

The microsandbox project from superradcompany/microsandbox provides lightweight, hardware-isolated virtualization without requiring a separate daemon. This guide walks through integrating microsandbox into existing projects using the official SDKs, with complete code examples from the source.

Understanding microsandbox's Three-Layer Architecture

Before integration, it helps to understand how the components connect:

Layer Location Role in Integration
Runtime crates/runtime Boots microVMs via libkrun; spawned as child process by your app
SDKs sdk/rust, sdk/python, sdk/node-ts, sdk/go Language-specific wrappers around the agent-client protocol
CLI/MCP crates/cli, mcp/ Reference implementations and AI agent interfaces

The agent-client protocol—implemented in packages/agent-client/rust/src/lib.rs—serializes configuration structs and streams them to the runtime, which handles VM lifecycle, rootfs patches, networking, volumes, and secrets.

Host Prerequisites for microsandbox Integration

The runtime has platform-specific requirements that must be satisfied before your SDK calls will succeed:

  • Linux: KVM enabled (/dev/kvm accessible)
  • macOS: Apple Silicon (uses Hypervisor.framework)
  • Windows: Windows 10+ with Windows Hypervisor Platform (WHP)

No separate daemon installation is required—the SDK downloads and manages the runtime binary automatically on first use.

Step-by-Step Integration Guide

1. Add the SDK Dependency

Install the language-specific SDK for your project:


# Rust (Cargo.toml)

[dependencies]
microsandbox = "0.1"

# Python

uv add microsandbox

# TypeScript/Node

npm install microsandbox

# Go

go get github.com/superradcompany/microsandbox/sdk/go

2. Create a Sandbox with the Builder Pattern

All SDKs expose a builder API that constructs a configuration struct serialized to the runtime. Here are implementations in each supported language.

Rust Integration

The Rust SDK in sdk/rust/README.md provides the most direct access to the builder pattern:

use microsandbox::Sandbox;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Build and launch a sandbox
    let sandbox = Sandbox::builder("my-rust-app")
        .image("python")          // Pulls OCI image on first run
        .cpus(2)
        .memory(1024)
        .network(|n| n.policy(
            microsandbox::NetworkPolicy::builder()
                .default_deny()
                .rule(|r| r.egress().allow().domain("api.github.com"))
                .build()?,
        ))
        .secret_env("GITHUB_TOKEN", "my-secret-token", "api.github.com")
        .create()
        .await?;

    // Execute command inside VM
    let out = sandbox.exec("python", ["-c", "print('Hello from microVM!')"])
        .await?;
    println!("stdout: {}", out.stdout()?.trim());

    // Filesystem operations
    let fs = sandbox.fs();
    fs.write("/tmp/config.json", br#"{"debug":true}"#).await?;
    
    // Cleanup
    sandbox.stop().await?;
    Ok(())
}

The Sandbox::builder() method returns a configurator that implements the builder pattern defined in the Rust SDK, ultimately calling the runtime via the agent-client protocol.

Python Integration

The Python SDK (sdk/python/README.md) offers async/await syntax with dictionary-based configuration:

import asyncio
from microsandbox import Sandbox

async def main():
    sandbox = await Sandbox.create(
        "my-python-app",
        image="python",
        cpus=2,
        memory=1024,
        network={
            "allow": ["api.github.com"],
        },
        secrets=[{
            "env": "GITHUB_TOKEN",
            "value": "my-secret-token",
            "allowed_host": "api.github.com",
        }],
    )

    out = await sandbox.exec("python", ["-c", "print('Hello from microsandbox!')"])
    print("stdout:", out.stdout_text)

    await sandbox.write_file("/tmp/message.txt", b"Hello from host")
    content = await sandbox.read_file("/tmp/message.txt")
    print("file content:", content.decode())

    await sandbox.stop()

asyncio.run(main())

The Sandbox.create() classmethod wraps the same underlying protocol used by the Rust implementation.

TypeScript/Node Integration

The Node-TS SDK (sdk/node-ts/README.md) provides a fluent builder matching the Rust API:

import { Sandbox } from "microsandbox";

async function run() {
  const sandbox = await Sandbox.builder("my-ts-app")
    .image("python")
    .cpus(2)
    .memory(1024)
    .secretEnv("GITHUB_TOKEN", "my-secret-token", "api.github.com")
    .create();

  const out = await sandbox.exec("python", [
    "-c",
    "print('Hello from microsandbox!')",
  ]);
  console.log("stdout:", out.stdout());

  await sandbox.fs().write("/tmp/hello.txt", Buffer.from("Hello"));
  const data = await sandbox.fs().read("/tmp/hello.txt");
  console.log("file:", data.toString());

  await sandbox.stop();
}

run().catch(console.error);

Go Integration

The Go SDK (sdk/go/README.md) uses functional options and requires explicit runtime installation:

package main

import (
	"context"
	"fmt"
	"log"
	microsandbox "github.com/superradcompany/microsandbox/sdk/go"
)

func main() {
	ctx := context.Background()

	// Downloads runtime on first call
	if err := microsandbox.EnsureInstalled(ctx); err != nil {
		log.Fatalf("install error: %v", err)
	}

	sbx, err := microsandbox.CreateSandbox(ctx, "my-go-app",
		microsandbox.WithImage("python"),
		microsandbox.WithCPUs(2),
		microsandbox.WithMemory(1024),
		microsandbox.WithSecretEnv("GITHUB_TOKEN", "my-secret-token", "api.github.com"),
	)
	if err != nil {
		log.Fatalf("create error: %v", err)
	}
	defer sbx.Stop(ctx)

	out, err := sbx.Exec(ctx, "python", []string{"-c", "print('Hello from microsandbox!')"})
	if err != nil {
		log.Fatalf("exec error: %v", err)
	}
	fmt.Println("stdout:", out.Stdout())
}

Note the explicit EnsureInstalled() call—unlike other SDKs, the Go implementation requires this before creating sandboxes.

3. Manage Sandbox Lifecycle

Every SDK provides consistent lifecycle methods:

Method Purpose Behavior
create() / CreateSandbox() Boot the microVM Spawns runtime as child process, returns handle
exec() / Exec() Run command in guest Streams stdout/stderr via control channel
fs() / file methods Guest filesystem access Read/write through 9P or virtio-fs
stop() / Stop() Terminate VM Sends shutdown signal, reclaims resources
detach() Outlive parent Allows VM to continue after host process exits

The runtime in crates/runtime/lib/lib.rs manages these operations through a control channel that persists for the VM's lifetime.

Advanced Integration Patterns

Network Policy Configuration

Both Rust and TypeScript SDKs expose network policy builders for fine-grained egress control. The Rust implementation demonstrates default_deny() with explicit allow rules—a pattern implemented in the runtime's network namespace handling.

Secrets Management

The secret_env() / WithSecretEnv() methods inject environment variables that are:

  • Only exposed to processes matching the allowed_host egress rule
  • Stored in the runtime's memory, never written to disk
  • Scoped to the individual sandbox instance

This implementation lives in the runtime's init system, visible in the core runtime source.

Volume Mounts and Persistence

For data that must survive VM restarts, mount host directories as volumes:

// Rust example
Sandbox::builder("persistent-app")
    .volume("/host/data", "/app/data")
    .create()
    .await?

The volume mapping is processed by crates/runtime/lib/lib.rs during VM boot, configuring virtio-fs shares before the guest init starts.

Key Source Files for Deep Integration

File Purpose Relevance
crates/runtime/lib/lib.rs Core runtime, VM lifecycle Understand how your SDK calls translate to VM operations
packages/agent-client/rust/src/lib.rs Protocol serialization Build custom SDKs or debug wire format
crates/cli/src/main.rs CLI implementation Reference for integrating the same APIs in other contexts
mcp/src/main.rs MCP server for AI agents Model for programmatic control interfaces
sdk/*/README.md Language-specific docs API reference and version compatibility

Summary

  • No daemon required: The SDK spawns crates/runtime as a child process, inheriting parent environment
  • Four official SDKs: Rust, Python, TypeScript, and Go with consistent builder APIs
  • Platform prerequisites: KVM (Linux), Apple Silicon (macOS), or WHP (Windows)
  • Core workflow: Add dependency → create sandbox with builder → exec commands → stop or detach
  • Security features: Network egress policies, host-scoped secrets, and hardware-level isolation via libkrun

Frequently Asked Questions

Can I run microsandbox without installing anything system-wide?

Yes. The SDKs automatically download and cache the runtime binary on first use. The Go SDK requires explicit EnsureInstalled(); other SDKs handle this transparently. No root privileges or system services are needed beyond the platform virtualization prerequisites.

How do I debug a sandbox that fails to start?

Check the runtime logs and verify platform support. On Linux, ensure /dev/kvm exists and your user has access. The CLI in crates/cli/src/main.rs provides verbose logging flags that mirror SDK behavior. Enable debug output in your SDK initialization to see the agent-client protocol exchanges.

What's the performance overhead of the SDK-to-runtime communication?

The agent-client protocol uses an efficient binary format over a local socket. For high-throughput scenarios, use volume mounts rather than streaming large files through the fs() API. The runtime in crates/runtime/lib/lib.rs implements zero-copy paths for virtio-fs where possible.

Can I use microsandbox in production CI/CD pipelines?

Yes. The MCP server in mcp/src/main.rs demonstrates programmatic control suitable for automation. Sandboxes are deterministic and start in under 100ms on supported hardware. Use sandbox.detach() for long-running workers that must survive CI runner restarts.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →