Skip to main content

a2a_protocol_server/tool_loop/
schema.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! Checking a call's arguments against the schema the tool advertised before
5//! the call is put to the policy and run (adversarial review T2).
6//!
7//! The loop used to check that arguments were a JSON object and that the tool
8//! was in the set, and no more: a model that sent `{"amount": "everything"}` to
9//! a tool whose schema says `amount` is a number reached the tool, which then
10//! had to defend itself. Here the schema is enforced for the keywords below.
11//! It is a checker for the subset of JSON Schema that tool parameters use, not
12//! a general validator, and says so: a keyword it does not implement is named,
13//! and [`ArgumentCheck::Strict`] refuses a call to a tool whose schema uses
14//! one, rather than let a constraint the tool's author wrote go unchecked.
15//!
16//! **Checked:** `type` (one name or several), `enum`, `const`, `properties`,
17//! `required`, `additionalProperties` (`false` or a schema), `items` (one
18//! schema), `minItems`, `maxItems`, `uniqueItems`, `minLength`, `maxLength`
19//! (in characters), `minimum`, `maximum`, `exclusiveMinimum`,
20//! `exclusiveMaximum`, `minProperties`, `maxProperties`, `anyOf`, `oneOf`,
21//! `allOf`, `not`, and the booleans `true` and `false` as schemas.
22//!
23//! **Annotations, ignored by definition:** `$schema`, `$id`, `$comment`,
24//! `title`, `description`, `default`, `examples`, `deprecated`, `readOnly`,
25//! `writeOnly`, `format` (an annotation unless a validator is asked to assert
26//! it, as in JSON Schema 2019-09 and later), `$defs` and `definitions`.
27//!
28//! **Not implemented, and named as such:** everything else, among them `$ref`,
29//! `pattern`, `patternProperties`, `multipleOf`, `if`/`then`/`else`,
30//! `contains`, `prefixItems`, `propertyNames`, `dependentRequired`,
31//! `unevaluatedProperties` and a tuple-form `items`.
32//!
33//! Numbers are compared as `f64`, so an integer past 2^53 is compared by its
34//! nearest double.
35
36use std::collections::BTreeSet;
37
38use serde_json::Value;
39
40/// How many violations a refusal lists before it says how many more there are.
41const MAX_REPORTED: usize = 5;
42
43/// Whether, and how strictly, a call's arguments are checked against the
44/// tool's schema ([`Tool::parameters`](super::Tool::parameters)); see
45/// [`ToolLoop::with_argument_check`](super::ToolLoop::with_argument_check).
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
47#[non_exhaustive]
48pub enum ArgumentCheck {
49    /// The arguments must be a JSON object and nothing more, as in every
50    /// earlier release. The default.
51    #[default]
52    Off,
53    /// The arguments must satisfy the keywords this module implements. A
54    /// keyword it does not implement is not checked.
55    Checked,
56    /// As [`Checked`](Self::Checked), and a call to a tool whose schema uses a
57    /// keyword that is not implemented is refused without being run, because
58    /// the constraint it states would otherwise go unchecked.
59    Strict,
60}
61
62/// Keywords that describe a schema and never constrain a value.
63const 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
79/// Why `arguments` may not be run against `schema`, if they may not.
80pub(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
113/// The keywords in `schema`, and in every schema it applies to a part of the
114/// value, that are neither implemented nor annotations. Independent of any
115/// value: a constraint on a property the call leaves out is still unchecked.
116fn 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
150/// Keywords whose rule [`check`] applies, besides the applicators [`scan`]
151/// descends into.
152const 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        // Every integer a JSON number can hold converts to a finite `f64` with
198        // no fraction, so this one test covers `i64`, `u64` and floats alike.
199        "integer" => value
200            .as_f64()
201            .is_some_and(|f| f.is_finite() && f.fract() == 0.0),
202        _ => false,
203    }
204}
205
206/// JSON equality, with numbers equal when their values are.
207fn 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
220/// Appends to `found` each way `value` breaks `schema`, which sits at `at`.
221fn 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
278/// `type`: one name, or a list of which the value must match one.
279fn 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
294/// `required`, `properties` and `additionalProperties`, of an object.
295fn 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
342/// `items` (one schema, for every element) and `uniqueItems`, of an array.
343fn array_keyword(key: &str, rule: &Value, items: &[Value], at: &str, found: &mut Vec<String>) {
344    if key == "items" {
345        // A list-form `items` is not a schema and constrains nothing here; a
346        // `Strict` loop has refused the tool already (see `scan`).
347        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
361/// `anyOf`, `oneOf`, `allOf` and `not`.
362fn 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
402/// `minItems`, `maxItems`, `minProperties`, `maxProperties`, `minLength` and
403/// `maxLength`.
404fn 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
423/// `minimum`, `maximum`, `exclusiveMinimum` and `exclusiveMaximum`.
424fn 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;