1use std::collections::BTreeSet;
37
38use serde_json::Value;
39
40const MAX_REPORTED: usize = 5;
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
47#[non_exhaustive]
48pub enum ArgumentCheck {
49 #[default]
52 Off,
53 Checked,
56 Strict,
60}
61
62const ANNOTATIONS: [&str; 13] = [
64 "$schema",
65 "$id",
66 "$comment",
67 "title",
68 "description",
69 "default",
70 "examples",
71 "deprecated",
72 "readOnly",
73 "writeOnly",
74 "format",
75 "$defs",
76 "definitions",
77];
78
79pub(super) fn refusal(mode: ArgumentCheck, schema: &Value, arguments: &Value) -> Option<String> {
81 if mode == ArgumentCheck::Off {
82 return None;
83 }
84 if mode == ArgumentCheck::Strict {
85 let mut unsupported = BTreeSet::new();
86 scan(schema, &mut unsupported);
87 if !unsupported.is_empty() {
88 let names: Vec<_> = unsupported.into_iter().collect();
89 return Some(format!(
90 "this tool's schema uses {}, which the loop cannot check, so the call was not run",
91 names.join(", ")
92 ));
93 }
94 }
95 let mut found = Vec::new();
96 check(schema, arguments, "", &mut found);
97 let extra = found.len().saturating_sub(MAX_REPORTED);
98 found.truncate(MAX_REPORTED);
99 if found.is_empty() {
100 return None;
101 }
102 let tail = if extra > 0 {
103 format!(" (and {extra} more)")
104 } else {
105 String::new()
106 };
107 Some(format!(
108 "the arguments do not match this tool's schema: {}{tail}",
109 found.join("; ")
110 ))
111}
112
113fn scan(schema: &Value, out: &mut BTreeSet<String>) {
117 let object = match schema {
118 Value::Bool(_) => return,
119 Value::Object(o) => o,
120 _ => {
121 out.insert("a schema that is neither an object nor a boolean".to_owned());
122 return;
123 }
124 };
125 for (key, rule) in object {
126 match key.as_str() {
127 "properties" => match rule.as_object() {
128 Some(props) => props.values().for_each(|s| scan(s, out)),
129 None => drop(out.insert(key.clone())),
130 },
131 "items" if rule.is_array() => {
132 out.insert("items as a list (tuple form)".to_owned());
133 }
134 "additionalProperties" | "items" | "not" => scan(rule, out),
135 "anyOf" | "oneOf" | "allOf" => match rule.as_array() {
136 Some(branches) => branches.iter().for_each(|s| scan(s, out)),
137 None => drop(out.insert(key.clone())),
138 },
139 "exclusiveMinimum" | "exclusiveMaximum" if !rule.is_number() => {
140 out.insert(format!("{key} as a boolean (draft 4)"));
141 }
142 k if IMPLEMENTED.contains(&k) || ANNOTATIONS.contains(&k) => {}
143 other => {
144 out.insert(other.to_owned());
145 }
146 }
147 }
148}
149
150const IMPLEMENTED: [&str; 15] = [
153 "type",
154 "enum",
155 "const",
156 "required",
157 "minItems",
158 "maxItems",
159 "uniqueItems",
160 "minLength",
161 "maxLength",
162 "minimum",
163 "maximum",
164 "exclusiveMinimum",
165 "exclusiveMaximum",
166 "minProperties",
167 "maxProperties",
168];
169
170fn place(at: &str) -> String {
171 if at.is_empty() {
172 "the arguments".to_owned()
173 } else {
174 format!("'{at}'")
175 }
176}
177
178const fn type_of(value: &Value) -> &'static str {
179 match value {
180 Value::Null => "null",
181 Value::Bool(_) => "boolean",
182 Value::Number(_) => "number",
183 Value::String(_) => "string",
184 Value::Array(_) => "array",
185 Value::Object(_) => "object",
186 }
187}
188
189fn is_type(name: &str, value: &Value) -> bool {
190 match name {
191 "null" => value.is_null(),
192 "boolean" => value.is_boolean(),
193 "object" => value.is_object(),
194 "array" => value.is_array(),
195 "string" => value.is_string(),
196 "number" => value.is_number(),
197 "integer" => value
200 .as_f64()
201 .is_some_and(|f| f.is_finite() && f.fract() == 0.0),
202 _ => false,
203 }
204}
205
206fn same(a: &Value, b: &Value) -> bool {
208 match (a, b) {
209 (Value::Number(x), Value::Number(y)) => x == y || x.as_f64() == y.as_f64(),
210 (Value::Array(x), Value::Array(y)) => {
211 x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same(p, q))
212 }
213 (Value::Object(x), Value::Object(y)) => {
214 x.len() == y.len() && x.iter().all(|(k, v)| y.get(k).is_some_and(|w| same(v, w)))
215 }
216 _ => a == b,
217 }
218}
219
220fn check(schema: &Value, value: &Value, at: &str, found: &mut Vec<String>) {
222 let object = match schema {
223 Value::Bool(false) => {
224 found.push(format!("{}: no value is allowed here", place(at)));
225 return;
226 }
227 Value::Object(o) => o,
228 _ => return,
229 };
230 for (key, rule) in object {
231 keyword(key, rule, object, value, at, found);
232 }
233}
234
235fn keyword(
236 key: &str,
237 rule: &Value,
238 schema: &serde_json::Map<String, Value>,
239 value: &Value,
240 at: &str,
241 found: &mut Vec<String>,
242) {
243 let here = place(at);
244 match key {
245 "type" => type_keyword(rule, value, &here, found),
246 "enum" => {
247 if rule
248 .as_array()
249 .is_some_and(|o| !o.iter().any(|x| same(x, value)))
250 {
251 found.push(format!("{here}: is not one of the allowed values"));
252 }
253 }
254 "const" if !same(rule, value) => {
255 found.push(format!("{here}: is not the required value"));
256 }
257 "required" | "properties" | "additionalProperties" => {
258 if let Some(object) = value.as_object() {
259 object_keyword(key, rule, schema, object, at, found);
260 }
261 }
262 "items" | "uniqueItems" => {
263 if let Some(items) = value.as_array() {
264 array_keyword(key, rule, items, at, found);
265 }
266 }
267 "minItems" | "maxItems" | "minProperties" | "maxProperties" | "minLength" | "maxLength" => {
268 sized(key, rule, value, &here, found);
269 }
270 "minimum" | "maximum" | "exclusiveMinimum" | "exclusiveMaximum" => {
271 bounded(key, rule, value, &here, found);
272 }
273 "anyOf" | "oneOf" | "allOf" | "not" => combined(key, rule, value, at, found),
274 _ => {}
275 }
276}
277
278fn type_keyword(rule: &Value, value: &Value, here: &str, found: &mut Vec<String>) {
280 let names: Vec<&str> = match rule {
281 Value::String(s) => vec![s],
282 Value::Array(a) => a.iter().filter_map(Value::as_str).collect(),
283 _ => return,
284 };
285 if !names.iter().any(|n| is_type(n, value)) {
286 found.push(format!(
287 "{here}: expected {}, got {}",
288 names.join(" or "),
289 type_of(value)
290 ));
291 }
292}
293
294fn object_keyword(
296 key: &str,
297 rule: &Value,
298 schema: &serde_json::Map<String, Value>,
299 object: &serde_json::Map<String, Value>,
300 at: &str,
301 found: &mut Vec<String>,
302) {
303 let here = place(at);
304 match key {
305 "required" => {
306 for name in rule
307 .as_array()
308 .into_iter()
309 .flatten()
310 .filter_map(Value::as_str)
311 {
312 if !object.contains_key(name) {
313 found.push(format!("{here}: missing required property '{name}'"));
314 }
315 }
316 }
317 "properties" => {
318 for (name, sub) in rule.as_object().into_iter().flatten() {
319 if let Some(v) = object.get(name) {
320 check(sub, v, &format!("{at}/{name}"), found);
321 }
322 }
323 }
324 _ => {
325 let known = schema.get("properties").and_then(Value::as_object);
326 for (name, v) in object
327 .iter()
328 .filter(|(n, _)| !known.is_some_and(|k| k.contains_key(*n)))
329 {
330 match rule {
331 Value::Bool(false) => found.push(format!(
332 "{here}: has the property '{name}', which is not allowed"
333 )),
334 Value::Bool(true) => {}
335 sub => check(sub, v, &format!("{at}/{name}"), found),
336 }
337 }
338 }
339 }
340}
341
342fn array_keyword(key: &str, rule: &Value, items: &[Value], at: &str, found: &mut Vec<String>) {
344 if key == "items" {
345 for (i, v) in items.iter().enumerate() {
348 check(rule, v, &format!("{at}/{i}"), found);
349 }
350 return;
351 }
352 let repeated = items
353 .iter()
354 .enumerate()
355 .any(|(i, a)| items[..i].iter().any(|b| same(a, b)));
356 if rule.as_bool() == Some(true) && repeated {
357 found.push(format!("{}: items must be unique", place(at)));
358 }
359}
360
361fn combined(key: &str, rule: &Value, value: &Value, at: &str, found: &mut Vec<String>) {
363 let here = place(at);
364 if key == "not" {
365 let mut sub = Vec::new();
366 check(rule, value, at, &mut sub);
367 if sub.is_empty() {
368 found.push(format!("{here}: matches a shape that is not allowed"));
369 }
370 return;
371 }
372 let Some(branches) = rule.as_array() else {
373 return;
374 };
375 if key == "allOf" {
376 for branch in branches {
377 check(branch, value, at, found);
378 }
379 return;
380 }
381 let passing = branches
382 .iter()
383 .filter(|b| {
384 let mut sub = Vec::new();
385 check(b, value, at, &mut sub);
386 sub.is_empty()
387 })
388 .count();
389 let (broken, needs) = if key == "anyOf" {
390 (passing == 0, "at least one is needed")
391 } else {
392 (passing != 1, "exactly one is needed")
393 };
394 if broken {
395 found.push(format!(
396 "{here}: matches {passing} of the {} shapes allowed, {needs}",
397 branches.len()
398 ));
399 }
400}
401
402fn sized(key: &str, rule: &Value, value: &Value, here: &str, found: &mut Vec<String>) {
405 let Some(limit) = rule.as_u64() else { return };
406 let (size, what) = match (key, value) {
407 ("minItems" | "maxItems", Value::Array(a)) => (a.len(), "items"),
408 ("minProperties" | "maxProperties", Value::Object(o)) => (o.len(), "properties"),
409 ("minLength" | "maxLength", Value::String(s)) => (s.chars().count(), "characters"),
410 _ => return,
411 };
412 let size = u64::try_from(size).unwrap_or(u64::MAX);
413 let (broken, bound) = if key.starts_with("min") {
414 (size < limit, "at least")
415 } else {
416 (size > limit, "at most")
417 };
418 if broken {
419 found.push(format!("{here}: has {size} {what}, needs {bound} {limit}"));
420 }
421}
422
423fn bounded(key: &str, rule: &Value, value: &Value, here: &str, found: &mut Vec<String>) {
425 let (Some(limit), Some(n)) = (rule.as_f64(), value.as_f64()) else {
426 return;
427 };
428 let (broken, bound) = match key {
429 "minimum" => (n < limit, "at least"),
430 "maximum" => (n > limit, "at most"),
431 "exclusiveMinimum" => (n <= limit, "more than"),
432 _ => (n >= limit, "less than"),
433 };
434 if broken {
435 found.push(format!("{here}: is {n}, needs {bound} {limit}"));
436 }
437}
438
439#[cfg(test)]
440#[path = "schema_tests.rs"]
441mod tests;