Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(lume): add MCP server with async VM creation and provisioning status (#836)

Francesco Bonacci33f9467ea98e
diff --git a/docs/content/docs/lume/examples/claude-code/homebrew-testing.mdx b/docs/content/docs/lume/examples/claude-code/homebrew-testing.mdx
new file mode 100644
index 0000000000..13bf521724
--- /dev/null
+++ b/docs/content/docs/lume/examples/claude-code/homebrew-testing.mdx
@@ -0,0 +1,205 @@
+---
+title: Homebrew Testing
+description: Test Homebrew formulas in a clean, isolated macOS environment
+---
+
+import { Callout } from 'fumadocs-ui/components/callout';
+
+This example demonstrates testing Homebrew packages in a **clean, isolated macOS environment**. Unlike your host machine cluttered with dependencies, a fresh VM sandbox ensures reproducible testing conditions.
+
+## Why use a sandbox?
+
+Testing Homebrew formulas on your host has problems:
+
+- **Dependency pollution** — Existing packages may mask missing dependencies
+- **State accumulation** — Previous installs leave behind configs and files
+- **Risk of breakage** — Testing can corrupt your development environment
+
+A macOS VM sandbox solves these:
+
+- **Clean slate** — Every test starts from a known state
+- **Isolation** — Bad installs don't affect your host
+- **Reproducibility** — Others can replicate your exact environment
+
+## Prerequisites
+
+- [Sandbox VM set up](/lume/examples/claude-code/sandbox)
+- A "golden image" VM for quick resets
+
+### Create a golden image
+
+Before testing, create a clean snapshot you can restore:
+
+```bash
+# Stop the sandbox if running
+lume stop sandbox
+
+# Create a golden image
+lume clone sandbox sandbox-golden
+
+# Now you can always reset to this clean state
+```
+
+## Example prompt
+
+Ask Claude Code:
+
+> "SSH into the sandbox. Install the 'jq' Homebrew formula, verify it works by parsing some JSON, then tell me if it installed correctly."
+
+## What Claude does
+
+1. **Connects to the sandbox** via SSH
+2. **Installs the formula** with `brew install`
+3. **Tests the installation** with sample data
+4. **Reports results** including version and functionality
+
+## Example session
+
+```
+You: SSH into [email protected]. Test the 'jq' Homebrew formula -
+ install it, verify it parses JSON correctly, and report the results.
+
+Claude: I'll connect to the sandbox and test the jq formula.
+
+[Runs: ssh [email protected]]
+
+First, let me check if Homebrew is installed:
+
+[Runs: brew --version]
+Homebrew 4.2.0
+
+Now installing jq:
+
+[Runs: brew install jq]
+==> Downloading https://ghcr.io/v2/homebrew/core/jq/manifests/1.7.1
+==> Fetching jq
+==> Installing jq
+==> Pouring jq--1.7.1.arm64_sonoma.bottle.tar.gz
+/opt/homebrew/Cellar/jq/1.7.1: 19 files, 1.4MB
+
+Verifying the installation:
+
+[Runs: jq --version]
+jq-1.7.1
+
+Testing JSON parsing:
+
+[Runs: echo '{"name": "test", "values": [1, 2, 3]}' | jq '.name']
+"test"
+
+[Runs: echo '{"name": "test", "values": [1, 2, 3]}' | jq '.values | add']
+6
+
+Testing with a more complex query:
+
+[Runs: curl -s https://api.github.com/repos/jqlang/jq | jq '{name, stars: .stargazers_count, language}']
+{
+ "name": "jq",
+ "stars": 28534,
+ "language": "C"
+}
+
+Test Results:
+- Installation: Success
+- Version: jq-1.7.1
+- Basic parsing: Working
+- Array operations: Working
+- API response parsing: Working
+
+The jq formula installed correctly and all functionality tests passed.
+```
+
+## Resetting for the next test
+
+After testing, reset the sandbox to the clean state:
+
+```bash
+# Stop and delete the modified sandbox
+lume stop sandbox
+lume delete sandbox
+
+# Restore from golden image
+lume clone sandbox-golden sandbox
+
+# Start fresh for the next test
+lume run sandbox --no-display --shared-dir ~/my-project
+```
+
+Or automate it in a script:
+
+```bash
+#!/bin/bash
+# reset-sandbox.sh
+
+VM_NAME="sandbox"
+GOLDEN_IMAGE="sandbox-golden"
+
+lume stop $VM_NAME 2>/dev/null
+lume delete $VM_NAME 2>/dev/null
+lume clone $GOLDEN_IMAGE $VM_NAME
+lume run $VM_NAME --no-display
+
+echo "Sandbox reset complete"
+```
+
+## Testing your own formula
+
+If you're developing a Homebrew formula:
+
+```
+You: SSH into the sandbox. Install my formula from ./my-formula.rb in the shared folder
+ and verify it works.
+
+Claude: I'll test your local formula.
+
+[Runs: ssh [email protected]]
+[Runs: cd /Volumes/My\ Shared\ Files]
+[Runs: brew install --formula ./my-formula.rb]
+
+# Claude tests the installed tool and reports any issues
+```
+
+## Common testing scenarios
+
+### Test a formula with dependencies
+
+```
+You: Install 'ffmpeg' and verify video conversion works.
+```
+
+Claude will install ffmpeg with all its dependencies and test encoding.
+
+### Test formula upgrades
+
+```
+You: The sandbox has jq 1.6. Upgrade to 1.7 and verify nothing breaks.
+```
+
+### Test conflicting packages
+
+```
+You: Try installing both '[email protected]' and '[email protected]', then test importing
+ packages in each version.
+```
+
+### Verify formula uninstallation
+
+```
+You: Install jq, uninstall it, and verify it's completely removed with no leftover files.
+```
+
+## Why this matters
+
+| Testing Approach | Clean Environment | Isolated | Resettable |
+|-----------------|-------------------|----------|------------|
+| Host machine | No | No | No |
+| Docker | Yes | Yes | Yes (but no macOS) |
+| **macOS VM** | **Yes** | **Yes** | **Yes** |
+
+Homebrew is macOS-specific. Testing Homebrew formulas requires macOS, and testing them properly requires isolation.
+
+## Next steps
+
+- [Sandbox Setup](/lume/examples/claude-code/sandbox) — Initial VM configuration
+- [Claude Cowork with MCP](/lume/examples/claude-cowork/sandbox) — Use MCP for native VM integration
+- [Unattended Setup](/lume/guide/fundamentals/unattended-setup) — Pre-configure VMs with Homebrew
diff --git a/docs/content/docs/lume/examples/claude-code/meta.json b/docs/content/docs/lume/examples/claude-code/meta.json
new file mode 100644
index 0000000000..0dadc14830
--- /dev/null
+++ b/docs/content/docs/lume/examples/claude-code/meta.json
@@ -0,0 +1,6 @@
+{
+ "title": "Claude Code",
+ "description": "Run Claude Code CLI in isolated macOS VM sandboxes",
+ "icon": "Terminal",
+ "pages": ["sandbox", "homebrew-testing"]
+}
diff --git a/docs/content/docs/lume/examples/claude-cowork-sandbox.mdx b/docs/content/docs/lume/examples/claude-code/sandbox.mdx
similarity index 87%
rename from docs/content/docs/lume/examples/claude-cowork-sandbox.mdx
rename to docs/content/docs/lume/examples/claude-code/sandbox.mdx
index 6f4b0a5301..ae6b4a324f 100644
--- a/docs/content/docs/lume/examples/claude-cowork-sandbox.mdx
+++ b/docs/content/docs/lume/examples/claude-code/sandbox.mdx
@@ -1,11 +1,11 @@
---
-title: Claude Code in a macOS Sandbox
-description: Run Claude Code safely in an isolated macOS VM
+title: Sandbox Setup
+description: Run Claude Code CLI safely in an isolated macOS VM
---
import { Callout } from 'fumadocs-ui/components/callout';
-[Claude Cowork](https://www.anthropic.com/news/cowork) uses Apple's Virtualization Framework to run AI agents in an isolated sandbox. You can build the same setup with Lume—run [Claude Code](https://claude.ai/code) on your host while it executes commands inside a sandboxed macOS VM.
+Run [Claude Code](https://docs.anthropic.com/en/docs/claude-code) on your host while it executes commands inside a sandboxed macOS VM via SSH. No MCP required—just the `lume` CLI and SSH.
## Why sandbox Claude Code?
@@ -15,7 +15,7 @@ Claude Code is powerful—it can read files, run commands, install packages, and
- **Isolate risky operations** — Test destructive commands, untrusted code, or experimental changes
- **Reset instantly** — Clone a fresh VM to undo everything Claude did
-## What we're building
+## Architecture
```
┌─────────────────────────────────────────────────────┐
@@ -73,7 +73,7 @@ curl -fsSL https://claude.ai/install.sh | bash
brew install --cask claude-code
```
-See [Claude Code docs](https://code.claude.com/docs) for other installation methods.
+See [Claude Code docs](https://docs.anthropic.com/en/docs/claude-code) for other installation methods.
## Step 5: Use Claude Code with the sandbox
@@ -175,7 +175,7 @@ But it can:
## Next steps
+- [Homebrew Testing](/lume/examples/claude-code/homebrew-testing) — Test packages in a clean environment
+- [Claude Cowork with MCP](/lume/examples/claude-cowork/sandbox) — Use MCP for native VM integration
- [Unattended Setup](/lume/guide/fundamentals/unattended-setup) — Customize the VM configuration
-- [HTTP API](/lume/guide/advanced/http-server) — Automate VM control programmatically
-- [Lumier](/lume/guide/advanced/lumier) — Docker-based ephemeral VMs that reset automatically
-- [Claude Code docs](https://code.claude.com/docs) — Learn more about Claude Code's capabilities
+- [Claude Code docs](https://docs.anthropic.com/en/docs/claude-code) — Learn more about Claude Code's capabilities
diff --git a/docs/content/docs/lume/examples/claude-cowork/meta.json b/docs/content/docs/lume/examples/claude-cowork/meta.json
new file mode 100644
index 0000000000..0ca5bbfc74
--- /dev/null
+++ b/docs/content/docs/lume/examples/claude-cowork/meta.json
@@ -0,0 +1,6 @@
+{
+ "title": "Claude Cowork",
+ "description": "Use Claude Cowork with Lume MCP connector",
+ "icon": "Bot",
+ "pages": ["sandbox", "numbers-stock-analysis"]
+}
diff --git a/docs/content/docs/lume/examples/claude-cowork/numbers-stock-analysis.mdx b/docs/content/docs/lume/examples/claude-cowork/numbers-stock-analysis.mdx
new file mode 100644
index 0000000000..4e12530da5
--- /dev/null
+++ b/docs/content/docs/lume/examples/claude-cowork/numbers-stock-analysis.mdx
@@ -0,0 +1,174 @@
+---
+title: Stock Analysis with Numbers
+description: Create financial reports using macOS-only Numbers.app via MCP
+---
+
+import { Callout } from 'fumadocs-ui/components/callout';
+
+This example demonstrates a task that **requires macOS**: creating a stock analysis report using Apple's Numbers spreadsheet app. Numbers is only available on macOS—this workflow wouldn't work in Docker or a Linux VM.
+
+Using the Lume MCP connector, Claude Cowork can execute commands in the VM without manual SSH setup.
+
+## Why macOS?
+
+Numbers.app is Apple's spreadsheet application, comparable to Excel but with tighter macOS integration. It's perfect for:
+
+- Financial reports with charts
+- Data visualization
+- PDF export for sharing
+
+Since Numbers only runs on macOS, this task showcases the unique value of macOS VM sandboxes.
+
+## Prerequisites
+
+- [Lume MCP connector configured](/lume/examples/claude-cowork/sandbox)
+- Sandbox VM created with `--unattended tahoe`
+
+## Example prompt
+
+Ask Cowork:
+
+> "Start the sandbox VM with ~/reports shared. Fetch Apple (AAPL) stock prices for the last 30 days, create a spreadsheet in Numbers with the data and a line chart, then export it as a PDF to the shared folder."
+
+## What Cowork does
+
+1. **Starts the VM** via `lume_run_vm` with shared directory
+2. **Fetches stock data** via `lume_exec` using curl or Python
+3. **Creates a Numbers spreadsheet** via `lume_exec` with AppleScript
+4. **Exports to PDF** at `/Volumes/My Shared Files/aapl-analysis.pdf`
+
+## Example session
+
+```
+You: Start the sandbox with ~/reports shared, then create a stock analysis
+ report for AAPL in Numbers and export it as PDF.
+
+Cowork: I'll start the sandbox and create the stock analysis report.
+
+[Calls lume_run_vm with name="sandbox", shared_dir="~/reports", no_display=true]
+VM 'sandbox' started successfully.
+
+[Calls lume_exec with name="sandbox", command="python3 << 'EOF'
+import urllib.request
+import json
+import csv
+
+# Fetch stock data from a free API
+url = \"https://query1.finance.yahoo.com/v8/finance/chart/AAPL?interval=1d&range=1mo\"
+req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
+data = json.loads(urllib.request.urlopen(req).read())
+
+# Extract timestamps and prices
+timestamps = data['chart']['result'][0]['timestamp']
+closes = data['chart']['result'][0]['indicators']['quote'][0]['close']
+
+# Write to CSV
+with open('/tmp/aapl_data.csv', 'w', newline='') as f:
+ writer = csv.writer(f)
+ writer.writerow(['Date', 'Close'])
+ for ts, close in zip(timestamps, closes):
+ from datetime import datetime
+ date = datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
+ writer.writerow([date, f'{close:.2f}'])
+
+print('Data saved to /tmp/aapl_data.csv')
+EOF"]
+Data saved to /tmp/aapl_data.csv
+
+Now I'll create a Numbers spreadsheet using AppleScript:
+
+[Calls lume_exec with name="sandbox", command="osascript << 'EOF'
+tell application \"Numbers\"
+ activate
+ set newDoc to make new document
+ tell table 1 of sheet 1 of newDoc
+ set csvData to read POSIX file \"/tmp/aapl_data.csv\"
+ set csvLines to paragraphs of csvData
+ repeat with i from 1 to count of csvLines
+ set csvLine to item i of csvLines
+ set AppleScript's text item delimiters to \",\"
+ set parts to text items of csvLine
+ set AppleScript's text item delimiters to \"\"
+ set value of cell 1 of row i to item 1 of parts
+ set value of cell 2 of row i to item 2 of parts
+ end repeat
+ end tell
+ tell sheet 1 of newDoc
+ set newChart to make new chart with properties {chart type:line_2d}
+ end tell
+ export newDoc to POSIX file \"/Volumes/My Shared Files/aapl-analysis.pdf\" as PDF
+ close newDoc saving no
+end tell
+EOF"]
+Success
+
+Done! I've created the stock analysis report. You can find it at:
+~/reports/aapl-analysis.pdf (via the shared folder)
+
+The report contains:
+- 30 days of AAPL closing prices
+- A line chart showing price trends
+- Data table with dates and values
+```
+
+## Key techniques
+
+### Automating Numbers with AppleScript
+
+Numbers can be controlled via AppleScript through `lume_exec`:
+
+```applescript
+tell application "Numbers"
+ -- Create documents
+ set newDoc to make new document
+
+ -- Manipulate cells
+ tell table 1 of sheet 1 of newDoc
+ set value of cell 1 of row 1 to "Hello"
+ end tell
+
+ -- Add charts
+ make new chart with properties {chart type:line_2d}
+
+ -- Export
+ export newDoc to POSIX file "/path/to/output.pdf" as PDF
+end tell
+```
+
+### Fetching financial data
+
+Many free APIs provide stock data:
+
+```bash
+# Yahoo Finance (unofficial)
+curl "https://query1.finance.yahoo.com/v8/finance/chart/AAPL?interval=1d&range=1mo"
+
+# Alpha Vantage (requires free API key)
+curl "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=AAPL&apikey=YOUR_KEY"
+```
+
+## Variations
+
+Try these related tasks:
+
+- "Create a portfolio tracker comparing AAPL, GOOGL, and MSFT"
+- "Generate a monthly expense report from this CSV in Numbers"
+- "Create a chart in Numbers showing my app's download stats"
+
+## Why this matters
+
+This example shows why macOS sandboxes are valuable:
+
+| Approach | Can use Numbers.app? | Native macOS automation? |
+|----------|---------------------|-------------------------|
+| Docker | No | No |
+| Linux VM | No | No |
+| **macOS VM** | **Yes** | **Yes** |
+
+Tasks requiring Numbers, Keynote, Pages, or other macOS-only apps need a macOS environment. Lume provides that in an isolated sandbox.
+
+## Next steps
+
+- [Sandbox with MCP](/lume/examples/claude-cowork/sandbox) — MCP connector setup
+- [Claude Code Sandbox](/lume/examples/claude-code/sandbox) — SSH-based alternative
+- [Homebrew Testing](/lume/examples/claude-code/homebrew-testing) — Test packages in a clean environment
diff --git a/docs/content/docs/lume/examples/claude-cowork/sandbox.mdx b/docs/content/docs/lume/examples/claude-cowork/sandbox.mdx
new file mode 100644
index 0000000000..37939e6d8c
--- /dev/null
+++ b/docs/content/docs/lume/examples/claude-cowork/sandbox.mdx
@@ -0,0 +1,186 @@
+---
+title: Sandbox with MCP
+description: Use Claude Cowork with Lume MCP connector for VM management
+---
+
+import { Callout } from 'fumadocs-ui/components/callout';
+
+[Claude Cowork](https://www.anthropic.com/news/cowork) can manage macOS VMs natively using Lume's MCP connector. Instead of manually starting VMs and providing SSH credentials, Cowork uses MCP tools to control the full VM lifecycle.
+
+## How it works
+
+```
+┌─────────────────────────────────────────────────────────────────┐
+│ Your Mac (Host) │
+│ │
+│ ┌──────────────────┐ ┌───────────────────────────┐ │
+│ │ Claude Cowork │◄── MCP ──►│ Lume MCP Server │ │
+│ │ (Desktop app) │ (stdio) │ (lume serve --mcp) │ │
+│ └──────────────────┘ └─────────────┬─────────────┘ │
+│ │ │
+│ │ VM Control │
+│ ▼ │
+│ ┌─────────────────────────────────────────────────────────────┐│
+│ │ macOS VM Sandbox ││
+│ │ Cowork can: list, run, stop, clone, delete, exec commands ││
+│ └─────────────────────────────────────────────────────────────┘│
+└─────────────────────────────────────────────────────────────────┘
+```
+
+## Prerequisites
+
+1. **Lume installed** with MCP support
+2. **A sandbox VM** created with `--unattended tahoe`
+3. **sshpass** for command execution: `brew install hudochenkov/sshpass/sshpass`
+
+## Setup
+
+### 1. Configure Claude Desktop
+
+Add the Lume MCP server to your Claude Desktop config:
+
+**`~/Library/Application Support/Claude/claude_desktop_config.json`**
+
+```json
+{
+ "mcpServers": {
+ "lume": {
+ "command": "lume",
+ "args": ["serve", "--mcp"]
+ }
+ }
+}
+```
+
+<Callout type="info">
+If `lume` isn't in your PATH, use the full path: `/Users/yourname/.local/bin/lume`
+</Callout>
+
+### 2. Restart Claude Desktop
+
+After saving the config, restart Claude Desktop. The Lume tools will now be available to Cowork.
+
+### 3. Create a sandbox VM
+
+If you haven't already:
+
+```bash
+lume create sandbox --os macos --ipsw latest --unattended tahoe
+```
+
+## Available MCP tools
+
+| Tool | Description |
+|------|-------------|
+| `lume_list_vms` | List all VMs with status and IP addresses |
+| `lume_get_vm` | Get detailed VM info |
+| `lume_run_vm` | Start a VM with optional shared directory |
+| `lume_stop_vm` | Stop a running VM |
+| `lume_clone_vm` | Clone a VM (for golden images) |
+| `lume_delete_vm` | Delete a VM |
+| `lume_exec` | Execute commands inside the VM |
+
+## Example workflow
+
+Ask Cowork:
+
+> "Start my sandbox VM with ~/project shared, then run the tests in the shared folder."
+
+Cowork will:
+
+```
+[Calls lume_run_vm with name="sandbox", shared_dir="~/project"]
+VM 'sandbox' started successfully.
+
+[Calls lume_exec with name="sandbox", command="cd /Volumes/My\\ Shared\\ Files && npm test"]
+
+> jest
+
+PASS src/app.test.js
+ 42 passing (1.2s)
+
+All tests passed!
+```
+
+## Example session
+
+```
+You: List my VMs and start the sandbox with my project folder shared.
+
+Cowork: I'll check your VMs and start the sandbox.
+
+[Calls lume_list_vms]
+Found 2 VMs:
+- sandbox (stopped)
+- dev-vm (running, IP: 192.168.64.3)
+
+[Calls lume_run_vm with name="sandbox", shared_dir="~/my-project", no_display=true]
+VM 'sandbox' started successfully.
+
+[Calls lume_get_vm with name="sandbox"]
+sandbox:
+ State: running
+ IP: 192.168.64.5
+ SSH: available
+
+The sandbox is now running. Your project files are available at /Volumes/My Shared Files
+inside the VM. What would you like me to do next?
+```
+
+## Resetting the sandbox
+
+Ask Cowork:
+
+> "Reset the sandbox to a clean state using the golden image."
+
+```
+[Calls lume_stop_vm with name="sandbox"]
+VM stopped.
+
+[Calls lume_delete_vm with name="sandbox"]
+VM deleted.
+
+[Calls lume_clone_vm with name="sandbox-golden", new_name="sandbox"]
+VM cloned successfully.
+
+[Calls lume_run_vm with name="sandbox", no_display=true]
+VM 'sandbox' started from clean state.
+```
+
+## Advantages over SSH
+
+| Feature | SSH (Claude Code) | MCP (Claude Cowork) |
+|---------|------------------|---------------------|
+| VM lifecycle | Manual (`lume run/stop`) | Automated via tools |
+| IP lookup | Manual (`lume get`) | Automatic |
+| Credentials | User provides | Configured once |
+| Reset workflow | Script required | Natural language |
+
+With MCP, Cowork can manage the entire VM lifecycle through conversation.
+
+## Troubleshooting
+
+### Cowork doesn't see Lume tools
+
+1. Check `claude_desktop_config.json` syntax
+2. Verify `lume serve --mcp` works: `npx @modelcontextprotocol/inspector lume serve --mcp`
+3. Restart Claude Desktop completely
+
+### lume_exec fails
+
+Ensure sshpass is installed:
+
+```bash
+brew install hudochenkov/sshpass/sshpass
+```
+
+### VM has no IP address
+
+The VM might not be fully booted. Wait a few seconds and try again, or check with `lume get sandbox`.
+
+## Next steps
+
+- [Stock Analysis with Numbers](/lume/examples/claude-cowork/numbers-stock-analysis) — Use macOS-only apps via MCP
+- [MCP Server Reference](/lume/guide/advanced/mcp-server) — Full MCP documentation
+- [Claude Code Sandbox](/lume/examples/claude-code/sandbox) — SSH-based alternative
diff --git a/docs/content/docs/lume/examples/index.mdx b/docs/content/docs/lume/examples/index.mdx
index 1abcf8e7ea..d16ebdfefd 100644
--- a/docs/content/docs/lume/examples/index.mdx
+++ b/docs/content/docs/lume/examples/index.mdx
@@ -4,7 +4,7 @@ description: Step-by-step tutorials and use cases for Lume
---
import { Card, Cards } from 'fumadocs-ui/components/card';
-import { Box, Cloud, Terminal } from 'lucide-react';
+import { Bot, Terminal } from 'lucide-react';
# Examples
@@ -12,18 +12,34 @@ Explore real-world examples and tutorials for using Lume to create and manage ma
<Cards>
<Card
- icon={<Cloud className="w-6 h-6" />}
- href="/lume/examples/claude-cowork-sandbox"
- title="Claude Cowork Sandbox"
- description="Run Claude Code in an isolated macOS VM sandbox"
+ icon={<Terminal className="w-6 h-6" />}
+ href="/lume/examples/claude-code"
+ title="Claude Code"
+ description="Run Claude Code CLI in isolated macOS VMs using SSH"
+ />
+ <Card
+ icon={<Bot className="w-6 h-6" />}
+ href="/lume/examples/claude-cowork"
+ title="Claude Cowork"
+ description="Use Claude Cowork with Lume MCP connector"
/>
</Cards>
## Available Examples
-### Development Environments
+### Claude Code
+
+Run the Claude Code CLI in isolated macOS sandboxes using SSH:
+
+- **[Sandbox Setup](/lume/examples/claude-code/sandbox)** — Create and configure a sandboxed macOS VM
+- **[Homebrew Testing](/lume/examples/claude-code/homebrew-testing)** — Test Homebrew formulas in a clean environment
+
+### Claude Cowork
+
+Use Claude Cowork with the Lume MCP connector for native VM management:
-- **[Claude Cowork Sandbox](/lume/examples/claude-cowork-sandbox)** - Set up a sandboxed macOS environment for running Claude Code safely with full system access
+- **[Sandbox with MCP](/lume/examples/claude-cowork/sandbox)** — Configure the MCP connector for VM lifecycle control
+- **[Stock Analysis with Numbers](/lume/examples/claude-cowork/numbers-stock-analysis)** — Use macOS-only apps like Numbers.app
## Coming Soon
diff --git a/docs/content/docs/lume/examples/meta.json b/docs/content/docs/lume/examples/meta.json
index 2f51d9dd0a..82acebbe70 100644
--- a/docs/content/docs/lume/examples/meta.json
+++ b/docs/content/docs/lume/examples/meta.json
@@ -2,5 +2,5 @@
"title": "Examples",
"description": "Step-by-step tutorials and use cases",
"icon": "Blocks",
- "pages": ["claude-cowork-sandbox"]
+ "pages": ["claude-code", "claude-cowork"]
}
diff --git a/docs/content/docs/lume/guide/advanced/http-server.mdx b/docs/content/docs/lume/guide/advanced/http-server.mdx
index 3d4dad6650..550546ab54 100644
--- a/docs/content/docs/lume/guide/advanced/http-server.mdx
+++ b/docs/content/docs/lume/guide/advanced/http-server.mdx
@@ -49,6 +49,8 @@ curl -X POST http://localhost:7777/lume/vms/my-vm/stop
### Create a VM
+VM creation is asynchronous—returns immediately with 202 Accepted while provisioning runs in the background:
+
```bash
curl -X POST http://localhost:7777/lume/vms \
-H "Content-Type: application/json" \
@@ -57,10 +59,28 @@ curl -X POST http://localhost:7777/lume/vms \
"os": "macOS",
"cpu": 4,
"memory": "8GB",
- "diskSize": "50GB"
+ "diskSize": "50GB",
+ "ipsw": "latest",
+ "unattended": "tahoe"
}'
```
+Response:
+```json
+{
+ "message": "VM creation started",
+ "name": "my-vm",
+ "status": "provisioning"
+}
+```
+
+Poll the list endpoint to check provisioning status:
+
+```bash
+# Check status (will show "provisioning (ipsw_install)" or "provisioning (unattended_setup)")
+curl http://localhost:7777/lume/vms | jq '.[] | select(.name == "my-vm") | .status'
+```
+
### Get VM details
```bash
diff --git a/docs/content/docs/lume/guide/advanced/mcp-server.mdx b/docs/content/docs/lume/guide/advanced/mcp-server.mdx
new file mode 100644
index 0000000000..e543d00530
--- /dev/null
+++ b/docs/content/docs/lume/guide/advanced/mcp-server.mdx
@@ -0,0 +1,263 @@
+---
+title: MCP Server
+description: Integrate Lume with AI agents via Model Context Protocol
+---
+
+import { Callout } from 'fumadocs-ui/components/callout';
+
+Lume supports the [Model Context Protocol (MCP)](https://modelcontextprotocol.io/), allowing AI agents like Claude Desktop and Claude Cowork to manage VMs directly through native tool integration.
+
+```
+┌─────────────────────────────────────────────────────────────────┐
+│ Your Mac (Host) │
+│ │
+│ ┌──────────────────┐ ┌───────────────────────────┐ │
+│ │ Claude Desktop │◄── MCP ──►│ Lume MCP Server │ │
+│ │ or Claude Cowork │ (stdio) │ (lume serve --mcp) │ │
+│ └──────────────────┘ └─────────────┬─────────────┘ │
+│ │ │
+│ │ VM Control │
+│ ▼ │
+│ ┌─────────────────────────────────────────────────────────────┐│
+│ │ macOS VM Sandbox ││
+│ │ Claude can: create, list, run, stop, clone, delete, exec ││
+│ └─────────────────────────────────────────────────────────────┘│
+└─────────────────────────────────────────────────────────────────┘
+```
+
+## Quick setup
+
+### 1. Configure Claude Desktop
+
+Edit `~/Library/Application Support/Claude/claude_desktop_config.json`:
+
+```json
+{
+ "mcpServers": {
+ "lume": {
+ "command": "lume",
+ "args": ["serve", "--mcp"]
+ }
+ }
+}
+```
+
+<Callout type="info">
+If `lume` isn't in your PATH, use the full path: `/Users/yourname/.local/bin/lume`
+</Callout>
+
+### 2. Restart Claude Desktop
+
+Claude will now have access to Lume's VM management tools.
+
+### 3. Try it out
+
+Ask Claude:
+- "List my VMs"
+- "Start the sandbox VM"
+- "Run `ls -la` in the sandbox VM"
+- "Stop the sandbox VM"
+
+## Available tools
+
+| Tool | Description |
+|------|-------------|
+| `lume_create_vm` | Create a new macOS VM (async, returns immediately) |
+| `lume_list_vms` | List all VMs with status, IP addresses, and resource allocation |
+| `lume_get_vm` | Get detailed VM info (IP, VNC URL, SSH availability) |
+| `lume_run_vm` | Start a VM with optional shared directory |
+| `lume_stop_vm` | Stop a running VM gracefully |
+| `lume_clone_vm` | Clone a VM (useful for golden images) |
+| `lume_delete_vm` | Delete a VM and its files |
+| `lume_exec` | Execute commands inside a VM via SSH |
+
+## Creating VMs
+
+The `lume_create_vm` tool creates new macOS VMs asynchronously. Since VM creation takes 15-30 minutes (downloading IPSW, installing macOS, optional unattended setup), the tool returns immediately while provisioning continues in the background.
+
+### Parameters
+
+| Parameter | Required | Default | Description |
+|-----------|----------|---------|-------------|
+| `name` | Yes | - | Name for the new VM |
+| `ipsw` | No | `latest` | IPSW path or "latest" to download |
+| `unattended` | No | - | Preset name (e.g., "tahoe", "sequoia") for automatic setup |
+| `cpu` | No | 4 | Number of CPU cores |
+| `memory` | No | `8GB` | Memory size (e.g., "8GB", "16GB") |
+| `disk_size` | No | `64GB` | Disk size (e.g., "64GB", "128GB") |
+| `storage` | No | - | Storage location name or path |
+
+### Provisioning status
+
+During creation, VMs show a `provisioning` status with the current operation:
+
+```
+NAME STATUS IP
+sandbox provisioning (ipsw_install) -
+dev-vm running 192.168.64.3
+test stopped -
+```
+
+The operation progresses through:
+1. `ipsw_install` — Downloading and installing macOS
+2. `unattended_setup` — Running Setup Assistant automation (if `unattended` specified)
+
+Poll `lume_list_vms` or `lume_get_vm` to monitor progress. Once complete, status changes to `stopped`.
+
+### Example
+
+```
+You: Create a new sandbox VM with unattended setup
+
+Claude: I'll create a new macOS VM with automatic configuration.
+
+[Calls lume_create_vm with name="sandbox", unattended="tahoe"]
+
+VM 'sandbox' creation started. Status: provisioning.
+I'll monitor the progress...
+
+[Calls lume_list_vms periodically]
+Status: provisioning (ipsw_install)...
+Status: provisioning (unattended_setup)...
+Status: stopped
+
+The sandbox VM is ready! Would you like me to start it?
+```
+
+## Command execution
+
+The `lume_exec` tool runs commands inside VMs via SSH. It requires:
+
+1. **SSH enabled** in the VM (automatic with `--unattended tahoe`)
+2. **sshpass installed** on your host for password-based auth
+
+```bash
+# Install sshpass
+brew install hudochenkov/sshpass/sshpass
+```
+
+For VMs created with `--unattended tahoe`:
+- Username: `lume`
+- Password: `lume`
+
+## Example workflow
+
+Here's what an AI agent interaction looks like:
+
+```
+You: Create a sandbox VM and run my tests
+
+Claude: I'll set up a sandbox and run your tests.
+
+[Calls lume_list_vms to check existing VMs]
+
+No sandbox VM exists. I'll create one with unattended setup.
+
+[Calls lume_create_vm with name="sandbox", unattended="tahoe"]
+
+VM creation started. This will take 15-30 minutes.
+I'll monitor the progress and let you know when it's ready.
+
+[Polls lume_list_vms until status changes from "provisioning" to "stopped"]
+
+The sandbox is ready! Now starting it with your project directory shared.
+
+[Calls lume_run_vm with name="sandbox", shared_dir="~/project"]
+[Calls lume_get_vm to get IP address]
+[Calls lume_exec with command="cd /Volumes/My\ Shared\ Files && npm test"]
+
+Tests completed! Here are the results:
+✓ 42 tests passed
+✗ 2 tests failed
+...
+```
+
+## MCP vs HTTP API
+
+| Feature | MCP Server | HTTP Server |
+|---------|-----------|-------------|
+| Command | `lume serve --mcp` | `lume serve` |
+| Transport | stdio (spawned by client) | HTTP (port 7777) |
+| Use case | AI agent integration | Scripts, CI/CD, SDKs |
+| Lifecycle | On-demand, client-managed | Background daemon |
+
+Use MCP for AI agent integration. Use HTTP for programmatic access from scripts and applications.
+
+## Testing with MCP Inspector
+
+Debug your MCP setup with the official inspector:
+
+```bash
+npx @modelcontextprotocol/inspector lume serve --mcp
+```
+
+This opens a web UI where you can:
+- See all available tools
+- Test tool calls interactively
+- Inspect request/response payloads
+
+## Troubleshooting
+
+### Claude doesn't see Lume tools
+
+1. Check the config file path is correct
+2. Verify `lume` is accessible (try running `lume --version`)
+3. Restart Claude Desktop completely (quit and reopen)
+
+### lume_exec fails with "sshpass not found"
+
+Install sshpass:
+
+```bash
+brew install hudochenkov/sshpass/sshpass
+```
+
+### lume_exec fails with "no IP address"
+
+The VM might not be running or hasn't acquired an IP yet:
+
+```bash
+# Check VM status
+lume ls
+
+# Start the VM if needed
+lume run my-vm --no-display
+
+# Wait a few seconds for IP assignment
+lume get my-vm
+```
+
+### SSH connection refused
+
+Ensure SSH is enabled in the VM. For existing VMs:
+
+```bash
+# Connect via VNC and enable in System Settings > Sharing > Remote Login
+# Or if you can SSH with a different method:
+ssh lume@<ip> "sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist"
+```
+
+New VMs created with `--unattended tahoe` have SSH enabled automatically.
+
+## Security considerations
+
+<Callout type="warn">
+The MCP server gives AI agents direct control over your VMs. Only use it with trusted AI applications.
+</Callout>
+
+The MCP server:
+- Runs locally (stdio transport, no network exposure)
+- Has full access to VM lifecycle operations
+- Can execute commands inside VMs with SSH access
+
+Consider:
+- Using dedicated sandbox VMs for AI agent tasks
+- Cloning VMs before letting agents modify them
+- Reviewing agent actions in Claude's interface
+
+## Related
+
+- [Claude Cowork Sandbox](/lume/examples/claude-cowork/sandbox) — MCP-based sandbox workflow
+- [Claude Code Sandbox](/lume/examples/claude-code/sandbox) — SSH-based sandbox setup
+- [HTTP Server](/lume/guide/advanced/http-server) — REST API for scripts and CI/CD
+- [Unattended Setup](/lume/guide/fundamentals/unattended-setup) — Automated VM configuration
diff --git a/docs/content/docs/lume/guide/advanced/meta.json b/docs/content/docs/lume/guide/advanced/meta.json
index d52c8f4790..972a1fd56e 100644
--- a/docs/content/docs/lume/guide/advanced/meta.json
+++ b/docs/content/docs/lume/guide/advanced/meta.json
@@ -2,5 +2,5 @@
"title": "Advanced",
"description": "Advanced features and automation",
"icon": "Wrench",
- "pages": ["http-server", "lumier"]
+ "pages": ["http-server", "mcp-server", "lumier"]
}
diff --git a/docs/content/docs/lume/guide/fundamentals/vm-management.mdx b/docs/content/docs/lume/guide/fundamentals/vm-management.mdx
index 6334f3d13b..1110a81465 100644
--- a/docs/content/docs/lume/guide/fundamentals/vm-management.mdx
+++ b/docs/content/docs/lume/guide/fundamentals/vm-management.mdx
@@ -165,14 +165,16 @@ lume config storage remove old-location
### Use storage in commands
-Most commands accept `--storage` to target a specific location:
+Most commands accept `--storage` to target a specific location. You can use either a **named location** or a **direct path**:
```bash
-# Create in specific storage
+# Use a named storage location
lume create my-vm --os macos --ipsw latest --storage external-ssd
-
-# Run from specific storage
lume run my-vm --storage external-ssd
+
+# Or use a direct path
+lume create my-vm --os macos --ipsw latest --storage /Volumes/MySSD/vms
+lume run my-vm --storage /Volumes/MySSD/vms/my-vm
```
Without `--storage`, Lume uses the default location or searches all locations.
diff --git a/docs/content/docs/lume/guide/getting-started/faq.mdx b/docs/content/docs/lume/guide/getting-started/faq.mdx
index 1fb8fd4240..64580d8213 100644
--- a/docs/content/docs/lume/guide/getting-started/faq.mdx
+++ b/docs/content/docs/lume/guide/getting-started/faq.mdx
@@ -92,6 +92,12 @@ Apple's macOS Software License Agreement (section 2.B.iii) limits you to **2 con
Linux VMs have no such limitation. You can run as many as your hardware supports.
+### Can I run VMs inside a VM (nested virtualization)?
+
+**macOS VMs**: No. Apple's Virtualization Framework doesn't support nested virtualization for macOS guests. If you try to run `lume create` inside a macOS VM, you'll get "Virtualization is not available on this hardware."
+
+**Linux VMs**: Yes, on macOS 15+. Linux guests can run VMs inside them using KVM or other hypervisors. This is useful for testing Kubernetes, Docker, or other virtualization workloads.
+
## Images
### How do I get the latest macOS IPSW URL?
@@ -129,6 +135,21 @@ lume run linux-vm --mount /path/to/ubuntu.iso
lume run linux-vm
```
+## VM Status
+
+### What do the different VM statuses mean?
+
+Check VM status with `lume ls`:
+
+| Status | Description |
+|--------|-------------|
+| `stopped` | VM is not running and ready to start |
+| `running` | VM is running |
+| `provisioning (ipsw_install)` | VM is being created—downloading and installing macOS |
+| `provisioning (unattended_setup)` | VM is being created—running automated Setup Assistant |
+
+VMs in `provisioning` status are being created asynchronously. Wait for status to change to `stopped` before starting them.
+
## Troubleshooting
### VM won't start
@@ -136,7 +157,8 @@ lume run linux-vm
1. Check if another VM is running: `lume ls`
2. Stop any running VMs: `lume stop <name>`
3. Check available disk space
-4. Try running with `--no-display` to see if it's a VNC issue
+4. If VM shows `provisioning`, wait for creation to complete
+5. Try running with `--no-display` to see if it's a VNC issue
### Can't connect to VM via SSH
diff --git a/docs/content/docs/lume/guide/getting-started/quickstart.mdx b/docs/content/docs/lume/guide/getting-started/quickstart.mdx
index c3d7f52637..7d583ee14b 100644
--- a/docs/content/docs/lume/guide/getting-started/quickstart.mdx
+++ b/docs/content/docs/lume/guide/getting-started/quickstart.mdx
@@ -194,3 +194,4 @@ Now that you have a VM running, you can:
- Learn more [VM operations](/lume/guide/fundamentals/vm-management) like modifying resources and managing storage locations
- Set up [automated configuration](/lume/guide/fundamentals/unattended-setup) with custom YAML files
- Integrate with your tools via the [HTTP API](/lume/guide/advanced/http-server)
+- Connect AI agents like Claude Desktop via [MCP](/lume/guide/advanced/mcp-server)
diff --git a/docs/src/middleware.ts b/docs/src/middleware.ts
index 074874baa9..a96448a589 100644
--- a/docs/src/middleware.ts
+++ b/docs/src/middleware.ts
@@ -14,7 +14,7 @@ const redirects: Record<string, string> = {
'/cuabench/reference': '/docs/cuabench/reference/cli-reference',
'/lume': '/docs/lume/guide/getting-started/introduction',
'/lume/guide': '/docs/lume/guide/getting-started/introduction',
- '/lume/examples': '/docs/lume/examples/claude-cowork-sandbox',
+ '/lume/examples': '/docs/lume/examples/claude-code/sandbox',
'/lume/reference': '/docs/lume/reference/cli-reference',
// Legacy redirects for old URLs without /cua prefix
'/guide': '/docs/cua/guide/get-started/what-is-cua',
diff --git a/libs/lume/Package.resolved b/libs/lume/Package.resolved
index bc561a9be5..de61d2304e 100644
--- a/libs/lume/Package.resolved
+++ b/libs/lume/Package.resolved
@@ -1,5 +1,5 @@
{
- "originHash" : "ed46cd7e7ee1e4dbe96119cd4c31378f844f34f7da24d4a76eb473505049f454",
+ "originHash" : "1cb747fbdb02d29b37fa7c39fd36b4176166b95adbd4c2b0a4475a21cdcf9c19",
"pins" : [
{
"identity" : "dynamic",
@@ -10,6 +10,15 @@
"revision" : "772883073d044bc754d401cabb6574624eb3778f"
}
},
+ {
+ "identity" : "eventsource",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/mattt/eventsource.git",
+ "state" : {
+ "revision" : "ca2a9d90cbe49e09b92f4b6ebd922c03ebea51d0",
+ "version" : "1.3.0"
+ }
+ },
{
"identity" : "swift-argument-parser",
"kind" : "remoteSourceControl",
@@ -46,6 +55,15 @@
"revision" : "3191b8f3109730af449c6332d0b1ca6653b857a0"
}
},
+ {
+ "identity" : "swift-log",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/apple/swift-log.git",
+ "state" : {
+ "revision" : "7ee16e465622412764b0ff0c1301801dc71b8f61",
+ "version" : "1.9.0"
+ }
+ },
{
"identity" : "swift-markdown",
"kind" : "remoteSourceControl",
@@ -55,6 +73,15 @@
"version" : "0.5.0"
}
},
+ {
+ "identity" : "swift-sdk",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/modelcontextprotocol/swift-sdk.git",
+ "state" : {
+ "revision" : "c0407a0b52677cb395d824cac2879b963075ba8c",
+ "version" : "0.10.2"
+ }
+ },
{
"identity" : "swift-syntax",
"kind" : "remoteSourceControl",
@@ -64,6 +91,15 @@
"revision" : "cdd571f366a4298bb863a9dcfe1295bb595041d5"
}
},
+ {
+ "identity" : "swift-system",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/apple/swift-system.git",
+ "state" : {
+ "revision" : "7c6ad0fc39d0763e0b699210e4124afd5041c5df",
+ "version" : "1.6.4"
+ }
+ },
{
"identity" : "yams",
"kind" : "remoteSourceControl",
diff --git a/libs/lume/Package.swift b/libs/lume/Package.swift
index 0dc1323ed4..ab20cec45e 100644
--- a/libs/lume/Package.swift
+++ b/libs/lume/Package.swift
@@ -13,7 +13,8 @@ let package = Package(
.package(url: "https://github.com/apple/swift-format.git", branch: ("release/5.10")),
.package(url: "https://github.com/apple/swift-atomics.git", .upToNextMajor(from: "1.2.0")),
.package(url: "https://github.com/mhdhejazi/Dynamic", branch: "master"),
- .package(url: "https://github.com/jpsim/Yams.git", from: "5.0.0")
+ .package(url: "https://github.com/jpsim/Yams.git", from: "5.0.0"),
+ .package(url: "https://github.com/modelcontextprotocol/swift-sdk.git", from: "0.10.0")
],
targets: [
// Targets are the basic building blocks of a package, defining a module or a test suite.
@@ -24,7 +25,8 @@ let package = Package(
.product(name: "ArgumentParser", package: "swift-argument-parser"),
.product(name: "Atomics", package: "swift-atomics"),
.product(name: "Dynamic", package: "Dynamic"),
- .product(name: "Yams", package: "Yams")
+ .product(name: "Yams", package: "Yams"),
+ .product(name: "MCP", package: "swift-sdk")
],
path: "src",
resources: [
diff --git a/libs/lume/src/Commands/Serve.swift b/libs/lume/src/Commands/Serve.swift
index 1722413176..3b0324b690 100644
--- a/libs/lume/src/Commands/Serve.swift
+++ b/libs/lume/src/Commands/Serve.swift
@@ -5,42 +5,59 @@ struct Serve: AsyncParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Start the VM management server"
)
-
- @Option(help: "Port to listen on")
+
+ @Option(help: "Port to listen on (HTTP mode only)")
var port: UInt16 = 7777
-
+
+ @Flag(name: .long, help: "Run as MCP server (stdio transport) for AI agent integration")
+ var mcp: Bool = false
+
func run() async throws {
- // Record telemetry
- TelemetryClient.shared.record(event: TelemetryEvent.serve, properties: [
- "port": port
- ])
-
- let server = await Server(port: port)
-
- Logger.info("Starting server", metadata: ["port": "\(port)"])
-
- // Using custom error handling to prevent ArgumentParser from printing additional error messages
- do {
- try await server.start()
- } catch let error as PortError {
- // For port errors, just log once with the suggestion
- let suggestedPort = port + 1
-
- // Create a user-friendly error message that includes the suggestion
- let message = """
- \(error.localizedDescription)
- Try using a different port: lume serve --port \(suggestedPort)
- """
-
- // Log the message (without the "ERROR:" prefix that ArgumentParser will add)
- Logger.error(message)
-
- // Exit with a custom code to prevent ArgumentParser from printing the error again
- Foundation.exit(1)
- } catch {
- // For other errors, log once
- Logger.error("Failed to start server", metadata: ["error": error.localizedDescription])
- throw error
+ if mcp {
+ // MCP mode - run as MCP server over stdio
+ TelemetryClient.shared.record(event: TelemetryEvent.serve, properties: [
+ "mode": "mcp"
+ ])
+
+ let controller = LumeController()
+ let mcpServer = await LumeMCPServer(controller: controller)
+
+ // Note: Don't log to stdout in MCP mode as it interferes with the protocol
+ try await mcpServer.start()
+ } else {
+ // HTTP mode - run as HTTP server
+ TelemetryClient.shared.record(event: TelemetryEvent.serve, properties: [
+ "port": port,
+ "mode": "http"
+ ])
+
+ let server = await Server(port: port)
+
+ Logger.info("Starting server", metadata: ["port": "\(port)"])
+
+ // Using custom error handling to prevent ArgumentParser from printing additional error messages
+ do {
+ try await server.start()
+ } catch let error as PortError {
+ // For port errors, just log once with the suggestion
+ let suggestedPort = port + 1
+
+ // Create a user-friendly error message that includes the suggestion
+ let message = """
+ \(error.localizedDescription)
+ Try using a different port: lume serve --port \(suggestedPort)
+ """
+
+ // Log the message (without the "ERROR:" prefix that ArgumentParser will add)
+ Logger.error(message)
+
+ // Exit with a custom code to prevent ArgumentParser from printing the error again
+ Foundation.exit(1)
+ } catch {
+ // For other errors, log once
+ Logger.error("Failed to start server", metadata: ["error": error.localizedDescription])
+ throw error
+ }
}
}
}
\ No newline at end of file
diff --git a/libs/lume/src/FileSystem/VMDirectory.swift b/libs/lume/src/FileSystem/VMDirectory.swift
index 9a324f95a5..a207575fdf 100644
--- a/libs/lume/src/FileSystem/VMDirectory.swift
+++ b/libs/lume/src/FileSystem/VMDirectory.swift
@@ -16,6 +16,7 @@ struct VMDirectory: Sendable {
static let disk = "disk.img"
static let config = "config.json"
static let sessions = "sessions.json"
+ static let provisioning = ".provisioning"
}
// MARK: - Properties
@@ -25,6 +26,7 @@ struct VMDirectory: Sendable {
let diskPath: Path
let configPath: Path
let sessionsPath: Path
+ let provisioningPath: Path
/// The name of the VM directory
var name: String { dir.name }
@@ -40,6 +42,7 @@ struct VMDirectory: Sendable {
self.diskPath = dir.file(FileNames.disk)
self.configPath = dir.file(FileNames.config)
self.sessionsPath = dir.file(FileNames.sessions)
+ self.provisioningPath = dir.file(FileNames.provisioning)
}
}
@@ -189,6 +192,52 @@ extension VMDirectory {
}
}
+// MARK: - Provisioning Marker Management
+
+/// Represents the provisioning state of a VM during long-running operations
+struct ProvisioningMarker: Codable {
+ /// The type of operation being performed (e.g., "ipsw_install", "unattended_setup")
+ let operation: String
+}
+
+extension VMDirectory {
+ /// Saves a provisioning marker to indicate the VM is being created/configured
+ /// - Parameter marker: The provisioning marker containing operation type
+ /// - Throws: VMDirectoryError if the save operation fails
+ func saveProvisioningMarker(_ marker: ProvisioningMarker) throws {
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = .prettyPrinted
+
+ do {
+ let data = try encoder.encode(marker)
+ guard FileManager.default.createFile(atPath: provisioningPath.path, contents: data) else {
+ throw VMDirectoryError.fileCreationFailed(provisioningPath.path)
+ }
+ } catch {
+ throw VMDirectoryError.fileCreationFailed(provisioningPath.path)
+ }
+ }
+
+ /// Loads the provisioning marker if it exists
+ /// - Returns: The provisioning marker, or nil if not in provisioning state
+ func loadProvisioningMarker() -> ProvisioningMarker? {
+ guard let data = FileManager.default.contents(atPath: provisioningPath.path) else {
+ return nil
+ }
+ return try? JSONDecoder().decode(ProvisioningMarker.self, from: data)
+ }
+
+ /// Removes the provisioning marker after creation completes
+ func clearProvisioningMarker() {
+ try? FileManager.default.removeItem(atPath: provisioningPath.path)
+ }
+
+ /// Checks if the VM is currently being provisioned
+ func isProvisioning() -> Bool {
+ provisioningPath.exists()
+ }
+}
+
// MARK: - CustomStringConvertible
extension VMDirectory: CustomStringConvertible {
var description: String {
@@ -237,14 +286,16 @@ extension VMDirectory {
///
/// - Parameters:
/// - locationName: The storage location name for this VM
- /// - isRunning: Whether the VM is currently running
+ /// - status: The VM status ("running", "stopped", or "provisioning")
+ /// - provisioningOperation: Optional operation type if status is "provisioning"
/// - vncUrl: Optional VNC URL if running
/// - ipAddress: Optional IP address if running
/// - sshAvailable: Optional SSH availability status
/// - Returns: VMDetails or nil if config cannot be loaded
func getDetails(
locationName: String,
- isRunning: Bool,
+ status: String,
+ provisioningOperation: String? = nil,
vncUrl: String?,
ipAddress: String?,
sshAvailable: Bool? = nil
@@ -260,7 +311,8 @@ extension VMDirectory {
memorySize: config.memorySize ?? 0,
diskSize: getDiskSize(),
display: config.display.string,
- status: isRunning ? "running" : "stopped",
+ status: status,
+ provisioningOperation: provisioningOperation,
vncUrl: vncUrl,
ipAddress: ipAddress,
sshAvailable: sshAvailable,
diff --git a/libs/lume/src/LumeController.swift b/libs/lume/src/LumeController.swift
index 5c10824a75..9aa14c90cf 100644
--- a/libs/lume/src/LumeController.swift
+++ b/libs/lume/src/LumeController.swift
@@ -116,11 +116,23 @@ final class LumeController {
}
/// Get VM details using lightweight path (no VM object instantiation)
- /// Checks SharedVM cache for running status and gets VNC/IP info if running
+ /// Checks provisioning marker first, then SharedVM cache for running status
@MainActor
private func getVMDetailsLightweight(vmDir: VMDirectory, locationName: String) -> VMDetails? {
let vmName = vmDir.name
+ // Check provisioning marker FIRST - if present, VM is being created
+ if let marker = vmDir.loadProvisioningMarker() {
+ return vmDir.getDetails(
+ locationName: locationName,
+ status: "provisioning",
+ provisioningOperation: marker.operation,
+ vncUrl: nil,
+ ipAddress: nil,
+ sshAvailable: nil
+ )
+ }
+
// Check if VM is running via SharedVM cache (same-process fast path)
let runningVM = SharedVM.shared.getVM(name: vmName)
var isRunning = runningVM != nil
@@ -159,7 +171,8 @@ final class LumeController {
return vmDir.getDetails(
locationName: locationName,
- isRunning: isRunning,
+ status: isRunning ? "running" : "stopped",
+ provisioningOperation: nil,
vncUrl: vncUrl,
ipAddress: ipAddress,
sshAvailable: sshAvailable
@@ -388,6 +401,239 @@ final class LumeController {
}
}
+ /// Creates a VM asynchronously, returning immediately while the VM is being provisioned.
+ /// The VM will appear with status "provisioning" in `lume ls` until creation completes.
+ /// Poll VM status to check progress.
+ ///
+ /// - Parameters:
+ /// - name: Name for the new VM
+ /// - os: Operating system type ("macos" or "linux")
+ /// - diskSize: Disk size in bytes
+ /// - cpuCount: Number of CPU cores
+ /// - memorySize: Memory size in bytes
+ /// - display: Display resolution string (e.g., "1920x1080")
+ /// - ipsw: Path to IPSW file or "latest" for macOS
+ /// - storage: Optional storage location name or path
+ /// - unattendedConfig: Optional unattended setup configuration
+ @MainActor
+ public func createAsync(
+ name: String,
+ os: String,
+ diskSize: UInt64,
+ cpuCount: Int,
+ memorySize: UInt64,
+ display: String,
+ ipsw: String?,
+ storage: String? = nil,
+ unattendedConfig: UnattendedConfig? = nil
+ ) throws {
+ Logger.info(
+ "Starting async VM creation",
+ metadata: [
+ "name": name,
+ "os": os,
+ "location": storage ?? "default",
+ "unattended": unattendedConfig != nil ? "yes" : "no",
+ ])
+
+ // Validate parameters upfront (this checks VM doesn't already exist)
+ try validateCreateParameters(name: name, os: os, ipsw: ipsw, storage: storage)
+
+ Logger.info("Spawning background task for VM creation", metadata: ["name": name])
+
+ // All parameters passed to Task are value types (Sendable)
+ // The Task will create its own LumeController instance
+ Task.detached { @MainActor @Sendable in
+ // Create a new controller for the background task
+ let controller = LumeController()
+
+ // Get the VM directory
+ let vmDir: VMDirectory
+ do {
+ vmDir = try controller.home.getVMDirectory(name, storage: storage)
+ } catch {
+ Logger.error("Failed to get VM directory",
+ metadata: ["name": name, "error": error.localizedDescription])
+ return
+ }
+
+ // Create the VM directory and write provisioning marker first
+ // so VM appears in list immediately
+ do {
+ try FileManager.default.createDirectory(
+ atPath: vmDir.dir.path,
+ withIntermediateDirectories: true
+ )
+
+ // Create minimal config so VM shows up in list
+ let config = try VMConfig(
+ os: os,
+ cpuCount: cpuCount,
+ memorySize: memorySize,
+ diskSize: diskSize,
+ display: display
+ )
+ try vmDir.saveConfig(config)
+
+ // Write provisioning marker
+ try vmDir.saveProvisioningMarker(ProvisioningMarker(operation: "ipsw_install"))
+ Logger.info("Provisioning marker created", metadata: ["name": name])
+ } catch {
+ Logger.error("Failed to create provisioning marker",
+ metadata: ["name": name, "error": error.localizedDescription])
+ return
+ }
+
+ do {
+ // Run the internal create which does all the work
+ // (skips validation since we already validated)
+ try await controller.createInternal(
+ name: name,
+ os: os,
+ diskSize: diskSize,
+ cpuCount: cpuCount,
+ memorySize: memorySize,
+ display: display,
+ ipsw: ipsw,
+ storage: storage,
+ unattendedConfig: unattendedConfig,
+ vmDir: vmDir
+ )
+
+ // Clear marker on success
+ vmDir.clearProvisioningMarker()
+ Logger.info("Async VM creation completed successfully", metadata: ["name": name])
+
+ } catch {
+ // Clear marker and cleanup on failure
+ vmDir.clearProvisioningMarker()
+ do {
+ try vmDir.delete()
+ } catch let cleanupError {
+ Logger.error("Failed to clean up VM directory after async creation failure",
+ metadata: ["error": cleanupError.localizedDescription])
+ }
+ Logger.error("Async VM creation failed",
+ metadata: ["name": name, "error": error.localizedDescription])
+ }
+ }
+ }
+
+ /// Internal create method that skips validation (used by createAsync)
+ @MainActor
+ private func createInternal(
+ name: String,
+ os: String,
+ diskSize: UInt64,
+ cpuCount: Int,
+ memorySize: UInt64,
+ display: String,
+ ipsw: String?,
+ storage: String? = nil,
+ unattendedConfig: UnattendedConfig? = nil,
+ debug: Bool = false,
+ debugDir: String? = nil,
+ noDisplay: Bool = true,
+ vncPort: Int = 0,
+ vmDir: VMDirectory? = nil
+ ) async throws {
+ Logger.info(
+ "Creating VM (internal)",
+ metadata: [
+ "name": name,
+ "os": os,
+ "location": storage ?? "default",
+ ])
+
+ let vm = try await createTempVMConfig(
+ os: os,
+ cpuCount: cpuCount,
+ memorySize: memorySize,
+ diskSize: diskSize,
+ display: display
+ )
+
+ // Track the temp directory for cleanup on failure
+ let tempVMDir = vm.vmDirContext.dir
+
+ do {
+ try await vm.setup(
+ ipswPath: ipsw ?? "none",
+ cpuCount: cpuCount,
+ memorySize: memorySize,
+ diskSize: diskSize,
+ display: display
+ )
+
+ // If vmDir was pre-created (async flow), we need to handle finalization differently
+ if let existingVmDir = vmDir {
+ // Delete the pre-created directory (with just config and marker)
+ // and let finalize create it fresh with all the VM files
+ try existingVmDir.delete()
+ }
+
+ try vm.finalize(to: name, home: home, storage: storage)
+ } catch {
+ // Clean up the temporary VM directory on setup/finalize failure
+ Logger.info("Cleaning up temporary VM directory after failed creation",
+ metadata: ["path": tempVMDir.dir.path])
+ do {
+ try tempVMDir.delete()
+ } catch let cleanupError {
+ Logger.error("Failed to clean up temporary VM directory",
+ metadata: ["error": cleanupError.localizedDescription])
+ }
+ throw error
+ }
+
+ Logger.info("VM created successfully", metadata: ["name": name])
+
+ // Run unattended setup if config is provided
+ if let config = unattendedConfig, os.lowercased() == "macos" {
+ // Update provisioning marker for unattended phase (only if async flow)
+ if vmDir != nil {
+ // Re-get the vmDir since we deleted and recreated it
+ let updatedVmDir = try home.getVMDirectory(name, storage: storage)
+ try updatedVmDir.saveProvisioningMarker(ProvisioningMarker(operation: "unattended_setup"))
+ }
+
+ // Wait for the installation VZVirtualMachine to fully release auxiliary storage locks.
+ Logger.info("Waiting for installation resources to be released before unattended setup")
+ try await Task.sleep(nanoseconds: 3_000_000_000) // 3 seconds
+ Logger.info("Starting unattended Setup Assistant automation", metadata: ["name": name])
+
+ // Load the finalized VM
+ let finalVM = try get(name: name, storage: storage)
+
+ // Run the unattended installer
+ let installer = UnattendedInstaller()
+ do {
+ try await installer.install(
+ vm: finalVM,
+ config: config,
+ vncPort: vncPort,
+ noDisplay: noDisplay,
+ debug: debug,
+ debugDir: debugDir
+ )
+ } catch {
+ // Clean up the finalized VM directory on unattended setup failure
+ Logger.info("Cleaning up VM after failed unattended setup",
+ metadata: ["name": name])
+ do {
+ let vmDirToDelete = try home.getVMDirectory(name, storage: storage)
+ try vmDirToDelete.delete()
+ } catch let cleanupError {
+ Logger.error("Failed to clean up VM after unattended setup failure",
+ metadata: ["error": cleanupError.localizedDescription])
+ }
+ throw error
+ }
+
+ Logger.info("Unattended setup completed", metadata: ["name": name])
+ }
+ }
+
/// Run unattended Setup Assistant automation on an existing macOS VM
@MainActor
public func setup(
diff --git a/libs/lume/src/Resources/unattended-presets/sequoia.yml b/libs/lume/src/Resources/unattended-presets/sequoia.yml
index ddfa80cab3..93cfe67e65 100644
--- a/libs/lume/src/Resources/unattended-presets/sequoia.yml
+++ b/libs/lume/src/Resources/unattended-presets/sequoia.yml
@@ -231,7 +231,35 @@ boot_commands:
- "<delay 2>"
# ============================================
- # 3. Enable Full Disk Access for Remote Users
+ # 3. Disable Screen Lock and Sleep
+ # ============================================
+ # Disable screen saver
+ - "<type 'defaults -currentHost write com.apple.screensaver idleTime -int 0'>"
+ - "<enter>"
+ - "<delay 1>"
+
+ # Disable require password after sleep/screen saver
+ - "<type 'defaults write com.apple.screensaver askForPassword -int 0'>"
+ - "<enter>"
+ - "<delay 1>"
+
+ # Prevent display from sleeping (never)
+ - "<type 'sudo pmset -a displaysleep 0'>"
+ - "<enter>"
+ - "<delay 1>"
+
+ # Prevent system sleep (never)
+ - "<type 'sudo pmset -a sleep 0'>"
+ - "<enter>"
+ - "<delay 1>"
+
+ # Disable auto-logout
+ - "<type 'sudo defaults write /Library/Preferences/.GlobalPreferences com.apple.autologout.AutoLogOutDelay -int 0'>"
+ - "<enter>"
+ - "<delay 1>"
+
+ # ============================================
+ # 4. Enable Full Disk Access for Remote Users
# ============================================
# This requires navigating System Settings GUI since TCC.db is SIP-protected
@@ -275,6 +303,7 @@ boot_commands:
# ============================================
# SSH is now enabled - Connect with: ssh lume@<ip-address> (password: lume)
# Auto-login is enabled - VM will boot directly to desktop
+ # Screen lock and sleep are disabled - VM stays awake and unlocked
# Full disk access for remote users is enabled via TCC database
# Health check to verify setup was successful
diff --git a/libs/lume/src/Resources/unattended-presets/tahoe.yml b/libs/lume/src/Resources/unattended-presets/tahoe.yml
index 4e5fd80966..6f88a4caa7 100644
--- a/libs/lume/src/Resources/unattended-presets/tahoe.yml
+++ b/libs/lume/src/Resources/unattended-presets/tahoe.yml
@@ -261,7 +261,35 @@ boot_commands:
- "<delay 2>"
# ============================================
- # 3. Enable Full Disk Access for Remote Users
+ # 3. Disable Screen Lock and Sleep
+ # ============================================
+ # Disable screen saver
+ - "<type 'defaults -currentHost write com.apple.screensaver idleTime -int 0'>"
+ - "<enter>"
+ - "<delay 1>"
+
+ # Disable require password after sleep/screen saver
+ - "<type 'defaults write com.apple.screensaver askForPassword -int 0'>"
+ - "<enter>"
+ - "<delay 1>"
+
+ # Prevent display from sleeping (never)
+ - "<type 'sudo pmset -a displaysleep 0'>"
+ - "<enter>"
+ - "<delay 1>"
+
+ # Prevent system sleep (never)
+ - "<type 'sudo pmset -a sleep 0'>"
+ - "<enter>"
+ - "<delay 1>"
+
+ # Disable auto-logout
+ - "<type 'sudo defaults write /Library/Preferences/.GlobalPreferences com.apple.autologout.AutoLogOutDelay -int 0'>"
+ - "<enter>"
+ - "<delay 1>"
+
+ # ============================================
+ # 4. Enable Full Disk Access for Remote Users
# ============================================
# This requires navigating System Settings GUI since TCC.db is SIP-protected
@@ -305,6 +333,7 @@ boot_commands:
# ============================================
# SSH is now enabled - Connect with: ssh lume@<ip-address> (password: lume)
# Auto-login is enabled - VM will boot directly to desktop
+ # Screen lock and sleep are disabled - VM stays awake and unlocked
# Full disk access for remote users is enabled via TCC database
# Health check to verify setup was successful
diff --git a/libs/lume/src/Server/Handlers.swift b/libs/lume/src/Server/Handlers.swift
index 8854afd1c2..1a5e7f47da 100644
--- a/libs/lume/src/Server/Handlers.swift
+++ b/libs/lume/src/Server/Handlers.swift
@@ -93,7 +93,15 @@ extension Server {
do {
let sizes = try request.parse()
let vmController = LumeController()
- try await vmController.create(
+
+ // Load unattended config if specified
+ var unattendedConfig: UnattendedConfig? = nil
+ if let unattendedArg = request.unattended {
+ unattendedConfig = try UnattendedConfig.load(from: unattendedArg)
+ }
+
+ // Use async create - returns immediately while VM is provisioned in background
+ try vmController.createAsync(
name: request.name,
os: request.os,
diskSize: sizes.diskSize,
@@ -101,14 +109,18 @@ extension Server {
memorySize: sizes.memory,
display: request.display,
ipsw: request.ipsw,
- storage: request.storage
+ storage: request.storage,
+ unattendedConfig: unattendedConfig
)
+ // Return 202 Accepted - VM creation is in progress
return HTTPResponse(
- statusCode: .ok,
+ statusCode: .accepted,
headers: ["Content-Type": "application/json"],
body: try JSONEncoder().encode([
- "message": "VM created successfully", "name": request.name,
+ "message": "VM creation started",
+ "name": request.name,
+ "status": "provisioning",
])
)
} catch {
diff --git a/libs/lume/src/Server/MCPServer.swift b/libs/lume/src/Server/MCPServer.swift
new file mode 100644
index 0000000000..5dbeaf9fcc
--- /dev/null
+++ b/libs/lume/src/Server/MCPServer.swift
@@ -0,0 +1,534 @@
+import Foundation
+import MCP
+
+/// MCP (Model Context Protocol) server for Lume VM management
+/// Allows AI agents like Claude to manage VMs through MCP tools
+@MainActor
+final class LumeMCPServer {
+ private let controller: LumeController
+ private var mcpServer: MCP.Server?
+
+ init(controller: LumeController) {
+ self.controller = controller
+ }
+
+ func start() async throws {
+ mcpServer = MCP.Server(
+ name: "lume",
+ version: "1.0.0",
+ capabilities: .init(tools: .init(listChanged: false))
+ )
+
+ await registerTools()
+
+ let transport = StdioTransport()
+ try await mcpServer?.start(transport: transport)
+ await mcpServer?.waitUntilCompleted()
+ }
+
+ private func registerTools() async {
+ // Register ListTools handler
+ await mcpServer?.withMethodHandler(ListTools.self) { [weak self] _ in
+ guard let self = self else {
+ return ListTools.Result(tools: [])
+ }
+ return await MainActor.run {
+ ListTools.Result(tools: self.toolDefinitions)
+ }
+ }
+
+ // Register CallTool handler
+ await mcpServer?.withMethodHandler(CallTool.self) { [weak self] params in
+ guard let self = self else {
+ return CallTool.Result(content: [.text("Server not available")], isError: true)
+ }
+ return await self.handleToolCall(params)
+ }
+ }
+
+ // MARK: - Tool Definitions
+
+ private var toolDefinitions: [Tool] {
+ [
+ Tool(
+ name: "lume_list_vms",
+ description: "List all virtual machines with their status, IP addresses, and resource allocation",
+ inputSchema: .object([
+ "type": .string("object"),
+ "properties": .object([
+ "storage": .object([
+ "type": .string("string"),
+ "description": .string("Optional storage location name or path to filter VMs")
+ ])
+ ])
+ ])
+ ),
+ Tool(
+ name: "lume_get_vm",
+ description: "Get detailed information about a specific VM including IP address, VNC URL, and SSH availability",
+ inputSchema: .object([
+ "type": .string("object"),
+ "properties": .object([
+ "name": .object([
+ "type": .string("string"),
+ "description": .string("Name of the VM")
+ ]),
+ "storage": .object([
+ "type": .string("string"),
+ "description": .string("Optional storage location name or path")
+ ])
+ ]),
+ "required": .array([.string("name")])
+ ])
+ ),
+ Tool(
+ name: "lume_run_vm",
+ description: "Start a VM with optional shared directory for file access. The shared directory will be available at /Volumes/My Shared Files inside the VM.",
+ inputSchema: .object([
+ "type": .string("object"),
+ "properties": .object([
+ "name": .object([
+ "type": .string("string"),
+ "description": .string("Name of the VM to start")
+ ]),
+ "shared_dir": .object([
+ "type": .string("string"),
+ "description": .string("Host directory path to share with the VM (appears at /Volumes/My Shared Files)")
+ ]),
+ "no_display": .object([
+ "type": .string("boolean"),
+ "description": .string("Run headless without VNC window (default: true)")
+ ]),
+ "storage": .object([
+ "type": .string("string"),
+ "description": .string("Optional storage location name or path")
+ ])
+ ]),
+ "required": .array([.string("name")])
+ ])
+ ),
+ Tool(
+ name: "lume_stop_vm",
+ description: "Stop a running VM gracefully",
+ inputSchema: .object([
+ "type": .string("object"),
+ "properties": .object([
+ "name": .object([
+ "type": .string("string"),
+ "description": .string("Name of the VM to stop")
+ ]),
+ "storage": .object([
+ "type": .string("string"),
+ "description": .string("Optional storage location name or path")
+ ])
+ ]),
+ "required": .array([.string("name")])
+ ])
+ ),
+ Tool(
+ name: "lume_clone_vm",
+ description: "Clone a VM to create a copy. Useful for creating golden images for instant reset.",
+ inputSchema: .object([
+ "type": .string("object"),
+ "properties": .object([
+ "name": .object([
+ "type": .string("string"),
+ "description": .string("Name of the source VM to clone")
+ ]),
+ "new_name": .object([
+ "type": .string("string"),
+ "description": .string("Name for the cloned VM")
+ ])
+ ]),
+ "required": .array([.string("name"), .string("new_name")])
+ ])
+ ),
+ Tool(
+ name: "lume_delete_vm",
+ description: "Delete a VM and all its associated files",
+ inputSchema: .object([
+ "type": .string("object"),
+ "properties": .object([
+ "name": .object([
+ "type": .string("string"),
+ "description": .string("Name of the VM to delete")
+ ]),
+ "storage": .object([
+ "type": .string("string"),
+ "description": .string("Optional storage location name or path")
+ ])
+ ]),
+ "required": .array([.string("name")])
+ ])
+ ),
+ Tool(
+ name: "lume_exec",
+ description: "Execute a command inside a running VM via SSH. Requires SSH to be enabled in the VM (default for VMs created with --unattended tahoe).",
+ inputSchema: .object([
+ "type": .string("object"),
+ "properties": .object([
+ "name": .object([
+ "type": .string("string"),
+ "description": .string("Name of the VM")
+ ]),
+ "command": .object([
+ "type": .string("string"),
+ "description": .string("Shell command to execute inside the VM")
+ ]),
+ "user": .object([
+ "type": .string("string"),
+ "description": .string("SSH username (default: lume)")
+ ]),
+ "password": .object([
+ "type": .string("string"),
+ "description": .string("SSH password (default: lume)")
+ ]),
+ "storage": .object([
+ "type": .string("string"),
+ "description": .string("Optional storage location name or path")
+ ])
+ ]),
+ "required": .array([.string("name"), .string("command")])
+ ])
+ ),
+ Tool(
+ name: "lume_create_vm",
+ description: "Create a new macOS VM asynchronously. Returns immediately while the VM is being provisioned. Poll lume_list_vms or lume_get_vm to check progress (status will be 'provisioning' until complete).",
+ inputSchema: .object([
+ "type": .string("object"),
+ "properties": .object([
+ "name": .object([
+ "type": .string("string"),
+ "description": .string("Name for the new VM")
+ ]),
+ "ipsw": .object([
+ "type": .string("string"),
+ "description": .string("Path to IPSW file or 'latest' to download (default: latest)")
+ ]),
+ "unattended": .object([
+ "type": .string("string"),
+ "description": .string("Unattended setup preset (e.g., 'tahoe', 'sequoia') for automatic macOS configuration")
+ ]),
+ "cpu": .object([
+ "type": .string("integer"),
+ "description": .string("Number of CPU cores (default: 4)")
+ ]),
+ "memory": .object([
+ "type": .string("string"),
+ "description": .string("Memory size, e.g., '8GB' (default: 8GB)")
+ ]),
+ "disk_size": .object([
+ "type": .string("string"),
+ "description": .string("Disk size, e.g., '64GB' (default: 64GB)")
+ ]),
+ "storage": .object([
+ "type": .string("string"),
+ "description": .string("Optional storage location name or path")
+ ])
+ ]),
+ "required": .array([.string("name")])
+ ])
+ )
+ ]
+ }
+
+ // MARK: - Tool Call Handler
+
+ private func handleToolCall(_ params: CallTool.Parameters) async -> CallTool.Result {
+ do {
+ switch params.name {
+ case "lume_list_vms":
+ return try await handleListVMs(params.arguments)
+ case "lume_get_vm":
+ return try await handleGetVM(params.arguments)
+ case "lume_run_vm":
+ return try await handleRunVM(params.arguments)
+ case "lume_stop_vm":
+ return try await handleStopVM(params.arguments)
+ case "lume_clone_vm":
+ return try await handleCloneVM(params.arguments)
+ case "lume_delete_vm":
+ return try await handleDeleteVM(params.arguments)
+ case "lume_exec":
+ return try await handleExec(params.arguments)
+ case "lume_create_vm":
+ return try await handleCreateVM(params.arguments)
+ default:
+ return CallTool.Result(
+ content: [.text("Unknown tool: \(params.name)")],
+ isError: true
+ )
+ }
+ } catch {
+ return CallTool.Result(
+ content: [.text("Error: \(error.localizedDescription)")],
+ isError: true
+ )
+ }
+ }
+
+ // MARK: - Tool Implementations
+
+ private func handleListVMs(_ args: [String: Value]?) async throws -> CallTool.Result {
+ let storage = args?["storage"]?.stringValue
+ let vms = try controller.list(storage: storage)
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ let json = try encoder.encode(vms)
+ return CallTool.Result(content: [.text(String(data: json, encoding: .utf8) ?? "[]")])
+ }
+
+ private func handleGetVM(_ args: [String: Value]?) async throws -> CallTool.Result {
+ guard let name = args?["name"]?.stringValue else {
+ return CallTool.Result(content: [.text("Error: 'name' is required")], isError: true)
+ }
+ let storage = args?["storage"]?.stringValue
+
+ let vm = try controller.get(name: name, storage: storage)
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ let json = try encoder.encode(vm.details)
+ return CallTool.Result(content: [.text(String(data: json, encoding: .utf8) ?? "{}")])
+ }
+
+ private func handleRunVM(_ args: [String: Value]?) async throws -> CallTool.Result {
+ guard let name = args?["name"]?.stringValue else {
+ return CallTool.Result(content: [.text("Error: 'name' is required")], isError: true)
+ }
+
+ let storage = args?["storage"]?.stringValue
+ let noDisplay = args?["no_display"]?.boolValue ?? true
+
+ var sharedDirectories: [SharedDirectory] = []
+ if let sharedDir = args?["shared_dir"]?.stringValue {
+ // Expand ~ to home directory
+ let expandedPath = (sharedDir as NSString).expandingTildeInPath
+ sharedDirectories.append(SharedDirectory(hostPath: expandedPath, tag: "shared", readOnly: false))
+ }
+
+ try await controller.runVM(
+ name: name,
+ noDisplay: noDisplay,
+ sharedDirectories: sharedDirectories,
+ storage: storage
+ )
+
+ // Get VM details after starting to return IP
+ let vm = try controller.get(name: name, storage: storage)
+ var response = "VM '\(name)' started successfully."
+ if let ip = vm.details.ipAddress {
+ response += "\nIP Address: \(ip)"
+ response += "\nSSH: ssh lume@\(ip) (password: lume)"
+ }
+ if !sharedDirectories.isEmpty {
+ response += "\nShared directory available at: /Volumes/My Shared Files"
+ }
+
+ return CallTool.Result(content: [.text(response)])
+ }
+
+ private func handleStopVM(_ args: [String: Value]?) async throws -> CallTool.Result {
+ guard let name = args?["name"]?.stringValue else {
+ return CallTool.Result(content: [.text("Error: 'name' is required")], isError: true)
+ }
+ let storage = args?["storage"]?.stringValue
+
+ try await controller.stopVM(name: name, storage: storage)
+ return CallTool.Result(content: [.text("VM '\(name)' stopped successfully.")])
+ }
+
+ private func handleCloneVM(_ args: [String: Value]?) async throws -> CallTool.Result {
+ guard let name = args?["name"]?.stringValue else {
+ return CallTool.Result(content: [.text("Error: 'name' is required")], isError: true)
+ }
+ guard let newName = args?["new_name"]?.stringValue else {
+ return CallTool.Result(content: [.text("Error: 'new_name' is required")], isError: true)
+ }
+
+ try controller.clone(name: name, newName: newName)
+ return CallTool.Result(content: [.text("VM '\(name)' cloned to '\(newName)' successfully.")])
+ }
+
+ private func handleDeleteVM(_ args: [String: Value]?) async throws -> CallTool.Result {
+ guard let name = args?["name"]?.stringValue else {
+ return CallTool.Result(content: [.text("Error: 'name' is required")], isError: true)
+ }
+ let storage = args?["storage"]?.stringValue
+
+ try await controller.delete(name: name, storage: storage)
+ return CallTool.Result(content: [.text("VM '\(name)' deleted successfully.")])
+ }
+
+ private func handleExec(_ args: [String: Value]?) async throws -> CallTool.Result {
+ guard let name = args?["name"]?.stringValue else {
+ return CallTool.Result(content: [.text("Error: 'name' is required")], isError: true)
+ }
+ guard let command = args?["command"]?.stringValue else {
+ return CallTool.Result(content: [.text("Error: 'command' is required")], isError: true)
+ }
+
+ let user = args?["user"]?.stringValue ?? "lume"
+ let password = args?["password"]?.stringValue ?? "lume"
+ let storage = args?["storage"]?.stringValue
+
+ // Get VM to find IP address
+ let vm = try controller.get(name: name, storage: storage)
+ guard let ip = vm.details.ipAddress else {
+ return CallTool.Result(
+ content: [.text("Error: VM '\(name)' has no IP address. Is it running?")],
+ isError: true
+ )
+ }
+
+ // Check if SSH is available
+ if vm.details.sshAvailable == false {
+ return CallTool.Result(
+ content: [.text("Error: SSH is not available on VM '\(name)'. Make sure SSH is enabled in the VM.")],
+ isError: true
+ )
+ }
+
+ // Find sshpass in common locations
+ let sshpassPaths = [
+ "/opt/homebrew/bin/sshpass",
+ "/usr/local/bin/sshpass",
+ "/usr/bin/sshpass"
+ ]
+
+ var sshpassPath: String?
+ for path in sshpassPaths {
+ if FileManager.default.fileExists(atPath: path) {
+ sshpassPath = path
+ break
+ }
+ }
+
+ guard let sshpass = sshpassPath else {
+ return CallTool.Result(
+ content: [.text("Error: sshpass not found. Install it with: brew install hudochenkov/sshpass/sshpass")],
+ isError: true
+ )
+ }
+
+ // Execute command via SSH using sshpass
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: sshpass)
+ process.arguments = [
+ "-p", password,
+ "ssh",
+ "-o", "StrictHostKeyChecking=no",
+ "-o", "UserKnownHostsFile=/dev/null",
+ "-o", "LogLevel=ERROR",
+ "\(user)@\(ip)",
+ command
+ ]
+
+ let outputPipe = Pipe()
+ let errorPipe = Pipe()
+ process.standardOutput = outputPipe
+ process.standardError = errorPipe
+
+ try process.run()
+ process.waitUntilExit()
+
+ let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile()
+ let errorData = errorPipe.fileHandleForReading.readDataToEndOfFile()
+
+ let output = String(data: outputData, encoding: .utf8) ?? ""
+ let errorOutput = String(data: errorData, encoding: .utf8) ?? ""
+
+ let isError = process.terminationStatus != 0
+
+ var result = output
+ if !errorOutput.isEmpty {
+ if !result.isEmpty {
+ result += "\n"
+ }
+ result += errorOutput
+ }
+ if result.isEmpty {
+ result = isError ? "Command failed with exit code \(process.terminationStatus)" : "Command completed successfully (no output)"
+ }
+
+ return CallTool.Result(content: [.text(result)], isError: isError)
+ }
+
+ private func handleCreateVM(_ args: [String: Value]?) async throws -> CallTool.Result {
+ guard let name = args?["name"]?.stringValue else {
+ return CallTool.Result(content: [.text("Error: 'name' is required")], isError: true)
+ }
+
+ let ipsw = args?["ipsw"]?.stringValue ?? "latest"
+ let unattendedPreset = args?["unattended"]?.stringValue
+ let cpuCount = args?["cpu"]?.intValue ?? 4
+ let storage = args?["storage"]?.stringValue
+
+ // Parse memory size (default 8GB)
+ let memorySize: UInt64
+ if let memoryStr = args?["memory"]?.stringValue {
+ memorySize = try parseSize(memoryStr)
+ } else {
+ memorySize = 8 * 1024 * 1024 * 1024 // 8GB default
+ }
+
+ // Parse disk size (default 64GB)
+ let diskSize: UInt64
+ if let diskStr = args?["disk_size"]?.stringValue {
+ diskSize = try parseSize(diskStr)
+ } else {
+ diskSize = 64 * 1024 * 1024 * 1024 // 64GB default
+ }
+
+ // Load unattended config if specified
+ var unattendedConfig: UnattendedConfig? = nil
+ if let preset = unattendedPreset {
+ unattendedConfig = try UnattendedConfig.load(from: preset)
+ }
+
+ // Use async create - returns immediately
+ try controller.createAsync(
+ name: name,
+ os: "macos",
+ diskSize: diskSize,
+ cpuCount: cpuCount,
+ memorySize: memorySize,
+ display: "1920x1080",
+ ipsw: ipsw,
+ storage: storage,
+ unattendedConfig: unattendedConfig
+ )
+
+ var response = "VM '\(name)' creation started. Status: provisioning."
+ response += "\nUse lume_list_vms or lume_get_vm to monitor progress."
+ if unattendedPreset != nil {
+ response += "\nUnattended setup will run automatically after IPSW installation."
+ }
+
+ return CallTool.Result(content: [.text(response)])
+ }
+}
+
+// MARK: - Value Extension for type-safe argument access
+
+extension Value {
+ var stringValue: String? {
+ if case .string(let value) = self {
+ return value
+ }
+ return nil
+ }
+
+ var boolValue: Bool? {
+ if case .bool(let value) = self {
+ return value
+ }
+ return nil
+ }
+
+ var intValue: Int? {
+ if case .int(let value) = self {
+ return value
+ }
+ return nil
+ }
+}
diff --git a/libs/lume/src/Server/Requests.swift b/libs/lume/src/Server/Requests.swift
index f78f4331aa..38a708b2cc 100644
--- a/libs/lume/src/Server/Requests.swift
+++ b/libs/lume/src/Server/Requests.swift
@@ -65,6 +65,8 @@ struct CreateVMRequest: Codable {
let display: String
let ipsw: String?
let storage: String?
+ /// Preset name or path to YAML config file for unattended macOS Setup Assistant automation
+ let unattended: String?
func parse() throws -> (memory: UInt64, diskSize: UInt64) {
return (
diff --git a/libs/lume/src/VM/VMDetails.swift b/libs/lume/src/VM/VMDetails.swift
index 46c65935fc..189bf8275e 100644
--- a/libs/lume/src/VM/VMDetails.swift
+++ b/libs/lume/src/VM/VMDetails.swift
@@ -37,6 +37,8 @@ struct VMDetails: Codable {
let diskSize: DiskSize
let display: String
let status: String
+ /// Operation type when status is "provisioning" (e.g., "ipsw_install", "unattended_setup")
+ let provisioningOperation: String?
let vncUrl: String?
let ipAddress: String?
let sshAvailable: Bool?
@@ -45,7 +47,7 @@ struct VMDetails: Codable {
enum CodingKeys: String, CodingKey {
case name, os, cpuCount, memorySize, diskSize, display, status
- case vncUrl, ipAddress, sshAvailable, locationName, sharedDirectories
+ case provisioningOperation, vncUrl, ipAddress, sshAvailable, locationName, sharedDirectories
}
init(
@@ -56,6 +58,7 @@ struct VMDetails: Codable {
diskSize: DiskSize,
display: String,
status: String,
+ provisioningOperation: String? = nil,
vncUrl: String?,
ipAddress: String?,
sshAvailable: Bool? = nil,
@@ -69,6 +72,7 @@ struct VMDetails: Codable {
self.diskSize = diskSize
self.display = display
self.status = status
+ self.provisioningOperation = provisioningOperation
self.vncUrl = vncUrl
self.ipAddress = ipAddress
self.sshAvailable = sshAvailable
@@ -86,6 +90,7 @@ struct VMDetails: Codable {
try container.encode(diskSize, forKey: .diskSize)
try container.encode(display, forKey: .display)
try container.encode(status, forKey: .status)
+ try container.encode(provisioningOperation, forKey: .provisioningOperation)
try container.encode(vncUrl, forKey: .vncUrl)
try container.encode(ipAddress, forKey: .ipAddress)
try container.encode(sshAvailable, forKey: .sshAvailable)
diff --git a/libs/lume/src/VM/VMDetailsPrinter.swift b/libs/lume/src/VM/VMDetailsPrinter.swift
index f96543b47a..eb5daaeeed 100644
--- a/libs/lume/src/VM/VMDetailsPrinter.swift
+++ b/libs/lume/src/VM/VMDetailsPrinter.swift
@@ -26,9 +26,13 @@ enum VMDetailsPrinter {
}),
Column(header: "display", width: 12, getValue: { $0.display }),
Column(
- header: "status", width: 16,
- getValue: {
- $0.status
+ header: "status", width: 28,
+ getValue: { vm in
+ // Show operation type for provisioning status
+ if vm.status == "provisioning", let op = vm.provisioningOperation {
+ return "provisioning (\(op))"
+ }
+ return vm.status
}),
Column(header: "storage", width: 16, getValue: { $0.locationName }),
Column(