# How to Integrate microsandbox into an Existing Project: A Complete Guide for Developers

> Integrate microsandbox into your project easily. Add an SDK dependency and use the builder API to spawn hardware-isolated microVMs without a separate daemon. Start securing your code now.

- Repository: [Super Rad Company/microsandbox](https://github.com/superradcompany/microsandbox)
- Tags: how-to-guide
- Published: 2026-08-20

---

**Integrate microsandbox into your existing project by adding a language-specific SDK dependency and using the builder API to spawn hardware-isolated microVMs as child processes—no separate daemon required.**

microsandbox is a lightweight, hardware-isolated microVM platform from superradcompany/microsandbox that embeds directly into applications. Unlike container solutions that require a background daemon, microsandbox's **runtime spawns as a child process** of your application, giving you fine-grained control over sandbox lifecycle, networking policies, and resource allocation.

## Architecture Overview: Three Layers of microsandbox

Understanding microsandbox's architecture helps you integrate it effectively:

| Layer | Description | Location in Repository |
|-------|-------------|------------------------|
| **Runtime** | Tiny Linux kernel via libkrun that boots microVMs and manages lifecycle (start, stop, snapshot) | `crates/runtime` |
| **SDKs** | Language-specific client libraries wrapping the agent-client protocol with async, high-level APIs | `sdk/rust/`, `sdk/python/`, `sdk/node-ts/`, `sdk/go/` |
| **CLI / MCP** | `msb` command-line tool and MCP server for AI agent integration | `crates/cli/`, `mcp/` |

The **agent-client protocol** in [`packages/agent-client/rust/src/lib.rs`](https://github.com/superradcompany/microsandbox/blob/main/packages/agent-client/rust/src/lib.rs) is the communication backbone that all SDKs use to control the runtime.

## Host Prerequisites for microsandbox Integration

Before integrating, verify your host meets these requirements:

- **Linux** — KVM enabled (check with `ls /dev/kvm`)
- **macOS** — Apple Silicon (uses Hypervisor.framework)
- **Windows** — Windows 10+ with Windows Hypervisor Platform (WHP) enabled

The SDK automatically handles runtime binary installation on first use.

## Integration Steps for microsandbox

### Step 1: Add the SDK Dependency

Install the appropriate SDK for your language:

**Rust** — Add to [`Cargo.toml`](https://github.com/superradcompany/microsandbox/blob/main/Cargo.toml):

```toml
[dependencies]
microsandbox = "0.1"
tokio = { version = "1", features = ["full"] }

```

**Python** — Using `uv` or `pip`:

```bash
uv add microsandbox

# or

pip install microsandbox

```

**TypeScript/Node** — Using `npm`:

```bash
npm install microsandbox

```

**Go** — Using `go get`:

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

```

### Step 2: Create and Configure a Sandbox

Use the builder pattern to define your sandbox configuration. The SDK serializes this into a configuration struct sent to the runtime via the control channel.

### Step 3: Execute Commands and Manage Files

Interact with the guest through `exec`, filesystem methods, and networking APIs.

### Step 4: Clean Up or Detach

Stop the sandbox with `sandbox.stop().await?` or call `sandbox.detach()` to let it outlive your host process for long-running workers.

## Language-Specific Integration Examples

### Rust Integration with microsandbox

The Rust SDK in [`sdk/rust/README.md`](https://github.com/superradcompany/microsandbox/blob/main/sdk/rust/README.md) provides the most complete builder API:

```rust
use microsandbox::Sandbox;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Build and launch sandbox with resource limits and network policy
    let sandbox = Sandbox::builder("my-rust-app")
        .image("python")
        .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 the microVM
    let out = sandbox.exec("python", ["-c", "print('Hello from a microVM!')"])
        .await?;
    println!("stdout: {}", out.stdout()?.trim());

    // Read and write guest filesystem
    let fs = sandbox.fs();
    fs.write("/tmp/config.json", br#"{"debug":true}"#).await?;
    let data = fs.read("/tmp/config.json").await?;

    // Clean up
    sandbox.stop().await?;
    Ok(())
}

```

### Python Integration with microsandbox

The Python SDK in [`sdk/python/README.md`](https://github.com/superradcompany/microsandbox/blob/main/sdk/python/README.md) offers dictionary-based configuration:

```python
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())

```

### TypeScript/Node Integration with microsandbox

The Node-TS SDK in [`sdk/node-ts/README.md`](https://github.com/superradcompany/microsandbox/blob/main/sdk/node-ts/README.md) follows the same builder pattern as Rust:

```typescript
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 with microsandbox

The Go SDK in [`sdk/go/README.md`](https://github.com/superradcompany/microsandbox/blob/main/sdk/go/README.md) uses functional options and requires explicit runtime installation:

```go
package main

import (
	"context"
	"fmt"
	"log"

	microsandbox "github.com/superradcompany/microsandbox/sdk/go"
)

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

	// Download and install runtime binary on first run
	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())
}

```

## Key Configuration Options for microsandbox Integration

When you integrate microsandbox, these builder options control sandbox behavior:

| Option | Purpose | Example |
|--------|---------|---------|
| `image` | OCI image to pull and run | `"python"`, `"node:18"` |
| `cpus` / `memory` | Resource limits | `.cpus(2)`, `.memory(1024)` |
| `network` | Egress firewall rules | Default-deny with specific allows |
| `secret_env` | Inject secrets scoped to specific hosts | Token only sent to `api.github.com` |
| `volumes` | Mount host directories into guest | Persistent data across restarts |

The runtime in [`crates/runtime/lib/lib.rs`](https://github.com/superradcompany/microsandbox/blob/main/crates/runtime/lib/lib.rs) applies these configurations when booting the microVM.

## How microsandbox Runtime Integration Works

When you call `create()` or `CreateSandbox()`:

1. **Configuration serialization** — The builder constructs a config struct serialized over the agent-client protocol defined in [`packages/agent-client/rust/src/lib.rs`](https://github.com/superradcompany/microsandbox/blob/main/packages/agent-client/rust/src/lib.rs)
2. **Runtime spawning** — The SDK launches the runtime as a child process; no pre-existing daemon needed
3. **MicroVM boot** — The runtime uses libkrun to start a hardware-isolated VM with your specified root filesystem
4. **Guest initialization** — Networking, volumes, and secrets are configured before your code runs

This child-process model means the sandbox **inherits your application's environment** and terminates cleanly when stopped or dropped.

## Summary

- **microsandbox integrates as a library dependency** — add the Rust, Python, TypeScript, or Go SDK to your project
- **No daemon required** — the runtime spawns as a child process on demand via the builder API
- **Hardware isolation via libkrun** — microVMs use KVM (Linux), Hypervisor.framework (macOS), or WHP (Windows)
- **Unified control channel** — all SDKs communicate through the agent-client protocol implemented in [`packages/agent-client/rust/src/lib.rs`](https://github.com/superradcompany/microsandbox/blob/main/packages/agent-client/rust/src/lib.rs)
- **Complete lifecycle control** — create, exec, manage filesystem, configure networking, and stop or detach sandboxes programmatically

## Frequently Asked Questions

### Does microsandbox require root privileges to integrate?

No. The microsandbox runtime uses hardware virtualization APIs (KVM, Hypervisor.framework, WHP) that typically require membership in the `kvm` group on Linux or standard user permissions on macOS and Windows. You do not need to run your application as root.

### Can microsandbox run on CI/CD environments without nested virtualization?

Nested virtualization support varies by provider. GitHub Actions, AWS EC2, and GCP support nested KVM on specific instance types. For environments without nested virtualization, the microsandbox runtime will fail to start—check [`crates/runtime/lib/lib.rs`](https://github.com/superradcompany/microsandbox/blob/main/crates/runtime/lib/lib.rs) for the specific error handling.

### How does the Python SDK differ from the Rust SDK in microsandbox?

The Python SDK in [`sdk/python/README.md`](https://github.com/superradcompany/microsandbox/blob/main/sdk/python/README.md) provides a dictionary-based configuration API rather than the fluent builder pattern used in Rust. Both wrap the same agent-client protocol and offer identical capabilities: sandbox creation, command execution, filesystem operations, and networking policies. The Python SDK handles async/await patterns using `asyncio`.

### What happens if the host application crashes while a microsandbox is running?

By default, the microsandbox runtime terminates with its parent process. Call `sandbox.detach()` before your application exits to allow the microVM to continue running independently. Re-attach later using the sandbox name. The runtime implementation in [`crates/runtime/lib/lib.rs`](https://github.com/superradcompany/microsandbox/blob/main/crates/runtime/lib/lib.rs) handles both attached and detached lifecycle modes.