Microsandbox Guide: Secure MicroVM Code Execution in 200ms

6月4日 Published inSystem Utilities

Microsandbox is a self-hosted platform designed for the secure execution of untrusted code. Whether you are dealing with user-submitted scripts or AI-generated output, every process runs inside a hardware-isolated microVM to ensure your host system remains protected.

Hardware Isolation Each sandbox operates as a lightweight microVM, preventing malicious code from ever reaching the host environment.

Fast Startup Achieve cold starts in under 200 milliseconds—a massive leap in efficiency compared to traditional VMs, which often require 10 seconds or more to initialize.

Self-Hosted Maintain full control over your infrastructure with a platform that requires no external dependencies.

OCI Compatibility Images follow the OCI standard, allowing you to drop them directly into your existing container pipelines.

AI-Ready With built-in support for the Model Context Protocol (MCP), Microsandbox integrates natively with Claude, Agno, and other popular AI tools.

Module Function Recent Update
microsandbox-core Core runtime engine Downgraded MCP version; removed unused dependencies (#244)
microsandbox-server Server component Added --host flag (#253)
microsandbox-cli Command-line tool Added --host flag (#253)
microsandbox-portal Admin portal Downgraded MCP version; removed unused dependencies (#244)
sdk Software development kit Improved CLI documentation and MCP protocol notes (#241)
docs Documentation Moved cloud hosting guide to a separate file (#228)

Installation and Usage

Start the Server

  1. Install the platform via curl: curl -sSL https://get.microsandbox.dev | sh

  2. Launch in development mode: msb server start --dev The server communicates via MCP, allowing AI tools to connect directly.

  3. Pull an environment image (optional): msb pull microsandbox/python

SDK Integration

Python

import asyncio
from microsandbox import PythonSandbox

async def main():
    async with PythonSandbox.create(name="test") as sb:
        exec = await sb.run("name = 'Python'")
        exec = await sb.run("print(f'Hello {name}!')")
    print(await exec.output())  # Hello Python!

asyncio.run(main())

JavaScript

import { NodeSandbox } from "microsandbox";

async function main() {
  const sb = await NodeSandbox.create({ name: "test" });
  try {
    let exec = await sb.run("var name = 'JavaScript'");
    exec = await sb.run("console.log(`Hello ${name}!`)");
    console.log(await exec.output()); // Hello JavaScript!
  } finally {
    await sb.stop();
  }
}

main().catch(console.error);

Rust

use microsandbox::{SandboxOptions, PythonSandbox};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut sb = PythonSandbox::create(SandboxOptions::builder().name("test").build()).await?;
    let exec = sb.run(r#"name = "Python""#).await?;
    let exec = sb.run(r#"print(f"Hello {name}!")"#).await?;
    println!("{}", exec.output().await?); // Hello Python!
    sb.stop().await?;
    Ok(())
}

Development Workflow

The Microsandbox CLI is designed to mirror familiar workflows like npm or Cargo.

  1. Initialize a project: msb init This generates a Sandboxfile.

  2. Add a sandbox environment:

    msb add app \
        --image python \
        --cpus 1 \
        --memory 1024 \
        --start 'python -c "print(\"hello\")"'
    
  3. Run the sandbox:

    • Execute the default script: msb run --sandbox app or msr app
    • Execute a specific script: msr app~start
  4. One-off sandboxes: Run a command and automatically clean up upon exit: msb exe --image python or msx python

  5. Install as a system command: Register the sandbox globally for easy access: msb install --image alpine or msi alpine Then simply run: alpine

Use Cases

Development and Coding AI agents can build, test, and execute code entirely within the sandbox. For example, a React application flow:

git init task-tracker
cd task-tracker
npm create vite@latest --template react-ts
npm install
npm run dev

This setup is perfect for AI pair programming, coding education, and automated code generation.

Data Analysis Process sensitive data with strict isolation guarantees.

import pandas as pd
sales_data = pd.read_csv('q2_sales.csv')
monthly_growth = sales_data.groupby('month')['revenue'].sum()

Result: Q2 growth of 24.7%. East region leads. Mobile conversion rate peaked at 18.4%. Ideal for financial modeling, healthcare data, and privacy-focused processing.

Web Browsing and Automation Enable AI to scrape and compare prices within a secure environment.

retailers = ['TechStore', 'BestDeal', 'OnlineMart']
for retailer in retailers:
    products = scrape(retailer, 'laptops under $1000')
    filter_by_price(products, 1000)

Excellent for building price trackers, content aggregators, and automated QA tools.

App Deployment Deploy AI-generated applications in seconds and receive a shareable link.

msb deploy weather-app --image node:18
# Returns: https://msbl.ink/w37x9f

Features 2.3-second deployment and automatic resource cleanup. A great fit for educational platforms and live demonstrations.

Technical Architecture

Microsandbox utilizes a three-tier architecture consisting of the client, the server, and the microVM layer.

flowchart TB
    subgraph Client Process
        Business Logic --> SDK Call
    end

    subgraph Server Process
        SDK Request --> Server Handler
    end

    subgraph MicroVM Cluster
        Server Scheduler --> Python Env
        Server Scheduler --> Node Env
        Server Scheduler --> Ruby Env
    end
  • Client: The SDK transmits execution requests to the server.
  • Server: Manages the lifecycle of microVM instances and routes requests accordingly.
  • MicroVMs: Individual environments run in isolation, protected by hardware-level security.