//! The dispatch's own tests. The tool TABLE is empty until 2c's handler half, //! so what is asserted here is the contract every handler group codes against //! — the refusals, and the fact that a catalogued tool with no implementation //! says so by name rather than pretending to be unknown. use super::*; use crate::mcp::protocol::TOOLS; use cotton_store::file_identity::read_file_identity; #[test] fn no_two_handler_groups_claim_one_tool() { // The registry PANICS on a duplicate; building it is the assertion. let _ = handler_for("create_todo"); } #[test] fn every_catalogued_tool_has_an_implementation() { // The port's own finish line, and the reason it is a TEST rather than a // number somebody quotes: a tool an assistant can SEE and cannot CALL is // the one failure mode a catalogue generated from the TypeScript cannot // catch by itself. The message names the gap so a red run is a to-do list. let missing: Vec<&str> = TOOLS .iter() .filter(|tool| handler_for(tool.name).is_none()) .map(|tool| tool.name) .collect(); assert!( missing.is_empty(), "{} of {} catalogued tools have no handler: {}", missing.len(), TOOLS.len(), missing.join(", ") ); } #[test] fn every_registered_handler_names_a_catalogued_tool() { // A handler for a name the catalogue does not carry is unreachable — the // transport looks the tool up first — so it is a group that misspelled a // name, not a feature. for tool in TOOLS { if let Some(_handler) = handler_for(tool.name) { assert!( crate::mcp::protocol::tool_by_name(tool.name).is_some(), "{}", tool.name ); } } } // ── the phone's own context (design P3) ───────────────────────────────────── /// A workspace on disk, in memory — the fold is what these assert, and a /// mocked driver would prove nothing about the stamps an op carries. fn phone_fixture() -> (cotton_store::driver::Driver, FileIdentity, String) { let workspace_id = "00000000-0000-4000-8000-00000000f0f0".to_string(); let owner_id = "00000000-0000-4000-8000-0000000000bb".to_string(); let db = cotton_store::test_template::create_workspace_in_memory_for_test(&cotton_store::meta::Meta { workspace_id: workspace_id.clone(), owner_id: owner_id.clone(), device_id: "device:phone-fixture".to_string(), last_server_seq: 0, last_hlc: None, }) .expect("a fresh file"); db.run( "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at, _hlc) VALUES (?, ?, \ ?, ?, '')", &[ rusqlite::types::Value::Text(workspace_id.clone()), rusqlite::types::Value::Text("Phone fixture".to_string()), rusqlite::types::Value::Text(owner_id.clone()), rusqlite::types::Value::Text("2026-09-08T10:00:00.000Z".to_string()), ], ) .expect("the workspace row every domain table keys back to"); let file = read_file_identity(&db) .expect("the file reads") .expect("the file is seeded"); (db, file, owner_id) } /// The device id the phone in these tests writes under. Any id would do; what /// matters is that it is NOT `server:mcp`. const PHONE_DEVICE: &str = "device:iphone-7f3c"; /// The owner at a device, for a test: the device's row is seeded if the file /// has none for that key, and the actor names it. `device_id` is the device's /// KEY (`cotton_devices.device_id`), the string the phone contexts here were /// already built with. fn owner_at( db: &cotton_store::driver::Driver, workspace_id: &str, device_id: &str, ) -> cotton_store::actor::Actor { let row_id = format!("row-{device_id}"); db.run( "INSERT OR IGNORE INTO cotton_devices (id, workspace_id, device_id, name, approved_at, \ approved_by_device, created_at, updated_at) VALUES (?, ?, ?, 'Test phone', \ '2026-09-08T09:00:00.000Z', 'self', '2026-09-08T09:00:00.000Z', '2026-09-08T09:00:00.000Z')", &[ rusqlite::types::Value::Text(row_id.clone()), rusqlite::types::Value::Text(workspace_id.to_string()), rusqlite::types::Value::Text(device_id.to_string()), ], ) .expect("the device's row"); cotton_store::actor::Actor::Owner( cotton_store::actor::DeviceId::in_file(db, &row_id).expect("the row names the device"), ) } /// RULE: A write from the phone is asked by the owner at that device and is stamped with the file's author, never with the device id the context was labelled with. #[test] fn a_phone_authored_op_is_stamped_with_the_files_author_and_asked_by_the_owner() { // The whole of the difference between a phone's write and an assistant's, // asserted on the op that lands: stamped `server:mcp`/`agent` instead, // every tap would read as somebody else's in the person's own history — // and two writers sharing one device id collide on the HLC besides. let (db, file, owner_id) = phone_fixture(); let services = ToolServices::none(); let now = "2026-09-08T10:00:00.000Z" .parse::>() .expect("a fixed instant"); let mut ctx = Ctx::phone( &db, &file, &owner_id, PHONE_DEVICE, owner_at(&db, file.id().as_str(), PHONE_DEVICE), cotton_store::mint::Held::Replica, now, Arc::new(crate::random::SystemRandom), &services, ); assert!( ctx.writer().expect("a phone can write").actor().is_owner(), "the owner at the screen" ); let mut args = Map::new(); args.insert("title".to_string(), Value::from("Ring the plumber back")); let answer = call_tool(&mut ctx, "create_todo", &args).expect("the todo is filed"); let id = answer["id"].as_str().expect("the new row's id").to_string(); // The author is read off the ROW's stamp: there is no log any more, and a // stamp ends in the device id that wrote it — which is exactly what another // device's cursor names. let row = db .get( "SELECT substr(_hlc, 20) AS author FROM cotton_todos WHERE id = ?", &[rusqlite::types::Value::Text(id.clone())], ) .expect("the file is readable") .expect("the write landed"); let author = cotton_store::mint::file_author(&db).expect("the file's author"); assert_eq!(row.text("author"), Some(author.as_str())); assert!(author.starts_with("device:"), "{author}"); assert_ne!(row.text("author"), Some(PHONE_DEVICE), "the author is the file's, not the label"); } #[test] fn a_phone_writes_no_audit_row() { // `cotton_mcp_audit` answers "what did an assistant do in my database". A // person tapping a button is not an entry in it — so the tool's own extra // line is a no-op here, and the CALL's row is never written at all because // that row is the server transport's and a phone does not run one. let (db, file, owner_id) = phone_fixture(); let services = ToolServices::none(); let now = "2026-09-08T10:00:00.000Z" .parse::>() .expect("a fixed instant"); let mut ctx = Ctx::phone( &db, &file, &owner_id, PHONE_DEVICE, owner_at(&db, file.id().as_str(), PHONE_DEVICE), cotton_store::mint::Held::Replica, now, Arc::new(crate::random::SystemRandom), &services, ); let mut args = Map::new(); args.insert("title".to_string(), Value::from("Book the van")); call_tool(&mut ctx, "create_todo", &args).expect("the todo is filed"); // And the line a handler writes for itself, which `dev_reveal_secret` uses. ctx.audit("dev_reveal_secret", "opened SAMPLE (one)"); let audited = db .get("SELECT COUNT(*) AS n FROM cotton_mcp_audit", &[]) .expect("the audit table is readable") .expect("count answers a row"); assert_eq!(audited.int("n"), Some(0)); } #[test] fn a_phone_may_call_a_write_tool_where_a_read_only_token_may_not() { // Scopes gate DISPATCH, and a phone calls tools BY NAME — so it carries // both, where a worker (which calls a pipeline directly) carries none. let (db, file, owner_id) = phone_fixture(); let services = ToolServices::none(); let now = "2026-09-08T10:00:00.000Z" .parse::>() .expect("a fixed instant"); let ctx = Ctx::phone( &db, &file, &owner_id, PHONE_DEVICE, owner_at(&db, file.id().as_str(), PHONE_DEVICE), cotton_store::mint::Held::Replica, now, Arc::new(crate::random::SystemRandom), &services, ); assert!(crate::mcp::tokens::has_scope(ctx.scopes, "write")); assert!(crate::mcp::tokens::has_scope(ctx.scopes, "read")); } #[test] fn a_string_limit_is_refused_at_the_mcp_door() { // `limit: "all"` is the owner's APP's spelling — `bounded_limit` reads that // one string as the whole set so a phone screen drawing its own file gets // all of it (Cotton note "The phone and Mac app — how a screen is built"). An assistant's context is // finite, which is the entire reason these tools page, so the escape hatch // is structurally unreachable from MCP rather than merely undocumented: the // phone reaches `handler_for` directly through `cotton-ffi`'s `run_tool` // and never comes through this door. let (db, file, owner_id) = phone_fixture(); let services = ToolServices::none(); let now = "2026-09-12T10:00:00.000Z" .parse::>() .expect("a fixed instant"); let mut ctx = Ctx::phone( &db, &file, &owner_id, PHONE_DEVICE, owner_at(&db, file.id().as_str(), PHONE_DEVICE), cotton_store::mint::Held::Replica, now, Arc::new(crate::random::SystemRandom), &services, ); let mut args = Map::new(); args.insert("limit".to_string(), Value::from("all")); let refusal = call_tool(&mut ctx, "list_people", &args).expect_err("a string limit is refused"); assert!( refusal.to_string().contains("limit must be a number"), "the refusal names the argument: {refusal}" ); // A NUMBER still works, and so does no limit at all — the door refuses one // shape, not the parameter. let mut numbered = Map::new(); numbered.insert("limit".to_string(), Value::from(5)); call_tool(&mut ctx, "list_people", &numbered).expect("a numeric limit is fine"); call_tool(&mut ctx, "list_people", &Map::new()).expect("no limit is fine"); } #[test] fn the_whole_set_spelling_lifts_the_page_at_the_handler() { // The other half: the handler an app reaches directly DOES read it, and // reads it as far past the tool's own ceiling (`MAX_LIST` for `list_people`) as // the fixture goes. A number would clamp; this does not. use crate::mcp::handlers::common::{bounded_limit, WHOLE_SET, WHOLE_SET_LIMIT}; let mut args = Map::new(); args.insert("limit".to_string(), Value::from(WHOLE_SET)); assert_eq!(bounded_limit(&args, 50, 200), WHOLE_SET_LIMIT); // Everything else is unchanged: absent takes the fallback, a number clamps // to the ceiling, and any OTHER string is not a spelling this understands // and falls through to the fallback rather than being read as "all". assert_eq!(bounded_limit(&Map::new(), 50, 200), 50); let mut over = Map::new(); over.insert("limit".to_string(), Value::from(9_000)); assert_eq!(bounded_limit(&over, 50, 200), 200); let mut nonsense = Map::new(); nonsense.insert("limit".to_string(), Value::from("everything")); assert_eq!(bounded_limit(&nonsense, 50, 200), 50); } /// RULE: a list or read tool answers up to MAX_LIST rows in one call, and the /// catalogue says no ceiling past it — nor the old 200. #[test] fn every_list_ceiling_is_the_one_named_cap() { use crate::mcp::handlers::common::{bounded_limit, MAX_LIST}; let mut over = Map::new(); over.insert("limit".to_string(), Value::from(9_000)); assert_eq!(bounded_limit(&over, 50, MAX_LIST), 5000); for tool in crate::mcp::catalogue::TOOLS { let schema: Value = serde_json::from_str(tool.input_schema).expect("a schema"); let Some(ceiling) = schema["properties"]["limit"]["maximum"].as_i64() else { continue }; assert!(ceiling <= MAX_LIST && ceiling != 200, "{}: limit at most {ceiling}", tool.name); } let list_records = crate::mcp::catalogue::TOOLS.iter().find(|tool| tool.name == "list_records").expect("list_records"); let schema: Value = serde_json::from_str(list_records.input_schema).expect("a schema"); assert_eq!(schema["properties"]["limit"]["maximum"], serde_json::json!(MAX_LIST)); assert_eq!(schema["properties"]["ids"]["maxItems"], serde_json::json!(MAX_LIST)); } // ── what a dispatcher does before it takes the file ───────────────────────── fn scopes(names: &[&str]) -> Vec { names.iter().map(|name| (*name).to_string()).collect() } fn args(value: Value) -> Map { value.as_object().expect("an object of arguments").clone() } const DOCUMENT: &str = "11111111-2222-4333-8444-555555555555"; #[test] fn a_search_by_meaning_is_embedded_before_the_file_and_a_text_search_is_not() { let services = ToolServices::none(); let reader = scopes(&["read"]); for mode in ["meaning", "both"] { assert_eq!( before_the_file( &reader, &services, "search_records", &args(serde_json::json!({ "query": " payment split ", "mode": mode })), ), // As the handler reads it: `query` arrives trimmed. Some(BeforeTheFile::EmbedQuery { query: "payment split".to_string() }), "{mode}" ); } // The default mode never reaches for the network, and neither does its // dispatcher. assert_eq!( before_the_file( &reader, &services, "search_records", &args(serde_json::json!({ "query": "ferry" })), ), None ); // A call the handler refuses spends nothing first. assert_eq!( before_the_file( &reader, &services, "search_records", &args(serde_json::json!({ "query": "ferry", "mode": "sideways" })), ), None ); } #[test] fn a_password_guess_is_run_before_the_file_only_for_a_call_that_may_make_it() { let services = ToolServices::none(); let guess = args(serde_json::json!({ "documentId": DOCUMENT, "passwordCandidates": [" hunter2 ", ""], })); assert_eq!( before_the_file(&scopes(&["read", "write"]), &services, "update_document", &guess), Some(BeforeTheFile::TryPasswords { document_id: DOCUMENT.to_string(), candidates: vec!["hunter2".to_string()], }) ); // THE SAME GATE THE CALL MEETS: a read-only token is refused by // `call_tool`, so nothing runs on its behalf first. assert_eq!( before_the_file(&scopes(&["read"]), &services, "update_document", &guess), None ); // An edit with no passwords runs no pipeline. assert_eq!( before_the_file( &scopes(&["read", "write"]), &services, "update_document", &args(serde_json::json!({ "documentId": DOCUMENT, "title": "A title" })), ), None ); // Over the cap is the handler's refusal, not a run of the first few. let cap = crate::mcp::handlers::documents::tools::DOCUMENT_MAX_PASSWORD_CANDIDATES; let too_many: Vec = (0..=cap).map(|n| format!("guess-{n}")).collect(); assert_eq!( before_the_file( &scopes(&["read", "write"]), &services, "update_document", &args(serde_json::json!({ "documentId": DOCUMENT, "passwordCandidates": too_many })), ), None ); } // ── the machines scope ────────────────────────────────────────────────────── /// RULE: a `machines` tool — `create_session`, `open_project_conversation` and every `dev_` tool — is refused without both `machines` and `write`, with a sentence naming the scope. /// Only a personal token may start work on the owner's Macs; the read+write pair every token holds today, and an assistant run's scopes, must not stand in for it. #[test] fn machines_scope_required_for_session_and_dev_tools() { let words = |values: &[&str]| -> Vec { values.iter().map(|value| (*value).to_string()).collect() }; for name in [ "create_session", "open_project_conversation", "dev_reveal_secret", ] { let mut tool = *tool_by_name(name).expect("catalogued"); tool.scope = McpScope::Machines; let refused = machines_refusal(&tool, &words(&["read", "write"])) .unwrap_or_else(|| panic!("{name} admitted without machines")); assert_eq!( refused.message(), format!( "`{name}` needs the \"machines\" scope: only a personal token may start work on \ your Macs. Ask the owner to reconnect with machines enabled." ) ); assert!(machines_refusal(&tool, &words(&["read", "machines"])).is_some()); assert!(machines_refusal(&tool, &words(&["machines", "write"])).is_none()); assert!(machines_refusal(&tool, phone_scopes()).is_none()); } // A tool of any other scope is not this check's to refuse. let todo = tool_by_name("create_todo").expect("catalogued"); assert!(machines_refusal(todo, &words(&["read"])).is_none()); }