//! Minting a connection and calling a tool — this crate's half of what //! `cotton-server`'s `support::mcp` does over HTTP. //! //! The SAME function names and the SAME signatures, deliberately: a suite that //! moved here reads exactly as it read there, so a reviewer comparing the two //! is comparing the assertions rather than the scaffolding. What changed is one //! layer — `rpc("tools/call")` over axum became `dispatch::call_tool` over the //! driver — and the answer is shaped by the very functions the transport shapes //! it with (`tool_text`, `is_raw_tool_content`), so an assertion about //! `isError` or about a content block is asserting the real envelope. //! //! WHAT IS NOT HERE, on purpose: minting. `POST /v1/mcp-tokens` is an owner //! route signed by an approved device, and what it produces is a row in the //! person's file — a transport fact, with its own suite in `cotton-server`. //! [`mint_token`] here registers a NAME and a SET OF SCOPES, which is all a //! handler has ever seen of a connection. #![allow(dead_code)] use cotton_tools::clock::Clock; use cotton_tools::mcp::dispatch::{self, Ctx}; use cotton_tools::mcp::protocol::{is_raw_tool_content, tool_by_name, tool_text, McpScope}; use cotton_tools::mcp::tokens::has_scope; use serde_json::{Map, Value}; use super::harness::Harness; /// Register a connection with these scopes and hand back its key. /// /// `&mut Harness` rather than `&Harness` so the call site reads as it did on /// the server, where minting really did approve a device and change the file. pub fn mint_token(h: &mut Harness, scopes: &[&str], name: &str) -> String { h.connect(scopes, name) } /// The same, for a suite holding an immutable harness. pub fn mint_token_ref(h: &Harness, scopes: &[&str], name: &str) -> String { h.connect(scopes, name) } /// What a tool answered — error or not, and the text it carried. pub struct ToolAnswer { pub is_error: bool, pub text: String, /// The whole result envelope: `{ content, isError }`, the object the /// JSON-RPC layer puts under `result`. For the two tools that answer with /// protocol content blocks rather than a JSON string. pub result: Value, } impl ToolAnswer { /// The JSON its text content carries. Panics with the sentence when the /// tool refused, rather than letting a parse fail somewhere unhelpful. pub fn json(&self) -> Value { assert!(!self.is_error, "the tool refused: {}", self.text); serde_json::from_str(&self.text) .unwrap_or_else(|error| panic!("not JSON ({error}): {}", self.text)) } } /// The raw answer, error or not — for the refusals a tool is SUPPOSED to give. pub fn call_tool_raw(h: &Harness, secret: &str, name: &str, args: Value) -> ToolAnswer { // A row a case wrote past the receipts gets them before the tool folds. super::harness::reconcile_all(&h.db); call_tool_in_prepared_file(h, secret, name, args) } /// Run the real handler on a fixture that is already prepared. Performance /// guards use this to measure the handler without repairing every unrelated /// raw fixture row first; ordinary tests keep using `call_tool_raw`. pub fn call_tool_in_prepared_file(h: &Harness, secret: &str, name: &str, args: Value) -> ToolAnswer { let connection = h.connection(secret); let args: Map = match args { Value::Object(args) => args, Value::Null => Map::new(), other => panic!("a tool's arguments are an object, not {other}"), }; // A write client only for a write tool, and only when the connection // carries the scope — the transport's own rule, kept here because a // read-only connection getting a writer is exactly what `Ctx::writer`'s // refusal exists to stop. let can_write = tool_by_name(name).is_some_and(|tool| { tool.scope == McpScope::Write && cotton_tools::mcp::lane_scope::may_write(&connection.scopes, tool) }); let audit = |tool: &str, summary: &str| h.record_audit(tool, summary); let result = { let mut ctx = Ctx::new( &h.db, &h.file, &h.owner_id, &connection.name, &connection.id, &connection.scopes, h.clock.now(), std::sync::Arc::clone(&h.random), can_write.then(|| { cotton_store::actor::Actor::Token( cotton_store::actor::TokenId::in_file(&h.db, &connection.id) .expect("the registered connection has a token actor"), ) }), &h.services.services, &audit, ); dispatch::call_tool(&mut ctx, name, &args) }; let envelope = match result { Ok(value) if is_raw_tool_content(&value) => serde_json::json!({ "content": value["content"].clone(), "isError": false, }), Ok(value) => tool_text(&value.to_string(), false), // A tool that ran and failed reports IN the result, not as a protocol // error — the model can read this and correct itself. Err(failure) => tool_text(failure.message(), true), }; ToolAnswer { is_error: envelope["isError"] == Value::Bool(true), text: envelope["content"][0]["text"] .as_str() .unwrap_or_default() .to_string(), result: envelope, } } /// Call a tool and parse the JSON its text content carries. pub fn call_tool(h: &Harness, secret: &str, name: &str, args: Value) -> Value { call_tool_raw(h, secret, name, args).json() } /// The same call, made by a caller whose request a PAIRED DEVICE's key signed /// (`Ctx::signed_by`, v13). /// /// `device_id` is a CREDENTIAL id — base64url of a raw Ed25519 public key, the /// string `cotton_devices.device_id` holds — never the replica's author id. No /// transport carries one into a tool call yet; this is what a transport that /// did would hand the handler, and it is how `log_session`'s attribution is /// driven. pub fn call_tool_signed_by( h: &Harness, secret: &str, device_id: &str, name: &str, args: Value, ) -> ToolAnswer { let connection = h.connection(secret); // A row a case wrote past the receipts gets them before the tool folds. super::harness::reconcile_all(&h.db); let args: Map = match args { Value::Object(args) => args, Value::Null => Map::new(), other => panic!("a tool's arguments are an object, not {other}"), }; let can_write = tool_by_name(name).is_some_and(|tool| tool.scope == McpScope::Write) && has_scope(&connection.scopes, "write"); let audit = |tool: &str, summary: &str| h.record_audit(tool, summary); let result = { let mut ctx = Ctx::new( &h.db, &h.file, &h.owner_id, &connection.name, &connection.id, &connection.scopes, h.clock.now(), std::sync::Arc::clone(&h.random), can_write.then(|| cotton_tools::mcp::writer::job("test")), &h.services.services, &audit, ) .signed_by(device_id); dispatch::call_tool(&mut ctx, name, &args) }; let envelope = match result { Ok(value) if is_raw_tool_content(&value) => serde_json::json!({ "content": value["content"].clone(), "isError": false, }), Ok(value) => tool_text(&value.to_string(), false), Err(failure) => tool_text(failure.message(), true), }; ToolAnswer { is_error: envelope["isError"] == Value::Bool(true), text: envelope["content"][0]["text"] .as_str() .unwrap_or_default() .to_string(), result: envelope, } } /// The whole result envelope — `{ content, isError }` — for the suites that /// read a content BLOCK rather than the JSON inside a text one. pub fn call_tool_result(h: &Harness, secret: &str, name: &str, args: Value) -> Value { call_tool_raw(h, secret, name, args).result } // ── the owner's own app ───────────────────────────────────────────────────── // // Appended in 4p, when `McpScope::Owner` arrived. Everything above builds a // `Ctx::new` from a TOKEN's scopes, which is the only caller the server has; // the phone is a different constructor with a different stamp, and an owner // tool is only reachable through it. /// Call a tool as the OWNER'S OWN APP — `Ctx::phone`, the constructor the /// device build uses. /// /// The whole difference from [`call_tool_raw`] is the context: `Ctx::phone` /// carries `owner`, `read` and `write`, writes under a DEVICE id with actor /// role `user`, and audits nothing. A suite asserting "the owner may and an /// assistant may not" needs both halves, and the assistant's half is already /// `call_tool_raw` with a write-scope token. /// 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. pub 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"), ) } pub fn call_tool_as_owner(h: &Harness, device_id: &str, name: &str, args: Value) -> ToolAnswer { // A row a case wrote past the receipts gets them before the tool folds. super::harness::reconcile_all(&h.db); let args: Map = match args { Value::Object(args) => args, Value::Null => Map::new(), other => panic!("a tool's arguments are an object, not {other}"), }; let result = { let mut ctx = Ctx::phone( &h.db, &h.file, &h.owner_id, device_id, owner_at(&h.db, &h.workspace_id, device_id), cotton_store::mint::Held::Replica, h.clock.now(), std::sync::Arc::clone(&h.random), &h.services.services, ); dispatch::call_tool(&mut ctx, name, &args) }; let envelope = match result { Ok(value) if is_raw_tool_content(&value) => serde_json::json!({ "content": value["content"].clone(), "isError": false, }), Ok(value) => tool_text(&value.to_string(), false), Err(failure) => tool_text(failure.message(), true), }; ToolAnswer { is_error: envelope["isError"] == Value::Bool(true), text: envelope["content"][0]["text"] .as_str() .unwrap_or_default() .to_string(), result: envelope, } }