Skip to main content

eclipse_core/
tools_defer.rs

1//! `tool_search`, `tool_describe`, `tool_call` — reaching a tool the model was not given.
2//!
3//! Every tool in the request costs its description in every turn's input, whether or not the
4//! model calls it. Ten tools is nothing; an MCP server that registers forty is four thousand
5//! tokens of promise on every turn, and the model's attention on the one it wants is diluted by
6//! thirty-nine it does not. Deferral is the answer: a deferred tool stays registered, stays
7//! callable, and simply is not described — until the model asks for it.
8//!
9//! Three verbs, in the order a model uses them:
10//!
11//! - [`ToolSearch`] — *what is there?* Keyword search over the withheld tools' names and
12//!   descriptions. Never touches a tool.
13//! - [`ToolDescribe`] — *what does it take?* The full argument schemas, so the call can be
14//!   formed correctly.
15//! - [`ToolCall`] — *do it.* Dispatches through [`ToolRegistry::dispatch_scoped`], the same
16//!   funnel a direct call goes through: policy, `[tools] disabled`, plugin hooks, the approval
17//!   prompt, and the output cap. A router that skipped any of that would be a way around the
18//!   approvals it was meant to route to.
19//!
20//! `tool_call` defaults to `allow` for exactly that reason: it has no side effect of its own,
21//! and the thing being approved is the tool on the other side of it. It refuses to call itself,
22//! which is the one target that would nest without bound.
23
24use crate::tools::{str_arg, CallScope, Tool, ToolError};
25use async_trait::async_trait;
26use serde_json::{json, Value};
27
28pub(crate) const SEARCH: &str = "tool_search";
29pub(crate) const DESCRIBE: &str = "tool_describe";
30pub(crate) const CALL: &str = "tool_call";
31
32/// How many matches one search returns by default, and at most.
33const DEFAULT_LIMIT: usize = 8;
34const MAX_LIMIT: usize = 20;
35
36/// How long a search-result line may get before it is cut. A listing exists to be scanned; a
37/// description that runs to three lines defeats that however well it reads on its own.
38const HEADLINE_MAX: usize = 100;
39
40/// First sentence of a description, single-spaced, cut at `HEADLINE_MAX`.
41fn headline(description: &str) -> String {
42    let line = description.split_whitespace().collect::<Vec<_>>().join(" ");
43    let first = match line.find(". ") {
44        Some(at) => &line[..=at],
45        None => &line[..],
46    };
47    if first.chars().count() <= HEADLINE_MAX {
48        return first.trim_end_matches('.').to_string();
49    }
50    let cut: String = first.chars().take(HEADLINE_MAX).collect();
51    format!("{}…", cut.trim_end())
52}
53
54/// Tools matching `query`, best first.
55///
56/// Four tiers, because a model asks in its own words rather than the tool's: the name contains
57/// the whole query; the name contains every word; the description contains every word; and — the
58/// tier that earns its keep — some of the words, ranked by how many. "edit file" does not occur in
59/// `patch`'s description, but "file" does, and returning `patch` with the ranking stated is far
60/// more use than returning nothing because one word missed. Nothing at all matches only when no
61/// word appears anywhere, and then the caller is told what there is.
62///
63/// Ties break on name order, which is stable and therefore reviewable.
64fn ranked<'a, I>(candidates: I, query: &str) -> Vec<&'a crate::tools::ToolDescriptor>
65where
66    I: IntoIterator<Item = &'a crate::tools::ToolDescriptor>,
67{
68    let query = query.trim().to_lowercase();
69    let words: Vec<&str> = query.split_whitespace().collect();
70    let mut scored: Vec<(u8, usize, &crate::tools::ToolDescriptor)> = Vec::new();
71    for d in candidates {
72        let name = d.name.to_lowercase();
73        let text = format!("{} {}", name, d.description.to_lowercase());
74        if words.is_empty() {
75            scored.push((3, 0, d));
76            continue;
77        }
78        let in_name = words.iter().filter(|w| name.contains(**w)).count();
79        let in_text = words.iter().filter(|w| text.contains(**w)).count();
80        let tier = if name.contains(&query) {
81            0
82        } else if in_name == words.len() {
83            1
84        } else if in_text == words.len() {
85            2
86        } else if in_text > 0 || in_name > 0 {
87            3
88        } else {
89            continue;
90        };
91        scored.push((tier, in_text.max(in_name), d));
92    }
93    // Most words matched first within a tier; the name is the tie-break so the order is fixed.
94    scored.sort_by(|a, b| {
95        a.0.cmp(&b.0)
96            .then_with(|| b.1.cmp(&a.1))
97            .then_with(|| a.2.name.cmp(&b.2.name))
98    });
99    scored.into_iter().map(|(_, _, d)| d).collect()
100}
101
102pub struct ToolSearch;
103
104#[async_trait]
105impl Tool for ToolSearch {
106    fn name(&self) -> &str {
107        SEARCH
108    }
109
110    fn description(&self) -> &str {
111        "Find tools this session has but does not describe: keyword search over their names and \
112         descriptions. Use it when the tool you want is not in your list — then `tool describe` \
113         it and `tool call` it. A tool you can already see needs neither."
114    }
115
116    fn parameters(&self) -> Value {
117        json!({"type":"object","properties":{
118            "query":{"type":"string","description":"Words to look for in a tool's name or description. Empty lists everything that is deferred."},
119            "limit":{"type":"integer","description":format!("How many to return at most. Default {DEFAULT_LIMIT}, maximum {MAX_LIMIT}.")}
120        },"required":[]})
121    }
122
123    fn describe_call(&self, args: &Value) -> String {
124        format!(
125            "tool_search {:?}",
126            args["query"].as_str().unwrap_or("(everything)")
127        )
128    }
129
130    async fn call(&self, args: Value) -> Result<String, ToolError> {
131        // A registry is not in scope for a plain `call`, so this is the scoped path's job.
132        let _ = args;
133        Err(ToolError::Failed(
134            "tool_search needs the registry; it is only reachable inside a run".into(),
135        ))
136    }
137
138    async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
139        let query = args["query"].as_str().unwrap_or("").to_string();
140        let limit = args["limit"]
141            .as_u64()
142            .map(|n| (n as usize).clamp(1, MAX_LIMIT))
143            .unwrap_or(DEFAULT_LIMIT);
144
145        let registry = scope.registry;
146        let described = registry.descriptors();
147        let (hidden, offered): (Vec<_>, Vec<_>) = described.iter().partition(|d| d.deferred);
148
149        if hidden.is_empty() {
150            return Ok(format!(
151                "Nothing is deferred: all {} tool(s) are already described in your list: {}. \
152                 Call one directly.",
153                offered.len(),
154                offered
155                    .iter()
156                    .map(|d| d.name.as_str())
157                    .collect::<Vec<_>>()
158                    .join(", ")
159            ));
160        }
161
162        let found = ranked(hidden.iter().copied(), &query);
163        if found.is_empty() {
164            return Ok(format!(
165                "No deferred tool matches {query:?}. There {} {}: {}. Try a word from a name.",
166                if hidden.len() == 1 { "is" } else { "are" },
167                hidden.len(),
168                hidden
169                    .iter()
170                    .map(|d| d.name.as_str())
171                    .collect::<Vec<_>>()
172                    .join(", ")
173            ));
174        }
175
176        let mut out = format!(
177            "{} of {} deferred tool(s){}:\n",
178            found.len().min(limit),
179            hidden.len(),
180            if query.trim().is_empty() {
181                String::new()
182            } else {
183                format!(" matching {:?}", query.trim())
184            }
185        );
186        for d in found.iter().take(limit) {
187            let mut notes = Vec::new();
188            if d.policy == crate::config::Policy::Ask {
189                notes.push("asks first");
190            }
191            if d.policy == crate::config::Policy::Deny {
192                notes.push("denied by policy — it will not run");
193            }
194            out.push_str(&format!(
195                "- {} — {}{}\n",
196                d.name,
197                headline(&d.description),
198                if notes.is_empty() {
199                    String::new()
200                } else {
201                    format!(" [{}]", notes.join("; "))
202                }
203            ));
204        }
205        if found.len() > limit {
206            out.push_str(&format!(
207                "… {} more. Narrow the query.\n",
208                found.len() - limit
209            ));
210        }
211        out.push_str(
212            "\nNext: `tool_describe` the one you want for its arguments, then `tool_call` it.",
213        );
214        Ok(out)
215    }
216}
217
218pub struct ToolDescribe;
219
220#[async_trait]
221impl Tool for ToolDescribe {
222    fn name(&self) -> &str {
223        DESCRIBE
224    }
225
226    fn description(&self) -> &str {
227        "The full argument schema of one or more tools, by name — including tools that are \
228         deferred or that you were not given. Use it before `tool_call`."
229    }
230
231    fn parameters(&self) -> Value {
232        json!({"type":"object","properties":{
233            "names":{"description":"A tool name, or a list of them.",
234                "oneOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]}
235        },"required":["names"]})
236    }
237
238    fn describe_call(&self, args: &Value) -> String {
239        let names: Vec<String> = match &args["names"] {
240            Value::String(s) => vec![s.clone()],
241            Value::Array(items) => items
242                .iter()
243                .filter_map(|v| v.as_str().map(str::to_string))
244                .collect(),
245            _ => Vec::new(),
246        };
247        format!("tool_describe {}", names.join(", "))
248    }
249
250    async fn call(&self, _args: Value) -> Result<String, ToolError> {
251        Err(ToolError::Failed(
252            "tool_describe needs the registry; it is only reachable inside a run".into(),
253        ))
254    }
255
256    async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
257        // Models send one name or a list depending on the day; both are the same request.
258        let names: Vec<String> = match &args["names"] {
259            Value::String(s) => vec![s.clone()],
260            Value::Array(items) => items
261                .iter()
262                .filter_map(|v| v.as_str().map(str::to_string))
263                .collect(),
264            _ => {
265                return Err(ToolError::InvalidArgs(
266                    "`names` must be a tool name or a list of them".into(),
267                ))
268            }
269        };
270        if names.is_empty() {
271            return Err(ToolError::InvalidArgs("`names` is empty".into()));
272        }
273
274        let registry = scope.registry;
275        let all = registry.descriptors();
276        let mut out = String::new();
277        for name in &names {
278            match all.iter().find(|d| &d.name == name) {
279                None => {
280                    let near = ranked(all.iter(), name)
281                        .into_iter()
282                        .take(3)
283                        .map(|d| d.name.as_str())
284                        .collect::<Vec<_>>()
285                        .join(", ");
286                    out.push_str(&format!(
287                        "{}: no such tool.{}\n",
288                        name,
289                        if near.is_empty() {
290                            String::new()
291                        } else {
292                            format!(" Closest registered: {near}.")
293                        }
294                    ));
295                }
296                Some(d) if d.disabled => {
297                    out.push_str(&format!(
298                        "{}: named in `[tools] disabled`. It will not run, so there is nothing to \
299                         describe.\n",
300                        name
301                    ));
302                }
303                Some(d) => {
304                    out.push_str(&format!(
305                        "{} — {}\n{}\n\n",
306                        d.name,
307                        d.description,
308                        serde_json::to_string_pretty(&d.parameters)
309                            .unwrap_or_else(|_| d.parameters.to_string())
310                    ));
311                }
312            }
313        }
314        Ok(out.trim_end().to_string())
315    }
316}
317
318pub struct ToolCall;
319
320#[async_trait]
321impl Tool for ToolCall {
322    fn name(&self) -> &str {
323        CALL
324    }
325
326    fn description(&self) -> &str {
327        "Call a tool by name, including one that is not in your list. Pass `arguments` as the \
328         object that tool's schema describes. The call goes through the same policy, approval \
329         and hook checks as a direct one, so a tool that asks first still asks first."
330    }
331
332    fn parameters(&self) -> Value {
333        json!({"type":"object","properties":{
334            "name":{"type":"string","description":"The tool to call."},
335            "arguments":{"description":"That tool's arguments, as an object (a JSON string is accepted too)."}
336        },"required":["name"]})
337    }
338
339    fn describe_call(&self, args: &Value) -> String {
340        format!(
341            "tool_call {} {}",
342            args["name"].as_str().unwrap_or("?"),
343            args["arguments"]
344        )
345    }
346
347    async fn call(&self, _args: Value) -> Result<String, ToolError> {
348        Err(ToolError::Failed(
349            "tool_call needs the registry; it is only reachable inside a run".into(),
350        ))
351    }
352
353    async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
354        let name = str_arg(&args, "name")?.to_string();
355        if name == CALL {
356            return Err(ToolError::Failed(
357                "`tool_call` cannot call itself. Name the tool you actually want.".into(),
358            ));
359        }
360        // A model that has just read a schema sometimes sends the arguments as a JSON string.
361        // Accepting it is cheaper than a round trip that only re-types them.
362        let raw = match &args["arguments"] {
363            Value::Null => String::new(),
364            Value::String(s) => s.clone(),
365            other => other.to_string(),
366        };
367        if !raw.trim().is_empty() {
368            serde_json::from_str::<Value>(&raw).map_err(|e| {
369                ToolError::InvalidArgs(format!("`arguments` is not a JSON object: {e}"))
370            })?;
371        }
372
373        // The funnel. Everything below this line is a direct call: same policy, same disabled
374        // list, same hooks, same approval prompt (on the inner tool's own describe_call), same
375        // output cap, same malformed accounting. The outer call's id travels with it (`#369`): the
376        // answer that unblocks this call is recorded against `tool_call`, so the inner prompt has to
377        // name the same row or a resumed run can never match the decision it was given.
378        let outcome = scope
379            .registry
380            .dispatch_scoped(&name, &raw, scope.approver, scope.call_id, scope.run)
381            .await;
382        if outcome.malformed {
383            return Err(ToolError::InvalidArgs(outcome.output));
384        }
385        // `#369`: the gate has not answered. Collapsing this into a failure told the model a call
386        // was waiting while the turn carried on and no row reached `eclipse approve`; the deferral
387        // goes up instead, and the runtime records it and stops.
388        if outcome.deferred {
389            return Err(ToolError::Deferred(outcome.output));
390        }
391        if outcome.is_error {
392            return Err(ToolError::Failed(outcome.output));
393        }
394        Ok(outcome.output)
395    }
396}
397
398/// A `[tools] deferred` pattern: exact, or a prefix when it ends in `*`.
399///
400/// `"*"` is the prefix `""`, which is every name — so it needs no special case, and neither does
401/// `"mcp_github_*"`.
402pub(crate) fn matches_pattern(pattern: &str, name: &str) -> bool {
403    match pattern.strip_suffix('*') {
404        Some(prefix) => name.starts_with(prefix),
405        None => pattern == name,
406    }
407}
408
409#[cfg(test)]
410mod tests {
411    use super::*;
412    use crate::config::Policy;
413    use crate::tools::{AllowAll, DenyAll, ToolRegistry, ToolSpec};
414    use std::sync::Arc;
415
416    /// A tool that says back what it was given, so a routed call is visibly the same call.
417    struct Echo {
418        name: &'static str,
419        text: &'static str,
420    }
421
422    #[async_trait]
423    impl Tool for Echo {
424        fn name(&self) -> &str {
425            self.name
426        }
427        fn description(&self) -> &str {
428            self.text
429        }
430        fn parameters(&self) -> Value {
431            json!({"type":"object","properties":{"msg":{"type":"string"}},"required":["msg"]})
432        }
433        async fn call(&self, args: Value) -> Result<String, ToolError> {
434            Ok(format!("echo: {}", args["msg"].as_str().unwrap_or("")))
435        }
436    }
437
438    fn registry(policy: Policy, deferred: &[&str]) -> ToolRegistry {
439        let mut r = ToolRegistry::new(4096);
440        r.register(
441            Arc::new(Echo {
442                name: "notes_add",
443                text: "Append a line to the notes file. One line only.",
444            }),
445            policy,
446        );
447        r.register(
448            Arc::new(Echo {
449                name: "web_thing",
450                text: "Fetch a page over HTTP and return its text. Follows redirects.",
451            }),
452            Policy::Allow,
453        );
454        let patterns: Vec<String> = deferred.iter().map(|s| s.to_string()).collect();
455        let unknown = r.defer(&patterns);
456        assert!(unknown.is_empty(), "{unknown:?}");
457        r
458    }
459
460    async fn run(
461        r: &ToolRegistry,
462        name: &str,
463        args: Value,
464        approver: &dyn crate::tools::Approver,
465    ) -> crate::tools::ToolOutcome {
466        r.dispatch(name, &args.to_string(), approver).await
467    }
468
469    /// `#369`: with `--approvals-out`, a gated call made *through* `tool_call` came back as a plain
470    /// failure — `Deferred` was collapsed into `Failed` — so no row reached `eclipse approve`, the
471    /// turn carried on, and the model was told something was waiting when nothing was. A nested
472    /// call now pauses the turn exactly like a top-level one, and the row it leaves names the outer
473    /// call, which is the id `decision_for` looks up on resume.
474    #[tokio::test]
475    async fn a_deferral_inside_tool_call_comes_back_as_waiting() {
476        struct Asked(std::sync::Mutex<Vec<String>>);
477        #[async_trait]
478        impl crate::tools::Approver for Asked {
479            async fn decide(&self, call: &crate::approvals::Pending) -> crate::approvals::Decision {
480                self.0.lock().unwrap().push(call.call_id.clone());
481                crate::approvals::Decision::Defer
482            }
483        }
484
485        let r = registry(Policy::Ask, &["notes_add"]);
486        let asked = Asked(std::sync::Mutex::new(Vec::new()));
487        let outcome = r
488            .dispatch_call(
489                "tool_call",
490                &json!({"name": "notes_add", "arguments": {"msg": "hi"}}).to_string(),
491                &asked,
492                Some("call-7"),
493            )
494            .await;
495        assert!(
496            !outcome.malformed,
497            "a deferral is not a broken call: {}",
498            outcome.output
499        );
500        assert!(
501            outcome.deferred,
502            "the deferral survives the funnel: {}",
503            outcome.output
504        );
505        assert!(
506            outcome.output.contains("not approved yet"),
507            "and says what it is: {}",
508            outcome.output
509        );
510        assert!(
511            !outcome.output.contains("echo:"),
512            "the tool did not run: {}",
513            outcome.output
514        );
515        assert_eq!(
516            asked.0.lock().unwrap().as_slice(),
517            ["call-7".to_string()],
518            "the prompt names the call the answer will be recorded against"
519        );
520    }
521
522    fn names(specs: &[ToolSpec]) -> Vec<String> {
523        specs.iter().map(|s| s.function.name.clone()).collect()
524    }
525
526    #[test]
527    fn a_pattern_is_exact_unless_it_ends_in_a_star() {
528        assert!(matches_pattern("notes_add", "notes_add"));
529        assert!(!matches_pattern("notes_add", "notes"));
530        assert!(matches_pattern("notes_*", "notes_add"));
531        assert!(!matches_pattern("notes_*", "web_thing"));
532        // `*` is the prefix `""`: every name, with no special case for the operator.
533        assert!(matches_pattern("*", "anything"));
534    }
535
536    #[test]
537    fn a_deferred_tool_is_not_offered_but_is_still_registered() {
538        let r = registry(Policy::Allow, &["notes_add"]);
539        assert!(!names(&r.specs()).contains(&"notes_add".to_string()));
540        assert!(r.names().contains(&"notes_add".to_string()));
541        let d = r
542            .descriptors()
543            .into_iter()
544            .find(|d| d.name == "notes_add")
545            .unwrap();
546        assert!(!d.advertised);
547        assert!(d.deferred);
548        assert!(!d.disabled);
549        assert_eq!(d.policy, Policy::Allow);
550    }
551
552    #[test]
553    fn deferring_something_registers_the_three_tools_that_reach_it() {
554        let r = registry(Policy::Allow, &["notes_add"]);
555        let offered = names(&r.specs());
556        for name in [SEARCH, DESCRIBE, CALL] {
557            assert!(
558                offered.contains(&name.to_string()),
559                "{name} not in {offered:?}"
560            );
561        }
562        // And a deferred tool cannot be reached by deferring the tools that reach it.
563        let d = r
564            .descriptors()
565            .into_iter()
566            .find(|d| d.name == CALL)
567            .unwrap();
568        assert!(!d.deferred);
569    }
570
571    #[test]
572    fn deferring_nothing_registers_no_extra_tools_and_a_typo_is_reported() {
573        let mut r = ToolRegistry::new(4096);
574        r.register(
575            Arc::new(Echo {
576                name: "a",
577                text: "a",
578            }),
579            Policy::Allow,
580        );
581        assert!(r.defer(&[]).is_empty());
582        assert_eq!(
583            r.names(),
584            ["a"],
585            "three dead tools would cost tokens for nothing"
586        );
587        let unknown = r.defer(&["nope".to_string()]);
588        assert_eq!(unknown, ["nope"]);
589        assert_eq!(
590            r.names(),
591            ["a"],
592            "a pattern that matched nothing defers nothing"
593        );
594    }
595
596    #[tokio::test]
597    async fn search_finds_a_deferred_tool_by_a_word_from_its_name_or_description() {
598        let r = registry(Policy::Allow, &["notes_add", "web_thing"]);
599        let by_name = run(&r, SEARCH, json!({"query": "notes"}), &AllowAll).await;
600        assert!(by_name.output.contains("notes_add"), "{}", by_name.output);
601        assert!(!by_name.output.contains("web_thing"), "{}", by_name.output);
602        let by_text = run(&r, SEARCH, json!({"query": "HTTP"}), &AllowAll).await;
603        assert!(by_text.output.contains("web_thing"), "{}", by_text.output);
604        // One line per tool: the first sentence, not the whole description.
605        assert!(
606            by_text.output.contains("Fetch a page over HTTP"),
607            "{}",
608            by_text.output
609        );
610        assert!(
611            !by_text.output.contains("Follows redirects"),
612            "{}",
613            by_text.output
614        );
615    }
616
617    #[tokio::test]
618    async fn a_query_in_the_model_s_own_words_still_finds_the_tool_by_the_words_that_do_match() {
619        // The case that made this tier necessary: asked for "edit file", a description search
620        // for every word returns nothing, and a model that gets nothing concludes there is
621        // nothing. One word hits "text file" in `patch`, so `patch` comes back first.
622        let r = registry(Policy::Allow, &["notes_add", "web_thing"]);
623        let text = run(&r, SEARCH, json!({"query": "edit file"}), &AllowAll)
624            .await
625            .output;
626        assert!(text.contains("notes_add"), "{text}");
627        // Ranked, not filtered to the exact words: the count says one of two, and the other is
628        // reachable with a narrower word rather than being invisible.
629        assert!(text.contains("1 of 2 deferred"), "{text}");
630        assert!(!text.contains("No deferred tool matches"), "{text}");
631    }
632
633    #[tokio::test]
634    async fn an_empty_search_lists_everything_deferred_and_says_what_to_do_next() {
635        let r = registry(Policy::Allow, &["*"]);
636        let out = run(&r, SEARCH, json!({}), &AllowAll).await.output;
637        assert!(
638            out.contains("notes_add") && out.contains("web_thing"),
639            "{out}"
640        );
641        assert!(out.contains("tool_describe"), "{out}");
642        assert!(out.contains("2 of 2 deferred"), "{out}");
643    }
644
645    #[tokio::test]
646    async fn a_search_that_matches_nothing_names_what_there_is_instead_of_returning_empty() {
647        let r = registry(Policy::Allow, &["notes_add", "web_thing"]);
648        let out = run(&r, SEARCH, json!({"query": "kalman"}), &AllowAll)
649            .await
650            .output;
651        assert!(out.contains("No deferred tool matches"), "{out}");
652        assert!(
653            out.contains("notes_add") && out.contains("web_thing"),
654            "{out}"
655        );
656    }
657
658    #[tokio::test]
659    async fn a_search_names_the_tools_already_in_the_list_rather_than_looking_more() {
660        let mut r = ToolRegistry::new(4096);
661        r.register(
662            Arc::new(Echo {
663                name: "hidden",
664                text: "withheld",
665            }),
666            Policy::Allow,
667        );
668        r.register(
669            Arc::new(Echo {
670                name: "shown",
671                text: "offered",
672            }),
673            Policy::Allow,
674        );
675        r.defer(&["hidden".to_string()]);
676        let out = run(&r, SEARCH, json!({"query": "zzz"}), &AllowAll)
677            .await
678            .output;
679        assert!(out.contains("No deferred tool matches"), "{out}");
680        assert!(out.contains("hidden"), "{out}");
681    }
682
683    #[test]
684    fn with_nothing_deferred_the_search_tool_is_not_registered_at_all() {
685        // The negative case that keeps three useless tools out of the request: `defer` is what
686        // registers them, so a registry nobody defers on has none.
687        let mut r = ToolRegistry::new(4096);
688        r.register(
689            Arc::new(Echo {
690                name: "solo",
691                text: "the only tool",
692            }),
693            Policy::Allow,
694        );
695        assert_eq!(r.names(), ["solo"]);
696        assert!(r.descriptors()[0].advertised);
697    }
698
699    #[tokio::test]
700    async fn describe_gives_the_arguments_schema_for_a_name_or_a_list() {
701        let r = registry(Policy::Allow, &["notes_add", "web_thing"]);
702        let one = run(&r, DESCRIBE, json!({"names": "notes_add"}), &AllowAll).await;
703        assert!(one.output.contains("\"msg\""), "{}", one.output);
704        assert!(one.output.contains("Append a line"), "{}", one.output);
705        let two = run(
706            &r,
707            DESCRIBE,
708            json!({"names": ["notes_add", "web_thing"]}),
709            &AllowAll,
710        )
711        .await;
712        assert!(
713            two.output.contains("notes_add") && two.output.contains("web_thing"),
714            "{}",
715            two.output
716        );
717    }
718
719    #[tokio::test]
720    async fn describe_a_name_that_does_not_exist_suggests_the_closest_instead_of_nothing() {
721        let r = registry(Policy::Allow, &["notes_add"]);
722        let out = run(&r, DESCRIBE, json!({"names": "notes"}), &AllowAll)
723            .await
724            .output;
725        assert!(out.contains("no such tool"), "{out}");
726        assert!(out.contains("notes_add"), "{out}");
727    }
728
729    #[tokio::test]
730    async fn call_runs_a_deferred_tool_through_the_same_funnel() {
731        let r = registry(Policy::Allow, &["notes_add"]);
732        let out = run(
733            &r,
734            CALL,
735            json!({"name": "notes_add", "arguments": {"msg": "hello"}}),
736            &AllowAll,
737        )
738        .await;
739        assert_eq!(out.output, "echo: hello");
740        assert!(!out.is_error);
741    }
742
743    #[tokio::test]
744    async fn arguments_may_arrive_as_a_json_string() {
745        let r = registry(Policy::Allow, &["notes_add"]);
746        let out = run(
747            &r,
748            CALL,
749            json!({"name": "notes_add", "arguments": "{\"msg\": \"as text\"}"}),
750            &AllowAll,
751        )
752        .await;
753        assert_eq!(out.output, "echo: as text", "{}", out.output);
754    }
755
756    #[tokio::test]
757    async fn a_tool_that_asks_still_asks_when_it_is_reached_through_tool_call() {
758        let r = registry(Policy::Ask, &["notes_add"]);
759        let denied = run(
760            &r,
761            CALL,
762            json!({"name": "notes_add", "arguments": {"msg": "x"}}),
763            &DenyAll,
764        )
765        .await;
766        assert!(
767            denied.is_error,
768            "a router must not be a way around the prompt"
769        );
770        assert!(denied.output.contains("declined"), "{}", denied.output);
771        let allowed = run(
772            &r,
773            CALL,
774            json!({"name": "notes_add", "arguments": {"msg": "x"}}),
775            &AllowAll,
776        )
777        .await;
778        assert_eq!(allowed.output, "echo: x");
779    }
780
781    #[tokio::test]
782    async fn tool_call_refuses_to_call_itself() {
783        let r = registry(Policy::Allow, &["notes_add"]);
784        let out = run(&r, CALL, json!({"name": CALL}), &AllowAll).await;
785        assert!(out.is_error);
786        assert!(out.output.contains("cannot call itself"), "{}", out.output);
787    }
788
789    #[tokio::test]
790    async fn tool_call_to_a_disabled_tool_is_refused_by_the_same_rule_as_a_direct_call() {
791        let mut r = registry(Policy::Allow, &["notes_add"]);
792        // Disabled after deferral, which is the order the runtime applies them in reverse:
793        // `disabled` first, then `deferred`. Either way the funnel is the same.
794        assert!(r.disable(&["notes_add".to_string()]).is_empty());
795        let out = run(
796            &r,
797            CALL,
798            json!({"name": "notes_add", "arguments": {"msg": "x"}}),
799            &AllowAll,
800        )
801        .await;
802        assert!(out.is_error);
803        assert!(
804            out.output.contains("disabled in the config"),
805            "{}",
806            out.output
807        );
808    }
809
810    #[tokio::test]
811    async fn tool_call_to_an_unknown_tool_says_unknown_rather_than_failing_silently() {
812        let r = registry(Policy::Allow, &["notes_add"]);
813        let out = run(&r, CALL, json!({"name": "nothing_here"}), &AllowAll).await;
814        assert!(out.is_error);
815        assert!(out.output.contains("unknown tool"), "{}", out.output);
816    }
817}