241 lines
13 KiB
Rust
241 lines
13 KiB
Rust
//! `--via-control` end to end (SPEC 10.3): the MCP server forwards tool calls
|
|
//! to a live app over the control channel, the app's gate queues or refuses
|
|
//! them, and a fallback kicks in when no app runs.
|
|
//!
|
|
//! The "app" is a real control server over a writable session, pumped on a
|
|
//! dedicated thread — the same pieces `tests/control.rs` drives, minus the
|
|
//! UI thread.
|
|
|
|
use std::time::Duration;
|
|
|
|
use notescraft_engine::{AppSettings, AssistantSettings, ControlServer, Registry, Session, register_core};
|
|
use serde_json::{Value, json};
|
|
|
|
mod common;
|
|
use common::seed;
|
|
|
|
/// The mcp server options for `--via-control`.
|
|
const VIA_CONTROL: notescraft_mcp::ServerOptions = notescraft_mcp::ServerOptions { write: false, allow_delete: false, via_control: true };
|
|
|
|
/// Spins up a writable app session whose assistant has `settings`, a live
|
|
/// control server over its vault and a pumping thread that never stops (the
|
|
/// test process ends first, the channel closes with the thread).
|
|
fn spun_up_app_with(name: &str, assistant: AssistantSettings) -> common::TempVault {
|
|
let vault = common::temp_vault(name);
|
|
seed(vault.path(), &[("alpha.md", "# Alpha\n\nfirst\n")]);
|
|
let mut app_session = Session::open(vault.path()).expect("open the app session");
|
|
app_session.set_assistant_settings(assistant);
|
|
let mut registry = Registry::new();
|
|
register_core(&mut registry).expect("register the core commands");
|
|
let mut handle = ControlServer::start_with(app_session.vault(), notescraft_engine::ControlOptions::default()).expect("start the control server");
|
|
std::thread::spawn(move || {
|
|
loop {
|
|
let _ = handle.pump(&mut app_session, ®istry);
|
|
std::thread::sleep(Duration::from_millis(2));
|
|
}
|
|
});
|
|
vault
|
|
}
|
|
|
|
/// The writable, reviewing app the forward tests need.
|
|
fn spun_up_app(name: &str) -> common::TempVault {
|
|
spun_up_app_with(name, AssistantSettings { allow_write: true, review_writes: true, ..AssistantSettings::default() })
|
|
}
|
|
|
|
/// An mcp server over a read-only session of `root`, `--via-control` set.
|
|
fn server(root: &std::path::Path, options: notescraft_mcp::ServerOptions) -> notescraft_mcp::Server {
|
|
let session = Session::open_read_only(root).expect("open the mcp session");
|
|
let mut registry = Registry::new();
|
|
register_core(&mut registry).expect("register the core commands");
|
|
notescraft_mcp::Server::new(session, registry, options)
|
|
}
|
|
|
|
/// One JSON-RPC round trip through the server.
|
|
fn roundtrip(server: &mut notescraft_mcp::Server, line: &str) -> Value {
|
|
let reply = server.handle_line(line).expect("a reply");
|
|
serde_json::from_str(&reply).expect("the reply is JSON")
|
|
}
|
|
|
|
/// Calls one tool and returns its structured content.
|
|
fn call(server: &mut notescraft_mcp::Server, name: &str, arguments: &Value) -> Value {
|
|
let reply = roundtrip(server, &json!({ "id": 7, "method": "tools/call", "params": { "name": name, "arguments": arguments } }).to_string());
|
|
reply.get("result").and_then(|result| result.get("structuredContent")).cloned().expect("structured content")
|
|
}
|
|
|
|
/// The tool names of one `tools/list`.
|
|
fn listed(server: &mut notescraft_mcp::Server) -> Vec<String> {
|
|
let reply = roundtrip(server, r#"{"id":2,"method":"tools/list"}"#);
|
|
reply
|
|
.get("result")
|
|
.and_then(|result| result.get("tools"))
|
|
.and_then(Value::as_array)
|
|
.map(|tools| tools.iter().filter_map(|tool| tool.get("name").and_then(Value::as_str)).map(str::to_owned).collect())
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
/// A tool call is forwarded and answered `{"queued": true, …}` by the app.
|
|
#[test]
|
|
fn a_write_is_forwarded_and_queued_by_the_app() {
|
|
let vault = spun_up_app("viactl-forward");
|
|
let mut server = server(vault.path(), VIA_CONTROL);
|
|
let answer = call(&mut server, "note_write", &json!({ "path": "alpha.md", "content": "agent text" }));
|
|
assert_eq!(answer.get("queued").and_then(Value::as_bool), Some(true), "{answer}");
|
|
assert_eq!(answer.get("pending_id").and_then(Value::as_u64), Some(1));
|
|
// Nothing was written to the vault.
|
|
let on_disk = std::fs::read_to_string(vault.path().join("alpha.md")).expect("read alpha");
|
|
assert!(on_disk.contains("first"), "{on_disk}");
|
|
}
|
|
|
|
/// The forwarded `tools/list` comes from the running app: it offers write
|
|
/// tools a local read-only server would never list.
|
|
#[test]
|
|
fn the_tool_list_is_forwarded_from_the_running_app() {
|
|
let vault = spun_up_app("viactl-list");
|
|
let mut forwarder = server(vault.path(), VIA_CONTROL);
|
|
let mut local = server(vault.path(), notescraft_mcp::READ_ONLY);
|
|
let names = listed(&mut forwarder);
|
|
assert!(names.iter().any(|name| name == "write_note"), "the forwarded list offers writes: {names:?}");
|
|
assert!(!names.iter().any(|name| name == "note_write"), "the assistant list leaves out the duplicate command tools: {names:?}");
|
|
assert!(names.len() <= 24, "a compact list keeps the agent's context small: {names:?}");
|
|
assert!(!listed(&mut local).iter().any(|name| name == "note_write"), "the local read-only list hides writes: {:?}", listed(&mut local));
|
|
}
|
|
|
|
/// The app's gate refuses through the forwarder, with its own code.
|
|
#[test]
|
|
fn a_closed_gate_is_refused_through_the_forwarder() {
|
|
let vault = spun_up_app_with("viactl-denied", AssistantSettings::default());
|
|
let mut server = server(vault.path(), VIA_CONTROL);
|
|
let answer = call(&mut server, "note_write", &json!({ "path": "alpha.md", "content": "no" }));
|
|
assert_eq!(answer.get("error").and_then(|error| error.get("code")).and_then(Value::as_str), Some("assistant_denied"), "{answer}");
|
|
}
|
|
|
|
/// Without a running app the server falls back to local execution — a
|
|
/// read-only session refuses the write exactly as `--via-control` absent.
|
|
#[test]
|
|
fn without_an_app_the_call_falls_back_to_local() {
|
|
let vault = common::temp_vault("viactl-fallback");
|
|
seed(vault.path(), &[("alpha.md", "# Alpha\n")]);
|
|
let mut forwarder = server(vault.path(), VIA_CONTROL);
|
|
let answer = call(&mut forwarder, "note_write", &json!({ "path": "alpha.md", "content": "no" }));
|
|
assert_eq!(answer.get("error").and_then(|error| error.get("code")).and_then(Value::as_str), Some("read_only"), "{answer}");
|
|
let on_disk = std::fs::read_to_string(vault.path().join("alpha.md")).expect("read alpha");
|
|
assert!(on_disk.contains("Alpha") && !on_disk.contains("no"), "{on_disk}");
|
|
// Reads still work locally.
|
|
let answer = call(&mut forwarder, "read_note", &json!({ "path": "alpha.md" }));
|
|
assert!(answer.get("content").is_some(), "{answer}");
|
|
}
|
|
|
|
/// The accepted change applies through the app: accept over the channel, then
|
|
/// read the written note.
|
|
#[test]
|
|
fn an_accepted_pending_change_is_applied_by_the_app() {
|
|
let vault = spun_up_app("viactl-accept");
|
|
let mut forwarder = server(vault.path(), VIA_CONTROL);
|
|
let queued = call(&mut forwarder, "note_write", &json!({ "path": "alpha.md", "content": "accepted text" }));
|
|
let pending_id = queued.get("pending_id").and_then(Value::as_u64).expect("the pending id");
|
|
// The user accepts from their own surface: a plain (cli source) call
|
|
// through the same channel, never a `cli` tool call through the gate.
|
|
let answer = call_forwarded_cli(vault.path(), "assistant.accept", &json!({ "id": pending_id }));
|
|
let applied = answer.get("accepted").and_then(Value::as_array).and_then(|rows| rows.first()).and_then(|row| row.get("applied")).and_then(Value::as_bool);
|
|
assert_eq!(applied, Some(true), "{answer}");
|
|
let on_disk = std::fs::read_to_string(vault.path().join("alpha.md")).expect("read alpha");
|
|
assert_eq!(on_disk, "accepted text", "the accept wrote through the normal path");
|
|
}
|
|
|
|
/// One plain `cli`-source control call, for the surface the user drives.
|
|
fn call_forwarded_cli(root: &std::path::Path, id: &str, params: &Value) -> Value {
|
|
use notescraft_engine::ControlClient;
|
|
let mut client = ControlClient::connect(root).expect("connect to the app");
|
|
client.run(id, params).expect("run the user command")
|
|
}
|
|
|
|
/// A composed alias is forwarded the same way: `append_note` reads through the
|
|
/// app and its final `note.write` is queued, so the appended text the dry run
|
|
/// computed lands in the pending change and on disk only once accepted.
|
|
#[test]
|
|
fn a_composed_append_is_dry_run_before_it_is_queued() {
|
|
let vault = spun_up_app("viactl-append");
|
|
let mut forwarder = server(vault.path(), VIA_CONTROL);
|
|
call(&mut forwarder, "append_note", &json!({ "path": "alpha.md", "content": "\nappended line\n" }));
|
|
let on_disk = std::fs::read_to_string(vault.path().join("alpha.md")).expect("read alpha");
|
|
assert_eq!(on_disk, "# Alpha\n\nfirst\n", "the append was queued, not written");
|
|
|
|
// The user's own view of the queue holds the appended text.
|
|
let pending = call_forwarded_cli(vault.path(), "assistant.pending", &json!({}));
|
|
let change = pending.get("pending").and_then(Value::as_array).and_then(|rows| rows.first()).cloned().expect("one pending change");
|
|
assert_eq!(change.get("kind").and_then(Value::as_str), Some("modify"));
|
|
assert_eq!(change.get("old").and_then(Value::as_str), Some("# Alpha\n\nfirst\n"));
|
|
let new = change.get("new").and_then(Value::as_str).expect("the dry run computed the text");
|
|
assert!(new.starts_with("# Alpha\n\nfirst\n") && new.contains("appended line"), "{new}");
|
|
|
|
// Accepting it applies exactly that text through the normal write path.
|
|
let accepted = call_forwarded_cli(vault.path(), "assistant.accept", &json!({ "id": 1 }));
|
|
let applied = accepted.get("accepted").and_then(Value::as_array).and_then(|rows| rows.first()).and_then(|row| row.get("applied")).and_then(Value::as_bool);
|
|
assert_eq!(applied, Some(true), "{accepted}");
|
|
let on_disk = std::fs::read_to_string(vault.path().join("alpha.md")).expect("read alpha");
|
|
assert_eq!(on_disk, new, "the accepted text is what the dry run computed");
|
|
}
|
|
|
|
/// The forwarded list hides what the app reports as disabled: a plugin tool
|
|
/// whose plugin is not enabled is offered neither by name nor by call
|
|
/// (SPEC 10.2), whatever the assistant toggle says.
|
|
#[test]
|
|
fn a_disabled_plugin_tool_is_not_forwarded() {
|
|
use notescraft_engine::{CommandResult, CommandSpec, ParamKind, ParamSpec};
|
|
|
|
#[expect(clippy::unnecessary_wraps, reason = "the registry signature demands CommandResult")]
|
|
fn go(_session: &mut Session, params: &Value) -> CommandResult {
|
|
Ok(params.clone())
|
|
}
|
|
|
|
let vault = common::temp_vault("viactl-plugin-off");
|
|
seed(vault.path(), &[("alpha.md", "# Alpha\n\nfirst\n")]);
|
|
let mut app_session = Session::open(vault.path()).expect("open the app session");
|
|
app_session.set_assistant_settings(AssistantSettings { plugin_tools: [("demo".to_owned(), true)].into(), ..AssistantSettings::default() });
|
|
let mut registry = Registry::new();
|
|
register_core(&mut registry).expect("register the core commands");
|
|
registry
|
|
.register(CommandSpec::new("plugin.demo.go", "Go", "the plugin demo", |_: &Session| false, go).with_param(ParamSpec::optional(
|
|
"args",
|
|
ParamKind::Any,
|
|
"the plugin arguments",
|
|
)))
|
|
.expect("register the plugin command");
|
|
let mut handle = ControlServer::start_with(app_session.vault(), notescraft_engine::ControlOptions::default()).expect("start the control server");
|
|
std::thread::spawn(move || {
|
|
loop {
|
|
let _ = handle.pump(&mut app_session, ®istry);
|
|
std::thread::sleep(Duration::from_millis(2));
|
|
}
|
|
});
|
|
|
|
// The toggle is on in the forwarder too, so only the app's own `enabled`
|
|
// flag can hide the tool.
|
|
let mut session = Session::open_read_only(vault.path()).expect("open the forwarder session");
|
|
let mut settings = AppSettings::default();
|
|
settings.assistant.plugin_tools.insert(String::from("demo"), true);
|
|
session.apply_app_settings(&settings).expect("apply the settings");
|
|
let mut forwarder_registry = Registry::new();
|
|
register_core(&mut forwarder_registry).expect("register the core commands");
|
|
let mut forwarder = notescraft_mcp::Server::new(session, forwarder_registry, VIA_CONTROL);
|
|
let names = listed(&mut forwarder);
|
|
assert!(!names.iter().any(|name| name == "plugin_demo_go"), "the app reports it disabled: {names:?}");
|
|
assert!(names.iter().any(|name| name == "read_note"), "the rest of the app's list comes through");
|
|
}
|
|
|
|
/// The agent asks `create_note`: with the write grant (review off) the note exists and the result says so; without it the
|
|
/// agent gets the gate's `assistant_denied` and nothing is created. This is the call a stub ACP agent makes through the MCP server.
|
|
#[test]
|
|
fn create_note_succeeds_with_the_grant_and_is_refused_without_it() {
|
|
let granted = spun_up_app_with("viactl-create-ok", AssistantSettings { allow_write: true, review_writes: false, ..AssistantSettings::default() });
|
|
let mut open = server(granted.path(), VIA_CONTROL);
|
|
let answer = call(&mut open, "create_note", &json!({ "path": "ideas.md", "content": "# Ideas\n" }));
|
|
assert!(answer.get("error").is_none() && answer.get("queued").is_none(), "{answer}");
|
|
assert_eq!(std::fs::read_to_string(granted.path().join("ideas.md")).ok().as_deref(), Some("# Ideas\n"));
|
|
let closed = spun_up_app_with("viactl-create-no", AssistantSettings::default());
|
|
let mut shut = server(closed.path(), VIA_CONTROL);
|
|
let answer = call(&mut shut, "create_note", &json!({ "path": "ideas.md", "content": "# Ideas\n" }));
|
|
assert_eq!(answer.get("error").and_then(|error| error.get("code")).and_then(Value::as_str), Some("assistant_denied"), "{answer}");
|
|
assert!(!closed.path().join("ideas.md").exists());
|
|
}
|