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_branch_exec",
100            "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.",
101            "inputSchema": {
102                "type": "object",
103                "properties": {
104                    "snapshot": { "type": "string", "description": "Name of a snapshot created by vm_snapshot" },
105                    "command": { "type": "string", "description": "Shell command to test inside the forked branch VM" },
106                    "cwd": { "type": "string", "description": "Optional working directory inside the branch guest" },
107                    "user": { "type": "string", "description": "Optional guest user (e.g. 'root')" },
108                    "timeout_ms": { "type": "integer", "description": "Command timeout in milliseconds (default 30000)" }
109                },
110                "required": ["snapshot", "command"]
111            }
112        },
113        {
114            "name": "vm_diff",
115            "description": "Inspect created, modified, and deleted files staged in Copy-on-Write (:cow) mounted workspaces without modifying the host filesystem.",
116            "inputSchema": {
117                "type": "object",
118                "properties": {
119                    "guest_path": { "type": "string", "description": "Optional specific :cow mount path (e.g. '/work'); omit to diff all :cow workspaces" }
120                }
121            }
122        },
123        {
124            "name": "vm_read_file",
125            "description": "Read the contents of a staged file inside a :cow workspace before committing it to the host.",
126            "inputSchema": {
127                "type": "object",
128                "properties": {
129                    "guest_path": { "type": "string", "description": "Guest mount path (e.g. '/work')" },
130                    "rel_path": { "type": "string", "description": "Relative file path inside the workspace (e.g. 'src/app.py')" }
131                },
132                "required": ["guest_path", "rel_path"]
133            }
134        },
135        {
136            "name": "vm_commit",
137            "description": "Atomically commit all staged Copy-on-Write (:cow) changes for a workspace back to the host directory.",
138            "inputSchema": {
139                "type": "object",
140                "properties": {
141                    "guest_path": { "type": "string", "description": "Guest :cow mount path to commit (e.g. '/work')" }
142                },
143                "required": ["guest_path"]
144            }
145        },
146        {
147            "name": "vm_discard",
148            "description": "Discard all staged Copy-on-Write (:cow) changes for a workspace, reverting it to the clean host directory state.",
149            "inputSchema": {
150                "type": "object",
151                "properties": {
152                    "guest_path": { "type": "string", "description": "Guest :cow mount path to discard (e.g. '/work')" }
153                },
154                "required": ["guest_path"]
155            }
156        },
157        {
158            "name": "vm_inspect",
159            "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).",
160            "inputSchema": {
161                "type": "object",
162                "properties": {
163                    "max_events": { "type": "integer", "description": "Maximum number of recent audit events to return (default 50)" }
164                }
165            }
166        }
167    ])
168}
169
170fn call_tool(state: &mut McpState, name: &str, args: &Value) -> Result<Value> {
171    match name {
172        "vm_exec" => {
173            let command = args
174                .get("command")
175                .and_then(|v| v.as_str())
176                .ok_or_else(|| format_err!("missing required string argument 'command'"))?;
177            let mut opts = ExecOptions::shell(command);
178            opts.cwd = args.get("cwd").and_then(|v| v.as_str()).map(str::to_string);
179            opts.user = args
180                .get("user")
181                .and_then(|v| v.as_str())
182                .map(str::to_string);
183            if let Some(t) = args.get("timeout_ms").and_then(|v| v.as_u64()) {
184                opts.timeout_ms = Some(t);
185            }
186            if let Some(env_obj) = args.get("env").and_then(|v| v.as_object()) {
187                let mut env = BTreeMap::new();
188                for (k, v) in env_obj {
189                    if let Some(s) = v.as_str() {
190                        env.insert(k.clone(), s.to_string());
191                    }
192                }
193                opts.env = env;
194            }
195            let vm = state.ensure_vm()?;
196            let res = vm.exec(&opts)?;
197            Ok(json!({
198                "stdout": res.stdout_lossy(),
199                "stderr": res.stderr_lossy(),
200                "exit_code": res.exit_code,
201                "signal": res.signal,
202                "pid": res.pid,
203                "ok": res.exit_code == Some(0) && res.signal.is_none(),
204            }))
205        }
206        "vm_snapshot" => {
207            let snap_name = args
208                .get("name")
209                .and_then(|v| v.as_str())
210                .ok_or_else(|| format_err!("missing required string argument 'name'"))?
211                .to_string();
212            let vm = state.ensure_vm()?;
213            let snap = vm.snapshot()?;
214            let workspace_count = snap.workspaces.len();
215            let has_disk = snap.disk.is_some();
216            state.snapshots.insert(snap_name.clone(), snap);
217            Ok(json!({
218                "snapshot": snap_name,
219                "workspaces": workspace_count,
220                "has_disk": has_disk,
221            }))
222        }
223        "vm_branch_exec" => {
224            let snap_name = args
225                .get("snapshot")
226                .and_then(|v| v.as_str())
227                .ok_or_else(|| format_err!("missing required string argument 'snapshot'"))?;
228            let command = args
229                .get("command")
230                .and_then(|v| v.as_str())
231                .ok_or_else(|| format_err!("missing required string argument 'command'"))?;
232            let snap = state
233                .snapshots
234                .get(snap_name)
235                .ok_or_else(|| format_err!("unknown snapshot {snap_name:?}"))?
236                .clone();
237            let mut opts = ExecOptions::shell(command);
238            opts.cwd = args.get("cwd").and_then(|v| v.as_str()).map(str::to_string);
239            opts.user = args
240                .get("user")
241                .and_then(|v| v.as_str())
242                .map(str::to_string);
243            if let Some(t) = args.get("timeout_ms").and_then(|v| v.as_u64()) {
244                opts.timeout_ms = Some(t);
245            }
246            let branch = snap.boot_branch(None, None)?;
247            let res = branch.exec(&opts)?;
248            let diffs: Vec<Value> = branch
249                .diff_all_workspaces()
250                .into_iter()
251                .map(|d| {
252                    json!({
253                        "guest_path": d.guest_path,
254                        "created": d.created,
255                        "modified": d.modified,
256                        "deleted": d.deleted,
257                    })
258                })
259                .collect();
260            branch.shutdown();
261            Ok(json!({
262                "snapshot": snap_name,
263                "stdout": res.stdout_lossy(),
264                "stderr": res.stderr_lossy(),
265                "exit_code": res.exit_code,
266                "signal": res.signal,
267                "ok": res.exit_code == Some(0) && res.signal.is_none(),
268                "diffs": diffs,
269            }))
270        }
271        "vm_diff" => {
272            let vm = state.ensure_vm()?;
273            let diffs = if let Some(gp) = args.get("guest_path").and_then(|v| v.as_str()) {
274                vec![vm.workspace_diff(gp)?]
275            } else {
276                vm.diff_all_workspaces()
277            };
278            let out: Vec<Value> = diffs
279                .into_iter()
280                .map(|d| {
281                    json!({
282                        "guest_path": d.guest_path,
283                        "created": d.created,
284                        "modified": d.modified,
285                        "deleted": d.deleted,
286                    })
287                })
288                .collect();
289            Ok(json!({ "diffs": out }))
290        }
291        "vm_read_file" => {
292            let gp = args
293                .get("guest_path")
294                .and_then(|v| v.as_str())
295                .ok_or_else(|| format_err!("missing required string argument 'guest_path'"))?;
296            let rel = args
297                .get("rel_path")
298                .and_then(|v| v.as_str())
299                .ok_or_else(|| format_err!("missing required string argument 'rel_path'"))?;
300            let vm = state.ensure_vm()?;
301            match vm.read_workspace_file(gp, rel)? {
302                Some(bytes) => Ok(json!({
303                    "exists": true,
304                    "bytes": bytes.len(),
305                    "content": String::from_utf8_lossy(&bytes),
306                })),
307                None => Ok(json!({ "exists": false })),
308            }
309        }
310        "vm_commit" => {
311            let gp = args
312                .get("guest_path")
313                .and_then(|v| v.as_str())
314                .ok_or_else(|| format_err!("missing required string argument 'guest_path'"))?;
315            let vm = state.ensure_vm()?;
316            let d = vm.commit_workspace(gp)?;
317            Ok(json!({
318                "committed": true,
319                "guest_path": d.guest_path,
320                "created": d.created,
321                "modified": d.modified,
322                "deleted": d.deleted,
323            }))
324        }
325        "vm_discard" => {
326            let gp = args
327                .get("guest_path")
328                .and_then(|v| v.as_str())
329                .ok_or_else(|| format_err!("missing required string argument 'guest_path'"))?;
330            let vm = state.ensure_vm()?;
331            vm.discard_workspace(gp)?;
332            Ok(json!({ "discarded": true, "guest_path": gp }))
333        }
334        "vm_inspect" => {
335            let max_events = args
336                .get("max_events")
337                .and_then(|v| v.as_u64())
338                .unwrap_or(50) as usize;
339            let (booted, procs, timings) = if let Some(vm) = &state.vm {
340                let procs: Vec<Value> = vm
341                    .active_processes()
342                    .into_iter()
343                    .map(|p| {
344                        json!({
345                            "pid": p.pid,
346                            "tgid": p.tgid,
347                            "ppid": p.ppid,
348                            "comm": p.comm,
349                        })
350                    })
351                    .collect();
352                (true, procs, serde_json::to_value(vm.timings()).ok())
353            } else {
354                (false, Vec::new(), None)
355            };
356            let events: Vec<Value> = {
357                let q = state.audit_ring.lock().unwrap();
358                let skip = q.len().saturating_sub(max_events);
359                q.iter().skip(skip).cloned().collect()
360            };
361            let mut snap_names: Vec<&String> = state.snapshots.keys().collect();
362            snap_names.sort();
363            Ok(json!({
364                "booted": booted,
365                "timings": timings,
366                "snapshots": snap_names,
367                "active_processes": procs,
368                "audit_events": events,
369            }))
370        }
371        other => Err(format_err!("unknown tool: {other}")),
372    }
373}
374
375fn handle_request(state: &mut McpState, req: &Value) -> Option<Value> {
376    let id = req.get("id").cloned();
377    let method = req.get("method").and_then(|m| m.as_str()).unwrap_or("");
378    let params = req.get("params").cloned().unwrap_or(Value::Null);
379
380    // JSON-RPC notifications (no `id`) must not receive a response.
381    let id = id?;
382
383    match method {
384        "initialize" => {
385            let client_ver = params
386                .get("protocolVersion")
387                .and_then(|v| v.as_str())
388                .unwrap_or(MCP_PROTOCOL_VERSION);
389            Some(json!({
390                "jsonrpc": "2.0",
391                "id": id,
392                "result": {
393                    "protocolVersion": client_ver,
394                    "capabilities": {
395                        "tools": {}
396                    },
397                    "serverInfo": {
398                        "name": "unkernel-rs",
399                        "version": env!("CARGO_PKG_VERSION")
400                    }
401                }
402            }))
403        }
404        "ping" => Some(json!({
405            "jsonrpc": "2.0",
406            "id": id,
407            "result": {}
408        })),
409        "tools/list" => Some(json!({
410            "jsonrpc": "2.0",
411            "id": id,
412            "result": {
413                "tools": tool_definitions()
414            }
415        })),
416        "tools/call" => {
417            let tool_name = params.get("name").and_then(|v| v.as_str()).unwrap_or("");
418            let tool_args = params
419                .get("arguments")
420                .cloned()
421                .unwrap_or_else(|| json!({}));
422            match call_tool(state, tool_name, &tool_args) {
423                Ok(result_val) => {
424                    let text = serde_json::to_string_pretty(&result_val)
425                        .unwrap_or_else(|_| result_val.to_string());
426                    Some(json!({
427                        "jsonrpc": "2.0",
428                        "id": id,
429                        "result": {
430                            "content": [{ "type": "text", "text": text }],
431                            "isError": false
432                        }
433                    }))
434                }
435                Err(err) => Some(json!({
436                    "jsonrpc": "2.0",
437                    "id": id,
438                    "result": {
439                        "content": [{ "type": "text", "text": format!("{err:#}") }],
440                        "isError": true
441                    }
442                })),
443            }
444        }
445        _ => Some(json!({
446            "jsonrpc": "2.0",
447            "id": id,
448            "error": {
449                "code": -32601,
450                "message": format!("Method not found: {method}")
451            }
452        })),
453    }
454}
455
456/// Run the MCP JSON-RPC 2.0 server reading newline-delimited requests from `reader`
457/// and writing responses to `writer`. Shuts down the VM cleanly when `reader` reaches EOF.
458pub fn run_mcp_with_io<R: BufRead, W: Write>(
459    cfg: VmConfig,
460    reader: R,
461    mut writer: W,
462) -> Result<()> {
463    let mut state = McpState::new(cfg);
464    for line in reader.lines() {
465        let line = match line {
466            Ok(l) => l,
467            Err(_) => break,
468        };
469        let trimmed = line.trim();
470        if trimmed.is_empty() {
471            continue;
472        }
473        let resp = match serde_json::from_str::<Value>(trimmed) {
474            Ok(req) => handle_request(&mut state, &req),
475            Err(e) => Some(json!({
476                "jsonrpc": "2.0",
477                "id": Value::Null,
478                "error": {
479                    "code": -32700,
480                    "message": format!("Parse error: {e}")
481                }
482            })),
483        };
484        if let Some(resp) = resp {
485            serde_json::to_writer(&mut writer, &resp)?;
486            writer.write_all(b"\n")?;
487            writer.flush()?;
488        }
489    }
490    state.shutdown();
491    Ok(())
492}
493
494/// Run the MCP server on process `stdin` / `stdout` (the standard MCP stdio transport).
495pub fn run_mcp_stdio(cfg: VmConfig) -> Result<()> {
496    let stdin = io::stdin();
497    let stdout = io::stdout();
498    run_mcp_with_io(cfg, stdin.lock(), stdout.lock())
499}