unkernel-rs 0.8.1

Native Rust + Wasmtime host library and CLI for unkernel (Linux 7.x on WebAssembly) — zero Node, zero JSPI, zero KVM
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! Zero-dependency Model Context Protocol (MCP) server over stdio (JSON-RPC 2.0).
//!
//! Exposes a sandboxed Linux 7.x micro-VM to MCP clients (Claude Desktop, Claude Code,
//! Cursor, Antigravity, OpenCode, `nono-agent`) with Copy-on-Write workspace diff/commit,
//! counterfactual `snapshot` -> `branch_exec`, and Level-3 VMI process/audit inspection.
//!
//! The VM is booted lazily on the first tool call so MCP `initialize` and `tools/list`
//! respond in <5 ms without blocking client startup.

use crate::host::{Vm, VmConfig, VmSnapshot};
use crate::kwtty::ExecOptions;
use crate::monitor::AuditEvent;
use serde_json::{Value, json};
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::io::{self, BufRead, Write};
use std::sync::{Arc, Mutex};
use wasmtime::{Result, format_err};

const MAX_AUDIT_RING: usize = 200;
const MCP_PROTOCOL_VERSION: &str = "2024-11-05";

struct McpState {
    base_cfg: VmConfig,
    vm: Option<Vm>,
    snapshots: HashMap<String, VmSnapshot>,
    audit_ring: Arc<Mutex<VecDeque<Value>>>,
}

impl McpState {
    fn new(mut cfg: VmConfig) -> Self {
        let audit_ring = Arc::new(Mutex::new(VecDeque::with_capacity(MAX_AUDIT_RING)));
        let ring_cb = audit_ring.clone();
        let prev_cb = cfg.monitor.audit_callback.take();
        cfg.monitor.audit_enabled = true;
        cfg.monitor.audit_callback = Some(Arc::new(move |ev: AuditEvent| {
            if let Ok(val) = serde_json::to_value(&ev) {
                let mut q = ring_cb.lock().unwrap();
                if q.len() >= MAX_AUDIT_RING {
                    q.pop_front();
                }
                q.push_back(val);
            }
            if let Some(cb) = &prev_cb {
                cb(ev);
            }
        }));
        Self {
            base_cfg: cfg,
            vm: None,
            snapshots: HashMap::new(),
            audit_ring,
        }
    }

    fn ensure_vm(&mut self) -> Result<&Vm> {
        if self.vm.is_none() {
            let vm = Vm::boot(self.base_cfg.clone())?;
            self.vm = Some(vm);
        }
        Ok(self.vm.as_ref().unwrap())
    }

    fn shutdown(&mut self) {
        if let Some(vm) = self.vm.take() {
            vm.shutdown();
        }
    }
}

fn tool_definitions() -> Value {
    json!([
        {
            "name": "vm_exec",
            "description": "Execute a shell command inside the sandboxed Linux 7.x Wasm micro-VM (air-gapped by default unless configured with --net). Returns stdout, stderr, exit_code, and pid.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "command": { "type": "string", "description": "Shell command executed via `sh -c <command>`" },
                    "cwd": { "type": "string", "description": "Optional working directory inside the guest" },
                    "user": { "type": "string", "description": "Optional guest user (e.g. 'root')" },
                    "env": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Optional environment variables" },
                    "timeout_ms": { "type": "integer", "description": "Command timeout in milliseconds (default 30000)" }
                },
                "required": ["command"]
            }
        },
        {
            "name": "vm_snapshot",
            "description": "Capture a named in-memory snapshot of the VM's Copy-on-Write (:cow) workspaces and ext4 disk overlay so you can fork counterfactual branches or safely experiment.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "name": { "type": "string", "description": "Snapshot identifier (e.g. 'before_refactor')" }
                },
                "required": ["name"]
            }
        },
        {
            "name": "vm_save_snapshot",
            "description": "Persist a named snapshot to a portable gzip-compressed .uksnap file on disk so it can be reloaded in a future session or shared.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "name": { "type": "string", "description": "Snapshot name previously created by vm_snapshot" },
                    "path": { "type": "string", "description": "Host destination file path (e.g. 'checkpoint.uksnap')" }
                },
                "required": ["name", "path"]
            }
        },
        {
            "name": "vm_load_snapshot",
            "description": "Load a portable .uksnap file from disk into the server's named snapshot table so you can call vm_branch_exec on it.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "name": { "type": "string", "description": "Name to register the loaded snapshot under" },
                    "path": { "type": "string", "description": "Host .uksnap file path to load" }
                },
                "required": ["name", "path"]
            }
        },
        {
            "name": "vm_branch_exec",
            "description": "Counterfactual execution: fork a disposable branch VM from a previously saved snapshot, run a command in isolation without mutating the parent VM or host files, and return stdout, stderr, exit_code, and staged workspace diffs.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "snapshot": { "type": "string", "description": "Name of a snapshot created by vm_snapshot" },
                    "command": { "type": "string", "description": "Shell command to test inside the forked branch VM" },
                    "cwd": { "type": "string", "description": "Optional working directory inside the branch guest" },
                    "user": { "type": "string", "description": "Optional guest user (e.g. 'root')" },
                    "timeout_ms": { "type": "integer", "description": "Command timeout in milliseconds (default 30000)" }
                },
                "required": ["snapshot", "command"]
            }
        },
        {
            "name": "vm_diff",
            "description": "Inspect created, modified, and deleted files staged in Copy-on-Write (:cow) mounted workspaces without modifying the host filesystem.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "guest_path": { "type": "string", "description": "Optional specific :cow mount path (e.g. '/work'); omit to diff all :cow workspaces" }
                }
            }
        },
        {
            "name": "vm_read_file",
            "description": "Read the contents of a staged file inside a :cow workspace before committing it to the host.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "guest_path": { "type": "string", "description": "Guest mount path (e.g. '/work')" },
                    "rel_path": { "type": "string", "description": "Relative file path inside the workspace (e.g. 'src/app.py')" }
                },
                "required": ["guest_path", "rel_path"]
            }
        },
        {
            "name": "vm_commit",
            "description": "Atomically commit all staged Copy-on-Write (:cow) changes for a workspace back to the host directory.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "guest_path": { "type": "string", "description": "Guest :cow mount path to commit (e.g. '/work')" }
                },
                "required": ["guest_path"]
            }
        },
        {
            "name": "vm_discard",
            "description": "Discard all staged Copy-on-Write (:cow) changes for a workspace, reverting it to the clean host directory state.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "guest_path": { "type": "string", "description": "Guest :cow mount path to discard (e.g. '/work')" }
                },
                "required": ["guest_path"]
            }
        },
        {
            "name": "vm_inspect",
            "description": "Inspect live guest Linux processes via Level-3 SharedMemory VMI, boot timings, saved snapshots, and recent untamperable host-side audit events (DNS, TCP, decrypted VMI-TLS, sensitive file reads).",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "max_events": { "type": "integer", "description": "Maximum number of recent audit events to return (default 50)" }
                }
            }
        }
    ])
}

fn call_tool(state: &mut McpState, name: &str, args: &Value) -> Result<Value> {
    match name {
        "vm_exec" => {
            let command = args
                .get("command")
                .and_then(|v| v.as_str())
                .ok_or_else(|| format_err!("missing required string argument 'command'"))?;
            let mut opts = ExecOptions::shell(command);
            opts.cwd = args.get("cwd").and_then(|v| v.as_str()).map(str::to_string);
            opts.user = args
                .get("user")
                .and_then(|v| v.as_str())
                .map(str::to_string);
            if let Some(t) = args.get("timeout_ms").and_then(|v| v.as_u64()) {
                opts.timeout_ms = Some(t);
            }
            if let Some(env_obj) = args.get("env").and_then(|v| v.as_object()) {
                let mut env = BTreeMap::new();
                for (k, v) in env_obj {
                    if let Some(s) = v.as_str() {
                        env.insert(k.clone(), s.to_string());
                    }
                }
                opts.env = env;
            }
            let vm = state.ensure_vm()?;
            let res = vm.exec(&opts)?;
            Ok(json!({
                "stdout": res.stdout_lossy(),
                "stderr": res.stderr_lossy(),
                "exit_code": res.exit_code,
                "signal": res.signal,
                "pid": res.pid,
                "ok": res.exit_code == Some(0) && res.signal.is_none(),
            }))
        }
        "vm_snapshot" => {
            let snap_name = args
                .get("name")
                .and_then(|v| v.as_str())
                .ok_or_else(|| format_err!("missing required string argument 'name'"))?
                .to_string();
            let vm = state.ensure_vm()?;
            let snap = vm.snapshot()?;
            let workspace_count = snap.workspaces.len();
            let has_disk = snap.disk.is_some();
            state.snapshots.insert(snap_name.clone(), snap);
            Ok(json!({
                "snapshot": snap_name,
                "workspaces": workspace_count,
                "has_disk": has_disk,
            }))
        }
        "vm_save_snapshot" => {
            let snap_name = args
                .get("name")
                .and_then(|v| v.as_str())
                .ok_or_else(|| format_err!("missing required string argument 'name'"))?;
            let path = args
                .get("path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| format_err!("missing required string argument 'path'"))?;
            let snap = state
                .snapshots
                .get(snap_name)
                .ok_or_else(|| format_err!("unknown snapshot {snap_name:?}"))?;
            snap.save(path)?;
            let bytes = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
            Ok(json!({
                "saved": true,
                "snapshot": snap_name,
                "path": path,
                "bytes": bytes,
            }))
        }
        "vm_load_snapshot" => {
            let snap_name = args
                .get("name")
                .and_then(|v| v.as_str())
                .ok_or_else(|| format_err!("missing required string argument 'name'"))?
                .to_string();
            let path = args
                .get("path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| format_err!("missing required string argument 'path'"))?;
            let snap = VmSnapshot::load(path)?;
            let workspace_count = snap.workspaces.len();
            let has_disk = snap.disk.is_some();
            state.snapshots.insert(snap_name.clone(), snap);
            Ok(json!({
                "loaded": true,
                "snapshot": snap_name,
                "path": path,
                "workspaces": workspace_count,
                "has_disk": has_disk,
            }))
        }
        "vm_branch_exec" => {
            let snap_name = args
                .get("snapshot")
                .and_then(|v| v.as_str())
                .ok_or_else(|| format_err!("missing required string argument 'snapshot'"))?;
            let command = args
                .get("command")
                .and_then(|v| v.as_str())
                .ok_or_else(|| format_err!("missing required string argument 'command'"))?;
            let snap = state
                .snapshots
                .get(snap_name)
                .ok_or_else(|| format_err!("unknown snapshot {snap_name:?}"))?
                .clone();
            let mut opts = ExecOptions::shell(command);
            opts.cwd = args.get("cwd").and_then(|v| v.as_str()).map(str::to_string);
            opts.user = args
                .get("user")
                .and_then(|v| v.as_str())
                .map(str::to_string);
            if let Some(t) = args.get("timeout_ms").and_then(|v| v.as_u64()) {
                opts.timeout_ms = Some(t);
            }
            let branch = snap.boot_branch(None, None)?;
            let res = branch.exec(&opts)?;
            let diffs: Vec<Value> = branch
                .diff_all_workspaces()
                .into_iter()
                .map(|d| {
                    json!({
                        "guest_path": d.guest_path,
                        "created": d.created,
                        "modified": d.modified,
                        "deleted": d.deleted,
                    })
                })
                .collect();
            branch.shutdown();
            Ok(json!({
                "snapshot": snap_name,
                "stdout": res.stdout_lossy(),
                "stderr": res.stderr_lossy(),
                "exit_code": res.exit_code,
                "signal": res.signal,
                "ok": res.exit_code == Some(0) && res.signal.is_none(),
                "diffs": diffs,
            }))
        }
        "vm_diff" => {
            let vm = state.ensure_vm()?;
            let diffs = if let Some(gp) = args.get("guest_path").and_then(|v| v.as_str()) {
                vec![vm.workspace_diff(gp)?]
            } else {
                vm.diff_all_workspaces()
            };
            let out: Vec<Value> = diffs
                .into_iter()
                .map(|d| {
                    json!({
                        "guest_path": d.guest_path,
                        "created": d.created,
                        "modified": d.modified,
                        "deleted": d.deleted,
                    })
                })
                .collect();
            Ok(json!({ "diffs": out }))
        }
        "vm_read_file" => {
            let gp = args
                .get("guest_path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| format_err!("missing required string argument 'guest_path'"))?;
            let rel = args
                .get("rel_path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| format_err!("missing required string argument 'rel_path'"))?;
            let vm = state.ensure_vm()?;
            match vm.read_workspace_file(gp, rel)? {
                Some(bytes) => Ok(json!({
                    "exists": true,
                    "bytes": bytes.len(),
                    "content": String::from_utf8_lossy(&bytes),
                })),
                None => Ok(json!({ "exists": false })),
            }
        }
        "vm_commit" => {
            let gp = args
                .get("guest_path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| format_err!("missing required string argument 'guest_path'"))?;
            let vm = state.ensure_vm()?;
            let d = vm.commit_workspace(gp)?;
            Ok(json!({
                "committed": true,
                "guest_path": d.guest_path,
                "created": d.created,
                "modified": d.modified,
                "deleted": d.deleted,
            }))
        }
        "vm_discard" => {
            let gp = args
                .get("guest_path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| format_err!("missing required string argument 'guest_path'"))?;
            let vm = state.ensure_vm()?;
            vm.discard_workspace(gp)?;
            Ok(json!({ "discarded": true, "guest_path": gp }))
        }
        "vm_inspect" => {
            let max_events = args
                .get("max_events")
                .and_then(|v| v.as_u64())
                .unwrap_or(50) as usize;
            let (booted, procs, timings) = if let Some(vm) = &state.vm {
                let procs: Vec<Value> = vm
                    .active_processes()
                    .into_iter()
                    .map(|p| {
                        json!({
                            "pid": p.pid,
                            "tgid": p.tgid,
                            "ppid": p.ppid,
                            "comm": p.comm,
                        })
                    })
                    .collect();
                (true, procs, serde_json::to_value(vm.timings()).ok())
            } else {
                (false, Vec::new(), None)
            };
            let events: Vec<Value> = {
                let q = state.audit_ring.lock().unwrap();
                let skip = q.len().saturating_sub(max_events);
                q.iter().skip(skip).cloned().collect()
            };
            let mut snap_names: Vec<&String> = state.snapshots.keys().collect();
            snap_names.sort();
            Ok(json!({
                "booted": booted,
                "timings": timings,
                "snapshots": snap_names,
                "active_processes": procs,
                "audit_events": events,
            }))
        }
        other => Err(format_err!("unknown tool: {other}")),
    }
}

fn handle_request(state: &mut McpState, req: &Value) -> Option<Value> {
    let id = req.get("id").cloned();
    let method = req.get("method").and_then(|m| m.as_str()).unwrap_or("");
    let params = req.get("params").cloned().unwrap_or(Value::Null);

    // JSON-RPC notifications (no `id`) must not receive a response.
    let id = id?;

    match method {
        "initialize" => {
            let client_ver = params
                .get("protocolVersion")
                .and_then(|v| v.as_str())
                .unwrap_or(MCP_PROTOCOL_VERSION);
            Some(json!({
                "jsonrpc": "2.0",
                "id": id,
                "result": {
                    "protocolVersion": client_ver,
                    "capabilities": {
                        "tools": {}
                    },
                    "serverInfo": {
                        "name": "unkernel-rs",
                        "version": env!("CARGO_PKG_VERSION")
                    }
                }
            }))
        }
        "ping" => Some(json!({
            "jsonrpc": "2.0",
            "id": id,
            "result": {}
        })),
        "tools/list" => Some(json!({
            "jsonrpc": "2.0",
            "id": id,
            "result": {
                "tools": tool_definitions()
            }
        })),
        "tools/call" => {
            let tool_name = params.get("name").and_then(|v| v.as_str()).unwrap_or("");
            let tool_args = params
                .get("arguments")
                .cloned()
                .unwrap_or_else(|| json!({}));
            match call_tool(state, tool_name, &tool_args) {
                Ok(result_val) => {
                    let text = serde_json::to_string_pretty(&result_val)
                        .unwrap_or_else(|_| result_val.to_string());
                    Some(json!({
                        "jsonrpc": "2.0",
                        "id": id,
                        "result": {
                            "content": [{ "type": "text", "text": text }],
                            "isError": false
                        }
                    }))
                }
                Err(err) => Some(json!({
                    "jsonrpc": "2.0",
                    "id": id,
                    "result": {
                        "content": [{ "type": "text", "text": format!("{err:#}") }],
                        "isError": true
                    }
                })),
            }
        }
        _ => Some(json!({
            "jsonrpc": "2.0",
            "id": id,
            "error": {
                "code": -32601,
                "message": format!("Method not found: {method}")
            }
        })),
    }
}

/// Run the MCP JSON-RPC 2.0 server reading newline-delimited requests from `reader`
/// and writing responses to `writer`. Shuts down the VM cleanly when `reader` reaches EOF.
pub fn run_mcp_with_io<R: BufRead, W: Write>(
    cfg: VmConfig,
    reader: R,
    mut writer: W,
) -> Result<()> {
    let mut state = McpState::new(cfg);
    for line in reader.lines() {
        let line = match line {
            Ok(l) => l,
            Err(_) => break,
        };
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        let resp = match serde_json::from_str::<Value>(trimmed) {
            Ok(req) => handle_request(&mut state, &req),
            Err(e) => Some(json!({
                "jsonrpc": "2.0",
                "id": Value::Null,
                "error": {
                    "code": -32700,
                    "message": format!("Parse error: {e}")
                }
            })),
        };
        if let Some(resp) = resp {
            serde_json::to_writer(&mut writer, &resp)?;
            writer.write_all(b"\n")?;
            writer.flush()?;
        }
    }
    state.shutdown();
    Ok(())
}

/// Run the MCP server on process `stdin` / `stdout` (the standard MCP stdio transport).
pub fn run_mcp_stdio(cfg: VmConfig) -> Result<()> {
    let stdin = io::stdin();
    let stdout = io::stdout();
    run_mcp_with_io(cfg, stdin.lock(), stdout.lock())
}