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);
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}")
}
})),
}
}
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(())
}
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())
}