Cotton code
1121 lines · 51.6 KB · RustRaw
//! The tool table: every tool name, each to its implementation.//!//! ============================================================================//! THE CONTRACT THE HANDLER GROUPS CODE AGAINST (design S6). One module per//! handler file of `packages/server/src/mcp/` — `records`, `projects`,//! `emails`, `money`, `documents`, `session_bus`,//! `feedback`, `albums`, `thoughts`, `calls`, `moods`,//! `people_suggestions`, `media_analysis`, `bin`, `photos`, `videos`,//! `storage`, `summaries` —//! each exporting `pub fn handlers() -> &'static [(&'static str, Handler)]`//! and each adding one line — its MODULE NAME — to the `handler_groups!`//! list below, which builds `HANDLER_GROUPS` and the names beside it.//!//!   pub type Handler = fn(&mut Ctx<'_>, &Map<String, Value>) -> ToolResult;//!   pub type ToolResult = Result<Value, ToolFailure>;//!//! SYNCHRONOUS, on purpose: a call runs inside `files.with_write`, which is a//! `spawn_blocking` closure holding the file's driver, and nothing may await//! while holding a driver (design S7). A handler that genuinely needs the//! network reaches it through `Ctx::services`, whose seams block.//!//! A handler is written as://!//!   fn create_todo(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {//!       let args = validate_create_todo(args).map_err(ToolFailure::new)?;   // hand-ported//!       let id = ctx.new_uuid();//!       ctx.writer()?.upsert("cotton_todos", &id, patch);                   // collects//!       ctx.commit()?;                                                      // mints + folds//!       Ok(json!({ "id": id }))//!   }//!//! WHAT `Ctx` HANDS OVER://!//!   ctx.read            `ReadDb` — `select(&Query)`, `by_id(table, id)`, `one(&Query)`//!   ctx.db()            the raw `&Driver`, for FTS and anything a query builder should not grow//!   ctx.writer()?       `&mut Writer` — `upsert(table, row_id, patch)`, `delete(table, row_id)`;//!                       refuses (as a ToolFailure) on a read-only connection//!   ctx.commit()?       mint + fold everything queued; a stale HLC is an ERROR//!   ctx.file            `.namespace()` for a derived record id, `.id()` for a media key or repo id//!   ctx.workspace_id / ctx.owner_user_id / ctx.agent (the connection's name) / ctx.token_id//!   ctx.now             the injected clock, never `Utc::now()`//!   ctx.new_uuid()      a v4 uuid from the injected `Random`, never `rand` directly//!   ctx.services        the OPTIONAL capabilities — `notify`, `media`, `documents`,//!                       `registry`, `meaning`, `statements`. Each is `None` on a server//!                       configured without it, and a tool that needs one REFUSES OUT LOUD//!                       rather than half-working.//!   ctx.audit(tool, summary)  a tool's own extra audit line (`dev_reveal_secret`), written//!                       into the same trail, before the call's own row.//!//! CONVENTIONS a handler keeps, because the TypeScript does: an absent field is//! OMITTED, never null; a list tool answers `{more, <plural>: [...]}`; ids are//! uuids and timestamps ISO; a refusal names the fix.//! ============================================================================//!//! The name-to-handler mapping is a `HashMap`: the mapping is the whole file,//! and a name that reaches no handler must fail loudly rather than fall//! through to a default that does something.use std::collections::HashMap;use std::sync::{Arc, OnceLock};use chrono::{DateTime, Utc};use cotton_store::actor::Actor;use cotton_store::driver::Driver;use cotton_store::file_identity::FileIdentity;use cotton_store::link_rule::FileKind;use cotton_store::mint::Held;use serde_json::{Map, Value};use crate::mcp::places::{Reach, ReachFile};use crate::mcp::protocol::{grants, tool_by_name, McpScope, ToolDef, ToolFailure};use crate::mcp::read_db::ReadDb;use crate::mcp::tokens::has_scope;use crate::mcp::writer::Writer;use crate::random::{uuid_v4, Random};pub type ToolResult = std::result::Result<Value, ToolFailure>;/// One tool's implementation. See the module note for the contract.pub type Handler = fn(&mut Ctx<'_>, &Map<String, Value>) -> ToolResult;/// What a handler group exports: `pub fn handlers() -> HandlerGroup`.pub type HandlerGroup = &'static [(&'static str, Handler)];/// The owner's phone, reached through the server rather than the database —/// `notify_owner`'s whole job, and `None` on a server with no push rail.pub type NotifyRail = Arc<dyn Fn(&Value) -> std::result::Result<Value, String> + Send + Sync>;/// One object-store HEAD, asked synchronously. `Ok(false)` is "not there yet",/// which is a FACT under offline-first and never an error; `Err` is a store/// that is broken.pub type MediaHeadRail = Arc<dyn Fn(&str) -> std::result::Result<bool, String> + Send + Sync>;/// The BYTES at one object key, asked synchronously. `Ok(None)` is "not there/// yet", which is a FACT under offline-first and never an error; `Err` is a/// store that is broken.////// [`MediaHeadRail`]'s sibling and deliberately not the same rail: a HEAD is a/// question a tool asks before it signs a link, and a GET pulls a whole object/// through this process. The one caller that wants the object itself is a tool/// that puts it INSIDE its result — `get_photo_bytes`, and a video's still/// frame — and both refuse anything over a 2 MB cap before they ask, because/// the protocol and the client's context window are the constraint.////// BLOCKING for [`MediaHeadRail`]'s reason: a handler is synchronous by design/// (S7), so the bridge to the async store is built on the server's side, on a/// thread that is already a blocking one. `None` on a server with no store, and/// the tool that needs it refuses BY NAME rather than answering an empty/// picture.pub type MediaGetRail =    Arc<dyn Fn(&str) -> std::result::Result<Option<Vec<u8>>, String> + Send + Sync>;/// Put BYTES at one object key, with their content type, synchronously — the/// one writer is a Cotton package: its file on export, the media it carries on/// import. `None` on a server with no store, and both package tools refuse by/// name.pub type MediaPutRail =    Arc<dyn Fn(&str, &[u8], &str) -> std::result::Result<(), String> + Send + Sync>;/// Sign a five-minute GET for one object key — BLOCKING, because a handler is.////// A signed URL is a bearer credential and a transcript is forever, so the/// TypeScript mints one only where a tool asked for it: `get_document` with/// `includeFileUrl`, a message's keyed attachment, a photo, a video, an album/// cover, a media-analysis frame. Every one of those needs this rail.////// BLOCKING is the whole shape. `ObjectStore::presign_get` is `async`; a/// handler is synchronous on purpose (design S7 — nothing may await while/// holding the file's driver). The filesystem store's URLs are HMAC over/// `method|key|exp` plus string assembly and need no I/O at all/// (`FsObjectStore::presign_blocking`), so the server builds this closure once/// per request from the store it already holds and a handler simply calls it./// `None` on a server with no object store, and the tool that needs one answers/// the base shape rather than half a link.////// The arguments are the key and the TTL in seconds; the answer is the URL, or/// the store's own refusal.pub type PresignRail = Arc<dyn Fn(&str, u64) -> std::result::Result<String, String> + Send + Sync>;/// Mint a short-lived PUT slot for one object key — BLOCKING, the same bridge/// [`MediaHeadRail`] is and deliberately not the same rail as a GET signer.////// A GET is a key and a TTL; a PUT also pins the CONTENT TYPE and the byte/// length the upload must announce, and it answers with the headers the caller/// must send verbatim as well as the URL. Folding the two into one signature/// would give every reader of a link three arguments it never uses.////// The one caller is `request_document_upload`. Arguments: the key, the TTL in/// seconds, the content type, and the byte size the caller promised. The answer/// is the URL and the headers, or the store's own refusal.pub type PresignPutRail = Arc<    dyn Fn(&str, u64, &str, u64) -> std::result::Result<(String, Vec<(String, String)>), String>        + Send        + Sync,>;/// The vector for ONE query string.////// The meaning lane's round trip, as a rail — but the round trip is NOT made/// through it. A handler runs holding the person's file, and embedding a/// query is a provider call whose meter row writes that same file; so the/// dispatcher embeds the query BEFORE it takes the file/// ([`BeforeTheFile::EmbedQuery`]) and the rail a call gets answers that/// vector, waiting on nothing.////// The answer is the QUANTISED vector — the same function that quantised the/// stored ones, so the scale on both sides of the dot product cannot drift/// apart — or the provider's own refusal as a sentence a person can read./// `None` on a server with no embedder, and the lane then answers `unreachable`/// with a sentence saying so rather than a silently shorter result list, which/// is the one thing a degraded search must never look like (D19).pub type EmbedQueryRail = Arc<dyn Fn(&str) -> std::result::Result<Vec<u8>, String> + Send + Sync>;/// The same device identity used by pairing and approval signs package bytes.#[derive(Clone)]pub struct ToolSigner {    pub author: cotton_core::definitions::ToolAuthor,    pub sign: ToolSignRail,}pub type ToolSignRail = Arc<dyn Fn(&[u8]) -> Result<[u8; 64], String> + Send + Sync>;/// The serving server's copy of every database to the backup disk, now.pub type BackupNowRail = Arc<dyn Fn() -> Result<Value, String> + Send + Sync>;/// A capability that lives on the SERVER rather than in the database.////// Each is `None` on a server configured without it. A tool that needs one/// refuses out loud — "this server has no storage to upload into" — rather than/// half-working, which is the shape of the TypeScript's own paused-pipeline/// answers.#[derive(Clone, Default)]pub struct ToolServices {    pub backup_now: Option<BackupNowRail>,    pub tool_signer: Option<ToolSigner>,    /// Reach the owner's phone. `notify_owner`'s whole job.    pub notify: Option<NotifyRail>,    /// The bytes bridge. Absent ⇒ every document, photo and video tool that    /// needs bytes refuses by name.    pub media_available: bool,    /// "Are the bytes there yet?" — one blocking question against the object    /// store, and the reason `publish_run` can refuse evidence that never    /// arrived instead of writing a row pointing at nothing.    ///    /// BLOCKING because a handler is synchronous by design (S7): the rail    /// bridges to the async store on the caller's side, on a thread that is    /// already a blocking one. `None` on a server with no store, and the tool    /// that needs it refuses out loud rather than publishing unverified.    pub media_head: Option<MediaHeadRail>,    /// The bytes at one object key. See [`MediaGetRail`].    pub media_get: Option<MediaGetRail>,    /// Bytes put at one object key. See [`MediaPutRail`].    pub media_put: Option<MediaPutRail>,    /// Mint a short-lived PUT slot for one object key. See [`PresignPutRail`].    pub presign_put: Option<PresignPutRail>,    /// Mint a short-lived GET link for one object key. See [`PresignRail`].    pub presign: Option<PresignRail>,    /// The documents pipeline, as its tools need it — a SEAM the worker slice    /// (2f) fills. `None` on a server with no object store, and every document    /// tool that needs bytes refuses BY NAME rather than half-working. See    /// [`crate::mcp::handlers::documents::rail::DocumentsRail`].    pub documents: Option<Arc<dyn crate::mcp::handlers::documents::rail::DocumentsRail>>,    /// Embed one query string, so `search_records` can answer by meaning. See    /// [`EmbedQueryRail`].    pub embed_query: Option<EmbedQueryRail>,    /// `COTTON_PUBLIC_URL`, or absent — the ONE origin this server answers    /// with, never derived from a request header. A share link answers a null    /// `url` with an instruction; a feedback registration REFUSES, because a    /// token whose ingest address is unknown is a credential to nowhere.    pub public_url: Option<String>,    /// Renders statement pages and reads their figures.  Statement booking    /// refuses when this is absent, because text-layer output is untrusted.    pub statement_visual: Option<        Arc<dyn crate::mcp::handlers::money::statement_visual_check::StatementVisualVerifier>,    >,    /// The vault — what seals a secret's payload and what opens one, under    /// this workspace's master key (schema v6 of the Rust ladder). `None` on a    /// build with no vault: a phone, a `cotton-server` started with no vault    /// key, or a Mac whose own key cannot open this workspace. Every tool that    /// needs it then refuses BY NAME (`vault_unavailable`) rather than storing    /// a plaintext credential. See [`crate::rails::VaultRail`].    pub vault: Option<Arc<dyn crate::rails::VaultRail>>,    /// **The developer tools, and the switch that is the same field.**    ///    /// `Some` on a server whose `COTTON_DEV_TOOLS` is on and `None` everywhere    /// else — on a phone, on a Mac with the line cleared, in a worker, in every    /// harness that did not ask for it. One field rather than a bool beside a    /// rail, because "may a `dev_` tool be called here" and "can this process    /// reach the pairing queue and the relay line" have one answer on every    /// machine that exists, and two fields would be two answers that could    /// disagree.    ///    /// Every `dev_` handler's FIRST LINE reads it and refuses by name    /// ([`crate::mcp::protocol::dev_tools_off`]). That is what closes the    /// phone's door as well as the wire's: [`call_tool`] refuses a developer    /// tool on a server with the switch off, but the owner's app dispatches    /// through `handler_for` and never through `call_tool`, so a check that    /// lived only at the door would not be a check at all.    ///    /// See [`crate::rails::DevToolsRail`] and the owner's decision of 27 Sep    /// 2026 ([until-the-app-goes-public-a-developer-mcp-dev-tools-behind-a-ser]).    pub dev_tools: Option<Arc<dyn crate::rails::DevToolsRail>>,    /// Which device is reading the file, and whether it holds a copy or    /// serves the file itself — what no row says and the `activity` table's    /// one record reads. Filled by the owner's own app (`cotton_ffi`'s    /// `authoring::run_with_ctx`), `None` everywhere else.    pub this_file: Option<crate::rails::ThisFile>,    /// `save_toolkit`'s source: the kit another database's Home makes    /// (`toolkits::compose`), read by the dispatcher before this file was    /// taken — one file is held at a time — and answered here by that    /// database's id or name.    pub kit_source: Option<KitSourceRail>,    /// `move_record` and `move_records`: the serving Mac holds both files.    pub record_moves: Option<MoveRail>,    /// `brief` in a project database: the owner's own entries — the Owner    /// section — read from their personal database before this file was    /// taken (`records_2::memory::owner_entries_of`). `None` where the    /// owner's personal database is not in the call's reach: no Owner section.    pub owner_memory: Option<Arc<Vec<cotton_core::rules::memory_briefing::BriefingEntry>>>,    /// `add_photo`: the pictures, by content hash, whose bytes the server put    /// in its media store before this file was taken. `None` where nothing    /// keeps picture bytes: no picture is added.    pub stored_photos: Option<Arc<Vec<String>>>,}/// The kit a database's Home makes, by the database's id or name, as read/// before the file was taken.pub type KitSourceRail =    Arc<dyn Fn(&str) -> std::result::Result<Vec<cotton_core::toolkits::KitTool>, String> + Send + Sync>;/// Move records out of the file holding this call and into `to`; the serving/// Mac supplies the paired-file operation.pub type MoveRail = Arc<    dyn Fn(&crate::mcp::handlers::moves::MoveAsk) -> std::result::Result<Value, String> + Send + Sync,>;impl ToolServices {    /// A context with NO server-side capability — what a WORKER holds.    ///    /// Every rail here is a bridge from a REQUEST to something outside the    /// person's file, and a worker has no request: it holds its own object    /// store, its own model and its own registry handle, and reaches them    /// directly. So the honest answer for a worker's context is that none of    /// them are there, rather than a half-built bag whose absent fields would    /// read as a composition somebody forgot.    ///    /// A handler that grows a rail dependency and is then called from a worker    /// refuses BY NAME, which is what the `None` on every one of these already    /// buys the request path.    pub fn none() -> ToolServices {        ToolServices {            backup_now: None,            tool_signer: None,            notify: None,            media_available: false,            media_head: None,            media_get: None,            media_put: None,            presign: None,            documents: None,            presign_put: None,            embed_query: None,            public_url: None,            statement_visual: None,            vault: None,            dev_tools: None,            this_file: None,            kit_source: None,            record_moves: None,            owner_memory: None,            stored_photos: None,        }    }}impl std::fmt::Debug for ToolServices {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.debug_struct("ToolServices")            .field("notify", &self.notify.is_some())            .field("media_available", &self.media_available)            .field("media_head", &self.media_head.is_some())            .field("media_get", &self.media_get.is_some())            .field("media_put", &self.media_put.is_some())            .field("presign_put", &self.presign_put.is_some())            .field("presign", &self.presign.is_some())            .field("documents", &self.documents.is_some())            .field("embed_query", &self.embed_query.is_some())            .field("statement_visual", &self.statement_visual.is_some())            .field("vault", &self.vault.is_some())            .field("dev_tools", &self.dev_tools.is_some())            .field("this_file", &self.this_file)            .field("kit_source", &self.kit_source.is_some())            .field("record_moves", &self.record_moves.is_some())            .field("owner_memory", &self.owner_memory.as_ref().map(|entries| entries.len()))            .field("stored_photos", &self.stored_photos.as_ref().map(|stored| stored.len()))            .field("public_url", &self.public_url)            .finish()    }}/// Everything one tool call may reach.pub struct Ctx<'a> {    /// Reads, scoped to this workspace.    pub read: ReadDb<'a>,    /// The write half — `None` when the connection cannot write, so a read-only    /// token gets a REFUSAL rather than a client whose writes are dropped.    writer: Option<Writer<'a>>,    /// Which file this is and the namespace its derived ids are made under,    /// read once when the file was opened. A derived record id takes    /// `file.namespace()`, a media key or repository id `file.id()`.    pub file: &'a FileIdentity,    /// `file.id()` as a string, for the queries and rows that name the file.    pub workspace_id: &'a str,    pub owner_user_id: &'a str,    /// The connection's name — stamped on every record and comment it writes.    pub agent: &'a str,    pub token_id: &'a str,    /// What this CONNECTION may do — the token's own scopes, never derived    /// from whether a writer happens to have been built.    pub scopes: &'a [String],    pub now: DateTime<Utc>,    pub random: Arc<dyn Random>,    pub services: &'a ToolServices,    /// The CREDENTIAL device id whose key signed this call — base64url of a raw    /// Ed25519 public key, the string `x-cotton-device` carries and    /// `cotton_devices.device_id` holds. `None` wherever the caller is not a    /// paired device.    ///    /// NOT the writer's device id, and the two must never be conflated: that    /// one is an AUTHOR id minted by the file's own replica    /// (`cotton_client::replica::resolve_device_id`), and it names who wrote an    /// op, not who was admitted. `cotton-store`'s `devices_in_the_file` test    /// says the same thing from the other side.    ///    /// `None` on every constructor here today, and the reason is worth writing    /// down rather than discovering: the MCP transport authenticates a TOKEN    /// (`cotton_mcp_tokens`, or an OAuth access token), never a device    /// signature, so an assistant's call genuinely does not know which device    /// it is. The one identity a server proves against a device key is    /// `verify_owner`'s, on the owner ROUTES, and no owner route dispatches a    /// tool. Set it with [`Ctx::signed_by`] the day one does.    pub caller_device: Option<&'a str>,    /// A tool's own extra audit line, written before the call's own row.    audit: &'a dyn Fn(&str, &str),    /// Every file the token reaches, when the caller fanned this call out    /// over them (see [`Ctx::within`]). `None` for a context built for its    /// one file alone.    reach: Option<&'a Reach>,}impl<'a> Ctx<'a> {    #[allow(clippy::too_many_arguments)]    pub fn new(        db: &'a Driver,        file: &'a FileIdentity,        owner_user_id: &'a str,        agent: &'a str,        token_id: &'a str,        scopes: &'a [String],        now: DateTime<Utc>,        random: Arc<dyn Random>,        writes_as: Option<Actor>,        services: &'a ToolServices,        audit: &'a dyn Fn(&str, &str),    ) -> Ctx<'a> {        Ctx {            read: ReadDb::new(db, file.id().as_str()),            // WHO THE CALL WRITES AS — the token or credential the serving Mac            // admitted it under; `None` is a call that may not write at all.            writer: writes_as.map(|actor| {                Writer::acting(                    db,                    file.id().as_str(),                    owner_user_id,                    actor,                    Held::Served,                    now,                    Arc::clone(&random),                )            }),            file,            workspace_id: file.id().as_str(),            owner_user_id,            agent,            token_id,            scopes,            now,            random,            services,            caller_device: None,            audit,            reach: None,        }    }    /// The context a WORKER runs a handler's own pipeline in.    ///    /// Two reasons this exists rather than a second copy of the pipeline. The    /// money run — resolve the account, write the lines, check the arithmetic,    /// book, classify — is the SAME work whether an assistant handed in a    /// reading over MCP or the statements worker read the paper itself, and a    /// second implementation of it is a second answer to "which account is this    /// statement's", which is exactly the drift that once minted an orphan    /// account off a re-spelled letterhead.    ///    /// What differs is the ACTOR: a worker writes as its own job    /// (`job:money-statements`), never as a token. `label` is the byline its    /// rows carry (`agent`). That is the whole of this constructor —    /// everything else is what [`Ctx::new`] builds.    ///    /// `scopes` is empty on purpose: scopes gate DISPATCH, and a worker calls    /// the pipeline directly rather than by tool name. `token_id` is empty for    /// the same reason — there is no token.    #[allow(clippy::too_many_arguments)]    pub fn for_worker(        db: &'a Driver,        file: &'a FileIdentity,        owner_user_id: &'a str,        actor: Actor,        label: &'a str,        now: DateTime<Utc>,        random: Arc<dyn Random>,        services: &'a ToolServices,        audit: &'a dyn Fn(&str, &str),    ) -> Ctx<'a> {        Ctx {            read: ReadDb::new(db, file.id().as_str()),            writer: Some(Writer::acting(                db,                file.id().as_str(),                owner_user_id,                actor,                Held::Served,                now,                Arc::clone(&random),            )),            file,            workspace_id: file.id().as_str(),            owner_user_id,            agent: label,            token_id: "",            scopes: &[],            now,            random,            services,            caller_device: None,            audit,            reach: None,        }    }    /// The same context, its writes made on a file held `held` (a phone's    /// replica rather than the serving Mac's file).    #[must_use]    pub fn held_as(mut self, held: Held) -> Ctx<'a> {        self.writer = self.writer.take().map(|writer| writer.held_as(held));        self    }    /// The context a PHONE writes in (design P3).    ///    /// The phone authors through the SAME handlers an assistant calls — that is    /// what makes "one implementation of who wins" a compiled function rather    /// than a claim about two ports of one algorithm. Two things are stamped    /// differently, and they are the whole of the difference:    ///    ///   THE OP CARRIES THIS DEVICE'S ID AND THE ACTOR ROLE `user`, never    ///   `server:mcp` / `agent`. A phone is one of the person's own devices and    ///   its writes are theirs; stamped as an assistant's, 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.    ///    ///   NOTHING IS AUDITED. `cotton_mcp_audit` answers "what did an assistant    ///   do in my database", and a person tapping a button is not an entry in    ///   it. So [`Ctx::audit`] here is a no-op, and the CALL's own row is not    ///   written either — that row is `cotton_server::mcp::server`'s, which a    ///   phone does not run.    ///    /// [`Self::scopes`] is read and write, because the phone calls tools BY    /// NAME through `call_tool` (a worker does not, which is why    /// [`Ctx::for_worker`] leaves them empty) and a device the owner approved    /// is not a credential with a narrower grant.    ///    /// The rails a phone cannot supply — `documents`, `media`, `statements`,    /// `meaning` — are `None` in its [`ToolServices`], and the handlers that    /// need one refuse out loud, which is already their contract.    /// The owner at one of their devices. `actor` is who the write is asked    /// by — `Actor::Owner` of this device's row — and `held` how this process    /// holds the file (a replica queues, a served file does not); `device_id`    /// is the file's author, kept for the labels a screen reads.    #[allow(clippy::too_many_arguments)]    pub fn phone(        db: &'a Driver,        file: &'a FileIdentity,        owner_user_id: &'a str,        device_id: &'a str,        actor: cotton_store::actor::Actor,        held: cotton_store::mint::Held,        now: DateTime<Utc>,        random: Arc<dyn Random>,        services: &'a ToolServices,    ) -> Ctx<'a> {        Ctx {            read: ReadDb::new(db, file.id().as_str()),            writer: Some(Writer::acting(                db,                file.id().as_str(),                owner_user_id,                actor,                held,                now,                Arc::clone(&random),            )),            file,            workspace_id: file.id().as_str(),            owner_user_id,            agent: device_id,            token_id: device_id,            scopes: phone_scopes(),            now,            random,            services,            caller_device: None,            audit: &NO_AUDIT,            reach: None,        }    }    /// Name the paired device whose key signed this call.    ///    /// The builder rather than a parameter on all four constructors: a device    /// identity is a fact about the TRANSPORT, and three of the four contexts    /// have none by construction (a worker is the server itself, a run is an    /// assistant, and a phone writing through the embedded core authenticates    /// against its own file rather than over a wire). See    /// [`Ctx::caller_device`].    #[must_use]    pub fn signed_by(mut self, device_id: &'a str) -> Ctx<'a> {        self.caller_device = Some(device_id);        self    }    /// Run inside a token's reach: the files the whole call may touch, of    /// which this context is bound to one. A builder beside    /// [`Ctx::signed_by`] rather than a parameter on every constructor,    /// because only the MCP route's wrapper fans a call out; a worker, an    /// assistant run and the phone each work in their one file.    #[must_use]    pub fn within(mut self, reach: &'a Reach) -> Ctx<'a> {        self.reach = Some(reach);        self    }    /// The reach this call runs within, or `None` for a context built for    /// its one file alone — never a reach guessed for it.    pub fn reach(&self) -> Option<&'a Reach> {        self.reach    }    /// The file of the reach this context is bound to — its name and whether    /// it is Mine — or `None` outside a reach.    pub fn place(&self) -> Option<&'a ReachFile> {        self.reach?            .files            .iter()            .find(|file| file.id == self.workspace_id)    }    /// What the open file is — the personal database, or a project's shared    /// one — from its own `cotton_workspaces` row, read by the same function    /// mint's link rule reads, so a handler and the fold never disagree about    /// where a write lands.    pub fn file_kind(&self) -> std::result::Result<FileKind, ToolFailure> {        cotton_store::link_rule::file_kind(self.db())            .map_err(|error| ToolFailure::new(format!("the file's kind could not be read: {error}")))    }    /// The raw driver — for FTS, aggregates and anything a query builder    /// should not grow to cover.    pub fn db(&self) -> &'a Driver {        self.read.driver()    }    /// The write half, or the refusal a read-only connection has earned.    ///    /// Unreachable in practice — `call_tool` refuses a write tool to a    /// read-only token before any handler runs — but a handler that writes    /// under a read scope is a bug, and this is where it stops.    pub fn writer(&mut self) -> std::result::Result<&mut Writer<'a>, ToolFailure> {        self.writer.as_mut().ok_or_else(|| {            ToolFailure::new(                "this token does not have \"write\" access. Ask the owner to reconnect with write \                 enabled.",            )        })    }    /// How this context's writer holds the file, or `None` for a read-only one.    pub fn writer_held(&self) -> Option<cotton_store::mint::Held> {        self.writer.as_ref().map(Writer::held)    }    /// Who this context's writes are asked by, or `None` for a read-only one.    pub fn writer_actor(&self) -> Option<&Actor> {        self.writer.as_ref().map(Writer::actor)    }    /// Every op this context's writer has minted and folded, in order.    ///    /// The server itself never asks: it IS the file, so a folded op is the    /// truth. The Mac's CLIENT rail does — a decision taken in its window runs    /// through this same handler over a REPLICA, where a folded op is not a sent    /// op, so it takes these and queues them in the replica's outbox.    pub fn written_ops(&self) -> &[cotton_store::protocol::types::CottonOp] {        self.writer.as_ref().map_or(&[], Writer::ops)    }    /// Forget everything queued and not yet committed (see    /// [`Writer::discard_queued`]).    pub fn discard_queued(&mut self) {        if let Some(writer) = self.writer.as_mut() {            writer.discard_queued();        }    }    /// Run `write` as a generic verb whose own change row is the action's    /// history ([`Writer::noting_history`]).    pub fn noting_history<T>(&mut self, write: impl FnOnce(&mut Self) -> T) -> T {        if let Some(writer) = self.writer.as_mut() {            writer.noting_history(true);        }        let out = write(self);        if let Some(writer) = self.writer.as_mut() {            writer.noting_history(false);        }        out    }    /// Mint and fold everything queued. A no-op when nothing was queued.    pub fn commit(&mut self) -> std::result::Result<(), ToolFailure> {        let Some(writer) = self.writer.as_mut() else {            return Ok(());        };        writer            .commit()            .map(|_| ())            .map_err(|error| ToolFailure::new(error.to_string()))    }    /// [`Ctx::commit`] as one batch of rows ([`Writer::commit_batch`]): the    /// same ops, with the file's shape read once for them all.    pub fn commit_batch(&mut self) -> std::result::Result<(), ToolFailure> {        let Some(writer) = self.writer.as_mut() else {            return Ok(());        };        writer            .commit_batch()            .map(|_| ())            .map_err(|error| ToolFailure::new(error.to_string()))    }    /// A v4 uuid from the injected source. NEVER `rand` directly: a suite that    /// cannot say which bytes were drawn can only assert the shape.    pub fn new_uuid(&self) -> String {        uuid_v4(self.random.as_ref())    }    /// This call's own extra audit line.    pub fn audit(&self, tool: &str, summary: &str) {        (self.audit)(tool, summary);    }    /// Is this the OWNER'S OWN APP asking — the phone, or the Mac's window?    ///    /// Asked of the scopes rather than of a flag of its own, because the answer    /// already has one home: `owner` is not a word a token can be minted with    /// (see [`crate::mcp::protocol::McpScope::Owner`]), so a context carrying it    /// is a device the owner approved and a context without it is a credential    /// somebody connected. A second field saying the same thing is a second    /// answer to one question, and the two would eventually disagree.    ///    /// [`Ctx::for_worker`] (empty scopes) answers `false`, which is right: a    /// worker is the server acting, never the person.    ///    /// A HANDLER asks this where the same verb has to behave differently on a    /// device rather than be allowed or refused outright.    pub fn is_owner_app(&self) -> bool {        has_scope(self.scopes, crate::mcp::protocol::McpScope::Owner.as_str())    }}/// What a phone may call: everything. A device the owner approved is not a/// pasted credential with a narrower grant, and the tool it is refused is the/// one the app has no button for — `machines` included: the owner's own app/// may start work on the owner's own Macs.////// **`owner` is here and nowhere else.** It is the third scope/// ([`crate::mcp::protocol::McpScope::Owner`]) and it is not grantable: no/// token carries it, so an owner tool is absent from every `tools/list` and/// refused at every dispatch that is not this one. Carrying it here is what/// makes "the owner's own app may, an assistant may not" a compiled fact/// rather than a sentence in a description.fn phone_scopes() -> &'static [String] {    static SCOPES: OnceLock<Vec<String>> = OnceLock::new();    SCOPES.get_or_init(|| {        vec![            "machines".to_string(),            "owner".to_string(),            "read".to_string(),            "write".to_string(),        ]    })}/// The audit line a phone does not write. See [`Ctx::phone`].static NO_AUDIT: fn(&str, &str) = |_tool, _summary| {};/// Declare every handler group ONCE, by its module name.////// The macro exists so a group's NAME and its `handlers()` function can never/// drift apart: both are derived from the single module identifier written in/// the list below, so adding a group without naming it is not something the/// language will let anyone write.macro_rules! handler_groups {    ($($module:ident),+ $(,)?) => {        /// Every handler group, in the order the TypeScript's imports name        /// them: its module name beside the function that yields its tools.        ///        /// A group adds ONE line to [`handler_groups!`] and nothing else in        /// this file. A catalogued tool no group claims is answered by NAME        /// rather than pretended out of existence.        static HANDLER_GROUPS: &[(&str, fn() -> HandlerGroup)] = &[            $((                stringify!($module),                crate::mcp::handlers::$module::handlers as fn() -> HandlerGroup,            ),)+        ];    };}handler_groups![    phrase,    records_1,    records_2,    bin,    calls,    storage,    summaries,    projects,    session_bus,    emails,    money,    documents,    photos,    videos,    albums,    media_analysis,    secrets,    // v13 — the `device` primitive's whole surface: one read. Its own group    // rather than a row in `session_bus`, because what it is about is the    // devices the owner admitted, not where work runs.    devices,    // 4p — the OWNER-SCOPE group. Appended rather than filed among the record    // groups because what it has in common is not a table: it is who may call    // it (`McpScope::Owner`).    owner,    // 4e — a group the day surface needed and the catalogue did not have.    // Owner-scope throughout, and its own group rather than rows in `owner`    // because it IS a table's own machinery: the repeat editor's four writes    // over a template and its projected occurrences.    recurrence,    // 4m — the message-ARCHIVE write surface the phone authors: hide and star    // a line, and the owner-private thread verbs (read, mute, pin, archive,    // clear, delete). Its own group rather than rows in `owner` because what    // they have in common IS a subject: one conversation.    chat,    // The GENERIC RECORD VERBS (v47): one set over every table, addressed by    // the table definition's id — a table the user defined lives in    // its own table `cotton_<id>`, a built-in is written through its own tools.    tables,    // The Cotton package (22 Oct 2026): a database's records out as one file,    // and into another through the mint.    package,    moves,    tool_packages,    // The DEVELOPER TOOLS (27 Sep 2026). Its own group because what its verbs    // have in common is not a table and not a scope but a SWITCH: they are    // listed to nobody and callable by nobody unless this server's    // `COTTON_DEV_TOOLS` is on. Last in the list so the tool block an assistant    // reads keeps its order when the switch is thrown — the block carries a    // cache breakpoint, and a set that reshuffled would miss it on every turn.    // Spec 9.7 piece 4: the mapping an MCP server connection reads by.    connections,    dev,];fn registry() -> &'static HashMap<&'static str, Handler> {    static REGISTRY: OnceLock<HashMap<&'static str, Handler>> = OnceLock::new();    REGISTRY.get_or_init(|| {        let mut table: HashMap<&'static str, Handler> = HashMap::new();        for (_group_name, group) in HANDLER_GROUPS {            for (name, handler) in group() {                if let Some(_existing) = table.insert(name, *handler) {                    // Two groups claiming one tool is the grid's own invariant                    // broken in code; the verb grid says one primitive owns a                    // tool, and this is the same rule at the dispatch.                    panic!("cotton-mcp: {name} is registered by two handler groups");                }            }        }        table    })}pub fn handler_for(name: &str) -> Option<Handler> {    registry().get(name).copied()}/// Run one tool call.////// The audit row records the tool name the caller supplied.pub fn call_tool(ctx: &mut Ctx<'_>, name: &str, args: &Map<String, Value>) -> ToolResult {    let handler = admitted(ctx.scopes, ctx.services, name, args)?;    let genesis = cotton_core::genesis::Genesis::here().map_err(ToolFailure::new)?;    if let Some(reason) = crate::mcp::places_classes::personal_refusal(genesis, name) {        let existing_personal = ctx.read.driver().get("SELECT kind FROM cotton_workspaces LIMIT 1", &[])            .map_err(|error| ToolFailure::new(error.to_string()))?            .is_some_and(|row| row.text("kind") == Some("personal"));        if !existing_personal { return Err(ToolFailure::new(reason)); }    }    if cotton_core::flavor::single_database() {        if let Some(table) = args.get("table").or_else(|| args.get("kind")).and_then(Value::as_str) {            crate::home_arrangement::require_table(ctx.read.driver(), ctx.workspace_id, table).map_err(ToolFailure::new)?;        }        for (table, cells) in crate::mcp::surface::TOOL_SURFACE {            if crate::mcp::surface::SHARED_TOOLS.contains(&name) { continue; }            if cells.also.contains(&name) || [&cells.list, &cells.get, &cells.create, &cells.update, &cells.remove].iter().any(|cell| cell.tool() == Some(name)) {                crate::home_arrangement::require_table(ctx.read.driver(), ctx.workspace_id, table).map_err(ToolFailure::new)?;            }        }        // Non-record engines have their own handler groups.        for (group, handlers) in HANDLER_GROUPS {            let key = match *group {                "money" | "money_views" => "accounts", "emails" => "email", "chat" => "messages",                "secrets" => "passwords",                "repos" | "session_bus" => "code", "summaries" => "assistants",                "media_analysis" | "albums" => "photos", "recurrence" => "todos",                "calls" | "documents" | "photos" | "videos" | "storage" | "connections" => group,                _ => continue,            };            if handlers().iter().any(|(verb, _)| *verb == name) && !crate::home_arrangement::tool_held(ctx.read.driver(), ctx.workspace_id, key).map_err(ToolFailure::new)? {                return Err(crate::mcp::protocol::no_such_tool_here(key));            }        }    }    // A handler runs inside the file, so the tool names itself to whoever    // holds it: a hold that runs long says which tool it was    // (`cotton_store::held::slow_hold_line`).    cotton_store::held::doing(&format!("the MCP tool {name}"));    // AN ASSISTANT SEAT IS ANOTHER PERSON (`cotton_store::audience`): a call    // that names an only-you record is refused, and every element of an    // answer that names one leaves it — reads take no single path through    // the file, so the answer is where they meet.    let holds = if ctx.owner_user_id.starts_with(cotton_store::audience::SEAT_PREFIX) {        cotton_store::audience::Holds::for_seat(ctx.read.driver()).map_err(|error| ToolFailure::new(error.to_string()))?    } else {        cotton_store::audience::Holds::none()    };    let held = |value: &Value| !holds.is_empty() && holds.names(value);    if held(&Value::Object(args.clone())) {        return Err(ToolFailure::new(format!("that record {}", cotton_store::audience::HELD_REFUSAL)));    }    let answer = handler(ctx, args)?;    let answer = if holds.is_empty() { answer } else { holds.redact(answer) };    if held(&answer) {        return Err(ToolFailure::new(format!("that record {}", cotton_store::audience::HELD_REFUSAL)));    }    // B3: a connection that read chats may not push for a while (`chat_reads`),    // and is never answered a sign-in code a text carries (`sign_in_codes`).    let reads_chat = crate::mcp::chat_reads::reads_chat(name, args, &answer);    let answer = if reads_chat { crate::mcp::sign_in_codes::withhold(answer, args) } else { answer };    if reads_chat {        // In EVERY database the connection reaches: a chat filed in a shared        // database is read there, and the push it must not make is one made in        // the personal database.        match ctx.reach() {            Some(reach) => {                for file in &reach.files {                    crate::mcp::chat_reads::note_read(&file.id, ctx.token_id, ctx.now);                }            }            None => crate::mcp::chat_reads::note_read(ctx.workspace_id, ctx.token_id, ctx.now),        }    }    Ok(answer)}/// What a dispatcher does for one call BEFORE it takes the person's file.////// A handler runs inside the file — every route, worker and phone sync waits/// on it while it does — so nothing a handler reaches may wait on the network/// or on something that needs the file itself (`cotton_store::held`). Two/// tools need exactly that, and for them the wait moves in front of the file:/// the dispatcher does it with nothing held, then hands the call a rail that/// answers what it came to and waits on nothing.#[derive(Debug, Clone, PartialEq, Eq)]pub enum BeforeTheFile {    /// `search_records` asking by meaning: this question, as the handler    /// reads it, is embedded if the file's lane is ready for it — the offline half    /// (`embed::query::resolve_meaning_lane_offline`) is a short read, and the    /// embedding a round trip to the provider. The rail answers the vector    /// for `query.trim()`.    EmbedQuery { query: String },    /// `update_document` with passwords to try: the documents pipeline, which    /// downloads the paper, calls a model and writes the file many times —    /// inside the file it waits on that same file. The rail's    /// `run_password_candidates` answers what the run came to.    TryPasswords {        document_id: String,        candidates: Vec<String>,    },    /// `save_toolkit`: the database `from` names is another file, and one    /// file is held at a time, so its Home is read into a kit first    /// (`toolkits::compose`) and the rail `kit_source` answers it.    ComposeKit { from: String },    /// `add_photo`: the picture's bytes go to the server's media store, a    /// round trip the file must not wait on, so they are stored first and the    /// handler writes the record naming them (`stored_photos`).    StorePhoto(crate::tool_pictures::ToolPhoto),}/// Does this call need something done before the file is taken, and what?////// Asked with the SAME gate [`call_tool`] applies — the tool exists, the/// scopes allow it, the arguments pass the checks made before any handler —/// so a call that would be refused never spends a provider call or runs a/// pipeline first. `services` are the ones the call will get; only their/// presence is read.pub fn before_the_file(    scopes: &[String],    services: &ToolServices,    name: &str,    args: &Map<String, Value>,) -> Option<BeforeTheFile> {    admitted(scopes, services, name, args).ok()?;    match name {        "search_records" => crate::mcp::handlers::records_2::search::meaning_query(args)            .map(|query| BeforeTheFile::EmbedQuery { query }),        "update_document" => crate::mcp::handlers::documents::tools::password_attempt(args).map(            |(document_id, candidates)| BeforeTheFile::TryPasswords {                document_id,                candidates,            },        ),        "update_record" => crate::mcp::handlers::tables::builtin::password_attempt(args).map(            |(document_id, candidates)| BeforeTheFile::TryPasswords {                document_id,                candidates,            },        ),        "add_photo" => crate::mcp::handlers::photos::sent_photo(args).map(BeforeTheFile::StorePhoto),        "save_toolkit" => args            .get("from")            .and_then(Value::as_str)            .map(|from| BeforeTheFile::ComposeKit { from: from.to_string() }),        _ => None,    }}/// Every refusal a call meets before its handler runs, in order — and the/// handler, when there is none.fn admitted(    scopes: &[String],    services: &ToolServices,    name: &str,    args: &Map<String, Value>,) -> std::result::Result<Handler, ToolFailure> {    let Some(tool) = tool_by_name(name) else {        return Err(ToolFailure::new(format!(            "unknown tool {}",            Value::String(name.to_string())        )));    };    // A DEVELOPER TOOL ON A SERVER WITH THE SWITCH OFF, refused before the    // scope is even looked at. The scope is about who is asking; this is about    // whether the tool exists here at all, and the second question comes first    // because its answer does not depend on the first — a read-only token and    // the owner's own app get the same sentence, naming the switch.    if crate::mcp::protocol::is_dev_tool(tool.name) && services.dev_tools.is_none() {        return Err(crate::mcp::protocol::dev_tools_off(tool.name));    }    if let Some(refusal) = machines_refusal(tool, scopes) {        return Err(refusal);    }    // A LANE TOKEN'S ONE WRITE, its session log; any other write it tries is    // refused here, naming what it may do.    let lane_door = crate::mcp::lane_scope::door(scopes, tool)?;    if !lane_door && !grants(scopes, tool.scope) {        // An OWNER tool is refused differently, because the fix is different.        // "Reconnect with owner enabled" would be an instruction nobody can        // follow: `owner` is not a word a token can be minted with, and telling        // a model otherwise sends the person hunting for a checkbox that does        // not exist. So the sentence names the scope and says who may call it.        if tool.scope == crate::mcp::protocol::McpScope::Owner {            return Err(ToolFailure::new(format!(                "`{}` is an owner-scope tool: the owner's app may call it; an assistant may not.",                tool.name            )));        }        // Named plainly so the user can fix it: the assistant should tell them        // to re-mint with write access rather than retry forever.        return Err(ToolFailure::new(format!(            "this token does not have \"{}\" access. Ask the owner to reconnect with {} enabled.",            tool.scope.as_str(),            tool.scope.as_str()        )));    }    let Some(handler) = handler_for(name) else {        // A CATALOGUED tool with no implementation yet. Named as itself rather        // than as "unknown tool", because the two are different facts and an        // assistant that cannot tell them apart retries the wrong one.        return Err(ToolFailure::new(format!(            "{} is not implemented on this server yet",            tool.name        )));    };    // **`limit: "all"` is the OWNER'S APP's spelling, and this is the door it    // may not come through.** `bounded_limit` reads that one string as "answer    // the whole set" so a phone screen drawing its own file gets all of it    // (`handlers/common.rs`'s `WHOLE_SET`); an assistant's context is finite,    // which is the entire reason these tools page at all. The phone does not    // call `call_tool` — it reaches `handler_for` directly through    // `cotton-ffi`'s `run_tool` — so refusing here costs the app nothing and    // makes the escape hatch structurally unreachable from MCP rather than    // merely undocumented.    if args.get("limit").is_some_and(Value::is_string) {        return Err(ToolFailure::new(            "limit must be a number — this tool pages, and the page size is how many rows come              back in one call.",        ));    }    Ok(handler)}/// The refusal a `machines` tool meets without both `machines` and `write`.////// Its own sentence, because the fix is its own: only a PERSONAL token may/// carry `machines` (the server drops the word at authentication for any/// other), so "reconnect with write enabled" would send the person to a/// checkbox that does not help.pub fn machines_refusal(tool: &ToolDef, scopes: &[String]) -> Option<ToolFailure> {    (tool.scope == McpScope::Machines && !grants(scopes, McpScope::Machines)).then(|| {        ToolFailure::new(format!(            "`{}` needs the \"machines\" scope: only a personal token may start work on your \             Macs. Ask the owner to reconnect with machines enabled.",            tool.name        ))    })}#[cfg(test)]#[path = "dispatch_tests.rs"]mod tests;