//! The DOMAINS tool as data — tables `domain` and `dns_record` — and the//! Cloudflare mapping that fills them (decision note 7767ed9c, piece 4).//!//! Carried in this crate rather than shipped as a file so the bridge can//! INSTALL it into whichever database a Cloudflare connection lands in,//! through the same checks a pasted package passes//! (`tool_packages::install_package`). It is an ordinary package: no engine,//! no Swift, rows in its own made tables, the shared list and page draw it.//!//! The mapping targets Cloudflare's own MCP server at//! `https://mcp.cloudflare.com/mcp`, which exposes the whole API through two//! tools, `search` and `execute`; `execute` runs a JavaScript async arrow//! function with `cloudflare.request({method, path})` in scope, with the//! credential's own permissions. Three calls: the zones, the registrar's//! domains (renewal dates, keyed by name so they land on the zone's row), and//! every zone's DNS records. The answer shapes are the Cloudflare API's own//! (`result` is the list; a zone has `id`, `name`, `status`, `plan.name`,//! `name_servers`, `created_on`; a record has `zone_id`, `name`, `type`,//! `content`, `ttl`, `proxied`, `priority`, `comment`).usesuper::mapping::{Mapping, Shaped};usecrate::mcp::dispatch::Ctx;usecrate::mcp::protocol::ToolFailure;use cotton_core::definitions::{package::ToolPackage, TableDefinition, ToolDefinition};use serde_json::{json, Value};pubconst TOOL_ID: &str = "domains";pubconst DOMAIN: &str = "domain";pubconst DNS_RECORD: &str = "dns_record";/// The package, decoded from the JSON beside this file.pubfn package() -> ToolPackage {let tool: ToolDefinition = serde_json::from_str(include_str!("domains/manifest.json")).expect("domains/manifest.json parses");let tables: Vec<TableDefinition> = [ include_str!("domains/tables/domain.json"), include_str!("domains/tables/dns_record.json"), ] .into_iter() .map(|raw| serde_json::from_str(raw).expect("a domains table parses")) .collect();ToolPackage { board: None, tool, tables, pictures: Default::default(), samples: Default::default() }}/// This build's own definition of a table Cotton itself carries and lets/// declare commands (`cotton_core::definitions::CARRIED_COMMAND_TABLES`), or/// `None` for any other table. The ONE place the commands of such a table are/// read from: what runs (`records.command`) and what an install by any other/// door writes (`install_package`) are both this, never a definition that/// arrived in a file or sits in a database's row.pubfn carried_table(id: &str) -> Option<TableDefinition> {if !cotton_core::definitions::CARRIED_COMMAND_TABLES.contains(&id) {returnNone; } package().tables.into_iter().find(|table| table.id == id)}/// Add the Domains tool to this file — the owner's act (`add_tool`, or/// connecting Cloudflare) — or bring it to this build's shape when it is/// already here. Answers whether it was written now.////// At this build's shape: a Domains installed by an older build lacks the/// columns a later one added (DNS at, Points to, Managed for), and nothing/// else would ever bring them — a package's definitions are not seeded at/// server start as a built-in's are. So a stored table missing a column the/// package declares is upgraded in place, through the same door/// (`install_package`: a column that stays keeps its type, rows are not/// touched). A table that has every column is left as it stands, so what the/// person changed on it — a label, the page's order — survives every pass.pubfn add(ctx: &mutCtx<'_>) -> Result<bool, ToolFailure> {let package = package();letmut current = installed_tool(ctx)?;for table in &package.tables { current = current && !crate::definitions::definition_rows(ctx, Some(&table.id))?.is_empty() && !behind(&crate::mcp::handlers::tables::definition(ctx, &table.id)?, table); }if current {returnOk(false); }crate::mcp::handlers::tool_packages::install_package(ctx, &package, crate::mcp::handlers::tool_packages::Door::Cotton, false)?;Ok(true)}/// The bridge's pass over a Domains this database HOLDS: brought to this/// build's shape ([`add`]), never installed — a tool is a record, added only/// by the owner (`add_tool`, or connecting Cloudflare, the connection's own/// setup act), so a Domains the owner removed stays removed. `None` when this/// database holds no Domains tool.pubfn ensure_installed(ctx: &mutCtx<'_>) -> Result<Option<bool>, ToolFailure> {if !installed_tool(ctx)? {returnOk(None); } add(ctx).map(Some)}/// Whether a stored table lacks a column this build's table declares — or/// an act: a page drawn off a stored table with no Reach this household here/// would never offer it, though `records.command` runs the build's own.pubfn behind(stored: &TableDefinition, shipped: &TableDefinition) -> bool {let acts = |table: &TableDefinition| -> Vec<String> { table.commands.iter().flatten().map(|command| command.id.clone()).collect() }; shipped.columns.iter().any(|column| !stored.columns.iter().any(|held| held.key == column.key)) || acts(shipped).iter().any(|act| !acts(stored).contains(act))}fn installed_tool(ctx: &Ctx<'_>) -> Result<bool, ToolFailure> {Ok(crate::mcp::handlers::tool_packages::live_tool_definitions(ctx)? .iter() .any(|tool| tool.id == TOOL_ID))}/// The URL the bridge dials for a server. Cloudflare's API server cuts any/// tool answer over about 24,000 characters unless asked not to, and a/// zone's DNS records pass that; `truncateToolResult=false` turns it off/// (github.com/cloudflare/mcp, src/truncate.ts). Every other server is/// dialled as the person gave it.pubfn dial_url(server_url: &str) -> String {letOk(mut url) = url::Url::parse(server_url) else {return server_url.to_string(); };if url.host_str().map(str::to_ascii_lowercase).as_deref() != Some("mcp.cloudflare.com") || url.query_pairs().any(|(key, _)| key == "truncateToolResult") {return server_url.to_string(); } url.query_pairs_mut().append_pair("truncateToolResult", "false"); url.to_string()}/// Whether a server is Cloudflare's API server, the one [`cloudflare_mapping`] speaks to.pubfn is_cloudflare_api(server_url: &str, tools: &[Value]) -> bool {let host = url::Url::parse(server_url).ok().and_then(|url| url.host_str().map(str::to_ascii_lowercase));let names: Vec<&str> = tools.iter().filter_map(|tool| tool.get("name")?.as_str()).collect(); host.as_deref() == Some("mcp.cloudflare.com") && names.contains(&"execute")}/// The JS every Cloudflare read pages with: every page up to the answer's/// `total_pages` (Cloudflare caps `per_page`, 50 for zones and accounts), so/// the last partial page is read too. A server that keeps answering past/// 1000 pages is an error, never a quiet stop that loses the rest.macro_rules! all_pages { () => {"const all = async (path) => { const out = []; for (let page = 1; ; page++) { const r = await cloudflare.request({ method: 'GET', path: `${path}&page=${page}` }); out.push(...(r.result || [])); if (!r.result_info || !(page < r.result_info.total_pages)) return out; if (page >= 1000) throw new Error(`${path}: more than 1000 pages`); } }; " };}const ZONES: &str = concat!("async () => { ", all_pages!(), "return await all('/zones?per_page=50'); }");const REGISTRAR: &str = concat!("async () => { ", all_pages!(), "const accounts = await all('/accounts?per_page=50'); const out = []; for (const account of accounts) { let domains; try { domains = await all(`/accounts/${account.id}/registrar/domains?per_page=50`); } catch (e) { /* an account without the registrar is not an error */ continue; } out.push(...domains); } return out; }");const RECORDS: &str = concat!("async () => { ", all_pages!(), "const zones = await all('/zones?per_page=50'); const out = []; for (const zone of zones) { out.push(...(await all(`/zones/${zone.id}/dns_records?per_page=500`))); } return out; }");/// The mapping for Cloudflare's API server: zones and registrar domains into/// `domain`, every zone's records into `dns_record`.pubfn cloudflare_mapping() -> Mapping {Mapping::parse(&json!({"calls": [ {"tool": "execute", "args": {"code": ZONES}, "every": "6h", "into": DOMAIN, "rows": null, "key": "id", "key_column": "external_id","columns": {"name": "name", "status": "status", "plan": "plan.name", "nameservers": "name_servers","created": {"path": "created_on", "as": "date"}, "account": "account.name","provider": {"value": "cloudflare"}, "dns_at": {"value": "cloudflare"} }}, {"tool": "execute", "args": {"code": REGISTRAR}, "every": "1d", "into": DOMAIN, "rows": null, "key": "name", "key_column": "name","columns": {"expires": {"path": "expires_at", "as": "date"}, "auto_renew": "auto_renew","registrar": {"value": "cloudflare"} }}, {"tool": "execute", "args": {"code": RECORDS}, "every": "6h", "into": DNS_RECORD, "rows": null, "key": "id", "key_column": "external_id","columns": {"name": "name", "type": "type", "content": "content", "ttl": {"path": "ttl", "as": "number"},"proxied": "proxied", "priority": {"path": "priority", "as": "number"}, "comment": "comment","domain": {"path": "zone_id", "link": {"table": DOMAIN, "column": "external_id"}} }} ]})) .expect("the Cloudflare mapping parses")}/// One account's rows, shaped: what [`shape_account`] answers.#[derive(Debug, Clone, Default, PartialEq)]pubstructAccountRows {/// One per zone, keyed by the zone's id (`external_id`), with its/// registration's facts folded in where the account registers it too.pub zones: Vec<Shaped>,/// A registration with no zone in the account, keyed by `name`.pub unzoned: Vec<Shaped>,/// Every zone's records, keyed by the record's id, linked to its zone.pub records: Vec<Shaped>,}/// Shape what Cloudflare's API answers — `/zones`, the registrar's domains,/// every zone's `/dns_records` — into the Domains rows, by the same mapping/// the bridge reads Cloudflare's MCP server with, so a row is the same/// whichever door brought it. Two things a mapping's columns cannot say are/// said here, because this reader holds the whole answer at once:////// - a zone and its registration are ONE row: the registration's expiry is/// folded into the zone's row rather than written as a second patch;/// - `dns_at` is Cloudflare only for a zone Cloudflare answers for (`active`);/// one still waiting on its nameservers is listed without it. A zone the/// account does not register says the registrar Cloudflare saw when the/// zone was added (`original_registrar`), where it saw one.pubfn shape_account(zones: &[Value], registrar: &[Value], records: &[Value]) -> Result<AccountRows, String> {let mapping = cloudflare_mapping();let call = |table: &str, key_column: &str| { mapping .calls .iter() .find(|call| call.into == table && call.key_column == key_column) .ok_or_else(|| format!("the Cloudflare mapping has no call into {table} by {key_column}")) };let (zone_call, registrar_call, record_call) = (call(DOMAIN, "external_id")?, call(DOMAIN, "name")?, call(DNS_RECORD, "external_id")?);letmut registered: Vec<(bool, Shaped)> = Vec::new();for domain in registrar { registered.push((false, registrar_call.shape(domain)?)); }letmut rows = AccountRows::default();for zone in zones {letmut shaped = zone_call.shape(zone)?;if zone.get("status").and_then(Value::as_str) != Some("active") { shaped.data.remove("dns_at"); }let name = zone.get("name").and_then(Value::as_str).unwrap_or_default();match registered.iter_mut().find(|(_, registration)| registration.key.eq_ignore_ascii_case(name)) {Some((folded, registration)) => { *folded = true;for (column, value) in registration.data.iter().filter(|(column, _)| *column != "name") { shaped.data.insert(column.clone(), value.clone()); } }None => {ifletSome(seen) = zone.get("original_registrar").and_then(Value::as_str).filter(|seen| !seen.trim().is_empty()) { shaped.data.insert("registrar".into(), Value::from(seen.trim())); } } } rows.zones.push(shaped); } rows.unzoned = registered.into_iter().filter(|(folded, _)| !folded).map(|(_, registration)| registration).collect();for record in records { rows.records.push(record_call.shape(record)?); }Ok(rows)}/// What an assistant proposes for a server: the Cloudflare mapping with the/// Domains tool to install when the server is Cloudflare's, otherwise a/// skeleton from the server's own tools for the assistant to fill.pubfn propose(server_url: &str, tools: &[Value]) -> Value {if is_cloudflare_api(server_url, tools) {return json!({"mapping": cloudflare_mapping().to_json(),"installs": [TOOL_ID],"ready": true,"note": "Cloudflare's API server: zones and registrar domains land in domain, every zone's records in dns_record. Keep it with set_connection_mapping, or change a column first." }); } json!({"mapping": super::mapping::skeleton(tools),"installs": [],"ready": false,"note": "No mapping is known for this server. Fill each call's into, key and columns from the tool's answer shape (its description and inputSchema are beside it), drop the calls that are not reads, then set_connection_mapping." })}#[cfg(test)]#[path = "domains_tests.rs"]mod domains_tests;