//! The MCP protocol layer — the tool catalogue's types, //! and the four helpers a tool result is built from. //! //! PURE: no clock, no network, no database, so the part most likely to be //! wrong is exercised directly. //! //! The catalogue ITSELF is `catalogue` (design S5) — 183 hand-written //! `ToolDef`s whose descriptions are the assistant-facing API. Argument //! VALIDATION (`validateX`) is hand-written control flow with its own refusal //! sentences and is ported per tool group; nothing here validates anything. use serde_json::{Map, Value}; pub use crate::mcp::catalogue::{PROTOCOL_VERSION, SERVER_NAME, SERVER_TITLE, SERVER_VERSION, TOOLS}; // ── the tool catalogue's types ────────────────────────────────────────────── /// What a caller may do. Four words, and the tool declares which one it needs. /// /// `Read` and `Write` are what a PASTED CREDENTIAL can carry: `cotton_mcp_tokens` /// grants one or both, the OAuth grant parses one or both, and `tools/list` is /// filtered by them. /// /// **`Owner` is not grantable and never will be.** It is the third answer to /// "who is asking" rather than a wider grant of the same kind: the owner's own /// app, holding a device key the owner approved, is not a credential somebody /// connected an assistant with. An Owner tool is therefore ABSENT from /// `tools/list` for every token — no token carries the word, so /// [`tool_catalogue`]'s own filter drops it with nothing special written — and a /// call to one is refused by [`crate::mcp::dispatch::call_tool`] with a sentence /// naming the scope. [`crate::mcp::dispatch::Ctx::phone`] is the one context /// that carries it. /// /// **`Machines` is what starts work on the owner's Macs** — a session, a /// project conversation, a message to a running session, every `dev_` tool. /// Only a PERSONAL token may hold it (the server drops the word at /// authentication for any other), and a `Machines` tool also needs `write`: /// it is listed and admitted only to a caller holding both /// ([`grants`]). No mint offers it yet, so today no token holds it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum McpScope { Read, Write, Owner, Machines, } impl McpScope { pub fn as_str(self) -> &'static str { match self { McpScope::Read => "read", McpScope::Write => "write", McpScope::Owner => "owner", McpScope::Machines => "machines", } } } /// Do these scopes reach a tool that declared `scope`? /// /// One word for every scope but `Machines`, which needs `machines` AND /// `write`: starting work on a Mac writes, and a read-only connection that /// somehow carried `machines` must not start a session. The one predicate both /// [`listed_to`] and the dispatcher's admission ask, so a tool is never listed /// to a caller its dispatch refuses. pub fn grants(granted_scopes: &[String], scope: McpScope) -> bool { let holds = |word: &str| granted_scopes.iter().any(|granted| granted == word); // A lane token reads, whatever else its row carries; its one write door // is admitted on its own (`crate::mcp::lane_scope::door`). if crate::mcp::lane_scope::lane_of(granted_scopes).is_some() { return scope == McpScope::Read && holds(McpScope::Read.as_str()); } match scope { McpScope::Machines => holds(McpScope::Machines.as_str()) && holds(McpScope::Write.as_str()), other => holds(other.as_str()), } } /// MCP tool annotations — what a client may assume BEFORE it calls. /// /// REQUIRED, not optional, so a tool that never chose cannot be written. The /// choice is the whole point: a missing `destructiveHint` on `delete_document` /// deletes with no prompt, and an invented one on `create_todo` makes Claude /// ask permission every time it files a todo. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Annotations { pub read_only_hint: bool, pub destructive_hint: bool, /// Only where a second identical call lands where the first one did. /// ABSENT rather than `false` where it does not hold — an absent field is /// absent on the wire too. pub idempotent_hint: Option, /// Always false: every tool touches the owner's own file, nothing else. pub open_world_hint: bool, } impl Annotations { /// The object a client is shown, in the key order the TypeScript emits. pub fn to_json(&self) -> Value { let mut out = Map::new(); out.insert("readOnlyHint".to_string(), Value::Bool(self.read_only_hint)); out.insert( "destructiveHint".to_string(), Value::Bool(self.destructive_hint), ); if let Some(idempotent) = self.idempotent_hint { out.insert("idempotentHint".to_string(), Value::Bool(idempotent)); } out.insert( "openWorldHint".to_string(), Value::Bool(self.open_world_hint), ); Value::Object(out) } } /// One tool, as the generated catalogue declares it. #[derive(Debug, Clone, Copy)] pub struct ToolDef { pub name: &'static str, pub title: &'static str, /// The AI-facing API. Written for a model choosing between tools. pub description: &'static str, pub scope: McpScope, pub annotations: Annotations, /// The JSON Schema, as the string the TypeScript stringifies to. Held as /// TEXT rather than a parsed tree because a `Value` cannot be a `const` /// and because the bytes are the thing that must not drift. pub input_schema: &'static str, /// Run this tool OUTSIDE the workspace write lock. /// /// The default is inside it, which is right for a tool that reads and /// writes a few rows. It is wrong for a tool that runs a whole document /// pipeline — model-seconds long, and every one of them a second in which /// the sync route cannot accept a push, so the owner's phone shows a sync /// failure for a workspace that is working perfectly. pub outside_write_lock: bool, } impl ToolDef { /// The schema as a tree. Parsed on demand: the catalogue is 183 small /// documents and `tools/list` is not a hot path, so a cache would buy a /// microsecond and cost a lifetime. pub fn input_schema_json(&self) -> Value { serde_json::from_str(self.input_schema).unwrap_or_else(|error| { // Generated data. A schema that will not parse is a generator bug, // and answering with `{}` would ship a tool whose arguments no // client could discover. panic!( "cotton-mcp: {}'s inputSchema is not JSON — {error}", self.name ) }) } } /// `serverInfo`, as `initialize` answers it. pub fn server_info() -> Value { let mut out = Map::new(); out.insert("name".to_string(), Value::from(SERVER_NAME)); out.insert("title".to_string(), Value::from(SERVER_TITLE)); out.insert("version".to_string(), Value::from(SERVER_VERSION)); Value::Object(out) } pub fn tool_by_name(name: &str) -> Option<&'static ToolDef> { TOOLS.iter().find(|tool| tool.name == name) } // ── the developer tools ───────────────────────────────────────────────────── /// What every developer-only tool's name starts with. /// /// **THE NAME IS THE DECLARATION.** A `dev_only: bool` on [`ToolDef`] would /// have been a second place to say the same thing — 221 existing entries each /// writing `false`, and one new tool able to ship with the field forgotten. The /// prefix cannot be forgotten: it is how the tool is called, it is what the /// owner asked for ("tools prefixed `dev_`"), and it is what a person reading a /// transcript sees. [`crate::mcp::surface::DEV_TOOLS`] names them once more so /// the grid stays total, and `tool_surface_tests` holds the two sets equal in /// both directions. pub const DEV_TOOL_PREFIX: &str = "dev_"; /// Is this a developer tool — one that exists only while the server's own /// `COTTON_DEV_TOOLS` switch is on? pub fn is_dev_tool(name: &str) -> bool { name.starts_with(DEV_TOOL_PREFIX) } /// What a developer tool answers on a server whose switch is off. /// /// ONE sentence, in one place, naming the switch and the file it lives in — so /// a model meets a closed door it can explain to the person rather than six /// differently-worded refusals. It says DO NOT RETRY for the reason /// `vault_unavailable` does: nothing the assistant can do will change the /// answer, and a retry loop against a server setting is a wasted turn. pub fn dev_tools_off(name: &str) -> ToolFailure { ToolFailure::new(format!( "dev_tools_off: `{name}` is a developer tool and this server has them switched off. They \ are on only while COTTON_DEV_TOOLS=1 is set in the Mac's {{dataDir}}/env and the server \ has been restarted. Nothing was done. Do not retry." )) } /// The refusal of a tool that is not in the database the call runs in: the /// server's for a personal-only tool asked of a seat or project token, and /// [`no_such_tool_here`]'s for a held-only tool a database does not hold. pub const NO_SUCH_TOOL_HERE: &str = "no such tool here"; /// A verb of a tool asked of a database that does not hold it: the sentence /// names the tool and how it arrives. pub fn no_such_tool_here(tool_id: &str) -> ToolFailure { ToolFailure::new(format!( "{NO_SUCH_TOOL_HERE}: {tool_id} is not in this database. import_tool brings it here, or name the database that holds it." )) } /// Is this tool shown to a caller holding these scopes? /// /// THE one listing predicate, and every surface that offers a set of tools to /// something that will read their descriptions goes through it: `tools/list` /// below, and the assistant run's own tool offer /// (`cotton-server`'s `assistant::deny::allowed`). Two implementations of /// "which tools may this caller see" would eventually disagree, and the way /// they disagree is a tool nobody meant to offer arriving in a model's context. /// /// `dev_tools` is the server's own `COTTON_DEV_TOOLS` switch, and it is a /// PARAMETER rather than a lookup for the same reason the scopes are: this /// function is pure, and every surface that lists has to answer the question /// rather than inherit somebody else's answer. A developer tool on a server /// with the switch off is listed to nobody at all — not even to the owner's own /// app, which carries every scope there is. /// /// An OWNER tool is seen by no caller at all, because [`McpScope::Owner`] is /// not a word a token — or an agent run — can carry. That is the whole of the /// rule and it needs no clause of its own: a scope nothing grants matches /// nothing. So an owner-scope tool never has to be spelled into a deny list to /// be kept out of a set, and spelling it there would be the weaker defence — /// the next owner-scope tool would arrive unlisted and undenied. pub fn listed_to(granted_scopes: &[String], tool: &ToolDef, dev_tools: bool) -> bool { if is_dev_tool(tool.name) && !dev_tools { return false; } grants(granted_scopes, tool.scope) || crate::mcp::lane_scope::door_listed(granted_scopes, tool) } /// What `tools/list` returns — the catalogue minus our own scope bookkeeping. /// /// Filtered by the token's scopes through [`listed_to`], so a read-only /// connection never sees a write tool it would only be refused for, and no /// connection sees an owner tool. pub fn tool_catalogue(granted_scopes: &[String], dev_tools: bool) -> Vec { TOOLS .iter() .filter(|tool| listed_to(granted_scopes, tool, dev_tools)) .map(|tool| { let mut out = Map::new(); out.insert("name".to_string(), Value::from(tool.name)); out.insert("title".to_string(), Value::from(tool.title)); out.insert("description".to_string(), Value::from(tool.description)); out.insert("inputSchema".to_string(), tool.input_schema_json()); out.insert("annotations".to_string(), tool.annotations.to_json()); Value::Object(out) }) .collect() } // ── tool results ──────────────────────────────────────────────────────────── /// A tool that ran and FAILED reports through the tool result (`isError`), not /// through a JSON-RPC error: a protocol error means "your call was malformed", /// and an assistant that cannot tell the two apart retries the wrong one. pub fn tool_text(text: &str, is_error: bool) -> Value { let mut block = Map::new(); block.insert("type".to_string(), Value::from("text")); block.insert("text".to_string(), Value::from(text)); let mut out = Map::new(); out.insert( "content".to_string(), Value::Array(vec![Value::Object(block)]), ); out.insert("isError".to_string(), Value::Bool(is_error)); if is_error && text == cotton_core::genesis::NO_PERSONAL_MESSAGE { out.insert("structuredContent".into(), serde_json::json!({ "error_code": cotton_core::genesis::NO_PERSONAL_DATABASE_IN_FLAVOUR, "message": text, })); } Value::Object(out) } /// A tool result that is already MCP content blocks, not a JSON object to /// stringify. The seam exists for `get_document_bytes`: a file travels as a /// base64 `resource`/`image` block — the protocol's own shape for binary — and /// wrapping that in a JSON string would hand the client text it cannot /// materialize as a file. pub fn tool_content(content: Vec) -> Value { let mut out = Map::new(); out.insert("rawContent".to_string(), Value::Bool(true)); out.insert("content".to_string(), Value::Array(content)); Value::Object(out) } pub fn is_raw_tool_content(result: &Value) -> bool { result.as_object().is_some_and(|object| { object.get("rawContent") == Some(&Value::Bool(true)) && object.get("content").is_some_and(Value::is_array) }) } // ── the failure a tool reports IN its result ──────────────────────────────── /// A tool that ran and failed. Reported as `isError: true` with a plain /// sentence the model can read and correct itself from — never as a JSON-RPC /// error, which means "your call was malformed". A refusal with a typed kind /// (`no_tool_draws_this_table`) carries it beside its words, so whoever /// answers it knows it by the kind and never by a sentence a database may /// reword. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] #[error("{0}")] pub struct ToolFailure(pub String, pub Option<&'static str>); impl ToolFailure { pub fn new(message: impl Into) -> ToolFailure { ToolFailure(message.into(), None) } /// A refusal of typed `kind`, said in `message`. pub fn kinded(kind: &'static str, message: impl Into) -> ToolFailure { ToolFailure(message.into(), Some(kind)) } /// The refusal's typed kind, when it has one. pub fn kind(&self) -> Option<&'static str> { self.1 } pub fn message(&self) -> &str { &self.0 } } #[cfg(test)] #[path = "protocol_tests.rs"] mod tests;