//! Typed connection state, scoped by the same read database as other MCP reads. use crate::connections::refusal::ConnectionRefusal; use crate::mcp::dispatch::{Ctx, ToolResult}; use crate::mcp::handlers::common::{optional_string, require_string, rows}; use crate::mcp::protocol::ToolFailure; use crate::mcp::read_db::{Order, Query}; use cotton_core::transforms::redact::{redact_connection_config, redact_connection_text}; use serde_json::{json, Map, Value}; const COLUMNS: &[&str] = &[ "id", "kind", "name", "reaches", "state", "last_read_at", "last_error", "read_requested_at", "schedule", "secret_id", "config", "database_id", ]; fn answer(ctx: &Ctx<'_>, mut row: Map) -> Result { let config = match row.remove("config") { Some(Value::String(text)) => serde_json::from_str(&text) .map_err(|_| ConnectionRefusal::SettingsUnreadable.failure(ctx))?, Some(value) => value, None => json!({}), }; row.insert("config".into(), redact_connection_config(&config)); // The address and the last error are text a server or a person wrote: a // URL with its userinfo, or an upstream error echoing the key it refused. for column in ["name", "reaches", "last_error"] { if let Some(Value::String(text)) = row.get(column) { let safe = redact_connection_text(text); row.insert(column.into(), Value::String(safe)); } } // database_id is the connection's stored destination; database is its home. row.insert("database".into(), Value::from(ctx.workspace_id)); Ok(Value::Object(row)) } pub fn list_connections(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let mut query = Query::on("cotton_connections") .columns(COLUMNS) .order_by("id", Order::Asc); if let Some(kind) = optional_string(args, "kind") { query = query.eq("kind", kind); } // Like list_devices and list_secrets, this small catalogue answers whole. let connections = rows(ctx, &query)? .into_iter() .map(|row| answer(ctx, row)) .collect::, _>>()?; Ok(json!({"connections": connections})) } pub fn get_connection(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let id = require_string(args, "id") .ok_or_else(|| ToolFailure::new("Pass id: the connection's id."))?; let query = Query::on("cotton_connections") .columns(COLUMNS) .eq("id", id); let row = rows(ctx, &query)? .into_iter() .next() .ok_or_else(|| ConnectionRefusal::Gone.failure(ctx))?; // The store keeps current read state, not a read-attempt history. Ok(json!({"connection": answer(ctx, row)?})) }