use std::sync::Arc;
use incurs::cli::Cli;
use incurs::command::{CommandDef, McpAnnotations, McpCommandOptions, TypedContext, TypedResult};
use incurs::mcp::{McpDiscovery, McpServeOptions, McpToolFilter};
use crate::engine::VmEngine;
use crate::model::{
CancelOutput, ExecutionEventsInput, ExecutionEventsOutput, ExecutionIdInput,
ExecutionInputInput, ExecutionSignalInput, ExecutionStartInput, ExecutionStartOutput,
InputOutput, IsolationStatus, IsolationWarmupInput, ProviderError, SignalOutput,
};
use crate::registry::ExecutionRegistry;
#[derive(Clone)]
pub struct App {
engine: Arc<dyn VmEngine>,
registry: ExecutionRegistry,
}
impl App {
pub fn new(engine: Arc<dyn VmEngine>) -> Self {
Self {
registry: ExecutionRegistry::new(Arc::clone(&engine)),
engine,
}
}
}
pub fn build_cli(app: App) -> Cli {
Cli::create("apoc-macos-vz")
.description("Native Rust Virtualization.framework execution provider for apoc")
.version(env!("CARGO_PKG_VERSION"))
.mcp(McpServeOptions {
version: Some(env!("CARGO_PKG_VERSION").to_string()),
instructions: Some(
"Run apoc-owned isolated executions through the native Rust VZ host.".to_string(),
),
tools: McpToolFilter {
discovery: McpDiscovery::Direct,
..McpToolFilter::default()
},
..McpServeOptions::default()
})
.group(execution_cli(app.clone()))
.group(isolation_cli(app))
}
fn execution_cli(app: App) -> Cli {
Cli::create("execution")
.command(
"start",
CommandDef::typed::<(), ExecutionStartInput, (), ExecutionStartOutput, _, _>(
"start",
{
let app = app.clone();
move |context: TypedContext<(), ExecutionStartInput, ()>| {
let app = app.clone();
async move { TypedResult::ok(app.registry.start(context.options).await) }
}
},
)
.description("Accept one isolated execution and return its provider identity.")
.mcp(write_tool("execution_start"))
.destructive(true)
.done(),
)
.command(
"events",
CommandDef::typed::<(), ExecutionEventsInput, (), ExecutionEventsOutput, _, _>(
"events",
{
let app = app.clone();
move |context: TypedContext<(), ExecutionEventsInput, ()>| {
let app = app.clone();
async move { result(app.registry.events(context.options).await) }
}
},
)
.description("Read provider events after one cursor with a bounded wait.")
.mcp(read_tool("execution_events"))
.done(),
)
.command(
"cancel",
CommandDef::typed::<(), ExecutionIdInput, (), CancelOutput, _, _>("cancel", {
let app = app.clone();
move |context: TypedContext<(), ExecutionIdInput, ()>| {
let app = app.clone();
async move { result(app.registry.cancel(context.options).await) }
}
})
.description("Cancel one accepted isolated execution.")
.mcp(write_tool("execution_cancel"))
.destructive(true)
.done(),
)
.command(
"input",
CommandDef::typed::<(), ExecutionInputInput, (), InputOutput, _, _>("input", {
let app = app.clone();
move |context: TypedContext<(), ExecutionInputInput, ()>| {
let app = app.clone();
async move { result(app.registry.input(context.options).await) }
}
})
.description("Write base64-decoded bytes to one active isolated execution.")
.mcp(write_tool("execution_input"))
.destructive(true)
.done(),
)
.command(
"signal",
CommandDef::typed::<(), ExecutionSignalInput, (), SignalOutput, _, _>("signal", {
move |context: TypedContext<(), ExecutionSignalInput, ()>| {
let app = app.clone();
async move { result(app.registry.signal(context.options).await) }
}
})
.description("Send one named signal to an active isolated execution.")
.mcp(write_tool("execution_signal"))
.destructive(true)
.done(),
)
}
fn isolation_cli(app: App) -> Cli {
Cli::create("isolation")
.command(
"status",
CommandDef::typed::<(), (), (), IsolationStatus, _, _>("status", {
let app = app.clone();
move |_context: TypedContext<(), (), ()>| {
let app = app.clone();
async move { result(app.engine.status()) }
}
})
.description("Return native VZ image, pool, snapshot, memory, and boot state.")
.mcp(read_tool("isolation_status"))
.done(),
)
.command(
"warmup",
CommandDef::typed::<(), IsolationWarmupInput, (), IsolationStatus, _, _>("warmup", {
let app = app.clone();
move |context: TypedContext<(), IsolationWarmupInput, ()>| {
let app = app.clone();
async move { result(app.engine.warmup(context.options).await) }
}
})
.description("Initialize the verified image and wait for one usable VM.")
.mcp(write_tool("isolation_warmup"))
.destructive(true)
.done(),
)
.command(
"drain",
CommandDef::typed::<(), (), (), IsolationStatus, _, _>("drain", {
move |_context: TypedContext<(), (), ()>| {
let app = app.clone();
async move { result(app.engine.drain().await) }
}
})
.description(
"Dispose of every idle native VZ VM and prevent new checkout during drain.",
)
.mcp(write_tool("isolation_drain"))
.destructive(true)
.done(),
)
}
fn result<T>(value: Result<T, ProviderError>) -> TypedResult<T> {
match value {
Ok(value) => TypedResult::ok(value),
Err(error) => TypedResult::error(error.code, error.message),
}
}
fn read_tool(name: &str) -> McpCommandOptions {
McpCommandOptions {
name: Some(name.to_string()),
annotations: Some(McpAnnotations {
read_only_hint: Some(true),
destructive_hint: Some(false),
idempotent_hint: Some(true),
open_world_hint: Some(false),
..McpAnnotations::default()
}),
..McpCommandOptions::default()
}
}
fn write_tool(name: &str) -> McpCommandOptions {
McpCommandOptions {
name: Some(name.to_string()),
annotations: Some(McpAnnotations {
read_only_hint: Some(false),
destructive_hint: Some(true),
idempotent_hint: Some(false),
open_world_hint: Some(true),
..McpAnnotations::default()
}),
destructive: true,
..McpCommandOptions::default()
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use super::*;
use crate::engine::UnavailableEngine;
#[test]
fn generated_catalog_exposes_only_the_native_vz_contract() {
let definitions = build_cli(App::new(Arc::new(UnavailableEngine)))
.tool_catalog()
.definitions()
.into_iter()
.map(|definition| (definition.name.clone(), definition))
.collect::<BTreeMap<_, _>>();
let expected = [
"execution_start",
"execution_events",
"execution_cancel",
"execution_input",
"execution_signal",
"isolation_status",
"isolation_warmup",
"isolation_drain",
];
assert_eq!(definitions.len(), expected.len());
for name in expected {
let definition = definitions
.get(name)
.unwrap_or_else(|| panic!("missing generated tool {name}"));
assert!(definition.input_schema.as_object().is_some());
assert!(definition.output_schema.is_some());
assert!(definition.annotations.is_some());
}
let start = &definitions["execution_start"].input_schema;
assert_eq!(start["properties"]["env"]["type"], "array");
assert_eq!(start["properties"]["exports"]["type"], "array");
assert!(start["properties"].get("options").is_none());
for field in [
"image_ref",
"vm_bundle",
"workspace",
"memory_mb",
"cpu_count",
"pids_max",
"network",
] {
assert!(
start["properties"].get(field).is_some(),
"missing typed launch field {field}"
);
}
}
}