1use crate::types::{parse_quin_slice, parse_tool_args, McpSystemError};
7use qualia_core_db::modalities::logic::shacl_extensions::{
8 credential_gates_target, degrade_violations, loci_for_shape, shapes_for_locus,
9 validate_enumerated_identity, CredentialGate, CryptoScheme, IdentifierBinding,
10 IdentityValidation, OperationMode, ShaclSeverity, ShapeRoute, ShapeViolation,
11 MAX_IDENTITY_BINDINGS, MAX_SHAPE_ROUTES,
12};
13use qualia_core_db::shacl_compiler::{validate_shacl_property, ShaclConstraint, ShaclDatatype};
14use qualia_core_db::verifiable_credential::Credential;
15use qualia_core_db::NQuin;
16use serde_json::{json, Value};
17
18fn parse_crypto_scheme(s: &str) -> CryptoScheme {
19 match s.to_ascii_lowercase().as_str() {
20 "ed25519" => CryptoScheme::Ed25519,
21 "mldsa65" | "ml-dsa-65" | "mldsa" => CryptoScheme::MlDsa65,
22 "blake3" | "blake3commitment" => CryptoScheme::Blake3Commitment,
23 "x25519" => CryptoScheme::X25519,
24 _ => CryptoScheme::Unknown,
25 }
26}
27
28fn parse_shacl_severity(s: &str) -> ShaclSeverity {
29 match s.to_ascii_lowercase().as_str() {
30 "critical" => ShaclSeverity::Critical,
31 "violation" => ShaclSeverity::Violation,
32 "warning" => ShaclSeverity::Warning,
33 _ => ShaclSeverity::Info,
34 }
35}
36
37fn parse_shacl_constraints(v: &Value) -> Result<Vec<ShaclConstraint>, McpSystemError> {
38 let arr = v
39 .get("constraints")
40 .and_then(Value::as_array)
41 .ok_or(McpSystemError::InvalidParameters)?;
42 let mut out = Vec::new();
43 for item in arr {
44 let kind = item
45 .get("kind")
46 .or_else(|| item.get("type"))
47 .and_then(Value::as_str)
48 .unwrap_or("");
49 match kind {
50 "datatype" | "Datatype" => {
51 let dt = item
52 .get("datatype")
53 .and_then(Value::as_str)
54 .unwrap_or("xsd:string");
55 let iri = format!("xsd:{dt}");
56 if let Some(dt) = ShaclDatatype::from_iri_hash(qualia_core_db::q_hash(&iri)) {
57 out.push(ShaclConstraint::Datatype(dt));
58 }
59 }
60 "minCount" | "MinCount" => {
61 let n = item.get("value").and_then(|x| x.as_u64()).unwrap_or(1) as u32;
62 out.push(ShaclConstraint::MinCount(n));
63 }
64 "maxCount" | "MaxCount" => {
65 let n = item.get("value").and_then(|x| x.as_u64()).unwrap_or(1) as u32;
66 out.push(ShaclConstraint::MaxCount(n));
67 }
68 "deonticObligate" => out.push(ShaclConstraint::DeonticObligate),
69 "deonticPermit" => out.push(ShaclConstraint::DeonticPermit),
70 "deonticForbid" => out.push(ShaclConstraint::DeonticForbid),
71 "epistemicKnowledge" => {
72 let min = item
73 .get("min_certainty")
74 .and_then(|x| x.as_u64())
75 .unwrap_or(128) as u8;
76 out.push(ShaclConstraint::EpistemicKnowledge { min_certainty: min });
77 }
78 "commonKnowledge" => out.push(ShaclConstraint::CommonKnowledge),
79 _ => {}
80 }
81 }
82 Ok(out)
83}
84
85pub fn validate_shacl(args: &[u8]) -> Result<String, McpSystemError> {
87 let v = parse_tool_args(args)?;
88 let quins = parse_quin_slice(&v, "quins")?;
89 let target_subject = v.get("target_subject").and_then(|x| x.as_u64()).unwrap_or(0);
90 let target_property = v.get("target_property").and_then(|x| x.as_u64()).unwrap_or(0);
91 if target_subject == 0 || target_property == 0 {
92 return Err(McpSystemError::InvalidParameters);
93 }
94 let constraints = parse_shacl_constraints(&v)?;
95 let valid = validate_shacl_property(&quins, target_subject, target_property, &constraints);
96 let payload = json!({
97 "valid": valid,
98 "targetSubject": target_subject,
99 "targetProperty": target_property,
100 "constraintCount": constraints.len(),
101 });
102 serde_json::to_string(&payload).map_err(|_| McpSystemError::ParseError)
103}
104
105pub fn validate_enumerated_identity_tool(args: &[u8]) -> Result<String, McpSystemError> {
107 let v = parse_tool_args(args)?;
108 let arr = v
109 .get("bindings")
110 .and_then(Value::as_array)
111 .ok_or(McpSystemError::InvalidParameters)?;
112 let n = arr.len().min(MAX_IDENTITY_BINDINGS);
113 let mut buf = [IdentifierBinding {
114 identifier: 0,
115 scheme: CryptoScheme::Unknown,
116 attested: false,
117 confidence: 0.0,
118 }; MAX_IDENTITY_BINDINGS];
119 for (i, b) in arr.iter().take(n).enumerate() {
120 buf[i] = IdentifierBinding {
121 identifier: b.get("identifier").and_then(|x| x.as_u64()).unwrap_or(0),
122 scheme: parse_crypto_scheme(b.get("scheme").and_then(Value::as_str).unwrap_or("unknown")),
123 attested: b.get("attested").and_then(Value::as_bool).unwrap_or(false),
124 confidence: b.get("confidence").and_then(Value::as_f64).unwrap_or(0.0) as f32,
125 };
126 }
127 let min_distinct = v.get("min_distinct").and_then(|x| x.as_u64()).unwrap_or(2) as u16;
128 let min_attested = v.get("min_attested").and_then(|x| x.as_u64()).unwrap_or(1) as u16;
129 let payload = match validate_enumerated_identity(&buf[..n], min_distinct, min_attested) {
130 IdentityValidation::Valid {
131 distinct,
132 attested,
133 aggregate_confidence,
134 } => json!({
135 "verdict": "valid", "distinct": distinct, "attested": attested,
136 "aggregateConfidence": aggregate_confidence,
137 }),
138 IdentityValidation::Underdetermined { distinct, attested } => json!({
139 "verdict": "underdetermined", "distinct": distinct, "attested": attested,
140 }),
141 IdentityValidation::DefinitiveCollapse => json!({
142 "verdict": "definitive_collapse",
143 "reason": "a binding asserts certainty (confidence>=1.0); identity must stay a confidence-relation",
144 }),
145 };
146 serde_json::to_string(&payload).map_err(|_| McpSystemError::ParseError)
147}
148
149pub fn shacl_credential_gate(args: &[u8]) -> Result<String, McpSystemError> {
151 let v = parse_tool_args(args)?;
152 let focus_node = v.get("focus_node").and_then(|x| x.as_u64()).unwrap_or(0);
153 let g = v.get("gate").ok_or(McpSystemError::InvalidParameters)?;
154 let gate = CredentialGate {
155 shape: g.get("shape").and_then(|x| x.as_u64()).unwrap_or(0),
156 required_claim_predicate: g.get("required_claim_predicate").and_then(|x| x.as_u64()).unwrap_or(0),
157 required_claim_object: g.get("required_claim_object").and_then(|x| x.as_u64()).unwrap_or(0),
158 accepted_issuer: g.get("accepted_issuer").and_then(|x| x.as_u64()).unwrap_or(0),
159 };
160 let c = v.get("credential").ok_or(McpSystemError::InvalidParameters)?;
161 let mut claims = Vec::new();
162 if let Some(items) = c.get("claims").and_then(Value::as_array) {
163 for q in items {
164 claims.push(NQuin {
165 subject: q.get("s").and_then(|x| x.as_u64()).unwrap_or(0),
166 predicate: q.get("p").and_then(|x| x.as_u64()).unwrap_or(0),
167 object: q.get("o").and_then(|x| x.as_u64()).unwrap_or(0),
168 context: 0,
169 metadata: 0,
170 parity: 0,
171 });
172 }
173 }
174 let vc = Credential {
175 issuer: c.get("issuer").and_then(|x| x.as_u64()).unwrap_or(0),
176 subject: c.get("subject").and_then(|x| x.as_u64()).unwrap_or(0),
177 issued_at: c.get("issued_at").and_then(|x| x.as_u64()).unwrap_or(0) as u32,
178 valid_until: c.get("valid_until").and_then(|x| x.as_u64()).unwrap_or(0) as u32,
179 claims,
180 };
181 let applies = credential_gates_target(&gate, focus_node, &vc);
182 let payload = json!({ "applies": applies, "focusNode": focus_node, "shape": gate.shape });
183 serde_json::to_string(&payload).map_err(|_| McpSystemError::ParseError)
184}
185
186pub fn shacl_degrade_violations(args: &[u8]) -> Result<String, McpSystemError> {
188 const MAX_V: usize = 256;
189 let v = parse_tool_args(args)?;
190 let arr = v
191 .get("violations")
192 .and_then(Value::as_array)
193 .ok_or(McpSystemError::InvalidParameters)?;
194 let n = arr.len().min(MAX_V);
195 let mut buf = [ShapeViolation {
196 shape: 0,
197 focus_node: 0,
198 severity: ShaclSeverity::Info,
199 }; MAX_V];
200 for (i, x) in arr.iter().take(n).enumerate() {
201 buf[i] = ShapeViolation {
202 shape: x.get("shape").and_then(|k| k.as_u64()).unwrap_or(0),
203 focus_node: x.get("focus_node").and_then(|k| k.as_u64()).unwrap_or(0),
204 severity: parse_shacl_severity(x.get("severity").and_then(Value::as_str).unwrap_or("info")),
205 };
206 }
207 let mode = if v.get("mode").and_then(Value::as_str).unwrap_or("online").eq_ignore_ascii_case("offgrid") {
208 OperationMode::OffGrid
209 } else {
210 OperationMode::Online
211 };
212 let mut out = buf;
213 let outcome = degrade_violations(&buf[..n], mode, &mut out[..n]);
214 let payload = json!({
215 "blocking": outcome.blocking,
216 "degraded": outcome.degraded,
217 "subgraphUsable": outcome.subgraph_usable,
218 });
219 serde_json::to_string(&payload).map_err(|_| McpSystemError::ParseError)
220}
221
222pub fn shacl_route(args: &[u8]) -> Result<String, McpSystemError> {
224 let v = parse_tool_args(args)?;
225 let arr = v
226 .get("routes")
227 .and_then(Value::as_array)
228 .ok_or(McpSystemError::InvalidParameters)?;
229 let n = arr.len().min(MAX_SHAPE_ROUTES);
230 let mut routes = [ShapeRoute { shape: 0, locus: 0 }; MAX_SHAPE_ROUTES];
231 for (i, r) in arr.iter().take(n).enumerate() {
232 routes[i] = ShapeRoute {
233 shape: r.get("shape").and_then(|k| k.as_u64()).unwrap_or(0),
234 locus: r.get("locus").and_then(|k| k.as_u64()).unwrap_or(0),
235 };
236 }
237 let mut out = [0u64; MAX_SHAPE_ROUTES];
238 let payload = if let Some(locus) = v.get("query_locus").and_then(Value::as_u64) {
239 let k = shapes_for_locus(&routes[..n], locus, &mut out);
240 json!({ "queryLocus": locus, "shapes": out[..k].to_vec() })
241 } else if let Some(shape) = v.get("query_shape").and_then(Value::as_u64) {
242 let k = loci_for_shape(&routes[..n], shape, &mut out);
243 json!({ "queryShape": shape, "loci": out[..k].to_vec() })
244 } else {
245 return Err(McpSystemError::InvalidParameters);
246 };
247 serde_json::to_string(&payload).map_err(|_| McpSystemError::ParseError)
248}