Cotton code
106 lines · 4.3 KB · RustRaw
//! The `connection` row as the bridge reads it.//!//! The synced table itself is the Connections tool's (note 7767ed9c, piece//! 2); this is the SHAPE every bridge agrees on, so the server's worker, the//! MCP verbs and a test can hand one another a connection without naming//! the table's columns in three places. `from_json` reads the row's generic//! JSON (a `list_records`/`get_record` answer, or a row read straight from//! SQL and turned into an object), so binding to the landed table is one//! reader, not a change to every caller.use serde_json::{Map, Value};/// `kind` of a connection that reads an MCP server.pub const KIND_MCP_SERVER: &str = "mcp_server";/// The `state` words a connection row carries, as the list draws them.pub mod state {    pub const READING: &str = "reading";    pub const PAUSED: &str = "paused";    pub const NEEDS_SIGN_IN: &str = "needs_sign_in";    pub const FAILED: &str = "failed";}#[derive(Debug, Clone, PartialEq, Eq)]pub struct ConnectionRow {    pub id: String,    pub kind: String,    pub name: String,    /// What it reaches: for an MCP server, the server URL.    pub reaches: String,    pub state: String,    /// The vault secret's id, once signed in.    pub credential: Option<String>,    /// The connection's own schedule word ("6h", "1d"); a call may say its own.    pub schedule: Option<String>,    /// Per kind. For `mcp_server`: `mapping` (see [`super::mapping`]), and    /// `tools` — the server's `tools/list` answer, kept at sign-in so the    /// page can list them and an assistant can propose a mapping offline.    pub config: Map<String, Value>,    /// Which database holds its rows; `None` means the row's own.    pub database: Option<String>,    /// When the person last asked Read now, and when it was last read: a    /// request after the last read is owed a read at the next pass.    pub read_requested_at: Option<String>,    pub last_read_at: Option<String>,}impl ConnectionRow {    /// Read one from the row's JSON. Only `id` and `kind` are required: a row    /// the app has just made has a URL and nothing else.    pub fn from_json(row: &Value) -> Result<ConnectionRow, String> {        let text = |key: &str| row.get(key).and_then(Value::as_str).map(str::to_string);        let id = text("id").ok_or("connection: id is missing")?;        let kind = text("kind").ok_or("connection: kind is missing")?;        let config = match row.get("config") {            None | Some(Value::Null) => Map::new(),            Some(Value::Object(map)) => map.clone(),            // A row read straight from SQL carries the JSON as text.            Some(Value::String(raw)) => serde_json::from_str::<Value>(raw)                .ok()                .and_then(|value| value.as_object().cloned())                .ok_or_else(|| format!("connection {id}: config is not a JSON object"))?,            Some(_) => return Err(format!("connection {id}: config is not an object")),        };        Ok(ConnectionRow {            id,            kind,            name: text("name").unwrap_or_default(),            reaches: text("reaches").unwrap_or_default(),            state: text("state").unwrap_or_else(|| state::NEEDS_SIGN_IN.to_string()),            // The landed table names them `secret_id` and `database_id`.            credential: text("secret_id").or_else(|| text("credential")),            schedule: text("schedule"),            config,            database: text("database_id").or_else(|| text("database")),            read_requested_at: text("read_requested_at"),            last_read_at: text("last_read_at"),        })    }    pub fn is_mcp_server(&self) -> bool {        self.kind == KIND_MCP_SERVER    }    /// The server's tools as kept at sign-in, each `{name, description, inputSchema}`.    pub fn tools(&self) -> Vec<Value> {        self.config            .get("tools")            .and_then(Value::as_array)            .cloned()            .unwrap_or_default()    }    /// Whether the person asked Read now since the last read.    pub fn read_owed(&self) -> bool {        super::table::read_requested(&self.state, self.read_requested_at.as_deref(), self.last_read_at.as_deref())    }    pub fn mapping(&self) -> Option<&Value> {        self.config.get("mapping").filter(|value| !value.is_null())    }}#[cfg(test)]#[path = "row_tests.rs"]mod row_tests;