Skip to main content

unkernel_rs/
mcp.rs

1//! Zero-dependency Model Context Protocol (MCP) server over stdio (JSON-RPC 2.0).
2//!
3//! Exposes a sandboxed Linux 7.x micro-VM to MCP clients (Claude Desktop, Claude Code,
4//! Cursor, Antigravity, OpenCode, `nono-agent`) with Copy-on-Write workspace diff/commit,
5//! counterfactual `snapshot` -> `branch_exec`, and Level-3 VMI process/audit inspection.
6//!
7//! The VM is booted lazily on the first tool call so MCP `initialize` and `tools/list`
8//! respond in <5 ms without blocking client startup.
9
10use crate::host::{Vm, VmConfig, VmSnapshot};
11use crate::kwtty::ExecOptions;
12use crate::monitor::AuditEvent;
13use serde_json::{Value, json};
14use std::collections::{BTreeMap, HashMap, VecDeque};
15use std::io::{self, BufRead, Write};
16use std::sync::{Arc, Mutex};
17use wasmtime::{Result, format_err};
18
19const MAX_AUDIT_RING: usize = 200;
20const MCP_PROTOCOL_VERSION: &str = "2024-11-05";
21
22struct McpState {
23    base_cfg: VmConfig,
24    vm: Option<Vm>,
25    snapshots: HashMap<String, VmSnapshot>,
26    audit_ring: Arc<Mutex<VecDeque<Value>>>,
27}
28
29impl McpState {
30    fn new(mut cfg: VmConfig) -> Self {
31        let audit_ring = Arc::new(Mutex::new(VecDeque::with_capacity(MAX_AUDIT_RING)));
32        let ring_cb = audit_ring.clone();
33        let prev_cb = cfg.monitor.audit_callback.take();
34        cfg.monitor.audit_enabled = true;
35        cfg.monitor.audit_callback = Some(Arc::new(move |ev: AuditEvent| {
36            if let Ok(val) = serde_json::to_value(&ev) {
37                let mut q = ring_cb.lock().unwrap();
38                if q.len() >= MAX_AUDIT_RING {
39                    q.pop_front();
40                }
41                q.push_back(val);
42            }
43            if let Some(cb) = &prev_cb {
44                cb(ev);
45            }
46        }));
47        Self {
48            base_cfg: cfg,
49            vm: None,
50            snapshots: HashMap::new(),
51            audit_ring,
52        }
53    }
54
55    fn ensure_vm(&mut self) -> Result<&Vm> {
56        if self.vm.is_none() {
57            let vm = Vm::boot(self.base_cfg.clone())?;
58            self.vm = Some(vm);
59        }
60        Ok(self.vm.as_ref().unwrap())
61    }
62
63    fn shutdown(&mut self) {
64        if let Some(vm) = self.vm.take() {
65            vm.shutdown();
66        }
67    }
68}
69
70fn tool_definitions() -> Value {
71    json!([
72        {
73            "name": "vm_exec",
74            "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.",
75            "inputSchema": {
76                "type": "object",
77                "properties": {
78                    "command": { "type": "string", "description": "Shell command executed via `sh -c <command>`" },
79                    "cwd": { "type": "string", "description": "Optional working directory inside the guest" },
80                    "user": { "type": "string", "description": "Optional guest user (e.g. 'root')" },
81                    "env": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Optional environment variables" },
82                    "timeout_ms": { "type": "integer", "description": "Command timeout in milliseconds (default 30000)" }
83                },
84                "required": ["command"]
85            }
86        },
87        {
88            "name": "vm_snapshot",
89            "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.",
90            "inputSchema": {
91                "type": "object",
92                "properties": {
93                    "name": { "type": "string", "description": "Snapshot identifier (e.g. 'before_refactor')" }
94                },
95                "required": ["name"]
96            }
97        },
98        {
99            "name": "vm_save_snapshot",
100            "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.",
101            "inputSchema": {
102                "type": "object",
103                "properties": {
104                    "name": { "type": "string", "description": "Snapshot name previously created by vm_snapshot" },
105                    "path": { "type": "string", "description": "Host destination file path (e.g. 'checkpoint.uksnap')" }
106                },
107                "required": ["name", "path"]
108            }
109        },
110        {
111            "name": "vm_load_snapshot",
112            "description": "Load a portable .uksnap file from disk into the server's named snapshot table so you can call vm_branch_exec on it.",
113            "inputSchema": {
114                "type": "object",
115                "properties": {
116                    "name": { "type": "string", "description": "Name to register the loaded snapshot under" },
117                    "path": { "type": "string", "description": "Host .uksnap file path to load" }
118                },
119                "required": ["name", "path"]
120            }
121        },
122        {
123            "name": "vm_branch_exec",
124            "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.",
125            "inputSchema": {
126                "type": "object",
127                "properties": {
128                    "snapshot": { "type": "string", "description": "Name of a snapshot created by vm_snapshot" },
129                    "command": { "type": "string", "description": "Shell command to test inside the forked branch VM" },
130                    "cwd": { "type": "string", "description": "Optional working directory inside the branch guest" },
131                    "user": { "type": "string", "description": "Optional guest user (e.g. 'root')" },
132                    "timeout_ms": { "type": "integer", "description": "Command timeout in milliseconds (default 30000)" }
133                },
134                "required": ["snapshot", "command"]
135            }
136        },
137        {
138            "name": "vm_diff",
139            "description": "Inspect created, modified, and deleted files staged in Copy-on-Write (:cow) mounted workspaces without modifying the host filesystem.",
140            "inputSchema": {
141                "type": "object",
142                "properties": {
143                    "guest_path": { "type": "string", "description": "Optional specific :cow mount path (e.g. '/work'); omit to diff all :cow workspaces" }
144                }
145            }
146        },
147        {
148            "name": "vm_read_file",
149            "description": "Read the contents of a staged file inside a :cow workspace before committing it to the host.",
150            "inputSchema": {
151                "type": "object",
152                "properties": {
153                    "guest_path": { "type": "string", "description": "Guest mount path (e.g. '/work')" },
154                    "rel_path": { "type": "string", "description": "Relative file path inside the workspace (e.g. 'src/app.py')" }
155                },
156                "required": ["guest_path", "rel_path"]
157            }
158        },
159        {
160            "name": "vm_commit",
161            "description": "Atomically commit all staged Copy-on-Write (:cow) changes for a workspace back to the host directory.",
162            "inputSchema": {
163                "type": "object",
164                "properties": {
165                    "guest_path": { "type": "string", "description": "Guest :cow mount path to commit (e.g. '/work')" }
166                },
167                "required": ["guest_path"]
168            }
169        },
170        {
171            "name": "vm_discard",
172            "description": "Discard all staged Copy-on-Write (:cow) changes for a workspace, reverting it to the clean host directory state.",
173            "inputSchema": {
174                "type": "object",
175                "properties": {
176                    "guest_path": { "type": "string", "description": "Guest :cow mount path to discard (e.g. '/work')" }
177                },
178                "required": ["guest_path"]
179            }
180        },
181        {
182            "name": "vm_inspect",
183            "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).",
184            "inputSchema": {
185                "type": "object",
186                "properties": {
187                    "max_events": { "type": "integer", "description": "Maximum number of recent audit events to return (default 50)" }
188                }
189            }
190        }
191    ])
192}
193
194fn call_tool(state: &mut McpState, name: &str, args: &Value) -> Result<Value> {
195    match name {
196        "vm_exec" => {
197            let command = args
198                .get("command")
199                .and_then(|v| v.as_str())
200                .ok_or_else(|| format_err!("missing required string argument 'command'"))?;
201            let mut opts = ExecOptions::shell(command);
202            opts.cwd = args.get("cwd").and_then(|v| v.as_str()).map(str::to_string);
203            opts.user = args
204                .get("user")
205                .and_then(|v| v.as_str())
206                .map(str::to_string);
207            if let Some(t) = args.get("timeout_ms").and_then(|v| v.as_u64()) {
208                opts.timeout_ms = Some(t);
209            }
210            if let Some(env_obj) = args.get("env").and_then(|v| v.as_object()) {
211                let mut env = BTreeMap::new();
212                for (k, v) in env_obj {
213                    if let Some(s) = v.as_str() {
214                        env.insert(k.clone(), s.to_string());
215                    }
216                }
217                opts.env = env;
218            }
219            let vm = state.ensure_vm()?;
220            let res = vm.exec(&opts)?;
221            Ok(json!({
222                "stdout": res.stdout_lossy(),
223                "stderr": res.stderr_lossy(),
224                "exit_code": res.exit_code,
225                "signal": res.signal,
226                "pid": res.pid,
227                "ok": res.exit_code == Some(0) && res.signal.is_none(),
228            }))
229        }
230        "vm_snapshot" => {
231            let snap_name = args
232                .get("name")
233                .and_then(|v| v.as_str())
234                .ok_or_else(|| format_err!("missing required string argument 'name'"))?
235                .to_string();
236            let vm = state.ensure_vm()?;
237            let snap = vm.snapshot()?;
238            let workspace_count = snap.workspaces.len();
239            let has_disk = snap.disk.is_some();
240            state.snapshots.insert(snap_name.clone(), snap);
241            Ok(json!({
242                "snapshot": snap_name,
243                "workspaces": workspace_count,
244                "has_disk": has_disk,
245            }))
246        }
247        "vm_save_snapshot" => {
248            let snap_name = args
249                .get("name")
250                .and_then(|v| v.as_str())
251                .ok_or_else(|| format_err!("missing required string argument 'name'"))?;
252            let path = args
253                .get("path")
254                .and_then(|v| v.as_str())
255                .ok_or_else(|| format_err!("missing required string argument 'path'"))?;
256            let snap = state
257                .snapshots
258                .get(snap_name)
259                .ok_or_else(|| format_err!("unknown snapshot {snap_name:?}"))?;
260            snap.save(path)?;
261            let bytes = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
262            Ok(json!({
263                "saved": true,
264                "snapshot": snap_name,
265                "path": path,
266                "bytes": bytes,
267            }))
268        }
269        "vm_load_snapshot" => {
270            let snap_name = args
271                .get("name")
272                .and_then(|v| v.as_str())
273                .ok_or_else(|| format_err!("missing required string argument 'name'"))?
274                .to_string();
275            let path = args
276                .get("path")
277                .and_then(|v| v.as_str())
278                .ok_or_else(|| format_err!("missing required string argument 'path'"))?;
279            let snap = VmSnapshot::load(path)?;
280            let workspace_count = snap.workspaces.len();
281            let has_disk = snap.disk.is_some();
282            state.snapshots.insert(snap_name.clone(), snap);
283            Ok(json!({
284                "loaded": true,
285                "snapshot": snap_name,
286                "path": path,
287                "workspaces": workspace_count,
288                "has_disk": has_disk,
289            }))
290        }
291        "vm_branch_exec" => {
292            let snap_name = args
293                .get("snapshot")
294                .and_then(|v| v.as_str())
295                .ok_or_else(|| format_err!("missing required string argument 'snapshot'"))?;
296            let command = args
297                .get("command")
298                .and_then(|v| v.as_str())
299                .ok_or_else(|| format_err!("missing required string argument 'command'"))?;
300            let snap = state
301                .snapshots
302                .get(snap_name)
303                .ok_or_else(|| format_err!("unknown snapshot {snap_name:?}"))?
304                .clone();
305            let mut opts = ExecOptions::shell(command);
306            opts.cwd = args.get("cwd").and_then(|v| v.as_str()).map(str::to_string);
307            opts.user = args
308                .get("user")
309                .and_then(|v| v.as_str())
310                .map(str::to_string);
311            if let Some(t) = args.get("timeout_ms").and_then(|v| v.as_u64()) {
312                opts.timeout_ms = Some(t);
313            }
314            let branch = snap.boot_branch(None, None)?;
315            let res = branch.exec(&opts)?;
316            let diffs: Vec<Value> = branch
317                .diff_all_workspaces()
318                .into_iter()
319                .map(|d| {
320                    json!({
321                        "guest_path": d.guest_path,
322                        "created": d.created,
323                        "modified": d.modified,
324                        "deleted": d.deleted,
325                    })
326                })
327                .collect();
328            branch.shutdown();
329            Ok(json!({
330                "snapshot": snap_name,
331                "stdout": res.stdout_lossy(),
332                "stderr": res.stderr_lossy(),
333                "exit_code": res.exit_code,
334                "signal": res.signal,
335                "ok": res.exit_code == Some(0) && res.signal.is_none(),
336                "diffs": diffs,
337            }))
338        }
339        "vm_diff" => {
340            let vm = state.ensure_vm()?;
341            let diffs = if let Some(gp) = args.get("guest_path").and_then(|v| v.as_str()) {
342                vec![vm.workspace_diff(gp)?]
343            } else {
344                vm.diff_all_workspaces()
345            };
346            let out: Vec<Value> = diffs
347                .into_iter()
348                .map(|d| {
349                    json!({
350                        "guest_path": d.guest_path,
351                        "created": d.created,
352                        "modified": d.modified,
353                        "deleted": d.deleted,
354                    })
355                })
356                .collect();
357            Ok(json!({ "diffs": out }))
358        }
359        "vm_read_file" => {
360            let gp = args
361                .get("guest_path")
362                .and_then(|v| v.as_str())
363                .ok_or_else(|| format_err!("missing required string argument 'guest_path'"))?;
364            let rel = args
365                .get("rel_path")
366                .and_then(|v| v.as_str())
367                .ok_or_else(|| format_err!("missing required string argument 'rel_path'"))?;
368            let vm = state.ensure_vm()?;
369            match vm.read_workspace_file(gp, rel)? {
370                Some(bytes) => Ok(json!({
371                    "exists": true,
372                    "bytes": bytes.len(),
373                    "content": String::from_utf8_lossy(&bytes),
374                })),
375                None => Ok(json!({ "exists": false })),
376            }
377        }
378        "vm_commit" => {
379            let gp = args
380                .get("guest_path")
381                .and_then(|v| v.as_str())
382                .ok_or_else(|| format_err!("missing required string argument 'guest_path'"))?;
383            let vm = state.ensure_vm()?;
384            let d = vm.commit_workspace(gp)?;
385            Ok(json!({
386                "committed": true,
387                "guest_path": d.guest_path,
388                "created": d.created,
389                "modified": d.modified,
390                "deleted": d.deleted,
391            }))
392        }
393        "vm_discard" => {
394            let gp = args
395                .get("guest_path")
396                .and_then(|v| v.as_str())
397                .ok_or_else(|| format_err!("missing required string argument 'guest_path'"))?;
398            let vm = state.ensure_vm()?;
399            vm.discard_workspace(gp)?;
400            Ok(json!({ "discarded": true, "guest_path": gp }))
401        }
402        "vm_inspect" => {
403            let max_events = args
404                .get("max_events")
405                .and_then(|v| v.as_u64())
406                .unwrap_or(50) as usize;
407            let (booted, procs, timings) = if let Some(vm) = &state.vm {
408                let procs: Vec<Value> = vm
409                    .active_processes()
410                    .into_iter()
411                    .map(|p| {
412                        json!({
413                            "pid": p.pid,
414                            "tgid": p.tgid,
415                            "ppid": p.ppid,
416                            "comm": p.comm,
417                        })
418                    })
419                    .collect();
420                (true, procs, serde_json::to_value(vm.timings()).ok())
421            } else {
422                (false, Vec::new(), None)
423            };
424            let events: Vec<Value> = {
425                let q = state.audit_ring.lock().unwrap();
426                let skip = q.len().saturating_sub(max_events);
427                q.iter().skip(skip).cloned().collect()
428            };
429            let mut snap_names: Vec<&String> = state.snapshots.keys().collect();
430            snap_names.sort();
431            Ok(json!({
432                "booted": booted,
433                "timings": timings,
434                "snapshots": snap_names,
435                "active_processes": procs,
436                "audit_events": events,
437            }))
438        }
439        other => Err(format_err!("unknown tool: {other}")),
440    }
441}
442
443fn handle_request(state: &mut McpState, req: &Value) -> Option<Value> {
444    let id = req.get("id").cloned();
445    let method = req.get("method").and_then(|m| m.as_str()).unwrap_or("");
446    let params = req.get("params").cloned().unwrap_or(Value::Null);
447
448    // JSON-RPC notifications (no `id`) must not receive a response.
449    let id = id?;
450
451    match method {
452        "initialize" => {
453            let client_ver = params
454                .get("protocolVersion")
455                .and_then(|v| v.as_str())
456                .unwrap_or(MCP_PROTOCOL_VERSION);
457            Some(json!({
458                "jsonrpc": "2.0",
459                "id": id,
460                "result": {
461                    "protocolVersion": client_ver,
462                    "capabilities": {
463                        "tools": {}
464                    },
465                    "serverInfo": {
466                        "name": "unkernel-rs",
467                        "version": env!("CARGO_PKG_VERSION")
468                    }
469                }
470            }))
471        }
472        "ping" => Some(json!({
473            "jsonrpc": "2.0",
474            "id": id,
475            "result": {}
476        })),
477        "tools/list" => Some(json!({
478            "jsonrpc": "2.0",
479            "id": id,
480            "result": {
481                "tools": tool_definitions()
482            }
483        })),
484        "tools/call" => {
485            let tool_name = params.get("name").and_then(|v| v.as_str()).unwrap_or("");
486            let tool_args = params
487                .get("arguments")
488                .cloned()
489                .unwrap_or_else(|| json!({}));
490            match call_tool(state, tool_name, &tool_args) {
491                Ok(result_val) => {
492                    let text = serde_json::to_string_pretty(&result_val)
493                        .unwrap_or_else(|_| result_val.to_string());
494                    Some(json!({
495                        "jsonrpc": "2.0",
496                        "id": id,
497                        "result": {
498                            "content": [{ "type": "text", "text": text }],
499                            "isError": false
500                        }
501                    }))
502                }
503                Err(err) => Some(json!({
504                    "jsonrpc": "2.0",
505                    "id": id,
506                    "result": {
507                        "content": [{ "type": "text", "text": format!("{err:#}") }],
508                        "isError": true
509                    }
510                })),
511            }
512        }
513        _ => Some(json!({
514            "jsonrpc": "2.0",
515            "id": id,
516            "error": {
517                "code": -32601,
518                "message": format!("Method not found: {method}")
519            }
520        })),
521    }
522}
523
524/// Run the MCP JSON-RPC 2.0 server reading newline-delimited requests from `reader`
525/// and writing responses to `writer`. Shuts down the VM cleanly when `reader` reaches EOF.
526pub fn run_mcp_with_io<R: BufRead, W: Write>(
527    cfg: VmConfig,
528    reader: R,
529    mut writer: W,
530) -> Result<()> {
531    let mut state = McpState::new(cfg);
532    for line in reader.lines() {
533        let line = match line {
534            Ok(l) => l,
535            Err(_) => break,
536        };
537        let trimmed = line.trim();
538        if trimmed.is_empty() {
539            continue;
540        }
541        let resp = match serde_json::from_str::<Value>(trimmed) {
542            Ok(req) => handle_request(&mut state, &req),
543            Err(e) => Some(json!({
544                "jsonrpc": "2.0",
545                "id": Value::Null,
546                "error": {
547                    "code": -32700,
548                    "message": format!("Parse error: {e}")
549                }
550            })),
551        };
552        if let Some(resp) = resp {
553            serde_json::to_writer(&mut writer, &resp)?;
554            writer.write_all(b"\n")?;
555            writer.flush()?;
556        }
557    }
558    state.shutdown();
559    Ok(())
560}
561
562/// Run the MCP server on process `stdin` / `stdout` (the standard MCP stdio transport).
563pub fn run_mcp_stdio(cfg: VmConfig) -> Result<()> {
564    let stdin = io::stdin();
565    let stdout = io::stdout();
566    run_mcp_with_io(cfg, stdin.lock(), stdout.lock())
567}