//! A connection's MAPPING: how a bridge turns what a server answers into rows //! of a table. Written by conversation — an assistant lists the server's //! tools, proposes the calls and the columns, the person keeps it — and kept //! on the connection row as `config.mapping`, so it syncs like any setting //! and the worker on the serving Mac reads it on its schedule. //! //! ```json //! { "calls": [ { //! "tool": "execute", //! "args": { "code": "async () => (await cloudflare.request({method:'GET', path:'/zones'})).result" }, //! "every": "6h", //! "into": "domain", //! "rows": null, //! "key": "id", //! "key_column": "external_id", //! "columns": { //! "name": "name", //! "status": "status", //! "plan": "plan.name", //! "created": { "path": "created_on", "as": "date" }, //! "provider": { "value": "cloudflare" }, //! "domain": { "path": "zone_id", "link": { "table": "domain", "column": "external_id" } } //! }, //! "page": { "cursor_arg": "cursor", "next_cursor": "nextCursor" } //! } ] } //! ``` //! //! One call: one tool, its arguments, how often, which table its rows land //! in, where in the answer the rows are (`rows`, a dotted path; null when //! the answer IS the array), which value of a row is its identity (`key`) //! and which column holds that identity (`key_column`, the dedupe: a row //! whose key is already there is updated, not repeated), then one entry per //! column. A column's value is a dotted path into the row, a literal //! (`{"value": …}`), or a path that LINKS to another table's record by one //! of its columns. `as` coerces: `date` keeps the day of an ISO instant, //! `text` stringifies, `number`, `bool`. Paging is by cursor — the server //! answers a `nextCursor` and the next call carries it in `cursor_arg`. //! //! Everything here is pure: the server's worker fetches, this file reads. use cotton_core::definitions::{ColumnType, TableDefinition}; use serde_json::{Map, Value}; use std::collections::BTreeMap; use std::time::Duration; /// A whole mapping: the calls, in order. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Mapping { pub calls: Vec, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Call { pub tool: String, pub args: Map, /// "30m", "6h", "1d"; `None` takes the connection's own schedule. pub every: Option, pub into: String, pub rows: Option, pub key: String, pub key_column: String, pub columns: BTreeMap, pub page: Option, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Paging { pub cursor_arg: String, pub next_cursor: String, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum Coerce { Date, Text, Number, Bool, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum ValueSpec { Path { path: String, coerce: Option }, Literal(Value), Link { path: String, table: String, column: String }, } /// One row as the mapping shaped it: its key, the column values it carries, /// and the links left for the writer to resolve against the table they name. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct Shaped { pub key: String, pub data: Map, /// `(column, table, that table's column, the value to find)`. pub links: Vec<(String, String, String, String)>, } /// The most pages one call turns, whatever the server keeps answering. pub const MAX_PAGES: usize = 50; /// The schedule a call runs on when neither it nor the connection says. pub const DEFAULT_EVERY: &str = "6h"; impl Mapping { pub fn parse(value: &Value) -> Result { let calls = value .get("calls") .and_then(Value::as_array) .ok_or("mapping: calls is required, a list of calls")?; if calls.is_empty() { return Err("mapping: calls is empty".into()); } let calls = calls .iter() .enumerate() .map(|(at, call)| Call::parse(call).map_err(|why| format!("mapping: calls[{at}]: {why}"))) .collect::, _>>()?; Ok(Mapping { calls }) } /// The mapping's own JSON, as it is kept on the row. pub fn to_json(&self) -> Value { Value::Object(Map::from_iter([("calls".to_string(), Value::Array(self.calls.iter().map(Call::to_json).collect()))])) } /// Every table the mapping writes into, and every one it links to. pub fn tables(&self) -> Vec<&str> { let mut tables: Vec<&str> = self.calls.iter().map(|call| call.into.as_str()).collect(); for call in &self.calls { for spec in call.columns.values() { if let ValueSpec::Link { table, .. } = spec { tables.push(table); } } } tables.sort_unstable(); tables.dedup(); tables } /// Check the mapping against the definitions of the tables it names: a /// table it writes into exists, every column it names is that table's, /// the key column is a text column, a link names a real table and column /// and lands in a `link` column of that table. The refusal names what is /// wrong, so an assistant writing a mapping can fix it in one turn. pub fn validate(&self, tables: &[TableDefinition]) -> Result<(), String> { for (at, call) in self.calls.iter().enumerate() { let table = tables .iter() .find(|table| table.id == call.into) .ok_or_else(|| format!("calls[{at}]: into {:?} is not a table here", call.into))?; let key = table .column(&call.key_column) .ok_or_else(|| format!("calls[{at}]: key_column {:?} is not a column of {:?}", call.key_column, call.into))?; if key.column_type != ColumnType::Text { return Err(format!("calls[{at}]: key_column {:?} must be a text column", call.key_column)); } if let Some(every) = &call.every { parse_every(every).map_err(|why| format!("calls[{at}]: every: {why}"))?; } for (column, spec) in &call.columns { let defined = table .column(column) .ok_or_else(|| format!("calls[{at}]: {column:?} is not a column of {:?}", call.into))?; if let ValueSpec::Link { table: linked, column: by, .. } = spec { if defined.column_type != ColumnType::Link { return Err(format!("calls[{at}]: {column:?} links but is not a link column of {:?}", call.into)); } if defined.link_to.as_deref() != Some(linked.as_str()) { return Err(format!( "calls[{at}]: {column:?} links to {:?}, not to {linked:?}", defined.link_to.as_deref().unwrap_or("nothing") )); } let target = tables .iter() .find(|table| &table.id == linked) .ok_or_else(|| format!("calls[{at}]: {column:?} links to {linked:?}, which is not a table here"))?; if target.column(by).is_none() { return Err(format!("calls[{at}]: {column:?} links by {by:?}, which is not a column of {linked:?}")); } } } } Ok(()) } } impl Call { fn parse(value: &Value) -> Result { let object = value.as_object().ok_or("a call is an object")?; let text = |key: &str| object.get(key).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()); let tool = text("tool").ok_or("tool is required")?.to_string(); let into = text("into").ok_or("into is required: the table the rows land in")?.to_string(); let key = text("key").ok_or("key is required: the path of a row's identity")?.to_string(); let args = match object.get("args") { None | Some(Value::Null) => Map::new(), Some(Value::Object(args)) => args.clone(), Some(_) => return Err("args must be an object".into()), }; let mut columns = BTreeMap::new(); if let Some(listed) = object.get("columns") { let listed = listed.as_object().ok_or("columns must be an object, column key to value")?; for (column, spec) in listed { columns.insert(column.clone(), ValueSpec::parse(spec).map_err(|why| format!("columns.{column}: {why}"))?); } } if columns.is_empty() { return Err("columns is empty: name at least one column".into()); } let page = match object.get("page") { None | Some(Value::Null) => None, Some(page) => { let page = page.as_object().ok_or("page must be an object")?; let field = |key: &str| page.get(key).and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string); Some(Paging { cursor_arg: field("cursor_arg").ok_or("page.cursor_arg is required")?, next_cursor: field("next_cursor").ok_or("page.next_cursor is required")?, }) } }; Ok(Call { tool, args, every: text("every").map(str::to_string), into, rows: text("rows").map(str::to_string), key, key_column: text("key_column").unwrap_or("external_id").to_string(), columns, page, }) } fn to_json(&self) -> Value { let mut object = Map::new(); object.insert("tool".into(), Value::from(self.tool.clone())); object.insert("args".into(), Value::Object(self.args.clone())); object.insert("every".into(), self.every.clone().map_or(Value::Null, Value::from)); object.insert("into".into(), Value::from(self.into.clone())); object.insert("rows".into(), self.rows.clone().map_or(Value::Null, Value::from)); object.insert("key".into(), Value::from(self.key.clone())); object.insert("key_column".into(), Value::from(self.key_column.clone())); object.insert( "columns".into(), Value::Object(self.columns.iter().map(|(column, spec)| (column.clone(), spec.to_json())).collect()), ); object.insert( "page".into(), self.page.as_ref().map_or(Value::Null, |page| { serde_json::json!({"cursor_arg": page.cursor_arg, "next_cursor": page.next_cursor}) }), ); Value::Object(object) } /// How often this call runs: its own word, else the connection's, else /// [`DEFAULT_EVERY`]. pub fn every(&self, connection_schedule: Option<&str>) -> Duration { self.every .as_deref() .or(connection_schedule) .and_then(|word| parse_every(word).ok()) .unwrap_or_else(|| parse_every(DEFAULT_EVERY).expect("the default schedule parses")) } /// The rows one answer carries, as the mapping finds them. /// /// `result` is the MCP `tools/call` result. A server that fills /// `structuredContent` is read there; otherwise the first text content is /// read as JSON. `isError` is the server's refusal and is answered as one. pub fn rows_of(&self, result: &Value) -> Result, String> { let answer = answer_of(result)?; let found = match &self.rows { None => &answer, Some(path) => value_at(&answer, path).ok_or_else(|| format!("the answer has nothing at {path:?}"))?, }; let rows = found.as_array().cloned().ok_or_else(|| match &self.rows { None => "the answer is not a list of rows; say where the rows are with \"rows\"".to_string(), Some(path) => format!("{path:?} in the answer is not a list"), })?; // A server that cuts a long answer to fit (Cloudflare's ends the list // with "--- TRUNCATED --- n more items") must not pass for a whole // read: the rows past the cut would be missed with no word said. if let Some(cut) = rows.iter().find_map(|row| row.as_str().filter(|text| text.trim_start().starts_with("--- TRUNCATED"))) { return Err(format!("the server cut its answer short ({}), so this read is not whole; ask it for smaller pages or turn its truncation off", cut.trim())); } Ok(rows) } /// The cursor the next page is asked with, if the answer offers one. pub fn next_cursor(&self, result: &Value) -> Option { let page = self.page.as_ref()?; let answer = answer_of(result).ok()?; value_at(&answer, &page.next_cursor) .and_then(|cursor| match cursor { Value::String(text) if !text.is_empty() => Some(text.clone()), Value::Number(number) => Some(number.to_string()), _ => None, }) } /// Shape one row of the answer as the table takes it. pub fn shape(&self, row: &Value) -> Result { let key = value_at(row, &self.key) .and_then(scalar_text) .ok_or_else(|| format!("a row has no {:?}", self.key))?; let mut shaped = Shaped { key: key.clone(), ..Shaped::default() }; shaped.data.insert(self.key_column.clone(), Value::from(key)); for (column, spec) in &self.columns { match spec { ValueSpec::Literal(value) => { shaped.data.insert(column.clone(), value.clone()); } ValueSpec::Path { path, coerce } => { if let Some(value) = value_at(row, path) { if let Some(value) = coerced(value, coerce.as_ref()) { shaped.data.insert(column.clone(), value); } } } ValueSpec::Link { path, table, column: by } => { if let Some(value) = value_at(row, path).and_then(scalar_text) { shaped.links.push((column.clone(), table.clone(), by.clone(), value)); } } } } Ok(shaped) } } impl ValueSpec { fn parse(value: &Value) -> Result { match value { Value::String(path) if !path.trim().is_empty() => Ok(ValueSpec::Path { path: path.trim().to_string(), coerce: None }), Value::String(_) => Err("a path is empty".into()), Value::Object(object) => { if let Some(literal) = object.get("value") { if object.len() != 1 { return Err("a literal is {\"value\": …} and nothing beside it".into()); } return Ok(ValueSpec::Literal(literal.clone())); } let path = object .get("path") .and_then(Value::as_str) .map(str::trim) .filter(|path| !path.is_empty()) .ok_or("path is required")? .to_string(); if let Some(link) = object.get("link") { let link = link.as_object().ok_or("link must be {\"table\", \"column\"}")?; let field = |key: &str| link.get(key).and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string); return Ok(ValueSpec::Link { path, table: field("table").ok_or("link.table is required")?, column: field("column").ok_or("link.column is required")?, }); } let coerce = match object.get("as").and_then(Value::as_str) { None => None, Some("date") => Some(Coerce::Date), Some("text") => Some(Coerce::Text), Some("number") => Some(Coerce::Number), Some("bool") => Some(Coerce::Bool), Some(other) => return Err(format!("as {other:?} is not one of date, text, number, bool")), }; Ok(ValueSpec::Path { path, coerce }) } _ => Err("a column's value is a path, {\"value\": …} or {\"path\", \"link\"}".into()), } } fn to_json(&self) -> Value { match self { ValueSpec::Path { path, coerce: None } => Value::from(path.clone()), ValueSpec::Path { path, coerce: Some(coerce) } => serde_json::json!({"path": path, "as": match coerce { Coerce::Date => "date", Coerce::Text => "text", Coerce::Number => "number", Coerce::Bool => "bool", }}), ValueSpec::Literal(value) => serde_json::json!({"value": value}), ValueSpec::Link { path, table, column } => serde_json::json!({"path": path, "link": {"table": table, "column": column}}), } } } /// "30m", "6h", "1d" — minutes, hours or days, a whole number of them. pub fn parse_every(word: &str) -> Result { let word = word.trim(); let (digits, unit) = word.split_at(word.trim_end_matches(|c: char| c.is_ascii_alphabetic()).len()); let count: u64 = digits .parse() .ok() .filter(|count| *count > 0) .ok_or_else(|| format!("{word:?} is not a schedule like 30m, 6h or 1d"))?; let seconds = match unit { "m" => 60, "h" => 3600, "d" => 86_400, _ => return Err(format!("{word:?} is not a schedule like 30m, 6h or 1d")), }; Ok(Duration::from_secs(count * seconds)) } /// The JSON a `tools/call` result carries. fn answer_of(result: &Value) -> Result { if result.get("isError").and_then(Value::as_bool) == Some(true) { let said = first_text(result).unwrap_or_else(|| "the server answered an error".to_string()); return Err(format!("the server refused: {said}")); } if let Some(structured) = result.get("structuredContent").filter(|value| !value.is_null()) { return Ok(structured.clone()); } let text = first_text(result).ok_or("the answer carries no text and no structuredContent")?; serde_json::from_str(&text).map_err(|_| "the answer's text is not JSON".to_string()) } fn first_text(result: &Value) -> Option { result .get("content")? .as_array()? .iter() .find(|item| item.get("type").and_then(Value::as_str) == Some("text"))? .get("text")? .as_str() .map(str::to_string) } /// A dotted path into a value: `plan.name`, `result.0.id`. pub fn value_at<'a>(value: &'a Value, path: &str) -> Option<&'a Value> { let mut cursor = value; for step in path.split('.') { cursor = match cursor { Value::Object(object) => object.get(step)?, Value::Array(items) => items.get(step.parse::().ok()?)?, _ => return None, }; } Some(cursor) } fn scalar_text(value: &Value) -> Option { match value { Value::String(text) if !text.is_empty() => Some(text.clone()), Value::Number(number) => Some(number.to_string()), _ => None, } } /// A value as the column takes it: a list of scalars is joined, an object is /// its JSON, null is left out; `as` narrows further. fn coerced(value: &Value, coerce: Option<&Coerce>) -> Option { if value.is_null() { return None; } match coerce { None => Some(match value { Value::Array(items) if items.iter().all(|item| !item.is_object() && !item.is_array()) => Value::from( items.iter().filter_map(|item| scalar_text(item).or_else(|| item.as_bool().map(|b| b.to_string()))).collect::>().join(", "), ), Value::Array(_) | Value::Object(_) => Value::from(value.to_string()), other => other.clone(), }), Some(Coerce::Text) => Some(match value { Value::String(text) => Value::from(text.clone()), other => Value::from(other.to_string()), }), Some(Coerce::Date) => { let text = value.as_str()?; let day = text.get(..10)?; (day.len() == 10 && day.as_bytes()[4] == b'-' && day.as_bytes()[7] == b'-').then(|| Value::from(day)) } Some(Coerce::Number) => match value { Value::Number(number) => Some(Value::Number(number.clone())), Value::String(text) => text.trim().parse::().ok().and_then(serde_json::Number::from_f64).map(Value::Number), _ => None, }, Some(Coerce::Bool) => match value { Value::Bool(flag) => Some(Value::Bool(*flag)), Value::String(text) => match text.trim().to_ascii_lowercase().as_str() { "true" | "yes" | "1" => Some(Value::Bool(true)), "false" | "no" | "0" => Some(Value::Bool(false)), _ => None, }, Value::Number(number) => Some(Value::Bool(number.as_f64() != Some(0.0))), _ => None, }, } } /// A skeleton for a server whose tools nobody has mapped yet: one call per /// tool with the columns left to fill, so the assistant's proposal starts /// from the server's own names rather than from nothing. Not a valid /// mapping — `into` and `columns` are the person's to say. pub fn skeleton(tools: &[Value]) -> Value { let calls: Vec = tools .iter() .filter_map(|tool| { let name = tool.get("name")?.as_str()?; Some(serde_json::json!({ "tool": name, "args": {}, "every": DEFAULT_EVERY, "into": "", "rows": null, "key": "id", "key_column": "external_id", "columns": {}, "description": tool.get("description").cloned().unwrap_or(Value::Null), "inputSchema": tool.get("inputSchema").cloned().unwrap_or(Value::Null), })) }) .collect(); serde_json::json!({ "calls": calls }) } #[cfg(test)] #[path = "mapping_tests.rs"] mod mapping_tests;