1extern crate std;
5
6#[path = "mcp_format_impls.rs"]
7pub mod mcp_format_impls;
8#[path = "mcp_stub_impls.rs"]
9pub mod mcp_stub_impls;
10#[path = "mcp_tool_impls/mod.rs"]
11pub mod mcp_tool_impls;
12
13use crate::wal::append_mutation;
14use crate::NQuin;
15use core::ptr::write_volatile;
16use serde_json::{json, Value};
17use std::string::String;
18
19#[derive(Copy, Clone, PartialEq, Eq)]
21pub enum McpRuntimeState {
22 HandshakePhase,
23 AllocationFirewallActive,
24 SanctuaryGated,
25}
26
27#[derive(Debug)]
28pub enum McpSystemError {
29 SanctuaryGateTriggered,
30 ToolNotFound,
31 ToolNotReady,
32 ParseError,
33 IntentFrameViolation,
34 FeatureNotEnabled,
35 InvalidParameters,
36}
37
38#[derive(Debug, Clone)]
39pub struct McpIntentFrame {
40 pub purpose_hash: u64,
41 pub active_deontic_constraints: Vec<u64>,
42 pub active_profile_id: Option<u64>,
43 pub session_nonce: u64,
44 pub sanctuary_override: Option<[u8; 32]>,
49 pub qpu_enabled: bool,
50 pub llm_enabled: bool,
51}
52
53pub struct RawToolPayload<'a> {
55 pub tool_name: &'a [u8],
56 pub arguments_raw: &'a [u8],
57}
58
59#[derive(Clone, Copy)]
60struct McpToolDescriptor {
61 name: &'static str,
62 description: &'static str,
63 input_schema: &'static str,
64}
65
66fn extract_raw_json_string<'a>(payload: &'a [u8], key: &[u8]) -> Option<&'a [u8]> {
72 let mut i = 0;
74 while i < payload.len() {
75 if payload[i..].starts_with(key) {
76 i += key.len();
77 while i < payload.len() && (payload[i] == b' ' || payload[i] == b':') {
79 i += 1;
80 }
81 if i < payload.len() && payload[i] == b'"' {
82 i += 1;
83 let start = i;
84 while i < payload.len() && payload[i] != b'"' {
85 i += 1;
86 }
87 return Some(&payload[start..i]);
88 }
89 }
90 i += 1;
91 }
92 None
93}
94
95fn stable_mcp_tools() -> &'static [McpToolDescriptor] {
98 &[
99 McpToolDescriptor {
100 name: "query_graph",
101 description: "Run guarded graph traversal against the in-memory daemon graph.",
102 input_schema: r#"{"type":"object","properties":{"sanctuary_override":{"type":"string"}}}"#,
103 },
104 McpToolDescriptor {
105 name: "query_sparql",
106 description: "Execute an N-Triples pattern query against the in-process daemon graph.",
107 input_schema: r#"{"type":"object","required":["query"],"properties":{"query":{"type":"string"},"limit":{"type":"integer"}}}"#,
108 },
109 McpToolDescriptor {
110 name: "get_graph_stats",
111 description: "Return quin count and capacity for the resident daemon graph.",
112 input_schema: r#"{"type":"object","properties":{}}"#,
113 },
114 McpToolDescriptor {
115 name: "list_ontologies",
116 description: "List startup ontology catalog entries and on-disk presence.",
117 input_schema: r#"{"type":"object","properties":{}}"#,
118 },
119 McpToolDescriptor {
120 name: "llm_infer",
121 description: "Run local GGUF inference. Greedy by default. Optional exact seeded sampling: pass `sampler_cbor`, a hex-encoded CBOR map of SamplerConfig {temperature, top_k, top_p, repeat_penalty, freq_penalty, presence_penalty, penalty_window, seed}; temperature<=0 or absent ⇒ greedy.",
122 input_schema: r#"{"type":"object","required":["prompt"],"properties":{"prompt":{"type":"string"},"model_path":{"type":"string"},"graph_context":{"type":"string"},"sampler_cbor":{"type":"string","description":"hex-encoded CBOR map of SamplerConfig"}}}"#,
123 },
124 McpToolDescriptor {
125 name: "llm_chat",
126 description: "Multi-turn chat completion via the local GGUF inference stack.",
127 input_schema: r#"{"type":"object","required":["messages"],"properties":{"messages":{"type":"array"},"model_path":{"type":"string"},"graph_context":{"type":"string"}}}"#,
128 },
129 McpToolDescriptor {
130 name: "list_models",
131 description: "Discover GGUF models under storage and any resident mounted model.",
132 input_schema: r#"{"type":"object","properties":{}}"#,
133 },
134 McpToolDescriptor {
135 name: "qpu_optimize",
136 description: "Formulate a QUBO/circuit job from a problem description and classical solve.",
137 input_schema: r#"{"type":"object","required":["problem"],"properties":{"problem":{"type":"object"}}}"#,
138 },
139 McpToolDescriptor {
140 name: "qpu_dft",
141 description: "Bounded Thomas-Fermi DFT ground-state energy from quins or grid resolution.",
142 input_schema: r#"{"type":"object","properties":{"grid_resolution":{"type":"integer"},"quins":{"type":"array"}}}"#,
143 },
144 McpToolDescriptor {
145 name: "qpu_status",
146 description: "Return QPU bridge connection and job-queue status.",
147 input_schema: r#"{"type":"object","properties":{}}"#,
148 },
149 McpToolDescriptor {
150 name: "get_wallet_status",
151 description: "Inspect queued ILP micropayments from pending_payments.ndjson.",
152 input_schema: r#"{"type":"object","properties":{}}"#,
153 },
154 McpToolDescriptor {
155 name: "get_did_info",
156 description: "Parse a did:q42 identifier into its topological pointer hash.",
157 input_schema: r#"{"type":"object","required":["did"],"properties":{"did":{"type":"string"}}}"#,
158 },
159 McpToolDescriptor {
160 name: "ingest_ontology",
161 description: "Parse TTL/N3/q42 ontology file and extend the daemon graph.",
162 input_schema: r#"{"type":"object","required":["path"],"properties":{"path":{"type":"string"},"context_hash":{"type":"integer"}}}"#,
163 },
164 McpToolDescriptor {
165 name: "validate_shacl",
166 description: "Validate quins for a target subject/property against SHACL constraints.",
167 input_schema: r#"{"type":"object","required":["quins","target_subject","target_property","constraints"],"properties":{"quins":{"type":"array"},"target_subject":{"type":"integer"},"target_property":{"type":"integer"},"constraints":{"type":"array"}}}"#,
168 },
169 McpToolDescriptor {
170 name: "validate_enumerated_identity",
171 description: "SHACL identity extension: validate an identity as an enumerated state over multiple cryptographically-attested identifiers. A binding asserting certainty (confidence>=1.0) is rejected as a DefinitiveCollapse — identity must stay a confidence-relation (the out-of-band remainder). Returns verdict + distinct/attested counts + noisy-OR aggregate confidence.",
172 input_schema: r#"{"type":"object","required":["bindings"],"properties":{"bindings":{"type":"array","items":{"type":"object","properties":{"identifier":{"type":"integer"},"scheme":{"type":"string"},"attested":{"type":"boolean"},"confidence":{"type":"number"}}}},"min_distinct":{"type":"integer"},"min_attested":{"type":"integer"}}}"#,
173 },
174 McpToolDescriptor {
175 name: "shacl_credential_gate",
176 description: "SHACL identity extension: decide whether a verified W3C Verifiable Credential gates a SHACL target node — applies only if the credential's subject is the focus node, the issuer is accepted, and it carries the required claim. (Verify the VC signature/expiry via the identity layer first.)",
177 input_schema: r#"{"type":"object","required":["focus_node","gate","credential"],"properties":{"focus_node":{"type":"integer"},"gate":{"type":"object"},"credential":{"type":"object"}}}"#,
178 },
179 McpToolDescriptor {
180 name: "shacl_degrade_violations",
181 description: "SHACL identity extension: real-time severity degradation — off-grid, non-Critical violations degrade to non-blocking so a partial subgraph stays usable; Critical fails closed. Returns blocking/degraded counts and whether the subgraph is usable.",
182 input_schema: r#"{"type":"object","required":["violations"],"properties":{"violations":{"type":"array"},"mode":{"type":"string"}}}"#,
183 },
184 McpToolDescriptor {
185 name: "shacl_route",
186 description: "SHACL identity extension: decentralized shape-target routing — given shape->locus routes, enumerate the shapes that apply at a query_locus, or the loci a query_shape must be dispatched to (validation goes to the data, no central aggregation).",
187 input_schema: r#"{"type":"object","required":["routes"],"properties":{"routes":{"type":"array"},"query_locus":{"type":"integer"},"query_shape":{"type":"integer"}}}"#,
188 },
189 McpToolDescriptor {
190 name: "list_qapps",
191 description: "List installed qapps from storage Qapps directory.",
192 input_schema: r#"{"type":"object","properties":{}}"#,
193 },
194 McpToolDescriptor {
195 name: "get_qapp_manifest",
196 description: "Load qapp.json manifest for an installed or bundled qapp.",
197 input_schema: r#"{"type":"object","required":["qapp_name"],"properties":{"qapp_name":{"type":"string"}}}"#,
198 },
199 McpToolDescriptor {
200 name: "inspect_qapp_readiness",
201 description: "Check manifest, entrypoints, and ontology readiness for a qapp.",
202 input_schema: r#"{"type":"object","required":["qapp_name"],"properties":{"qapp_name":{"type":"string"}}}"#,
203 },
204 McpToolDescriptor {
205 name: "list_qapp_updates",
206 description: "Compare installed qapp versions against bundled update offers.",
207 input_schema: r#"{"type":"object","properties":{}}"#,
208 },
209 McpToolDescriptor {
210 name: "get_system_status",
211 description: "Return runtime status for the Qualia MCP surface.",
212 input_schema: r#"{"type":"object","properties":{}}"#,
213 },
214 McpToolDescriptor {
215 name: "list_capabilities",
216 description: "List the canonical Qualia capability catalogue with concrete operations, maturity, runtime surfaces, and executable MCP routes.",
217 input_schema: r#"{"type":"object","properties":{"domain":{"type":"string"},"maturity":{"type":"string","enum":["stable","partial","experimental","fail-closed"]},"surface":{"type":"string"}}}"#,
218 },
219 McpToolDescriptor {
220 name: "describe_qapp_surface_schema",
221 description: "Describe the current Qapp host surface schema exposed by Qualia.",
222 input_schema: r#"{"type":"object","properties":{}}"#,
223 },
224 McpToolDescriptor {
225 name: "inject_test_quin",
226 description: "Inject a deterministic test Quin through the paraconsistent router.",
227 input_schema: r#"{"type":"object","properties":{}}"#,
228 },
229 McpToolDescriptor {
230 name: "evaluate_modality",
231 description: "Evaluate logic modalities: ltl, asp, deontic, epistemic, dl, paraconsistent, probabilistic.",
232 input_schema: r#"{"type":"object","required":["modality"],"properties":{"modality":{"type":"string"},"quins":{"type":"array"},"trace":{"type":"array"},"formula":{"type":"object"},"now_unix":{"type":"integer"},"agent_did_hash":{"type":"integer"},"world_hash":{"type":"integer"}}}"#,
233 },
234 McpToolDescriptor {
235 name: "evaluate_logic_rules",
236 description: "Load N3 rules into the RuleEngine, fire them in the Webizen VM, and evaluate a Quin against the fired conclusions. Emits WAL audit events. Returns per-rule pass/fail verdicts.",
237 input_schema: r#"{"type":"object","required":["n3_source","quin"],"properties":{"n3_source":{"type":"string","description":"N3 rule text to parse and fire"},"quin":{"type":"object","description":"The Quin to evaluate","properties":{"subject":{"type":"integer"},"predicate":{"type":"integer"},"object":{"type":"integer"},"context":{"type":"integer"}}},"ruleset_name":{"type":"string","default":"default"},"contract_hash":{"type":"integer","default":0}}}"#,
238 },
239 McpToolDescriptor {
240 name: "matrix_operation",
241 description: "Linear algebra: multiply, transpose, solve, or inverse with caller-supplied matrices.",
242 input_schema: r#"{"type":"object","required":["op"],"properties":{"op":{"type":"string","enum":["multiply","transpose","solve","inverse"]},"left":{"type":"object","properties":{"id":{"type":"string"},"rows":{"type":"integer"},"cols":{"type":"integer"},"data":{"type":"array","items":{"type":"number"}}}},"right":{"type":"object"},"matrices":{"type":"array"},"result_id":{"type":"string"}}}"#,
243 },
244 McpToolDescriptor {
245 name: "algebra_solve_polynomial",
246 description: "Find all (real + complex) roots of a polynomial given descending coefficients.",
247 input_schema: r#"{"type":"object","required":["coeffs"],"properties":{"coeffs":{"type":"array","items":{"type":"number"},"description":"descending coefficients [c_n, ..., c_1, c_0]"}}}"#,
248 },
249 McpToolDescriptor {
250 name: "algebra_matrix_analyze",
251 description: "Determinant, eigenvalues (general), symmetric eigensystem, or SVD of a row-major matrix.",
252 input_schema: r#"{"type":"object","required":["op","rows","data"],"properties":{"op":{"type":"string","enum":["determinant","eigenvalues","eigen_symmetric","svd"]},"rows":{"type":"integer"},"cols":{"type":"integer"},"data":{"type":"array","items":{"type":"number"}}}}"#,
253 },
254 McpToolDescriptor {
255 name: "cas",
256 description: "Symbolic algebra: differentiate/simplify/expand/evaluate a text expression (e.g. 'x^3 - 2*x^2'), or solve/factor a quadratic symbolically.",
257 input_schema: r#"{"type":"object","required":["op"],"properties":{"op":{"type":"string","enum":["differentiate","simplify","expand","evaluate","solve_quadratic","factor"]},"expr":{"type":"string"},"var":{"type":"string"},"env":{"type":"object"},"a":{"type":"number"},"b":{"type":"number"},"c":{"type":"number"}}}"#,
258 },
259 McpToolDescriptor {
260 name: "ode_solve",
261 description: "Run a configurable CFD or molecular-dynamics simulation step.",
262 input_schema: r#"{"type":"object","properties":{"type":{"type":"string","enum":["cfd","distributed","molecular_dynamics"]},"nx":{"type":"integer"},"ny":{"type":"integer"},"dx":{"type":"number"},"time_step":{"type":"number"},"total_time":{"type":"number"},"num_threads":{"type":"integer"}}}"#,
263 },
264 McpToolDescriptor {
265 name: "chemical_analysis",
266 description: "Predict molecular properties from SMILES or formula via ChemistryModelingLibrary.",
267 input_schema: r#"{"type":"object","properties":{"smiles":{"type":"string"},"formula":{"type":"string"},"molecular_weight":{"type":"number"},"prop":{"type":"string"},"properties":{"type":"array","items":{"type":"string"}}}}"#,
268 },
269 McpToolDescriptor {
270 name: "statistical_analysis",
271 description: "Descriptive statistics on caller-supplied tabular data.",
272 input_schema: r#"{"type":"object","required":["rows"],"properties":{"stat":{"type":"string","enum":["mean","variance","correlation"]},"rows":{"type":"array"},"columns":{"type":"array","items":{"type":"string"}},"column":{"type":"string"},"column_y":{"type":"string"},"method":{"type":"string"}}}"#,
273 },
274 McpToolDescriptor {
275 name: "ml_inference",
276 description: "Load a model by id and run inference on caller-supplied input bytes.",
277 input_schema: r#"{"type":"object","properties":{"model_id":{"type":"string"},"model_path":{"type":"string"},"input_data":{"type":"array","items":{"type":"integer"}},"input_hex":{"type":"string"},"batch_size":{"type":"integer"},"temperature":{"type":"number"},"max_tokens":{"type":"integer"}}}"#,
278 },
279 McpToolDescriptor {
280 name: "financial_model",
281 description: "Black-Scholes option pricing or portfolio risk with caller parameters.",
282 input_schema: r#"{"type":"object","properties":{"op":{"type":"string","enum":["option","risk"]},"underlying_price":{"type":"number"},"strike":{"type":"number"},"volatility":{"type":"number"},"assets":{"type":"array"},"cash_balance":{"type":"number"}}}"#,
283 },
284 McpToolDescriptor {
285 name: "medical_score",
286 description: "Clinical analysis for a caller-supplied patient record.",
287 input_schema: r#"{"type":"object","properties":{"patient_id":{"type":"string"},"score":{"type":"string","enum":["diagnosis","treatment","prognosis","prevention"]},"patient":{"type":"object"}}}"#,
288 },
289 McpToolDescriptor {
290 name: "engineering_analysis_op",
291 description: "Structural, thermal, or dynamic FEA with caller model geometry and loads.",
292 input_schema: r#"{"type":"object","properties":{"analysis":{"type":"string","enum":["structural","thermal","dynamic"]},"model":{"type":"object"},"dimensions":{"type":"array"},"youngs_modulus":{"type":"number"}}}"#,
293 },
294 McpToolDescriptor {
295 name: "computational_geometry",
296 description: "Native Rust/WASM computational geometry over caller data: robust orientation, 2D convex hull, triangle half-edge topology, Delaunay, Voronoi, nearest site, and primitive generation (box, sphere, cylinder, plane).",
297 input_schema: r#"{"type":"object","required":["op"],"properties":{"op":{"type":"string","enum":["orientation_2","convex_hull_2","triangle_topology","delaunay_2","voronoi_2","nearest_site","mesh_topology","create_box","create_sphere","create_cylinder","create_plane"]},"points":{"type":"array","items":{"type":"array","items":{"type":"number"}}},"vertex_count":{"type":"integer"},"triangles":{"type":"array","items":{"type":"array","items":{"type":"integer"}}},"width":{"type":"number"},"height":{"type":"number"},"depth":{"type":"number"},"radius":{"type":"number"},"size":{"type":"number"},"lat_segments":{"type":"integer"},"lon_segments":{"type":"integer"},"segments":{"type":"integer"},"query":{"type":"array","items":{"type":"number"}}}}"#,
298 },
299 McpToolDescriptor {
300 name: "computer_vision",
301 description: "Native computer_vision specialized lib (MIG-V2): list ops, rgb_to_gray, classical super_resolve (nearest/bilinear/bicubic/lanczos), mesh_quality_cleanup, class_score_to_sigma. Caller-supplied buffers; generative=false classical SR; GPU path used when Cool for nearest/bicubic.",
302 input_schema: r#"{"type":"object","required":["op"],"properties":{"op":{"type":"string","enum":["list","capability_summary","rgb_to_gray","super_resolve","mesh_quality_cleanup","class_score_to_sigma"]},"width":{"type":"integer"},"height":{"type":"integer"},"scale":{"type":"integer"},"kernel":{"type":"string","enum":["nearest","bilinear","bicubic","lanczos3"]},"rgb":{"type":"array","items":{"type":"integer"}},"class_hash":{"type":"integer"},"score":{"type":"number"},"positions":{"type":"array","items":{"type":"array","items":{"type":"number"}}},"indices":{"type":"array","items":{"type":"integer"}},"weld_epsilon":{"type":"number"}}}"#,
303 },
304 McpToolDescriptor {
305 name: "audio_features",
306 description: "Native qualia-audio features + honest capability registry: list (all capabilities with Present/Partial/Missing/NeedsWeights status), capability_summary (counts), log_mel, pitch_yin (real YIN F0+confidence), loudness_r128 (EBU R128 LUFS). Caller-supplied PCM samples; CPU; learned heads fail closed.",
307 input_schema: r#"{"type":"object","required":["op"],"properties":{"op":{"type":"string","enum":["list","capability_summary","log_mel","pitch_yin","loudness_r128"]},"samples":{"type":"array","items":{"type":"number"}},"sample_rate":{"type":"integer"},"n_mel":{"type":"integer"}}}"#,
308 },
309 McpToolDescriptor {
310 name: "geometry_manifests",
311 description: "List per-op capability manifests (backends, determinism class, resource limits) and run Reserve-mode budget queries for computational-geometry ops.",
312 input_schema: r#"{"type":"object","properties":{"op":{"type":"string","description":"Op name for a Reserve-mode budget query (omit to list all manifests)"},"device":{"type":"object","properties":{"cpu":{"type":"boolean"},"simd":{"type":"boolean"},"wgpu":{"type":"boolean"},"cuda":{"type":"boolean"},"wasm":{"type":"boolean"},"exact":{"type":"boolean"}}}}}"#,
313 },
314 McpToolDescriptor {
315 name: "bioinformatics_align",
316 description: "Pairwise nucleotide or protein alignment on caller query/target sequences.",
317 input_schema: r#"{"type":"object","required":["query","target"],"properties":{"query":{"type":"string"},"target":{"type":"string"},"mode":{"type":"string","enum":["dna","protein"]}}}"#,
318 },
319 McpToolDescriptor {
320 name: "chemical_descriptors",
321 description: "Compute Lipinski/Veber descriptors from a SMILES string.",
322 input_schema: r#"{"type":"object","required":["smiles"],"properties":{"smiles":{"type":"string"}}}"#,
323 },
324 McpToolDescriptor {
325 name: "clinical_risk",
326 description: "Clinical risk scores: framingham, cha2ds2_vasc, sofa, egfr.",
327 input_schema: r#"{"type":"object","properties":{"score":{"type":"string","enum":["framingham","cha2ds2","cha2ds2_vasc","sofa","egfr","renal"]},"age":{"type":"integer"},"input":{"type":"object"}}}"#,
328 },
329 McpToolDescriptor {
330 name: "parse_csv",
331 description: "Stream CSV into Quins via zero-heap parser. Requires field_mappings; accepts csv_data or file_path.",
332 input_schema: r#"{"type":"object","required":["field_mappings"],"properties":{"csv_data":{"type":"string"},"file_path":{"type":"string"},"field_mappings":{"type":"array","items":{"type":"object","required":["source_key"],"properties":{"source_key":{"type":"string"},"predicate":{"type":"string"},"predicate_hash":{"type":"integer"},"datatype":{"type":"string","enum":["integer","float","datetime","string"]}}}},"base_class_hash":{"type":"integer"},"context_hash":{"type":"integer"},"ingest_to_graph":{"type":"boolean"}}}"#,
333 },
334 McpToolDescriptor {
335 name: "parse_rdf",
336 description: "Parse RDF/RDF-Star (nt, turtle, nquads, trig, n3, jsonld, cbor) into quins via zero-heap streaming parsers.",
337 input_schema: r#"{"type":"object","required":["format"],"properties":{"format":{"type":"string"},"rdf_data":{"type":"string"},"file_path":{"type":"string"},"context_hash":{"type":"integer"},"ingest_to_graph":{"type":"boolean"}}}"#,
338 },
339 McpToolDescriptor {
340 name: "parse_json",
341 description: "Stream JSON objects into Quins via zero-heap parser. Requires field_mappings; accepts json_data or file_path.",
342 input_schema: r#"{"type":"object","required":["field_mappings"],"properties":{"json_data":{"type":"string"},"file_path":{"type":"string"},"field_mappings":{"type":"array","items":{"type":"object","required":["source_key"],"properties":{"source_key":{"type":"string"},"predicate":{"type":"string"},"predicate_hash":{"type":"integer"},"datatype":{"type":"string","enum":["integer","float","datetime","string"]}}}},"base_class_hash":{"type":"integer"},"context_hash":{"type":"integer"},"ingest_to_graph":{"type":"boolean"}}}"#,
343 },
344 McpToolDescriptor {
345 name: "serialize_csv",
346 description: "Serialize quins or daemon graph slice to CSV. Returns inline csv_data or writes file_path when output=file.",
347 input_schema: r#"{"type":"object","required":["headers","predicate_hashes"],"properties":{"quins":{"type":"array"},"use_graph":{"type":"boolean"},"context_hash":{"type":"integer"},"headers":{"type":"array","items":{"type":"string"}},"predicate_hashes":{"type":"array","items":{"type":"integer"}},"datatypes":{"type":"array","items":{"type":"string"}},"output":{"type":"string","enum":["inline","file"]},"file_path":{"type":"string"}}}"#,
348 },
349 McpToolDescriptor {
350 name: "serialize_json",
351 description: "Serialize quins or daemon graph slice to JSON array. Returns inline json_data or writes file_path when output=file.",
352 input_schema: r#"{"type":"object","required":["field_names","predicate_hashes"],"properties":{"quins":{"type":"array"},"use_graph":{"type":"boolean"},"context_hash":{"type":"integer"},"field_names":{"type":"array","items":{"type":"string"}},"predicate_hashes":{"type":"array","items":{"type":"integer"}},"datatypes":{"type":"array","items":{"type":"string"}},"output":{"type":"string","enum":["inline","file"]},"file_path":{"type":"string"}}}"#,
353 },
354 McpToolDescriptor {
355 name: "serialize_rdf",
356 description: "Serialize quins or graph slice to RDF/RDF-Star via resolver-backed zero-heap dispatch.",
357 input_schema: r#"{"type":"object","properties":{"quins":{"type":"array"},"use_graph":{"type":"boolean"},"context_hash":{"type":"integer"},"format":{"type":"string"},"rdf_star":{"type":"boolean"},"star":{"type":"boolean"},"output":{"type":"string","enum":["inline","file"]},"file_path":{"type":"string"}}}"#,
358 },
359 McpToolDescriptor {
360 name: "symbolic_logic_infer",
361 description: "Defeasible forward-chaining or bounded SAT with caller facts, rules, and clauses.",
362 input_schema: r#"{"type":"object","properties":{"solver":{"type":"string","enum":["defeasible","sat"]},"facts":{"type":"array"},"rules":{"type":"array"},"clauses":{"type":"array"},"max_iterations":{"type":"integer"}}}"#,
363 },
364 McpToolDescriptor {
365 name: "geometric_algebra_op",
366 description: "3D vector cross product, dot product, or angle between caller vectors.",
367 input_schema: r#"{"type":"object","required":["a","b"],"properties":{"op":{"type":"string","enum":["cross","angle","dot"]},"a":{"type":"array","items":{"type":"number"},"minItems":3,"maxItems":3},"b":{"type":"array","items":{"type":"number"},"minItems":3,"maxItems":3}}}"#,
368 },
369 McpToolDescriptor {
370 name: "run_docs_tests",
371 description: "Run docs/tests headless suites (logic, wasm, native, or both). Native/both require daemon on localhost:4242.",
372 input_schema: r#"{"type":"object","properties":{"mode":{"type":"string","enum":["logic","wasm","native","both"]}}}"#,
373 },
374 McpToolDescriptor {
375 name: "get_pending_tasks",
376 description: "Get tasks pending in the ambient orchestrator.",
377 input_schema: r#"{"type":"object","properties":{}}"#,
378 },
379 McpToolDescriptor {
380 name: "values_check",
381 description: "Values abuse-check (human-rights guard): does an agent claiming a natural-person-only dignity right trip the inverse rights-guard? Runs the real agency.n3 G1/G1' lane. agentType is a webcivics values class (CorporatePerson, ArtificialAgent, NaturalPerson, ...).",
382 input_schema: r#"{"type":"object","required":["agentType"],"properties":{"agentType":{"type":"string"},"claimsDignityRight":{"type":"boolean"}}}"#,
383 },
384 McpToolDescriptor {
385 name: "values_evaluate",
386 description: "Deontic-contract reasoner in values terms: is a norm (forbid/oblige/permit) bound to a party+action currently in force? Runs the native deontic VM and returns Active / Defeated (by an 'unless' exception) / Expired (past its window) / Malformed.",
387 input_schema: r#"{"type":"object","required":["modality","party","action"],"properties":{"modality":{"type":"string","enum":["forbid","oblige","permit"]},"party":{"type":"string"},"action":{"type":"string"},"object":{"type":"string"},"now":{"type":"integer"},"expiry":{"type":"integer"},"unless":{"type":"string"}}}"#,
388 },
389 McpToolDescriptor {
390 name: "graph_resolve",
391 description: "Resolve an identifier (IRI) against the live daemon graph: returns its modal identifier-KIND (open kind fabric — WebizenId / DidQ42 / ContentHash / ... or none for a plain dictionary reference) and its out-degree. Composes the hybrid-modality resolver (zero-alloc QuinIndex / slice scan + modal_kind) over one identity space.",
392 input_schema: r#"{"type":"object","required":["iri"],"properties":{"iri":{"type":"string"}}}"#,
393 },
394 McpToolDescriptor {
395 name: "jural_correlate",
396 description: "Hohfeldian jural relations: given one of the 8 positions (claim, duty, privilege, no-right, power, liability, immunity, disability) return the correlative the counterparty necessarily bears, the jural opposite, and its order (first-order conduct vs second-order control). Runs modalities/jural.rs.",
397 input_schema: r#"{"type":"object","required":["position"],"properties":{"position":{"type":"string","enum":["claim","duty","privilege","no-right","power","liability","immunity","disability"]}}}"#,
398 },
399 McpToolDescriptor {
400 name: "deontic_govern",
401 description: "Interaction governance: map a deontic verdict status (active/violated/defeated/expired/pending/discharged/malformed) + classification (nonDerogable/humanitarian/ambiguous) to the runtime PolicyMode the Webizen VM enacts — PreventiveBlock(DenyRollback) | PermissiveAudit(WAL) | Prioritize | Interactive | Allow. Runs interaction_governance::map_policy.",
402 input_schema: r#"{"type":"object","required":["status"],"properties":{"status":{"type":"string"},"nonDerogable":{"type":"boolean"},"humanitarian":{"type":"boolean"},"ambiguous":{"type":"boolean"}}}"#,
403 },
404 McpToolDescriptor {
405 name: "mcp_cooperate",
406 description: "Agent-cooperation gate (Track M): decide whether a VERIFIED, TYPED, GROUNDED calling agent's request passes the deontic gate before execution. Composes mcp_cooperation::authorize — an asserted-not-verified identity is DeniedUnverified; an ungrounded artificial agent (no human Principal, agency.n3 G1') is DeniedUngrounded; else the request runs the Phase-6 policy gate. Trust is behaviourally derived, not self-asserted.",
407 input_schema: r#"{"type":"object","required":["caller","verified"],"properties":{"caller":{"type":"string"},"role":{"type":"string"},"verified":{"type":"boolean"},"grounded":{"type":"boolean"},"requestStatus":{"type":"string"},"nonDerogable":{"type":"boolean"},"humanitarian":{"type":"boolean"},"ambiguous":{"type":"boolean"}}}"#,
408 },
409 McpToolDescriptor {
410 name: "conditioning_compile",
411 description: "Compile a conditioning profile into an execution contract and budget plan.",
412 input_schema: r#"{"type":"object","properties":{"profile":{"type":"object"}}}"#,
413 },
414 McpToolDescriptor {
415 name: "conditioning_validate",
416 description: "Validate a conditioning profile specification against schema and structural rules.",
417 input_schema: r#"{"type":"object","properties":{"profile":{"type":"object"}}}"#,
418 },
419 ]
420}
421
422pub unsafe fn enforce_fiduciary_tool_dispatch(
424 payload: RawToolPayload,
425 intent_frame: &McpIntentFrame,
426) -> Result<String, McpSystemError> {
427 mcp_tool_impls::cooperation_gate(payload.arguments_raw)?;
431
432 match payload.tool_name {
433 b"query_graph" => {
435 if intent_frame.sanctuary_override.is_none() {
439 let violation_quin = NQuin::new_conduct_violation(
440 b"EgressViolation: Invalid or Missing Cryptographic Sanctuary Override",
441 );
442 let _ = append_mutation(&violation_quin);
443 return Err(McpSystemError::SanctuaryGateTriggered);
444 }
445 execute_bare_metal_graph_traversal(payload.arguments_raw, intent_frame)
446 }
447
448 b"query_sparql" => execute_sparql_query(payload.arguments_raw, intent_frame),
449
450 b"get_graph_stats" => execute_graph_stats(payload.arguments_raw, intent_frame),
451
452 b"list_ontologies" => execute_list_ontologies(payload.arguments_raw, intent_frame),
453
454 b"llm_infer" => {
456 if !intent_frame.llm_enabled {
457 return Err(McpSystemError::FeatureNotEnabled);
458 }
459 execute_llm_infer(payload.arguments_raw, intent_frame)
460 }
461
462 b"llm_chat" => {
463 if !intent_frame.llm_enabled {
464 return Err(McpSystemError::FeatureNotEnabled);
465 }
466 execute_llm_chat(payload.arguments_raw, intent_frame)
467 }
468
469 b"list_models" => execute_list_models(payload.arguments_raw, intent_frame),
470
471 b"qpu_optimize" => {
473 if !intent_frame.qpu_enabled {
474 return Err(McpSystemError::FeatureNotEnabled);
475 }
476 execute_qpu_optimize(payload.arguments_raw, intent_frame)
477 }
478
479 b"qpu_dft" => {
480 if !intent_frame.qpu_enabled {
481 return Err(McpSystemError::FeatureNotEnabled);
482 }
483 execute_qpu_dft(payload.arguments_raw, intent_frame)
484 }
485
486 b"qpu_status" => execute_qpu_status(payload.arguments_raw, intent_frame),
487
488 b"matrix_operation" => execute_matrix_operation(payload.arguments_raw, intent_frame),
490 b"algebra_solve_polynomial" => {
491 mcp_tool_impls::algebra_solve_polynomial(payload.arguments_raw)
492 }
493 b"algebra_matrix_analyze" => mcp_tool_impls::algebra_matrix_analyze(payload.arguments_raw),
494 b"cas" => mcp_tool_impls::cas(payload.arguments_raw),
495
496 b"ode_solve" => execute_ode_solve(payload.arguments_raw, intent_frame),
497
498 b"chemical_analysis" => execute_chemical_analysis(payload.arguments_raw, intent_frame),
499
500 b"statistical_analysis" => {
501 execute_statistical_analysis(payload.arguments_raw, intent_frame)
502 }
503
504 b"ml_inference" => execute_ml_inference(payload.arguments_raw, intent_frame),
505
506 b"financial_model" => execute_financial_model(payload.arguments_raw, intent_frame),
507
508 b"medical_score" => execute_medical_score(payload.arguments_raw, intent_frame),
509
510 b"engineering_analysis_op" => {
511 execute_engineering_analysis(payload.arguments_raw, intent_frame)
512 }
513 b"computational_geometry" => mcp_tool_impls::computational_geometry(payload.arguments_raw),
514 b"geometry_manifests" => mcp_tool_impls::geometry_manifests(payload.arguments_raw),
515 b"computer_vision" => mcp_tool_impls::computer_vision(payload.arguments_raw),
516 #[cfg(not(target_arch = "wasm32"))]
517 b"audio_features" => mcp_tool_impls::audio_features(payload.arguments_raw),
518
519 b"get_wallet_status" => execute_wallet_status(payload.arguments_raw, intent_frame),
521
522 b"get_did_info" => execute_did_info(payload.arguments_raw, intent_frame),
523
524 b"ingest_ontology" => execute_ingest_ontology(payload.arguments_raw, intent_frame),
526
527 b"validate_shacl" => execute_shacl_validation(payload.arguments_raw, intent_frame),
528
529 b"validate_enumerated_identity" => {
531 execute_validate_enumerated_identity(payload.arguments_raw, intent_frame)
532 }
533 b"shacl_credential_gate" => {
534 execute_shacl_credential_gate(payload.arguments_raw, intent_frame)
535 }
536 b"shacl_degrade_violations" => {
537 execute_shacl_degrade_violations(payload.arguments_raw, intent_frame)
538 }
539 b"shacl_route" => execute_shacl_route(payload.arguments_raw, intent_frame),
540
541 b"inject_test_quin" => {
543 execute_paraconsistent_injection(payload.arguments_raw, intent_frame)
544 }
545
546 b"list_qapps" => execute_list_qapps(payload.arguments_raw, intent_frame),
547
548 b"get_qapp_manifest" => execute_get_qapp_manifest(payload.arguments_raw, intent_frame),
549
550 b"inspect_qapp_readiness" => {
551 execute_inspect_qapp_readiness(payload.arguments_raw, intent_frame)
552 }
553
554 b"list_qapp_updates" => execute_list_qapp_updates(payload.arguments_raw, intent_frame),
555
556 b"describe_qapp_surface_schema" => {
557 execute_describe_qapp_surface_schema(payload.arguments_raw, intent_frame)
558 }
559
560 b"get_system_status" => execute_system_status(payload.arguments_raw, intent_frame),
561 b"list_capabilities" => mcp_tool_impls::list_capabilities(payload.arguments_raw),
562
563 b"evaluate_modality" => execute_evaluate_modality(payload.arguments_raw, intent_frame),
565
566 b"evaluate_logic_rules" => mcp_tool_impls::evaluate_logic_rules(payload.arguments_raw),
567
568 b"bioinformatics_align" => {
569 execute_bioinformatics_align(payload.arguments_raw, intent_frame)
570 }
571
572 b"chemical_descriptors" => {
573 execute_chemical_descriptors(payload.arguments_raw, intent_frame)
574 }
575
576 b"clinical_risk" => execute_clinical_risk(payload.arguments_raw, intent_frame),
577
578 b"symbolic_logic_infer" => {
579 execute_symbolic_logic_infer(payload.arguments_raw, intent_frame)
580 }
581
582 b"geometric_algebra_op" => {
583 execute_geometric_algebra_op(payload.arguments_raw, intent_frame)
584 }
585
586 b"parse_csv" => execute_parse_csv(payload.arguments_raw, intent_frame),
588 b"parse_rdf" => execute_parse_rdf(payload.arguments_raw, intent_frame),
589 b"parse_json" => execute_parse_json(payload.arguments_raw, intent_frame),
590 b"serialize_csv" => execute_serialize_csv(payload.arguments_raw, intent_frame),
591 b"serialize_json" => execute_serialize_json(payload.arguments_raw, intent_frame),
592 b"serialize_rdf" => execute_serialize_rdf(payload.arguments_raw, intent_frame),
593
594 b"run_docs_tests" => execute_run_docs_tests(payload.arguments_raw, intent_frame),
595 b"get_pending_tasks" => execute_get_pending_tasks(payload.arguments_raw, intent_frame),
596
597 b"values_check" => mcp_tool_impls::values_check(payload.arguments_raw),
599 b"values_evaluate" => mcp_tool_impls::values_evaluate(payload.arguments_raw),
600 b"jural_correlate" => mcp_tool_impls::jural_correlate(payload.arguments_raw),
601 b"deontic_govern" => mcp_tool_impls::deontic_govern(payload.arguments_raw),
602 b"mcp_cooperate" => mcp_tool_impls::mcp_cooperate(payload.arguments_raw),
603 b"graph_resolve" => mcp_tool_impls::graph_resolve(payload.arguments_raw),
604
605 b"conditioning_compile" => mcp_tool_impls::conditioning_compile(payload.arguments_raw),
607 b"conditioning_validate" => mcp_tool_impls::conditioning_validate(payload.arguments_raw),
608
609 _ => Err(McpSystemError::ToolNotFound),
610 }
611}
612
613unsafe fn execute_get_pending_tasks(
615 args: &[u8],
616 _intent: &McpIntentFrame,
617) -> Result<String, McpSystemError> {
618 mcp_stub_impls::get_pending_tasks(args)
619}
620
621unsafe fn execute_sparql_query(
625 args: &[u8],
626 _intent: &McpIntentFrame,
627) -> Result<String, McpSystemError> {
628 mcp_stub_impls::query_sparql(args)
629}
630
631unsafe fn execute_bare_metal_graph_traversal(
633 _args: &[u8],
634 intent: &McpIntentFrame,
635) -> Result<String, McpSystemError> {
636 let mut arena = crate::webizen::SlgArena::new();
637 let contract = if intent
638 .active_deontic_constraints
639 .first()
640 .copied()
641 .unwrap_or(0)
642 != 0
643 {
644 intent.active_deontic_constraints[0]
645 } else {
646 intent.purpose_hash
647 };
648 let fired = arena.fire_registered_rules(contract);
649 Ok(fired.max(1).to_string())
650}
651
652unsafe fn execute_graph_stats(
654 args: &[u8],
655 _intent: &McpIntentFrame,
656) -> Result<String, McpSystemError> {
657 mcp_stub_impls::get_graph_stats(args)
658}
659
660unsafe fn execute_list_ontologies(
662 args: &[u8],
663 _intent: &McpIntentFrame,
664) -> Result<String, McpSystemError> {
665 mcp_stub_impls::list_ontologies(args)
666}
667
668unsafe fn execute_llm_infer(
672 args: &[u8],
673 _intent: &McpIntentFrame,
674) -> Result<String, McpSystemError> {
675 mcp_stub_impls::llm_infer(args)
676}
677
678unsafe fn execute_llm_chat(
680 args: &[u8],
681 _intent: &McpIntentFrame,
682) -> Result<String, McpSystemError> {
683 mcp_stub_impls::llm_chat(args)
684}
685
686unsafe fn execute_list_models(
688 args: &[u8],
689 _intent: &McpIntentFrame,
690) -> Result<String, McpSystemError> {
691 mcp_stub_impls::list_models(args)
692}
693
694unsafe fn execute_qpu_optimize(
698 args: &[u8],
699 _intent: &McpIntentFrame,
700) -> Result<String, McpSystemError> {
701 mcp_stub_impls::qpu_optimize(args)
702}
703
704unsafe fn execute_qpu_dft(args: &[u8], _intent: &McpIntentFrame) -> Result<String, McpSystemError> {
706 mcp_stub_impls::qpu_dft(args)
707}
708
709unsafe fn execute_qpu_status(
711 args: &[u8],
712 _intent: &McpIntentFrame,
713) -> Result<String, McpSystemError> {
714 mcp_stub_impls::qpu_status(args)
715}
716
717unsafe fn execute_matrix_operation(
721 args: &[u8],
722 _intent: &McpIntentFrame,
723) -> Result<String, McpSystemError> {
724 mcp_tool_impls::matrix_operation(args)
725}
726
727unsafe fn execute_ode_solve(
729 args: &[u8],
730 _intent: &McpIntentFrame,
731) -> Result<String, McpSystemError> {
732 mcp_tool_impls::ode_solve(args)
733}
734
735unsafe fn execute_chemical_analysis(
737 args: &[u8],
738 _intent: &McpIntentFrame,
739) -> Result<String, McpSystemError> {
740 mcp_tool_impls::chemical_analysis(args)
741}
742
743unsafe fn execute_statistical_analysis(
745 args: &[u8],
746 _intent: &McpIntentFrame,
747) -> Result<String, McpSystemError> {
748 mcp_tool_impls::statistical_analysis(args)
749}
750
751unsafe fn execute_ml_inference(
753 args: &[u8],
754 _intent: &McpIntentFrame,
755) -> Result<String, McpSystemError> {
756 mcp_tool_impls::ml_inference(args)
757}
758
759unsafe fn execute_financial_model(
761 args: &[u8],
762 _intent: &McpIntentFrame,
763) -> Result<String, McpSystemError> {
764 mcp_tool_impls::financial_model(args)
765}
766
767unsafe fn execute_medical_score(
769 args: &[u8],
770 _intent: &McpIntentFrame,
771) -> Result<String, McpSystemError> {
772 mcp_tool_impls::medical_score(args)
773}
774
775unsafe fn execute_engineering_analysis(
777 args: &[u8],
778 _intent: &McpIntentFrame,
779) -> Result<String, McpSystemError> {
780 mcp_tool_impls::engineering_analysis(args)
781}
782
783unsafe fn execute_wallet_status(
787 args: &[u8],
788 _intent: &McpIntentFrame,
789) -> Result<String, McpSystemError> {
790 mcp_stub_impls::get_wallet_status(args)
791}
792
793unsafe fn execute_did_info(
795 args: &[u8],
796 _intent: &McpIntentFrame,
797) -> Result<String, McpSystemError> {
798 mcp_stub_impls::get_did_info(args)
799}
800
801unsafe fn execute_ingest_ontology(
805 args: &[u8],
806 _intent: &McpIntentFrame,
807) -> Result<String, McpSystemError> {
808 mcp_stub_impls::ingest_ontology(args)
809}
810
811unsafe fn execute_shacl_validation(
813 args: &[u8],
814 _intent: &McpIntentFrame,
815) -> Result<String, McpSystemError> {
816 mcp_stub_impls::validate_shacl(args)
817}
818
819unsafe fn execute_validate_enumerated_identity(
821 args: &[u8],
822 _intent: &McpIntentFrame,
823) -> Result<String, McpSystemError> {
824 mcp_stub_impls::validate_enumerated_identity_tool(args)
825}
826
827unsafe fn execute_shacl_credential_gate(
829 args: &[u8],
830 _intent: &McpIntentFrame,
831) -> Result<String, McpSystemError> {
832 mcp_stub_impls::shacl_credential_gate(args)
833}
834
835unsafe fn execute_shacl_degrade_violations(
837 args: &[u8],
838 _intent: &McpIntentFrame,
839) -> Result<String, McpSystemError> {
840 mcp_stub_impls::shacl_degrade_violations(args)
841}
842
843unsafe fn execute_shacl_route(
845 args: &[u8],
846 _intent: &McpIntentFrame,
847) -> Result<String, McpSystemError> {
848 mcp_stub_impls::shacl_route(args)
849}
850
851unsafe fn execute_paraconsistent_injection(
855 _args: &[u8],
856 intent: &McpIntentFrame,
857) -> Result<String, McpSystemError> {
858 let candidate = NQuin {
859 subject: intent.purpose_hash,
860 predicate: crate::q_hash("q42:testClaim"),
861 object: intent.session_nonce,
862 context: intent.purpose_hash,
863 metadata: 0,
864 parity: 0,
865 };
866 let mut q = candidate;
867 q.parity = q.subject ^ q.predicate ^ q.object ^ q.context;
868
869 let mut consistent = [NQuin::default(); 8];
870 let mut isolated = [NQuin::default(); 8];
871 let (c, i) = crate::modalities::paraconsistent::route_paraconsistent(
872 &[q],
873 &mut consistent,
874 &mut isolated,
875 )
876 .map_err(|_| McpSystemError::ParseError)?;
877
878 for idx in 0..i {
879 let _ = append_mutation(&isolated[idx]);
880 }
881 Ok((c + i).to_string())
882}
883
884unsafe fn execute_list_qapps(
886 args: &[u8],
887 _intent: &McpIntentFrame,
888) -> Result<String, McpSystemError> {
889 mcp_stub_impls::list_qapps(args)
890}
891
892unsafe fn execute_get_qapp_manifest(
894 args: &[u8],
895 _intent: &McpIntentFrame,
896) -> Result<String, McpSystemError> {
897 let qapp_name = extract_raw_json_string(args, b"\"qapp_name\"").unwrap_or(b"");
898 if qapp_name.is_empty() {
899 return Err(McpSystemError::InvalidParameters);
900 }
901 let name = std::str::from_utf8(qapp_name).map_err(|_| McpSystemError::InvalidParameters)?;
902 mcp_stub_impls::get_qapp_manifest(name)
903}
904
905unsafe fn execute_inspect_qapp_readiness(
907 args: &[u8],
908 _intent: &McpIntentFrame,
909) -> Result<String, McpSystemError> {
910 let qapp_name = extract_raw_json_string(args, b"\"qapp_name\"").unwrap_or(b"");
911 if qapp_name.is_empty() {
912 return Err(McpSystemError::InvalidParameters);
913 }
914 let name = std::str::from_utf8(qapp_name).map_err(|_| McpSystemError::InvalidParameters)?;
915 mcp_stub_impls::inspect_qapp_readiness(name)
916}
917
918unsafe fn execute_list_qapp_updates(
920 args: &[u8],
921 _intent: &McpIntentFrame,
922) -> Result<String, McpSystemError> {
923 mcp_stub_impls::list_qapp_updates(args)
924}
925
926unsafe fn execute_describe_qapp_surface_schema(
928 _args: &[u8],
929 _intent: &McpIntentFrame,
930) -> Result<String, McpSystemError> {
931 let schema = r#"{
932 "host_shell": "webizen-studio",
933 "package_manifest": "qapp.json",
934 "layout_strategies": ["PointGrid", "CssGrid", "FlexBox", "Masonry"],
935 "presentation_modes": ["GridBound", "NodeRelational", "Spatial"],
936 "coordinate_spaces": ["GlobalCartesian", "RelativeAnchored"],
937 "layer_behaviors": ["Docked", "FloatingOverlay", "ModalOverlay", "FullManifold"],
938 "theme_scopes": ["environment", "app", "page", "module"],
939 "manifest_surfaces": ["static-web", "wasm-local", "online-daemon-aware", "native-aether-pane"],
940 "mcp_tools": ["list_qapps", "get_qapp_manifest", "inspect_qapp_readiness", "list_qapp_updates", "describe_qapp_surface_schema"]
941}"#;
942 Ok(schema.to_string())
943}
944
945unsafe fn execute_system_status(
947 _args: &[u8],
948 intent: &McpIntentFrame,
949) -> Result<String, McpSystemError> {
950 Ok(json!({
951 "server": "qualia-core-db-mcp",
952 "version": env!("CARGO_PKG_VERSION"),
953 "protocolVersion": "2025-03-26",
954 "toolCount": stable_mcp_tools().len(),
955 "qpuEnabled": intent.qpu_enabled,
956 "llmEnabled": intent.llm_enabled,
957 "activeProfileId": intent.active_profile_id,
958 })
959 .to_string())
960}
961
962unsafe fn execute_run_docs_tests(
964 args: &[u8],
965 _intent: &McpIntentFrame,
966) -> Result<String, McpSystemError> {
967 let mode = extract_raw_json_string(args, b"\"mode\"").unwrap_or(b"logic");
968 let mode_str = core::str::from_utf8(mode).unwrap_or("logic");
969 if !matches!(mode_str, "logic" | "wasm" | "native" | "both") {
970 return Err(McpSystemError::InvalidParameters);
971 }
972
973 if matches!(mode_str, "native" | "both") && !daemon_health_ok(4242) {
974 return Ok(json!({
975 "ok": false,
976 "mode": mode_str,
977 "error": "daemon_unreachable",
978 "hint": "Start the graph daemon with `qualia-cli service start` or `qualia-cli daemon start --dev`"
979 })
980 .to_string());
981 }
982
983 let root = resolve_repo_root();
984 let script = root.join("docs/tests/run-headless.mjs");
985 if !script.exists() {
986 return Ok(json!({
987 "ok": false,
988 "mode": mode_str,
989 "error": "runner_missing",
990 "path": script.display().to_string()
991 })
992 .to_string());
993 }
994
995 let output = std::process::Command::new("node")
996 .arg(script.as_os_str())
997 .arg("--mode")
998 .arg(mode_str)
999 .current_dir(&root)
1000 .output()
1001 .map_err(|_| McpSystemError::ToolNotReady)?;
1002
1003 let stdout = String::from_utf8_lossy(&output.stdout).to_string();
1004 let stderr = String::from_utf8_lossy(&output.stderr).to_string();
1005 Ok(json!({
1006 "ok": output.status.success(),
1007 "mode": mode_str,
1008 "exitCode": output.status.code(),
1009 "stdout": stdout,
1010 "stderr": stderr
1011 })
1012 .to_string())
1013}
1014
1015fn daemon_health_ok(port: u16) -> bool {
1019 use std::io::{Read, Write};
1020 use std::net::{SocketAddr, TcpStream};
1021 use std::time::Duration;
1022
1023 let addr: SocketAddr = format!("127.0.0.1:{port}")
1024 .parse()
1025 .unwrap_or_else(|_| SocketAddr::from(([127, 0, 0, 1], port)));
1026 let mut stream = match TcpStream::connect_timeout(&addr, Duration::from_secs(2)) {
1027 Ok(stream) => stream,
1028 Err(_) => return false,
1029 };
1030 let _ = stream.set_read_timeout(Some(Duration::from_secs(2)));
1031 let request =
1032 format!("GET /health HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n");
1033 if stream.write_all(request.as_bytes()).is_err() {
1034 return false;
1035 }
1036 let mut buf = [0u8; 512];
1037 match stream.read(&mut buf) {
1038 Ok(0) => false,
1039 Ok(n) => {
1040 let response = core::str::from_utf8(&buf[..n]).unwrap_or("");
1041 response.contains("200 OK") || response.contains("engine_version")
1042 }
1043 Err(_) => false,
1044 }
1045}
1046
1047fn resolve_repo_root() -> std::path::PathBuf {
1050 if let Ok(root) = std::env::var("QUALIA_REPO_ROOT") {
1051 return std::path::PathBuf::from(root);
1052 }
1053 let mut dir = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
1054 for _ in 0..8 {
1055 if dir.join("docs/tests/run-headless.mjs").exists() {
1056 return dir;
1057 }
1058 if !dir.pop() {
1059 break;
1060 }
1061 }
1062 dir
1063}
1064
1065unsafe fn execute_evaluate_modality(
1069 args: &[u8],
1070 _intent: &McpIntentFrame,
1071) -> Result<String, McpSystemError> {
1072 mcp_tool_impls::evaluate_modality(args)
1073}
1074
1075unsafe fn execute_bioinformatics_align(
1077 args: &[u8],
1078 _intent: &McpIntentFrame,
1079) -> Result<String, McpSystemError> {
1080 mcp_tool_impls::bioinformatics_align(args)
1081}
1082
1083unsafe fn execute_chemical_descriptors(
1085 args: &[u8],
1086 _intent: &McpIntentFrame,
1087) -> Result<String, McpSystemError> {
1088 mcp_tool_impls::chemical_descriptors(args)
1089}
1090
1091unsafe fn execute_clinical_risk(
1093 args: &[u8],
1094 _intent: &McpIntentFrame,
1095) -> Result<String, McpSystemError> {
1096 mcp_tool_impls::clinical_risk(args)
1097}
1098
1099unsafe fn execute_parse_csv(
1101 args: &[u8],
1102 _intent: &McpIntentFrame,
1103) -> Result<String, McpSystemError> {
1104 mcp_format_impls::parse_csv(args)
1105}
1106
1107unsafe fn execute_parse_rdf(
1109 args: &[u8],
1110 _intent: &McpIntentFrame,
1111) -> Result<String, McpSystemError> {
1112 mcp_format_impls::parse_rdf(args)
1113}
1114
1115unsafe fn execute_parse_json(
1117 args: &[u8],
1118 _intent: &McpIntentFrame,
1119) -> Result<String, McpSystemError> {
1120 mcp_format_impls::parse_json(args)
1121}
1122
1123unsafe fn execute_serialize_csv(
1125 args: &[u8],
1126 _intent: &McpIntentFrame,
1127) -> Result<String, McpSystemError> {
1128 mcp_format_impls::serialize_csv(args)
1129}
1130
1131unsafe fn execute_serialize_json(
1133 args: &[u8],
1134 _intent: &McpIntentFrame,
1135) -> Result<String, McpSystemError> {
1136 mcp_format_impls::serialize_json(args)
1137}
1138
1139unsafe fn execute_serialize_rdf(
1141 args: &[u8],
1142 _intent: &McpIntentFrame,
1143) -> Result<String, McpSystemError> {
1144 mcp_format_impls::serialize_rdf(args)
1145}
1146
1147unsafe fn execute_symbolic_logic_infer(
1149 args: &[u8],
1150 _intent: &McpIntentFrame,
1151) -> Result<String, McpSystemError> {
1152 mcp_tool_impls::symbolic_logic_infer(args)
1153}
1154
1155unsafe fn execute_geometric_algebra_op(
1157 args: &[u8],
1158 _intent: &McpIntentFrame,
1159) -> Result<String, McpSystemError> {
1160 mcp_tool_impls::geometric_algebra_op(args)
1161}
1162
1163pub unsafe fn scrub_transient_mcp_buffers(buffer: &mut [u8]) {
1165 for byte_ptr in buffer.iter_mut() {
1166 write_volatile(byte_ptr, 0x00);
1167 }
1168}
1169
1170#[inline]
1172fn hex_nibble(c: u8) -> Option<u8> {
1173 match c {
1174 b'0'..=b'9' => Some(c - b'0'),
1175 b'a'..=b'f' => Some(c - b'a' + 10),
1176 b'A'..=b'F' => Some(c - b'A' + 10),
1177 _ => None,
1178 }
1179}
1180
1181fn parse_sanctuary_override(value: &[u8]) -> Option<[u8; 32]> {
1202 if value.len() != 64 {
1203 return None;
1204 }
1205 let mut token = [0u8; 32];
1206 for (byte, pair) in token.iter_mut().zip(value.chunks_exact(2)) {
1207 let hi = hex_nibble(pair[0])?;
1208 let lo = hex_nibble(pair[1])?;
1209 *byte = (hi << 4) | lo;
1210 }
1211 if token.iter().all(|&b| b == 0) {
1212 return None;
1213 }
1214 Some(token)
1215}
1216
1217fn build_intent_frame(arguments: &[u8], qpu_enabled: bool, llm_enabled: bool) -> McpIntentFrame {
1221 let sanctuary_override = extract_raw_json_string(arguments, b"\"sanctuary_override\"")
1222 .and_then(parse_sanctuary_override);
1223
1224 McpIntentFrame {
1225 purpose_hash: crate::q_hash("purpose:General"),
1226 active_deontic_constraints: Vec::new(),
1227 active_profile_id: None,
1228 session_nonce: 0,
1229 sanctuary_override,
1230 qpu_enabled,
1231 llm_enabled,
1232 }
1233}
1234
1235fn tool_list_json() -> Vec<Value> {
1239 stable_mcp_tools()
1240 .iter()
1241 .filter(|tool| {
1242 #[cfg(target_arch = "wasm32")]
1243 {
1244 !matches!(
1246 tool.name,
1247 "list_ontologies" | "llm_infer" | "llm_chat" | "list_models" | "qpu_optimize" | "ingest_ontology"
1248 )
1249 }
1250 #[cfg(not(target_arch = "wasm32"))]
1251 {
1252 let _ = tool;
1253 true
1254 }
1255 })
1256 .map(|tool| {
1257 let input_schema = serde_json::from_str::<Value>(tool.input_schema)
1258 .unwrap_or_else(|_| json!({"type":"object"}));
1259 json!({
1260 "name": tool.name,
1261 "description": tool.description,
1262 "inputSchema": input_schema,
1263 })
1264 })
1265 .collect()
1266}
1267
1268fn system_resource_json() -> Value {
1271 json!({
1272 "uri": "qualia://qapp-surface-schema",
1273 "name": "Qapp Surface Schema",
1274 "description": "Static description of the current Qualia qapp host surface.",
1275 "mimeType": "application/json",
1276 })
1277}
1278
1279fn error_message(err: McpSystemError) -> (&'static str, i64) {
1283 match err {
1284 McpSystemError::SanctuaryGateTriggered => ("Sanctuary gate triggered", -32001),
1285 McpSystemError::ToolNotFound => ("Tool not found", -32601),
1286 McpSystemError::ToolNotReady => ("Tool not implemented on the current MCP surface", -32004),
1287 McpSystemError::ParseError => ("Parse error", -32700),
1288 McpSystemError::IntentFrameViolation => ("Intent frame violation", -32002),
1289 McpSystemError::FeatureNotEnabled => ("Feature not enabled", -32003),
1290 McpSystemError::InvalidParameters => ("Invalid parameters", -32602),
1291 }
1292}
1293
1294fn dispatch_tool_call(
1298 tool_name: &[u8],
1299 arguments_raw: &[u8],
1300 qpu_enabled: bool,
1301 llm_enabled: bool,
1302) -> Result<String, McpSystemError> {
1303 let intent_frame = build_intent_frame(arguments_raw, qpu_enabled, llm_enabled);
1304 let payload = RawToolPayload {
1305 tool_name,
1306 arguments_raw,
1307 };
1308 unsafe { enforce_fiduciary_tool_dispatch(payload, &intent_frame) }
1309}
1310
1311pub unsafe fn parse_and_evaluate_mcp_stream(stream_chunk: &[u8]) -> Result<String, McpSystemError> {
1313 if !stream_chunk.windows(12).any(|w| w == b"\"tools/call\"") {
1314 return Err(McpSystemError::ParseError);
1315 }
1316 let tool_name = extract_raw_json_string(stream_chunk, b"\"name\"").unwrap_or(b"");
1317 dispatch_tool_call(tool_name, stream_chunk, true, true)
1318}
1319
1320pub fn handle_jsonrpc_message(
1324 message: &str,
1325 qpu_enabled: bool,
1326 llm_enabled: bool,
1327) -> Option<String> {
1328 let request: Value = serde_json::from_str(message).ok()?;
1329 let id = request.get("id").cloned().unwrap_or(Value::Null);
1330 let method = request.get("method").and_then(Value::as_str).or_else(|| {
1331 if message.contains("\"tools/call\"") {
1332 Some("tools/call")
1333 } else {
1334 None
1335 }
1336 })?;
1337
1338 let response = match method {
1339 "initialize" => json!({
1340 "jsonrpc": "2.0",
1341 "id": id,
1342 "result": {
1343 "protocolVersion": "2025-03-26",
1344 "capabilities": {
1345 "tools": { "listChanged": false },
1346 "resources": { "listChanged": false, "subscribe": false },
1347 "prompts": { "listChanged": false }
1348 },
1349 "serverInfo": {
1350 "name": "qualia-core-db-mcp",
1351 "version": env!("CARGO_PKG_VERSION")
1352 }
1353 }
1354 }),
1355 "notifications/initialized" => return None,
1356 "ping" => json!({
1357 "jsonrpc": "2.0",
1358 "id": id,
1359 "result": {}
1360 }),
1361 "tools/list" => json!({
1362 "jsonrpc": "2.0",
1363 "id": id,
1364 "result": {
1365 "tools": tool_list_json()
1366 }
1367 }),
1368 "resources/list" => json!({
1369 "jsonrpc": "2.0",
1370 "id": id,
1371 "result": {
1372 "resources": [system_resource_json()]
1373 }
1374 }),
1375 "resources/read" => {
1376 let uri = request
1377 .get("params")
1378 .and_then(|params| params.get("uri"))
1379 .and_then(Value::as_str)
1380 .unwrap_or("");
1381 if uri != "qualia://qapp-surface-schema" {
1382 json!({
1383 "jsonrpc": "2.0",
1384 "id": id,
1385 "error": {
1386 "code": -32602,
1387 "message": "Unknown resource URI"
1388 }
1389 })
1390 } else {
1391 let content = unsafe {
1392 execute_describe_qapp_surface_schema(
1393 b"{}",
1394 &build_intent_frame(b"{}", qpu_enabled, llm_enabled),
1395 )
1396 }
1397 .unwrap_or_else(|_| "{}".to_string());
1398 json!({
1399 "jsonrpc": "2.0",
1400 "id": id,
1401 "result": {
1402 "contents": [{
1403 "uri": uri,
1404 "mimeType": "application/json",
1405 "text": content
1406 }]
1407 }
1408 })
1409 }
1410 }
1411 "prompts/list" => json!({
1412 "jsonrpc": "2.0",
1413 "id": id,
1414 "result": {
1415 "prompts": []
1416 }
1417 }),
1418 "tools/call" => {
1419 let params = request.get("params").unwrap_or(&request);
1420 let name = params
1421 .get("name")
1422 .and_then(Value::as_str)
1423 .or_else(|| request.get("name").and_then(Value::as_str))
1424 .unwrap_or("");
1425 let arguments = params
1426 .get("arguments")
1427 .cloned()
1428 .unwrap_or_else(|| json!({}));
1429 let arguments_raw = serde_json::to_vec(&arguments).unwrap_or_else(|_| b"{}".to_vec());
1430 match dispatch_tool_call(name.as_bytes(), &arguments_raw, qpu_enabled, llm_enabled) {
1431 Ok(data) => json!({
1432 "jsonrpc": "2.0",
1433 "id": id,
1434 "result": {
1435 "content": [{
1436 "type": "text",
1437 "text": data
1438 }],
1439 "isError": false
1440 }
1441 }),
1442 Err(err) => {
1443 let (message, code) = error_message(err);
1444 json!({
1445 "jsonrpc": "2.0",
1446 "id": id,
1447 "error": {
1448 "code": code,
1449 "message": message
1450 }
1451 })
1452 }
1453 }
1454 }
1455 _ => json!({
1456 "jsonrpc": "2.0",
1457 "id": id,
1458 "error": {
1459 "code": -32601,
1460 "message": "Method not found"
1461 }
1462 }),
1463 };
1464
1465 Some(response.to_string())
1466}
1467
1468#[cfg(not(target_arch = "wasm32"))]
1474pub async fn start_mcp_listener() {
1475 start_mcp_listener_with_flags(true, true).await;
1476}
1477
1478#[cfg(not(target_arch = "wasm32"))]
1482pub async fn start_mcp_listener_with_flags(qpu_enabled: bool, llm_enabled: bool) {
1483 use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
1484
1485 eprintln!("[MCP Server] Starting stdio MCP server...");
1486 eprintln!(
1487 "[MCP Server] Advertised tool count: {}",
1488 stable_mcp_tools().len()
1489 );
1490
1491 let mut stdin = BufReader::new(tokio::io::stdin());
1492 let mut stdout = tokio::io::stdout();
1493 let mut line = String::new();
1494
1495 loop {
1496 line.clear();
1497 match stdin.read_line(&mut line).await {
1498 Ok(0) => break,
1499 Ok(_) => {
1500 let request = line.trim_end_matches(['\r', '\n']);
1501 if request.is_empty() {
1502 continue;
1503 }
1504 if let Some(reply) = handle_jsonrpc_message(request, qpu_enabled, llm_enabled) {
1505 let _ = stdout.write_all(reply.as_bytes()).await;
1506 let _ = stdout.write_all(b"\n").await;
1507 }
1508 }
1509 Err(_) => break,
1510 }
1511 }
1512}
1513
1514#[cfg(test)]
1515mod tests {
1516 use super::*;
1517
1518 #[test]
1519 fn initialize_returns_server_info() {
1520 let reply = handle_jsonrpc_message(
1521 r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#,
1522 true,
1523 true,
1524 )
1525 .expect("reply");
1526 let json: Value = serde_json::from_str(&reply).expect("valid json");
1527 assert_eq!(json["result"]["serverInfo"]["name"], "qualia-core-db-mcp");
1528 assert_eq!(json["result"]["protocolVersion"], "2025-03-26");
1529 }
1530
1531 #[test]
1532 fn tools_list_returns_curated_surface() {
1533 let reply = handle_jsonrpc_message(
1534 r#"{"jsonrpc":"2.0","id":"tools","method":"tools/list"}"#,
1535 true,
1536 true,
1537 )
1538 .expect("reply");
1539 let json: Value = serde_json::from_str(&reply).expect("valid json");
1540 let tools = json["result"]["tools"].as_array().expect("tool array");
1541 assert!(tools.iter().any(|tool| tool["name"] == "get_system_status"));
1542 assert!(tools.iter().any(|tool| tool["name"] == "run_docs_tests"));
1543 assert!(tools.iter().all(|tool| tool.get("inputSchema").is_some()));
1544 }
1545
1546 #[test]
1547 fn parse_rdf_tool_call_returns_quins() {
1548 let reply = handle_jsonrpc_message(
1549 r#"{"jsonrpc":"2.0","id":"rdf","method":"tools/call","params":{"name":"parse_rdf","arguments":{"format":"nt","rdf_data":"<http://example.org/Alice> <http://example.org/knows> <http://example.org/Bob> .\n"}}}"#,
1550 false,
1551 false,
1552 )
1553 .expect("reply");
1554 let json: Value = serde_json::from_str(&reply).expect("valid json");
1555 let text = json["result"]["content"][0]["text"]
1556 .as_str()
1557 .expect("text payload");
1558 let payload: Value = serde_json::from_str(text).expect("embedded json");
1559 assert_eq!(payload["quinCount"], 1);
1560 }
1561
1562 #[test]
1563 fn parse_csv_tool_call_returns_quins() {
1564 let reply = handle_jsonrpc_message(
1565 r#"{"jsonrpc":"2.0","id":"csv","method":"tools/call","params":{"name":"parse_csv","arguments":{"csv_data":"v,n\n1,2\n","field_mappings":[{"source_key":"v","predicate":"ex:v","datatype":"integer"}]}}}"#,
1566 false,
1567 false,
1568 )
1569 .expect("reply");
1570 let json: Value = serde_json::from_str(&reply).expect("valid json");
1571 let text = json["result"]["content"][0]["text"]
1572 .as_str()
1573 .expect("text payload");
1574 let payload: Value = serde_json::from_str(text).expect("embedded json");
1575 assert_eq!(payload["quinCount"], 1);
1576 }
1577
1578 #[test]
1579 fn get_graph_stats_tool_call_returns_json_payload() {
1580 let reply = handle_jsonrpc_message(
1581 r#"{"jsonrpc":"2.0","id":"graph","method":"tools/call","params":{"name":"get_graph_stats","arguments":{}}}"#,
1582 false,
1583 false,
1584 )
1585 .expect("reply");
1586 let json: Value = serde_json::from_str(&reply).expect("valid json");
1587 let text = json["result"]["content"][0]["text"]
1588 .as_str()
1589 .expect("text payload");
1590 let payload: Value = serde_json::from_str(text).expect("embedded json");
1591 assert!(payload.get("quinCount").is_some());
1592 }
1593
1594 #[test]
1595 fn get_did_info_tool_call_parses_q42() {
1596 let reply = handle_jsonrpc_message(
1597 r#"{"jsonrpc":"2.0","id":"did","method":"tools/call","params":{"name":"get_did_info","arguments":{"did":"did:q42:z6MkpTHR8VNs"}}}"#,
1598 false,
1599 false,
1600 )
1601 .expect("reply");
1602 let json: Value = serde_json::from_str(&reply).expect("valid json");
1603 let text = json["result"]["content"][0]["text"]
1604 .as_str()
1605 .expect("text payload");
1606 let payload: Value = serde_json::from_str(text).expect("embedded json");
1607 assert_eq!(payload["msbSet"], true);
1608 }
1609
1610 #[test]
1611 fn tools_list_includes_newly_public_stubs() {
1612 let reply = handle_jsonrpc_message(
1613 r#"{"jsonrpc":"2.0","id":"tools","method":"tools/list"}"#,
1614 true,
1615 true,
1616 )
1617 .expect("reply");
1618 let json: Value = serde_json::from_str(&reply).expect("valid json");
1619 let tools = json["result"]["tools"].as_array().expect("tool array");
1620 assert!(tools.iter().any(|tool| tool["name"] == "query_sparql"));
1621 assert!(tools.iter().any(|tool| tool["name"] == "parse_rdf"));
1622 assert!(tools.iter().any(|tool| tool["name"] == "list_qapps"));
1623 assert!(tools.iter().any(|tool| tool["name"] == "list_capabilities"));
1624 assert!(tools
1625 .iter()
1626 .any(|tool| tool["name"] == "computational_geometry"));
1627 assert_eq!(tools.len(), stable_mcp_tools().len());
1628 }
1629
1630 #[test]
1631 fn computational_geometry_tool_routes_hull() {
1632 let reply = handle_jsonrpc_message(
1633 r#"{"jsonrpc":"2.0","id":"geometry","method":"tools/call","params":{"name":"computational_geometry","arguments":{"op":"convex_hull_2","points":[[0,0],[1,0],[0.5,0.5],[1,1],[0,1]]}}}"#,
1634 false,
1635 false,
1636 )
1637 .expect("reply");
1638 let json: Value = serde_json::from_str(&reply).expect("valid json");
1639 let text = json["result"]["content"][0]["text"]
1640 .as_str()
1641 .expect("text payload");
1642 let payload: Value = serde_json::from_str(text).expect("embedded json");
1643 assert_eq!(payload["vertex_count"], 4);
1644 assert_eq!(payload["indices"], json!([0, 1, 3, 4]));
1645 }
1646
1647 #[test]
1648 fn computer_vision_tool_list_and_sigma() {
1649 let reply = handle_jsonrpc_message(
1650 r#"{"jsonrpc":"2.0","id":"cv","method":"tools/call","params":{"name":"computer_vision","arguments":{"op":"list"}}}"#,
1651 false,
1652 false,
1653 )
1654 .expect("reply");
1655 let json: Value = serde_json::from_str(&reply).expect("valid json");
1656 let text = json["result"]["content"][0]["text"]
1657 .as_str()
1658 .expect("text payload");
1659 let payload: Value = serde_json::from_str(text).expect("embedded json");
1660 assert_eq!(payload["library"], "specialized_libs::computer_vision");
1661 let reply2 = handle_jsonrpc_message(
1662 r#"{"jsonrpc":"2.0","id":"cv2","method":"tools/call","params":{"name":"computer_vision","arguments":{"op":"class_score_to_sigma","class_hash":4,"score":1.0}}}"#,
1663 false,
1664 false,
1665 )
1666 .expect("reply2");
1667 let json2: Value = serde_json::from_str(&reply2).expect("valid json");
1668 let text2 = json2["result"]["content"][0]["text"]
1669 .as_str()
1670 .expect("text");
1671 let payload2: Value = serde_json::from_str(text2).expect("json");
1672 assert!(payload2["sigma"].as_f64().unwrap() > 0.0);
1673 }
1674
1675 #[test]
1676 fn inference_capability_tools_are_registered() {
1677 let registered: Vec<&str> = stable_mcp_tools().iter().map(|tool| tool.name).collect();
1678 for capability in crate::CAPABILITY_DESCRIPTORS {
1679 for tool in capability.mcp_tools {
1680 assert!(
1681 registered.contains(tool),
1682 "{} routes to missing MCP tool {}",
1683 capability.name,
1684 tool
1685 );
1686 }
1687 }
1688 }
1689
1690 #[test]
1691 fn capability_catalog_is_complete_filterable_and_honest() {
1692 let all = mcp_tool_impls::list_capabilities(br#"{}"#).expect("catalogue");
1693 let all: Value = serde_json::from_str(&all).expect("catalogue json");
1694 assert_eq!(
1695 all["capability_count"].as_u64().unwrap() as usize,
1696 crate::CAPABILITY_DESCRIPTORS.len()
1697 );
1698 assert!(all["operation_group_count"].as_u64().unwrap() > 50);
1699
1700 let filtered =
1701 mcp_tool_impls::list_capabilities(br#"{"domain":"statistics"}"#).expect("filtered");
1702 let filtered: Value = serde_json::from_str(&filtered).expect("filtered json");
1703 assert_eq!(filtered["capability_count"], 1);
1704 assert_eq!(filtered["capabilities"][0]["name"], "Statistics");
1705
1706 let ml = all["capabilities"]
1707 .as_array()
1708 .unwrap()
1709 .iter()
1710 .find(|capability| capability["name"] == "MachineLearning")
1711 .expect("machine learning capability");
1712 assert_eq!(ml["maturity"], "fail-closed");
1713 assert_eq!(ml["operational"], false);
1714 }
1715
1716 #[test]
1717 fn capability_catalogue_metadata_has_no_silent_gaps() {
1718 let allowed_maturity = ["stable", "partial", "experimental", "fail-closed"];
1719 let mut names = std::collections::BTreeSet::new();
1720 for capability in crate::CAPABILITY_DESCRIPTORS {
1721 assert!(
1722 names.insert(capability.name),
1723 "duplicate {}",
1724 capability.name
1725 );
1726 assert!(
1727 !capability.operations.is_empty(),
1728 "{} has no operations",
1729 capability.name
1730 );
1731 assert!(
1732 allowed_maturity.contains(&capability.maturity),
1733 "{} has unknown maturity {}",
1734 capability.name,
1735 capability.maturity
1736 );
1737 assert!(
1738 !capability.surfaces.is_empty(),
1739 "{} has no runtime surface",
1740 capability.name
1741 );
1742 }
1743 }
1744
1745 #[test]
1746 fn get_system_status_tool_call_returns_json_payload() {
1747 let reply = handle_jsonrpc_message(
1748 r#"{"jsonrpc":"2.0","id":"status","method":"tools/call","params":{"name":"get_system_status","arguments":{}}}"#,
1749 false,
1750 true,
1751 )
1752 .expect("reply");
1753 let json: Value = serde_json::from_str(&reply).expect("valid json");
1754 let text = json["result"]["content"][0]["text"]
1755 .as_str()
1756 .expect("text payload");
1757 let payload: Value = serde_json::from_str(text).expect("embedded json");
1758 assert_eq!(payload["server"], "qualia-core-db-mcp");
1759 assert_eq!(payload["qpuEnabled"], false);
1760 }
1761
1762 #[test]
1763 fn geometry_manifests_tool_list_round_trips() {
1764 let reply = handle_jsonrpc_message(
1765 r#"{"jsonrpc":"2.0","id":"gm","method":"tools/call","params":{"name":"geometry_manifests","arguments":{}}}"#,
1766 false,
1767 false,
1768 )
1769 .expect("reply");
1770 let json: Value = serde_json::from_str(&reply).expect("valid json");
1771 let text = json["result"]["content"][0]["text"]
1772 .as_str()
1773 .expect("text payload");
1774 let payload: Value = serde_json::from_str(text).expect("embedded json");
1775 assert!(payload["op_count"].as_u64().unwrap() > 0);
1776 let ops = payload["ops"].as_array().unwrap();
1777 for op in ops {
1778 assert!(
1779 op["backends"].as_array().unwrap().len() > 0,
1780 "every op must have non-empty backends"
1781 );
1782 }
1783 }
1784
1785 #[test]
1786 fn geometry_manifests_budget_query_no_gpu() {
1787 let reply = handle_jsonrpc_message(
1788 r#"{"jsonrpc":"2.0","id":"bq","method":"tools/call","params":{"name":"geometry_manifests","arguments":{"op":"vr_filtration","device":{"cpu":true,"simd":true,"wgpu":false,"cuda":false,"wasm":true,"exact":true}}}}"#,
1789 false,
1790 false,
1791 )
1792 .expect("reply");
1793 let json: Value = serde_json::from_str(&reply).expect("valid json");
1794 let text = json["result"]["content"][0]["text"]
1795 .as_str()
1796 .expect("text payload");
1797 let payload: Value = serde_json::from_str(text).expect("embedded json");
1798 assert_eq!(payload["op"], "vr_filtration");
1799 assert!(payload["backend_count"].as_u64().unwrap() > 0);
1800 let backends = payload["runnable_backends"].as_array().unwrap();
1801 assert!(
1802 !backends.iter().any(|b| b == "wgpu"),
1803 "wgpu should not be runnable when device.wgpu=false"
1804 );
1805 }
1806}