Skip to main content

wabot_feature_tool/
lib.rs

1//! # wabot-feature-tool
2//!
3//! The tool runtime shared by **mindsets** (end-user chatbots) and
4//! **agents** (driven programmatically). Port of
5//! `wabot-ts/src/feature/tool`.
6//!
7//! It was extracted from `MindsetOperator` when agents arrived and
8//! needed the same machinery: turn a set of `#[tools]` types into the
9//! schema an LLM sees ([`ToolInvoker::schema`]), and dispatch the
10//! model's function calls back into them ([`ToolInvoker::call`]) with
11//! validation and gating.
12//!
13//! ## Gating
14//!
15//! [`ToolGate`] is what makes mindset→agent delegation safe. A tool
16//! set marked `expose_to_mindsets = false` is invisible to a mindset
17//! unless the delegation allow-lists it explicitly, so a chatbot can
18//! never reach a privileged agent tool by accident:
19//!
20//! ```ignore
21//! ToolInvoker::new(container, tools)
22//!     .with_gate(ToolGate::default().for_mindset().allow(["read_catalog"]))
23//! ```
24//!
25//! A blocked call doesn't error — it returns `TOOL_NOT_ALLOWED` to the
26//! model, which is a thing the model can read and act on, unlike an
27//! exception.
28
29use std::collections::BTreeMap;
30use std::future::Future;
31use std::pin::Pin;
32use std::sync::Arc;
33
34use serde::{Deserialize, Serialize};
35use thiserror::Error;
36
37use wabot_core::injection::Container;
38use wabot_core::validation::{FieldType, ModelInfo, ModelValidationError, ValidationError};
39
40/// What a tool invocation can go wrong with.
41///
42/// Only [`ToolError::UnknownTool`] and [`ToolError::DuplicateName`]
43/// reach the caller of [`ToolInvoker::call`] — the other three are
44/// what the macro-generated closure reports, and the invoker turns
45/// them into a payload the *model* reads. See
46/// [`ToolInvoker::call`] for why.
47#[derive(Debug, Error)]
48pub enum ToolError {
49    #[error("function '{0}' is not registered in this tool set")]
50    UnknownTool(String),
51    #[error("duplicate tool name(s) exposed to the model: {details}. Tool function names must be unique across the set; rename a method or exclude one with allow/deny")]
52    DuplicateName { details: String },
53    #[error("invalid tool arguments: {0}")]
54    InvalidArguments(String),
55    #[error("validation failed: {0}")]
56    ValidationFailed(ModelValidationError),
57    #[error("tool handler returned error: {0}")]
58    Handler(String),
59}
60
61impl From<ValidationError> for ToolError {
62    fn from(e: ValidationError) -> Self {
63        let mut model = ModelValidationError::new();
64        model.push("(root)", e);
65        Self::ValidationFailed(model)
66    }
67}
68
69/// One parameter of a tool, as the model sees it.
70#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
71pub struct ToolParameter {
72    pub name: String,
73    /// JSON-schema type name: `string`, `number`, `integer`,
74    /// `boolean`, `array`, `object`.
75    #[serde(rename = "type")]
76    pub r#type: String,
77    pub description: String,
78    /// False when the argument struct declared the field optional.
79    ///
80    /// This is the *internal* truth, not what the provider is told:
81    /// adapters advertise every parameter as required and mark the
82    /// optional ones nullable, then
83    /// [`normalize_optional_arguments`] undoes it on the way back in.
84    /// Adapters read this to decide which parameters accept null.
85    #[serde(default = "default_true")]
86    pub required: bool,
87}
88
89fn default_true() -> bool {
90    true
91}
92
93/// Provider-neutral tool description shipped to the LLM. Shared by
94/// mindsets and agents; the chat adapters know this type.
95#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
96pub struct ToolSchema {
97    pub language: String,
98    pub name: String,
99    pub description: String,
100    pub parameters: Vec<ToolParameter>,
101}
102
103/// A tool the model can call: its schema plus a type-erased async
104/// body. `#[tools]` emits one of these per method.
105pub struct ToolDefinition {
106    pub name: &'static str,
107    pub description: &'static str,
108    pub language: &'static str,
109    /// The tool set this came from — what `allow`/`deny` match against
110    /// when you name a whole class rather than one function.
111    pub owner: &'static str,
112    /// `false` hides the tool from mindsets unless allow-listed.
113    pub expose_to_mindsets: bool,
114    /// Argument metadata, from the args struct's `#[derive(Validate)]`.
115    pub model_info: fn() -> &'static ModelInfo,
116    pub invoke: ToolInvokeFn,
117}
118
119impl std::fmt::Debug for ToolDefinition {
120    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121        f.debug_struct("ToolDefinition")
122            .field("name", &self.name)
123            .field("owner", &self.owner)
124            .field("expose_to_mindsets", &self.expose_to_mindsets)
125            .finish_non_exhaustive()
126    }
127}
128
129impl Clone for ToolDefinition {
130    fn clone(&self) -> Self {
131        Self {
132            name: self.name,
133            description: self.description,
134            language: self.language,
135            owner: self.owner,
136            expose_to_mindsets: self.expose_to_mindsets,
137            model_info: self.model_info,
138            invoke: self.invoke.clone(),
139        }
140    }
141}
142
143/// Deserialize + validate + dispatch + stringify, all inside the
144/// closure the macro emits.
145pub type ToolInvokeFn = Arc<
146    dyn Fn(Container, String) -> Pin<Box<dyn Future<Output = Result<String, ToolError>> + Send>>
147        + Send
148        + Sync,
149>;
150
151/// Which tools are reachable in a given context.
152///
153/// `allow` and `deny` accept either a tool-set name (`"CatalogTools"`)
154/// or a single function name (`"read_catalog"`), matching TS's
155/// class-or-function selector.
156#[derive(Debug, Default, Clone)]
157pub struct ToolGate {
158    allow: Vec<String>,
159    deny: Vec<String>,
160    for_mindset: bool,
161}
162
163impl ToolGate {
164    pub fn new() -> Self {
165        Self::default()
166    }
167
168    /// Only these are exposed and callable.
169    pub fn allow<S: Into<String>>(mut self, refs: impl IntoIterator<Item = S>) -> Self {
170        self.allow.extend(refs.into_iter().map(Into::into));
171        self
172    }
173
174    /// These are never exposed or callable, even if allow-listed.
175    pub fn deny<S: Into<String>>(mut self, refs: impl IntoIterator<Item = S>) -> Self {
176        self.deny.extend(refs.into_iter().map(Into::into));
177        self
178    }
179
180    /// Honour `expose_to_mindsets = false`. Set on the mindset→agent
181    /// delegation path, so a chatbot can't reach privileged tools.
182    pub fn for_mindset(mut self) -> Self {
183        self.for_mindset = true;
184        self
185    }
186
187    fn matches(&self, list: &[String], tool: &ToolDefinition) -> bool {
188        list.iter()
189            .any(|reference| reference == tool.name || reference == tool.owner)
190    }
191
192    /// The precedence TS uses: deny wins, then the mindset visibility
193    /// rule, then the allow-list if there is one.
194    pub fn allows(&self, tool: &ToolDefinition) -> bool {
195        if self.matches(&self.deny, tool) {
196            return false;
197        }
198        let explicitly_allowed = self.matches(&self.allow, tool);
199        if self.for_mindset && !tool.expose_to_mindsets && !explicitly_allowed {
200            return false;
201        }
202        if !self.allow.is_empty() {
203            return explicitly_allowed;
204        }
205        true
206    }
207}
208
209/// Turns tool definitions into an LLM schema and dispatches calls.
210pub struct ToolInvoker {
211    container: Container,
212    tools: Vec<ToolDefinition>,
213    gate: ToolGate,
214}
215
216impl ToolInvoker {
217    pub fn new(container: Container, tools: Vec<ToolDefinition>) -> Self {
218        // De-duplicate by (owner, name) so a tool set listed twice
219        // doesn't look like a name collision below.
220        let mut seen: BTreeMap<(&str, &str), ()> = BTreeMap::new();
221        let tools = tools
222            .into_iter()
223            .filter(|t| seen.insert((t.owner, t.name), ()).is_none())
224            .collect();
225        Self {
226            container,
227            tools,
228            gate: ToolGate::default(),
229        }
230    }
231
232    pub fn with_gate(mut self, gate: ToolGate) -> Self {
233        self.gate = gate;
234        self
235    }
236
237    pub fn gate(&self) -> &ToolGate {
238        &self.gate
239    }
240
241    /// Every tool, gated or not — for diagnostics.
242    pub fn all(&self) -> &[ToolDefinition] {
243        &self.tools
244    }
245
246    /// The schema the model sees.
247    ///
248    /// Errors on duplicate names rather than shipping them: the model
249    /// can't disambiguate two tools called the same thing, and
250    /// [`ToolInvoker::call`] would silently dispatch to whichever came
251    /// first.
252    pub fn schema(&self) -> Result<Vec<ToolSchema>, ToolError> {
253        let exposed: Vec<&ToolDefinition> =
254            self.tools.iter().filter(|t| self.gate.allows(t)).collect();
255        assert_unique_names(&exposed)?;
256        Ok(exposed.iter().map(|t| build_schema(t)).collect())
257    }
258
259    /// True when `name` exists in this set at all (gated or not).
260    pub fn has(&self, name: &str) -> bool {
261        self.tools.iter().any(|t| t.name == name)
262    }
263
264    /// Invoke a tool by name.
265    ///
266    /// **Almost every failure comes back as a `Ok(payload)` the model
267    /// reads, not as an `Err`.** A blocked tool, malformed JSON
268    /// arguments, arguments that fail validation and a handler that
269    /// errors all produce a JSON object naming the problem, because
270    /// the model can act on that — re-issue the call with the field
271    /// corrected — whereas an error propagating out of here aborts
272    /// the whole turn over something the model could have fixed
273    /// itself. Same choice TS's `ToolInvoker.invokeTool` makes.
274    ///
275    /// The one genuine `Err` is [`ToolError::UnknownTool`]: the model
276    /// named a function that does not exist, so there is nothing to
277    /// dispatch to and the caller decides what to do.
278    pub async fn call(&self, name: &str, args_json: &str) -> Result<String, ToolError> {
279        let tool = self
280            .tools
281            .iter()
282            .find(|t| t.name == name)
283            .ok_or_else(|| ToolError::UnknownTool(name.to_string()))?;
284
285        if !self.gate.allows(tool) {
286            tracing::warn!(tool = name, "tool call blocked by the gate");
287            return Ok(serde_json::json!({
288                "error": "TOOL_NOT_ALLOWED",
289                "message": format!(
290                    "Function '{name}' is not available in this context. Do not call it again."
291                ),
292            })
293            .to_string());
294        }
295
296        match (tool.invoke)(self.container.clone(), args_json.to_string()).await {
297            Ok(response) => Ok(response),
298            Err(error) => Ok(invocation_failure_payload(name, args_json, error)?),
299        }
300    }
301}
302
303/// Turn a failed invocation into something the model can act on.
304fn invocation_failure_payload(
305    name: &str,
306    args_json: &str,
307    error: ToolError,
308) -> Result<String, ToolError> {
309    let payload = match error {
310        ToolError::InvalidArguments(details) => {
311            tracing::error!(tool = name, args = args_json, %details, "tool received unparsable arguments");
312            serde_json::json!({
313                "error": "INVALID_JSON_ARGUMENTS",
314                "message": "The function call arguments are not valid JSON. Re-issue the call with a valid JSON object.",
315                "details": details,
316            })
317        }
318        ToolError::ValidationFailed(model) => {
319            tracing::warn!(
320                tool = name,
321                args = args_json,
322                "tool received invalid arguments"
323            );
324            serde_json::json!({
325                "error": "INVALID_ARGUMENTS",
326                "message": "The provided arguments did not pass validation. Inspect the errors below and re-issue the call with corrected arguments.",
327                "details": flatten_validation_error(&model),
328            })
329        }
330        ToolError::Handler(message) => {
331            tracing::error!(tool = name, %message, "tool handler failed");
332            serde_json::json!({ "message": message })
333        }
334        // Not produced by an invoke closure; surface rather than swallow.
335        other => return Err(other),
336    };
337    Ok(payload.to_string())
338}
339
340/// `{ path, message }` per failure, so the model is told *which*
341/// argument to fix rather than being handed a nested error tree.
342fn flatten_validation_error(model: &ModelValidationError) -> Vec<serde_json::Value> {
343    let mut out = Vec::new();
344    for (field, errors) in &model.properties {
345        for error in errors {
346            out.push(serde_json::json!({
347                "path": field,
348                "message": error.description,
349            }));
350        }
351    }
352    if out.is_empty() {
353        out.push(serde_json::json!({
354            "path": "(root)",
355            "message": model.description,
356        }));
357    }
358    out
359}
360
361fn assert_unique_names(tools: &[&ToolDefinition]) -> Result<(), ToolError> {
362    let mut owners_by_name: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
363    for tool in tools {
364        owners_by_name
365            .entry(tool.name)
366            .or_default()
367            .push(tool.owner);
368    }
369    let conflicts: Vec<String> = owners_by_name
370        .into_iter()
371        .filter(|(_, owners)| owners.len() > 1)
372        .map(|(name, owners)| format!("'{name}' ({})", owners.join(", ")))
373        .collect();
374    if conflicts.is_empty() {
375        Ok(())
376    } else {
377        Err(ToolError::DuplicateName {
378            details: conflicts.join("; "),
379        })
380    }
381}
382
383fn build_schema(tool: &ToolDefinition) -> ToolSchema {
384    schema_from_model_info(
385        tool.name,
386        tool.description,
387        tool.language,
388        (tool.model_info)(),
389    )
390}
391
392/// Describe a `#[derive(Validate)]` struct to a model as a tool.
393///
394/// Public because a tool set isn't the only thing shaped like one: an
395/// agent asked for a typed answer offers the answer struct as a
396/// synthetic tool, and it must be described exactly the way real tools
397/// are or the model treats it differently.
398pub fn schema_from_model_info(
399    name: &str,
400    description: &str,
401    language: &str,
402    info: &'static ModelInfo,
403) -> ToolSchema {
404    ToolSchema {
405        language: language.to_string(),
406        name: name.to_string(),
407        description: description.to_string(),
408        parameters: info
409            .properties
410            .iter()
411            .map(|p| ToolParameter {
412                name: p.name.to_string(),
413                r#type: type_label(&p.field_type),
414                description: parameter_description(
415                    p.description.unwrap_or(""),
416                    &p.field_type,
417                    p.optional,
418                ),
419                required: !p.optional,
420            })
421            .collect(),
422    }
423}
424
425/// TS strips `#` from descriptions and appends the ISO-8601 hint for
426/// dates, so a model knows the format without it being spelled out in
427/// every `#[description]`.
428fn parameter_description(raw: &str, field_type: &FieldType, optional: bool) -> String {
429    let mut description = raw.replace('#', " ").trim().to_string();
430    if matches!(field_type, FieldType::Date) {
431        description.push_str("\nFormat: ISO 8601 - YYYY-MM-DDTHH:mm:ssZ");
432    }
433    if optional {
434        description.push_str(OPTIONAL_HINT);
435    }
436    description
437}
438
439/// Told to the model for every optional argument. See
440/// [`normalize_optional_arguments`] for why an optional argument is
441/// presented as one the model must still answer.
442pub const OPTIONAL_HINT: &str =
443    "\nOptional: pass null if you have no value for it. Do not invent one.";
444
445/// Drop optional arguments the model declined to fill in.
446///
447/// ## Why arguments arrive this way
448///
449/// Adapters advertise **every** parameter as required and let the
450/// optional ones be null. That sounds backwards, and it is the more
451/// reliable shape in practice:
452///
453/// * OpenAI's strict mode *requires* every property to be listed in
454///   `required` — the alternative is turning strict off for any tool
455///   with one optional argument, losing schema enforcement for all of
456///   its arguments.
457/// * A model given a genuinely-optional parameter tends to either omit
458///   it silently or invent a plausible value. Asking it to answer
459///   `null` makes "I have no value" an explicit, checkable choice.
460///
461/// So the boundary has to undo it: a `null`, an empty string, or a
462/// blank one, on a property the args struct declared optional, is the
463/// model saying *nothing*, and the key is removed so it deserializes
464/// as `None` rather than `Some("")`. A missing key is already that.
465///
466/// Only properties **this** `ModelInfo` describes are touched.
467/// Required properties are left exactly as sent, so a required field
468/// the model nulled still fails validation and is reported back to it
469/// — this must never turn a missing answer into a silent default.
470///
471/// Nested models are not walked: `FieldType::Model` stores only a type
472/// name, so which of a nested struct's fields are optional isn't
473/// knowable here. Give a nested optional field `#[serde(default)]` and
474/// a type that accepts null.
475pub fn normalize_optional_arguments(value: &mut serde_json::Value, info: &ModelInfo) {
476    let Some(object) = value.as_object_mut() else {
477        return;
478    };
479    for property in info.properties {
480        if !property.optional {
481            continue;
482        }
483        let blank = object
484            .get(property.name)
485            .is_some_and(|v| v.is_null() || v.as_str().is_some_and(|s| s.trim().is_empty()));
486        if blank {
487            object.remove(property.name);
488        }
489    }
490}
491
492/// Parse a tool's JSON arguments into its args struct: normalize the
493/// optional ones, deserialize, then validate.
494///
495/// The one place that turns what a model wrote into a typed value —
496/// used by the `#[tools]` macro and by an agent reading a structured
497/// answer, so both treat a nulled optional argument identically.
498pub fn parse_tool_arguments<T>(args_json: &str) -> Result<T, ToolError>
499where
500    T: serde::de::DeserializeOwned + wabot_core::validation::Validate,
501{
502    let mut value: serde_json::Value = serde_json::from_str(args_json)
503        .map_err(|error| ToolError::InvalidArguments(error.to_string()))?;
504    normalize_optional_arguments(&mut value, T::model_info());
505    let parsed: T = serde_json::from_value(value)
506        .map_err(|error| ToolError::InvalidArguments(error.to_string()))?;
507    parsed.validate().map_err(ToolError::ValidationFailed)?;
508    Ok(parsed)
509}
510
511pub fn type_label(field_type: &FieldType) -> String {
512    match field_type {
513        FieldType::String | FieldType::Date => "string".into(),
514        FieldType::Integer => "integer".into(),
515        FieldType::Number => "number".into(),
516        FieldType::Boolean => "boolean".into(),
517        FieldType::Json => "object".into(),
518        FieldType::Array(_) => "array".into(),
519        FieldType::Model { .. } => "object".into(),
520        FieldType::Record(_) => "object".into(),
521    }
522}
523
524#[cfg(test)]
525mod tests {
526    use super::*;
527    use wabot_core::validation::{ModelInfo, PropertyInfo};
528
529    static EMPTY: ModelInfo = ModelInfo {
530        name: "Empty",
531        properties: &[],
532    };
533
534    static ONE_ARG: ModelInfo = ModelInfo {
535        name: "OneArg",
536        properties: &[PropertyInfo {
537            name: "query",
538            field_type: FieldType::String,
539            optional: false,
540            description: Some("What to look #up"),
541            constraints: &[],
542        }],
543    };
544
545    static A_DATE: ModelInfo = ModelInfo {
546        name: "ADate",
547        properties: &[PropertyInfo {
548            name: "when",
549            field_type: FieldType::Date,
550            optional: true,
551            description: Some("When"),
552            constraints: &[],
553        }],
554    };
555
556    fn tool(name: &'static str, owner: &'static str) -> ToolDefinition {
557        tool_with(name, owner, true, &EMPTY)
558    }
559
560    fn tool_with(
561        name: &'static str,
562        owner: &'static str,
563        expose_to_mindsets: bool,
564        info: &'static ModelInfo,
565    ) -> ToolDefinition {
566        let response = name.to_string();
567        ToolDefinition {
568            name,
569            description: "does a thing",
570            language: "english",
571            owner,
572            expose_to_mindsets,
573            model_info: match info.name {
574                "OneArg" => || &ONE_ARG,
575                "ADate" => || &A_DATE,
576                _ => || &EMPTY,
577            },
578            invoke: Arc::new(move |_c, args| {
579                let response = response.clone();
580                Box::pin(async move { Ok(format!("{response}:{args}")) })
581            }),
582        }
583    }
584
585    fn invoker(tools: Vec<ToolDefinition>) -> ToolInvoker {
586        ToolInvoker::new(Container::new(), tools)
587    }
588
589    #[test]
590    fn the_schema_carries_names_types_and_requiredness() {
591        let invoker = invoker(vec![tool_with("search", "Catalog", true, &ONE_ARG)]);
592        let schema = invoker.schema().unwrap();
593
594        assert_eq!(schema.len(), 1);
595        assert_eq!(schema[0].name, "search");
596        assert_eq!(schema[0].language, "english");
597        let param = &schema[0].parameters[0];
598        assert_eq!(param.name, "query");
599        assert_eq!(param.r#type, "string");
600        assert!(param.required);
601        assert_eq!(param.description, "What to look  up", "`#` is stripped");
602    }
603
604    #[test]
605    fn optional_arguments_and_dates_are_described_for_the_model() {
606        let invoker = invoker(vec![tool_with("when", "Calendar", true, &A_DATE)]);
607        let param = invoker.schema().unwrap().remove(0).parameters.remove(0);
608        assert!(!param.required, "an Option<T> field is not required");
609        assert_eq!(param.r#type, "string");
610        assert!(
611            param.description.contains("pass null"),
612            "an optional argument must tell the model how to decline it, \
613             since adapters still ask for it: {}",
614            param.description
615        );
616        assert!(
617            param.description.contains("ISO 8601"),
618            "a date should tell the model its format: {}",
619            param.description
620        );
621    }
622
623    #[tokio::test]
624    async fn calling_dispatches_to_the_tool() {
625        let invoker = invoker(vec![tool("search", "Catalog")]);
626        assert_eq!(
627            invoker.call("search", "{\"q\":1}").await.unwrap(),
628            "search:{\"q\":1}"
629        );
630    }
631
632    // ---- optional arguments ---------------------------------------
633
634    #[derive(Debug, serde::Deserialize, PartialEq)]
635    struct SearchArgs {
636        query: String,
637        #[serde(default)]
638        timezone: Option<String>,
639        #[serde(default)]
640        limit: Option<i64>,
641    }
642
643    static SEARCH_ARGS: ModelInfo = ModelInfo {
644        name: "SearchArgs",
645        properties: &[
646            PropertyInfo {
647                name: "query",
648                field_type: FieldType::String,
649                optional: false,
650                description: None,
651                constraints: &[],
652            },
653            PropertyInfo {
654                name: "timezone",
655                field_type: FieldType::String,
656                optional: true,
657                description: None,
658                constraints: &[],
659            },
660            PropertyInfo {
661                name: "limit",
662                field_type: FieldType::Integer,
663                optional: true,
664                description: None,
665                constraints: &[],
666            },
667        ],
668    };
669
670    impl wabot_core::validation::Validate for SearchArgs {
671        fn model_info() -> &'static ModelInfo {
672            &SEARCH_ARGS
673        }
674        fn validate(&self) -> Result<(), ModelValidationError> {
675            if self.query.is_empty() {
676                let mut error = ModelValidationError::new();
677                error.push("query", ValidationError::new("should not be empty"));
678                return Err(error);
679            }
680            Ok(())
681        }
682    }
683
684    /// The model is asked for every argument and answers `null` for
685    /// the ones it has nothing to say about. All four spellings of
686    /// "nothing" have to land on `None`.
687    #[test]
688    fn an_optional_argument_the_model_declined_becomes_none() {
689        for args in [
690            r#"{"query":"boots","timezone":null,"limit":null}"#,
691            r#"{"query":"boots","timezone":"","limit":null}"#,
692            r#"{"query":"boots","timezone":"   ","limit":null}"#,
693            r#"{"query":"boots"}"#,
694        ] {
695            let parsed: SearchArgs = parse_tool_arguments(args).unwrap();
696            assert_eq!(
697                parsed,
698                SearchArgs {
699                    query: "boots".into(),
700                    timezone: None,
701                    limit: None,
702                },
703                "parsing {args}"
704            );
705        }
706    }
707
708    #[test]
709    fn a_filled_in_optional_argument_survives() {
710        let parsed: SearchArgs =
711            parse_tool_arguments(r#"{"query":"boots","timezone":"UTC","limit":5}"#).unwrap();
712        assert_eq!(parsed.timezone.as_deref(), Some("UTC"));
713        assert_eq!(parsed.limit, Some(5));
714    }
715
716    /// The normalization must not become a way for a *required*
717    /// argument to go missing quietly.
718    #[test]
719    fn a_required_argument_answered_with_null_still_fails() {
720        let error = parse_tool_arguments::<SearchArgs>(r#"{"query":null}"#).unwrap_err();
721        assert!(
722            matches!(error, ToolError::InvalidArguments(_)),
723            "got {error:?}"
724        );
725
726        let error = parse_tool_arguments::<SearchArgs>(r#"{"query":""}"#).unwrap_err();
727        assert!(
728            matches!(error, ToolError::ValidationFailed(_)),
729            "an empty required string reaches the validator: {error:?}"
730        );
731    }
732
733    /// A null on an optional field of a type that can't hold an empty
734    /// string is exactly why the key is removed rather than coerced.
735    #[test]
736    fn a_nulled_optional_number_does_not_become_a_type_error() {
737        let parsed: SearchArgs = parse_tool_arguments(r#"{"query":"boots","limit":""}"#).unwrap();
738        assert_eq!(parsed.limit, None, "\"\" on an Option<i64> means absent");
739    }
740
741    #[test]
742    fn normalization_leaves_everything_it_does_not_know_about_alone() {
743        let mut value: serde_json::Value =
744            serde_json::from_str(r#"{"query":"","unknown":null,"nested":{"inner":null}}"#).unwrap();
745        normalize_optional_arguments(&mut value, &SEARCH_ARGS);
746        assert_eq!(
747            value,
748            serde_json::json!({"query":"","unknown":null,"nested":{"inner":null}}),
749            "only optional properties this ModelInfo describes are touched"
750        );
751    }
752
753    /// A failing tool must leave the model able to continue: it gets a
754    /// readable payload and can correct itself, instead of the turn
755    /// dying on an error it never sees.
756    #[tokio::test]
757    async fn a_failing_call_is_reported_to_the_model_not_raised() {
758        fn failing(name: &'static str, error: fn() -> ToolError) -> ToolDefinition {
759            ToolDefinition {
760                name,
761                description: "fails",
762                language: "english",
763                owner: "Broken",
764                expose_to_mindsets: true,
765                model_info: || &EMPTY,
766                invoke: Arc::new(move |_c, _args| Box::pin(async move { Err(error()) })),
767            }
768        }
769
770        let invoker = invoker(vec![
771            failing("bad_json", || {
772                ToolError::InvalidArguments("expected value at line 1".into())
773            }),
774            failing("bad_args", || {
775                let mut model = ModelValidationError::new();
776                model.push("query", ValidationError::new("should not be empty"));
777                ToolError::ValidationFailed(model)
778            }),
779            failing("boom", || ToolError::Handler("upstream is down".into())),
780        ]);
781
782        let json: serde_json::Value =
783            serde_json::from_str(&invoker.call("bad_json", "not json").await.unwrap()).unwrap();
784        assert_eq!(json["error"], "INVALID_JSON_ARGUMENTS");
785
786        let json: serde_json::Value =
787            serde_json::from_str(&invoker.call("bad_args", "{}").await.unwrap()).unwrap();
788        assert_eq!(json["error"], "INVALID_ARGUMENTS");
789        assert_eq!(
790            json["details"][0],
791            serde_json::json!({ "path": "query", "message": "should not be empty" }),
792            "the model is told which argument to fix"
793        );
794
795        let json: serde_json::Value =
796            serde_json::from_str(&invoker.call("boom", "{}").await.unwrap()).unwrap();
797        assert_eq!(json["message"], "upstream is down");
798    }
799
800    #[tokio::test]
801    async fn an_unknown_tool_is_an_error() {
802        let invoker = invoker(vec![tool("search", "Catalog")]);
803        assert!(matches!(
804            invoker.call("invented", "{}").await,
805            Err(ToolError::UnknownTool(_))
806        ));
807    }
808
809    #[test]
810    fn two_tools_with_the_same_name_are_refused() {
811        let invoker = invoker(vec![tool("search", "Catalog"), tool("search", "Docs")]);
812        let error = invoker.schema().unwrap_err();
813        let message = error.to_string();
814        assert!(matches!(error, ToolError::DuplicateName { .. }));
815        assert!(message.contains("'search'"), "{message}");
816        assert!(
817            message.contains("Catalog") && message.contains("Docs"),
818            "{message}"
819        );
820    }
821
822    #[test]
823    fn deny_resolves_a_name_conflict() {
824        let invoker = invoker(vec![tool("search", "Catalog"), tool("search", "Docs")])
825            .with_gate(ToolGate::new().deny(["Docs"]));
826        let schema = invoker.schema().expect("the conflict is gated away");
827        assert_eq!(schema.len(), 1);
828    }
829
830    #[test]
831    fn the_same_tool_set_listed_twice_is_not_a_conflict() {
832        let invoker = invoker(vec![tool("search", "Catalog"), tool("search", "Catalog")]);
833        assert_eq!(invoker.schema().unwrap().len(), 1);
834    }
835
836    #[test]
837    fn deny_wins_over_allow() {
838        let gate = ToolGate::new().allow(["search"]).deny(["search"]);
839        let invoker = invoker(vec![tool("search", "Catalog")]).with_gate(gate);
840        assert!(invoker.schema().unwrap().is_empty());
841    }
842
843    #[test]
844    fn an_allow_list_hides_everything_else() {
845        let invoker = invoker(vec![tool("search", "Catalog"), tool("write", "Catalog")])
846            .with_gate(ToolGate::new().allow(["search"]));
847        let names: Vec<String> = invoker
848            .schema()
849            .unwrap()
850            .into_iter()
851            .map(|s| s.name)
852            .collect();
853        assert_eq!(names, vec!["search"]);
854    }
855
856    #[test]
857    fn allow_can_name_a_whole_tool_set() {
858        let invoker = invoker(vec![tool("search", "Catalog"), tool("wipe", "Admin")])
859            .with_gate(ToolGate::new().allow(["Catalog"]));
860        let names: Vec<String> = invoker
861            .schema()
862            .unwrap()
863            .into_iter()
864            .map(|s| s.name)
865            .collect();
866        assert_eq!(names, vec!["search"]);
867    }
868
869    #[test]
870    fn privileged_tools_are_hidden_from_mindsets() {
871        let tools = vec![
872            tool_with("read", "Catalog", true, &EMPTY),
873            tool_with("wipe", "Admin", false, &EMPTY),
874        ];
875
876        // An agent sees both.
877        let agent_view = invoker(tools.clone());
878        assert_eq!(agent_view.schema().unwrap().len(), 2);
879
880        // A mindset delegating to that agent sees only the public one.
881        let mindset_view = invoker(tools.clone()).with_gate(ToolGate::new().for_mindset());
882        let names: Vec<String> = mindset_view
883            .schema()
884            .unwrap()
885            .into_iter()
886            .map(|s| s.name)
887            .collect();
888        assert_eq!(names, vec!["read"]);
889
890        // …unless the delegation allow-lists it explicitly.
891        let explicit = invoker(tools).with_gate(ToolGate::new().for_mindset().allow(["wipe"]));
892        let names: Vec<String> = explicit
893            .schema()
894            .unwrap()
895            .into_iter()
896            .map(|s| s.name)
897            .collect();
898        assert_eq!(names, vec!["wipe"]);
899    }
900
901    #[tokio::test]
902    async fn a_blocked_call_tells_the_model_instead_of_erroring() {
903        let invoker = invoker(vec![tool_with("wipe", "Admin", false, &EMPTY)])
904            .with_gate(ToolGate::new().for_mindset());
905
906        // The tool exists, so this is not UnknownTool…
907        assert!(invoker.has("wipe"));
908        let response = invoker.call("wipe", "{}").await.unwrap();
909        // …it's a payload the model can read and stop retrying on.
910        assert!(response.contains("TOOL_NOT_ALLOWED"), "{response}");
911        assert!(response.contains("Do not call it again"), "{response}");
912    }
913}