//! `set_audience` — who may hold one record of a shared database: an only-you //! hold (`only_you`) or the owner's release (`everyone`). The OWNER'S OWN ACT //! (`McpScope::Owner`: the owner's app calls it from the record tray; an //! assistant never can), and the store's fold refuses a release from anybody //! but the owner at one of their own devices whichever door it came through //! (`cotton_store::audience`). use serde_json::{json, Map, Value}; use cotton_store::audience::{self, AUDIENCES, ONLY_YOU}; use cotton_store::keep; use crate::mcp::dispatch::{Ctx, ToolResult}; use crate::mcp::handlers::common::{now_iso, optional_string}; use crate::mcp::handlers::keep_rules::record_target; use crate::mcp::protocol::ToolFailure; fn failure(error: impl std::fmt::Display) -> ToolFailure { ToolFailure::new(error.to_string()) } fn required(args: &Map, argument: &str) -> Result { optional_string(args, argument) .filter(|value| !value.trim().is_empty()) .ok_or_else(|| ToolFailure::new(format!("{argument} is required"))) } /// `set_audience { table, id, audience }`. Setting the audience a record /// already carries changes nothing and writes nothing. pub fn set_audience(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let table = required(args, "table")?; let id = required(args, "id")?; let wanted = required(args, "audience")?; if !AUDIENCES.contains(&wanted.as_str()) { return Err(ToolFailure::new(format!("audience is one of {}", AUDIENCES.join(", ")))); } // A definition's id (`todo`) or the table a record lives in, as a keep // rule names it. let target = record_target(&keep::record_target_of(&table, &id)); let Some((table, id)) = keep::record_target(&target).map(|(t, i)| (t.to_string(), i.to_string())) else { return Err(ToolFailure::new("table and id name one record")); }; let db = ctx.db(); let answer = json!({ "table": table, "id": id, "audience": wanted }); if audience::of_record(db, &table, &id).map_err(failure)?.as_deref() == Some(wanted.as_str()) { return Ok(answer); } let at = now_iso(ctx); let workspace_id = ctx.workspace_id.to_string(); let change = if wanted == ONLY_YOU { audience::mark(ctx.db(), &workspace_id, &table, &id, &at) } else { audience::release(ctx.db(), &workspace_id, &table, &id, &at) } .map_err(failure)?; let patch = change.patch.unwrap_or_default(); let writer = ctx.writer()?; writer.upsert(audience::TABLE, &change.row_id, patch); ctx.commit()?; Ok(answer) }