Skip to main content

agent_base/tool/
activate_tool.rs

1//! `activate_tool`: the model opens a tool that was named in the roster but not
2//! mounted.
3//!
4//! One call to open, and it stays open for the session (see [`ToolActivation`]).
5//! The tool hands back the full wire definition — description and schema — so
6//! the next call is made against the real shape and not a guess from the name.
7//!
8//! **Why it holds its own definitions instead of the registry.** Looking the
9//! tool up live would mean taking the registry lock from inside a call, which
10//! is the pattern that deadlocked before (`ToolEngine::tools_handle`'s docs).
11//! The candidate list is fixed at build time and is the same list the roster is
12//! rendered from, so the two cannot drift.
13
14use std::collections::HashMap;
15use std::sync::Arc;
16
17use async_trait::async_trait;
18use serde_json::{Value, json};
19
20use crate::types::{AgentError, AgentResult};
21
22use super::{Content, Tool, ToolActivation, ToolContext, ToolExposure};
23
24/// Opens one of the tools the roster names but does not mount.
25pub struct ActivateTool {
26    activation: ToolActivation,
27    /// Tool name -> the definition the model will get once it is open.
28    candidates: HashMap<String, (ToolExposure, Value)>,
29    /// The registry's shared deferred-definition catalog ([`ToolRegistry::deferred_defs`](super::ToolRegistry::deferred_defs)).
30    ///
31    /// Tools can register long after this opener is built (a factory inside
32    /// `build`, a plugin, a product's late mount). The catalog fills itself as
33    /// they land, so a roster name stays openable no matter when its tool
34    /// arrived. Set once after build; `None` in tests with no registry.
35    late: std::sync::OnceLock<Arc<std::sync::RwLock<HashMap<String, Value>>>>,
36}
37
38impl ActivateTool {
39    /// `candidates` is every tool this can open — the same list the roster is
40    /// rendered from. Keeping one list is what stops the two from drifting.
41    pub fn new(
42        activation: ToolActivation,
43        candidates: Vec<(String, ToolExposure, Value)>,
44    ) -> Arc<Self> {
45        Arc::new(Self {
46            activation,
47            candidates: candidates
48                .into_iter()
49                .map(|(name, exposure, def)| (name, (exposure, def)))
50                .collect(),
51            late: std::sync::OnceLock::new(),
52        })
53    }
54
55    /// Hand this opener the registry's shared deferred-definition catalog so
56    /// tools registered after [`Self::new`] become openable too. Idempotent;
57    /// the first call wins.
58    pub fn set_deferred_defs(&self, defs: Arc<std::sync::RwLock<HashMap<String, Value>>>) {
59        let _ = self.late.set(defs);
60    }
61
62    /// Candidates first (the build-time truth), then the late catalog (always
63    /// `Deferred`: a late tool only exists because its name was deferred).
64    fn lookup(&self, name: &str) -> Option<(ToolExposure, Value)> {
65        if let Some(hit) = self.candidates.get(name) {
66            return Some(hit.clone());
67        }
68        let defs = self.late.get()?;
69        let def = defs
70            .read()
71            .expect("deferred-defs lock poisoned")
72            .get(name)
73            .cloned()?;
74        Some((ToolExposure::Deferred, def))
75    }
76
77    /// Names in sorted order, for the error message a wrong guess deserves —
78    /// the union of the build-time candidates and whatever has registered late.
79    fn candidate_names(&self) -> Vec<String> {
80        let mut names: Vec<String> = self.candidates.keys().cloned().collect();
81        if let Some(defs) = self.late.get() {
82            let defs = defs.read().expect("deferred-defs lock poisoned");
83            for name in defs.keys() {
84                if !names.contains(name) {
85                    names.push(name.clone());
86                }
87            }
88        }
89        names.sort_unstable();
90        names
91    }
92}
93
94#[async_trait]
95impl Tool for ActivateTool {
96    fn name(&self) -> &'static str {
97        "activate_tool"
98    }
99
100    fn description(&self) -> &'static str {
101        "Mount a tool whose schema is not loaded yet.\n\n\
102         Some tools are named in the system message but their schemas are NOT loaded — until\n\
103         they are, only the name is known, and calling one fails: there is no parameter\n\
104         schema to call it with. This tool loads it.\n\
105         Pass the tool's name exactly as the roster spells it. The result is that tool's full\n\
106         description and argument schema, and from your next turn on it is callable exactly\n\
107         like any tool already in your list — and it stays mounted for the rest of the\n\
108         session, so open it once and use it as often as you need.\n\
109         A name that is not mountable comes back with the ones that are. A name that is\n\
110         already mounted comes back saying so. Do not open a capability on the chance it\n\
111         comes in handy: every mounted tool is sent on every later request."
112    }
113
114    fn schema(&self) -> Value {
115        json!({
116            "type": "object",
117            "properties": {
118                "name": {
119                    "type": "string",
120                    "description": "The tool name exactly as the roster spells it."
121                }
122            },
123            "required": ["name"],
124            "additionalProperties": false,
125        })
126    }
127
128    /// Exposure is `Direct`: this one must always be on the wire, or nothing can
129    /// ever be opened.
130    fn exposure(&self) -> ToolExposure {
131        ToolExposure::Direct
132    }
133
134    async fn call(&self, args: &Value, _ctx: &ToolContext) -> AgentResult<Vec<Content>> {
135        let name = args
136            .get("name")
137            .and_then(Value::as_str)
138            .map(str::trim)
139            .filter(|s| !s.is_empty())
140            .ok_or_else(|| AgentError::ToolArgsInvalid {
141                name: self.name().to_string(),
142                raw: "missing field `name` — pass the tool name exactly as the roster spells it"
143                    .to_string(),
144            })?;
145
146        let Some((exposure, definition)) = self.lookup(name) else {
147            return Ok(vec![Content::text(format!(
148                "No tool named `{name}` is mountable. Mountable names: {}.",
149                self.candidate_names().join(", ")
150            ))]);
151        };
152
153        match exposure {
154            ToolExposure::Hidden => Ok(vec![Content::text(format!(
155                "`{name}` is internal and is not mountable. It is not in the roster."
156            ))]),
157            ToolExposure::Direct => Ok(vec![Content::text(format!(
158                "`{name}` is already mounted — call it directly."
159            ))]),
160            ToolExposure::Deferred => {
161                let first_open = self.activation.activate(name);
162                let status = if first_open {
163                    "mounted"
164                } else {
165                    "already mounted"
166                };
167                Ok(vec![Content::text(format!(
168                    "`{name}` {status}. Call it from the next turn on, with these arguments:\n{}",
169                    serde_json::to_string_pretty(&definition).unwrap_or_default()
170                ))])
171            }
172        }
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use std::sync::atomic::AtomicBool;
179
180    use super::*;
181    use crate::engine::EventBus;
182    use crate::tool::ExecClock;
183    use crate::types::SessionId;
184    use serde_json::json;
185
186    fn test_context() -> ToolContext {
187        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
188        ToolContext {
189            session_id: SessionId::new(0),
190            user_event_tx: tx,
191            llm_client: None,
192            session_store: None,
193            language: crate::types::Language::En,
194            cancel_token: tokio_util::sync::CancellationToken::new(),
195            max_output_chars: None,
196            exec_clock: ExecClock::default(),
197            waiting_for_human: Arc::new(AtomicBool::new(false)),
198            event_bus: EventBus::new(1),
199        }
200    }
201
202    fn registry_free_tool() -> (ActivateTool, ToolActivation) {
203        let activation = ToolActivation::new();
204        let tool = ActivateTool::new(
205            activation.clone(),
206            vec![
207                (
208                    "browser_navigate".to_string(),
209                    ToolExposure::Deferred,
210                    json!({
211                        "name": "browser_navigate",
212                        "description": "Open a URL in the browser.",
213                        "parameters": {"type": "object", "properties": {"url": {"type": "string"}}},
214                    }),
215                ),
216                (
217                    "always_here".to_string(),
218                    ToolExposure::Direct,
219                    json!({"name": "always_here"}),
220                ),
221                (
222                    "internal".to_string(),
223                    ToolExposure::Hidden,
224                    json!({"name": "internal"}),
225                ),
226            ],
227        );
228        // `ActivateTool::new` returns Arc; unwrap for the tests to own the value.
229        let tool = Arc::try_unwrap(tool).ok().expect("single owner in tests");
230        (tool, activation)
231    }
232
233    async fn call(tool: &ActivateTool, args: Value) -> String {
234        let ctx = test_context();
235        let out = tool.call(&args, &ctx).await.expect("call succeeds");
236        out.iter()
237            .map(|c| match c {
238                Content::Text { text } => text.clone(),
239                _ => String::new(),
240            })
241            .collect()
242    }
243
244    /// Value: protects=the one thing the tool exists for — an opened tool must
245    /// be callable afterwards and its shape must come from us, not from the
246    /// model's reading of its name; fails_when=opening changes nothing, or
247    /// returns something other than the real definition. why_new=the tool is
248    /// new. seam=roster -> request; no_claim=that the model will read it.
249    #[tokio::test]
250    async fn opening_a_tool_mounts_it_and_hands_back_its_shape() {
251        let (tool, activation) = registry_free_tool();
252        let out = call(&tool, json!({"name": "browser_navigate"})).await;
253        assert!(
254            activation.is_active("browser_navigate"),
255            "opening must stick for the session"
256        );
257        assert!(out.contains("mounted"), "say what happened: {out}");
258        assert!(
259            out.contains("\"url\""),
260            "and hand back the real arguments, not just the name: {out}"
261        );
262    }
263
264    /// Value: protects=the model against a confidently wrong guess — a name
265    /// that is not mountable must come back with the list, because a silent
266    /// success leaves it calling a tool that never arrived; fails_when=an
267    /// unknown name is accepted. why_new=the tool is new. seam=roster; no_claim=
268    /// that the list is the only way to discover names.
269    #[tokio::test]
270    async fn an_unknown_name_is_refused_with_the_real_ones() {
271        let (tool, _activation) = registry_free_tool();
272        let out = call(&tool, json!({"name": "browser_nav"})).await;
273        assert!(out.contains("No tool named `browser_nav`"), "{out}");
274        assert!(
275            out.contains("browser_navigate"),
276            "the answer must name the tool it meant: {out}"
277        );
278    }
279
280    /// Value: protects=the reason `Hidden` exists — internal plumbing must stay
281    /// internal, and a roster-shaped hole must not become a way in;
282    /// fails_when=an internal tool can be mounted. why_new=the tool is new.
283    /// seam=exposure policy; no_claim=that no other path reaches a hidden tool.
284    #[tokio::test]
285    async fn an_internal_tool_cannot_be_mounted() {
286        let (tool, activation) = registry_free_tool();
287        let out = call(&tool, json!({"name": "internal"})).await;
288        assert!(out.contains("not mountable"), "{out}");
289        assert!(!activation.is_active("internal"), "and nothing was opened");
290    }
291
292    /// Value: protects=a turn the model could have spent working — a mounted
293    /// tool is already on the wire, so asking again must not read as success
294    /// and cost another round; fails_when=re-opening reports a fresh mount.
295    /// why_new=the tool is new. seam=session state; no_claim=about a session
296    /// where the tool was unmounted by other means.
297    #[tokio::test]
298    async fn opening_twice_is_reported_as_already_mounted() {
299        let (tool, _activation) = registry_free_tool();
300        call(&tool, json!({"name": "browser_navigate"})).await;
301        let out = call(&tool, json!({"name": "browser_navigate"})).await;
302        assert!(out.contains("already mounted"), "{out}");
303    }
304
305    /// Value: protects=the budget the roster exists to save — `Direct` tools
306    /// are already on every request, so "opening" one must not read as a win
307    /// and must not change the request; fails_when=a Direct tool is reported
308    /// mounted. why_new=the tool is new. seam=exposure policy.
309    #[tokio::test]
310    async fn an_already_mounted_tool_is_said_to_be() {
311        let (tool, activation) = registry_free_tool();
312        let out = call(&tool, json!({"name": "always_here"})).await;
313        assert!(out.contains("already mounted"), "{out}");
314        assert!(
315            !activation.is_active("always_here"),
316            "a Direct tool needs no activation entry"
317        );
318    }
319
320    /// Value: protects=the roster's promise for tools that register late (a
321    /// factory inside build, a plugin, a product's late mount) — the opener
322    /// must serve them from the registry's shared catalog instead of answering
323    /// "not mountable"; fails_when=a late-registered deferred tool cannot be
324    /// opened. why_new=session 20261121_f984398e: `close_agent` came back
325    /// "not mountable" because its tool registered after the candidates were
326    /// built. seam=registry catalog -> opener; no_claim=about which tools
327    /// should be late.
328    #[tokio::test]
329    async fn a_late_registered_deferred_tool_is_openable() {
330        let (tool, activation) = registry_free_tool();
331        let catalog: Arc<std::sync::RwLock<HashMap<String, Value>>> = Default::default();
332        catalog.write().unwrap().insert(
333            "close_agent".to_string(),
334            json!({"name": "close_agent", "description": "Close a sub-agent."}),
335        );
336        tool.set_deferred_defs(catalog);
337        let out = call(&tool, json!({"name": "close_agent"})).await;
338        assert!(
339            activation.is_active("close_agent"),
340            "opening must stick for the session: {out}"
341        );
342        assert!(out.contains("mounted"), "{out}");
343        assert!(
344            out.contains("Close a sub-agent"),
345            "hand back the real definition, not just the name: {out}"
346        );
347    }
348
349    /// Value: protects=the arg contract — a call with no name is a mistake the
350    /// model can correct if we say so, and an empty name is not a name;
351    /// fails_when=both are accepted and quietly do nothing.
352    /// why_new=the tool is new. seam=args.
353    #[tokio::test]
354    async fn a_missing_name_says_what_is_missing() {
355        let (tool, _activation) = registry_free_tool();
356        let err = tool.call(&json!({}), &test_context()).await;
357        let msg = format!("{:?}", err.expect_err("no name is an error"));
358        assert!(
359            msg.contains("`name`"),
360            "the error must name the field: {msg}"
361        );
362    }
363}