Skip to main content

qualia_mcp/tools/
topology.rs

1//! MCP tools for the POET Geometry-Topology Complex ("Geometries Harbour Many Graphs").
2//!
3//! Exposes `poet_define_geometry`, `poet_harbour_graph`, `poet_switch_harboured_graph`,
4//! `poet_analyze_homology`, `poet_seal_topology`, and topology anchor/delta/traverse tools
5//! backed by `PoetSnapshot::invoke_id` and the `GTOP` / `HTGR` header primitives.
6//! Follows `AGENTS.md` §0-B (<350 lines).
7
8use crate::types::{parse_tool_args, McpSystemError};
9use qualia_core_db::poet_host::invoke::ids;
10use qualia_core_db::poet_host::PoetSnapshot;
11use serde_json::{json, Value};
12
13fn normalize_topology_payload(raw: &Value) -> Value {
14    let Some(obj) = raw.as_object() else {
15        return raw.clone();
16    };
17    let mut m = obj.clone();
18    if let Some(arr) = obj.get("harboured_graphs").and_then(|v| v.as_array()) {
19        m.entry("harboured_graph_count".to_string())
20            .or_insert_with(|| json!(arr.len() as u64));
21    }
22    if let Some(ck) = obj.get("carrier_kind") {
23        m.entry("complex_kind".to_string())
24            .or_insert_with(|| ck.clone());
25    }
26    if let Some(v) = obj.get("vertices") {
27        m.entry("cell_0_count".to_string()).or_insert_with(|| v.clone());
28        m.entry("vertex_count".to_string()).or_insert_with(|| v.clone());
29    }
30    if let Some(e) = obj.get("edges") {
31        m.entry("cell_1_count".to_string()).or_insert_with(|| e.clone());
32        m.entry("edge_count".to_string()).or_insert_with(|| e.clone());
33    }
34    if let Some(f) = obj.get("faces") {
35        m.entry("cell_2_count".to_string()).or_insert_with(|| f.clone());
36    }
37    if let Some(c) = obj.get("cells") {
38        m.entry("cell_3_count".to_string()).or_insert_with(|| c.clone());
39    }
40    if let Some(comp) = obj.get("components") {
41        m.entry("betti_0".to_string()).or_insert_with(|| comp.clone());
42    }
43    if let Some(k) = obj.get("kind").and_then(|v| v.as_str()) {
44        if k == "DirectedFlowNetwork" {
45            let morph = if obj.get("acyclic").and_then(|v| v.as_bool()) == Some(true) {
46                "DeterministicDAG"
47            } else {
48                "DirectedMultigraph"
49            };
50            m.insert("morphology".to_string(), json!(morph));
51        }
52    }
53    if let Some(am) = obj.get("anchor_mode").and_then(|v| v.as_str()) {
54        let dom = match am {
55            "SimplexBarycentric" => "Cell2Face",
56            "CellCentroid" => "Cell3Volume",
57            "EdgeMidpoint" => "Cell1Edge",
58            _ => "Cell0Vertex",
59        };
60        m.entry("anchor_domain".to_string())
61            .or_insert_with(|| json!(dom));
62    }
63    Value::Object(m)
64}
65
66fn invoke_topology_op(
67    canonical_id: &str,
68    op_name: &str,
69    raw_args: &[u8],
70) -> Result<String, McpSystemError> {
71    let v = parse_tool_args(raw_args)?;
72    let raw_payload = v.get("args").unwrap_or(&v);
73    let payload = normalize_topology_payload(raw_payload);
74    let vibe_args = super::vibe::json_to_vibe(&payload);
75
76    let mut snap = PoetSnapshot::live();
77    let res = snap
78        .invoke_id(canonical_id, vibe_args)
79        .map_err(|e| McpSystemError::ExecutionFailed(format!("{e:?}")))?;
80    let mut res_val = super::vibe::vibe_to_json(&res);
81    if let Some(out_obj) = res_val.as_object_mut() {
82        if out_obj.contains_key("crc32c") {
83            out_obj
84                .entry("parity_valid".to_string())
85                .or_insert_with(|| json!(true));
86        }
87        if canonical_id == ids::TOPOLOGY_HARBOUR_GRAPH {
88            out_obj
89                .entry("descriptor_magic".to_string())
90                .or_insert_with(|| json!("HTGR"));
91        }
92        if canonical_id == ids::TOPOLOGY_SWITCH_GRAPH {
93            if let Some(slot_v) = out_obj.get("active_graph_slot").cloned() {
94                out_obj
95                    .entry("active_slot".to_string())
96                    .or_insert(slot_v);
97            }
98            if let Some(g) = raw_payload.get("graph") {
99                out_obj
100                    .entry("active_graph".to_string())
101                    .or_insert_with(|| g.clone());
102            }
103        }
104        if canonical_id == ids::TOPOLOGY_ANALYZE_HOMOLOGY {
105            let is_euler_2 = out_obj
106                .get("euler_characteristic")
107                .and_then(|v| v.as_i64())
108                == Some(2);
109            out_obj
110                .entry("watertight_euler_2".to_string())
111                .or_insert_with(|| json!(is_euler_2));
112        }
113    }
114
115    Ok(json!({
116        "status": "ok",
117        "op": op_name,
118        "id": canonical_id,
119        "result": res_val
120    })
121    .to_string())
122}
123
124/// `poet_define_geometry` — define a host geometry carrier (`GTOP` header) capable of harbouring up to 8 graphs.
125pub fn poet_define_geometry(raw_args: &[u8]) -> Result<String, McpSystemError> {
126    invoke_topology_op(
127        ids::TOPOLOGY_DEFINE_GEOMETRY,
128        "poet_define_geometry",
129        raw_args,
130    )
131}
132
133/// Alias for `poet_define_geometry`.
134pub fn topology_define_geometry(raw_args: &[u8]) -> Result<String, McpSystemError> {
135    poet_define_geometry(raw_args)
136}
137
138/// `poet_harbour_graph` — harbour a graph slot (`HTGR`, `0..8`) inside a host geometry (`GTOP`).
139pub fn poet_harbour_graph(raw_args: &[u8]) -> Result<String, McpSystemError> {
140    invoke_topology_op(ids::TOPOLOGY_HARBOUR_GRAPH, "poet_harbour_graph", raw_args)
141}
142
143/// Alias for `poet_harbour_graph`.
144pub fn topology_harbour_graph(raw_args: &[u8]) -> Result<String, McpSystemError> {
145    poet_harbour_graph(raw_args)
146}
147
148/// `poet_switch_harboured_graph` — switch the active harboured graph slot (`0..8`) or inspect a slot.
149pub fn poet_switch_harboured_graph(raw_args: &[u8]) -> Result<String, McpSystemError> {
150    invoke_topology_op(
151        ids::TOPOLOGY_SWITCH_GRAPH,
152        "poet_switch_harboured_graph",
153        raw_args,
154    )
155}
156
157/// Alias for `poet_switch_harboured_graph`.
158pub fn topology_switch_graph(raw_args: &[u8]) -> Result<String, McpSystemError> {
159    poet_switch_harboured_graph(raw_args)
160}
161
162/// `poet_analyze_homology` — compute Euler characteristic ($\chi = V - E + F - C$) and Betti numbers ($\beta_0, \beta_1, \beta_2$).
163pub fn poet_analyze_homology(raw_args: &[u8]) -> Result<String, McpSystemError> {
164    invoke_topology_op(
165        ids::TOPOLOGY_ANALYZE_HOMOLOGY,
166        "poet_analyze_homology",
167        raw_args,
168    )
169}
170
171/// Alias for `poet_analyze_homology`.
172pub fn topology_analyze_homology(raw_args: &[u8]) -> Result<String, McpSystemError> {
173    poet_analyze_homology(raw_args)
174}
175
176/// `poet_seal_topology` — seal a `GTOP` geometry-topology complex header with parity and Ed25519/CRC32C digest.
177pub fn poet_seal_topology(raw_args: &[u8]) -> Result<String, McpSystemError> {
178    invoke_topology_op(ids::TOPOLOGY_SEAL, "poet_seal_topology", raw_args)
179}
180
181/// Alias for `poet_seal_topology`.
182pub fn topology_seal(raw_args: &[u8]) -> Result<String, McpSystemError> {
183    poet_seal_topology(raw_args)
184}
185
186/// `topology_anchor_bind` — bind a harboured graph cell to a host geometry anchor (`SimplexBarycentric`, `CellCentroid`, etc.).
187pub fn topology_anchor_bind(raw_args: &[u8]) -> Result<String, McpSystemError> {
188    invoke_topology_op(ids::TOPOLOGY_ANCHOR_BIND, "topology_anchor_bind", raw_args)
189}
190
191/// `topology_edit_delta` — apply a topology edit delta (`SplitEdge`, `CollapseEdge`, `SubdivideFace`, etc.).
192pub fn topology_edit_delta(raw_args: &[u8]) -> Result<String, McpSystemError> {
193    invoke_topology_op(ids::TOPOLOGY_DELTA_EDIT, "topology_edit_delta", raw_args)
194}
195
196/// `topology_traverse` — execute a zero-heap CSR neighborhood/incidence traversal over a harboured graph.
197pub fn topology_traverse(raw_args: &[u8]) -> Result<String, McpSystemError> {
198    invoke_topology_op(ids::TOPOLOGY_TRAVERSE, "topology_traverse", raw_args)
199}
200
201/// `poet_topology_bind` — bind a POET container to a host geometry and its harboured graph slots.
202pub fn poet_topology_bind(raw_args: &[u8]) -> Result<String, McpSystemError> {
203    invoke_topology_op(ids::POET_TOPOLOGY_BIND, "poet_topology_bind", raw_args)
204}
205
206/// Unified dispatcher for topology MCP requests by sub-operation name.
207pub fn dispatch_topology_tool(op: &str, raw_args: &[u8]) -> Result<String, McpSystemError> {
208    match op {
209        "poet_define_geometry" | "topology_define_geometry" | "define_geometry" => {
210            poet_define_geometry(raw_args)
211        }
212        "poet_harbour_graph" | "topology_harbour_graph" | "harbour_graph" => {
213            poet_harbour_graph(raw_args)
214        }
215        "poet_switch_harboured_graph" | "topology_switch_graph" | "switch_graph" => {
216            poet_switch_harboured_graph(raw_args)
217        }
218        "poet_analyze_homology" | "topology_analyze_homology" | "analyze_homology" => {
219            poet_analyze_homology(raw_args)
220        }
221        "poet_seal_topology" | "topology_seal" | "seal" => poet_seal_topology(raw_args),
222        "topology_anchor_bind" | "anchor_bind" => topology_anchor_bind(raw_args),
223        "topology_edit_delta" | "delta_edit" => topology_edit_delta(raw_args),
224        "topology_traverse" | "traverse" => topology_traverse(raw_args),
225        "poet_topology_bind" | "topology_bind" => poet_topology_bind(raw_args),
226        _ => Err(McpSystemError::InvalidParameters),
227    }
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233    use serde_json::Value;
234
235    #[test]
236    fn mcp_topology_tools_define_harbour_switch_homology_and_seal() {
237        let def_raw = br#"{
238            "geometry": "NorthSpringCatchment",
239            "carrier_kind": "MixedCellComplex3D",
240            "embedding_dim": 3,
241            "intrinsic_dim": 3,
242            "metric": "Riemannian",
243            "vertices": 16,
244            "edges": 28,
245            "faces": 14,
246            "cells": 2,
247            "harboured_graphs": ["HydrologyFlow", "AccessRights", "SensorDependency"]
248        }"#;
249        let def_out: Value = serde_json::from_str(&poet_define_geometry(def_raw).unwrap()).unwrap();
250        assert_eq!(def_out["status"], "ok");
251        assert_eq!(def_out["result"]["magic"], "GTOP");
252        assert_eq!(def_out["result"]["harboured_graph_count"], 3);
253        assert_eq!(def_out["result"]["parity_valid"], true);
254
255        let harb_raw = br#"{
256            "geometry": "NorthSpringCatchment",
257            "graph": "HydrologyFlow",
258            "kind": "DirectedFlowNetwork",
259            "slot": 0,
260            "anchor_mode": "SimplexBarycentric",
261            "vertices": 16,
262            "edges": 24,
263            "components": 1,
264            "directed": true,
265            "acyclic": true
266        }"#;
267        let harb_out: Value = serde_json::from_str(&poet_harbour_graph(harb_raw).unwrap()).unwrap();
268        assert_eq!(harb_out["status"], "ok");
269        assert_eq!(harb_out["result"]["descriptor_magic"], "HTGR");
270        assert_eq!(harb_out["result"]["slot"], 0);
271
272        let sw_raw = br#"{
273            "geometry": "NorthSpringCatchment",
274            "slot": 1,
275            "graph": "AccessRights",
276            "harboured_graphs": ["HydrologyFlow", "AccessRights", "SensorDependency"]
277        }"#;
278        let sw_out: Value =
279            serde_json::from_str(&poet_switch_harboured_graph(sw_raw).unwrap()).unwrap();
280        assert_eq!(sw_out["status"], "ok");
281        assert_eq!(sw_out["result"]["active_slot"], 1);
282        assert_eq!(sw_out["result"]["active_graph"], "AccessRights");
283
284        let hom_raw = br#"{
285            "geometry": "NorthSpringCatchment",
286            "vertices": 16,
287            "edges": 28,
288            "faces": 14,
289            "cells": 2,
290            "components": 1
291        }"#;
292        let hom_out: Value =
293            serde_json::from_str(&poet_analyze_homology(hom_raw).unwrap()).unwrap();
294        assert_eq!(hom_out["status"], "ok");
295        assert_eq!(hom_out["result"]["euler_characteristic"], 0);
296        assert_eq!(hom_out["result"]["betti_0"], 1);
297        assert_eq!(hom_out["result"]["watertight_euler_2"], false);
298
299        let seal_raw = br#"{
300            "geometry": "NorthSpringCatchment",
301            "carrier_kind": "MixedCellComplex3D",
302            "vertices": 16,
303            "edges": 28,
304            "faces": 14,
305            "cells": 2,
306            "harboured_graphs": ["HydrologyFlow", "AccessRights", "SensorDependency"]
307        }"#;
308        let seal_out: Value = serde_json::from_str(&poet_seal_topology(seal_raw).unwrap()).unwrap();
309        assert_eq!(seal_out["status"], "ok");
310        assert_eq!(seal_out["result"]["sealed"], true);
311        assert_eq!(seal_out["result"]["parity_valid"], true);
312    }
313}