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}
30
31impl ActivateTool {
32    /// `candidates` is every tool this can open — the same list the roster is
33    /// rendered from. Keeping one list is what stops the two from drifting.
34    pub fn new(
35        activation: ToolActivation,
36        candidates: Vec<(String, ToolExposure, Value)>,
37    ) -> Arc<Self> {
38        Arc::new(Self {
39            activation,
40            candidates: candidates
41                .into_iter()
42                .map(|(name, exposure, def)| (name, (exposure, def)))
43                .collect(),
44        })
45    }
46
47    /// Names in sorted order, for the error message a wrong guess deserves.
48    fn candidate_names(&self) -> Vec<&str> {
49        let mut names: Vec<&str> = self.candidates.keys().map(|s| s.as_str()).collect();
50        names.sort_unstable();
51        names
52    }
53}
54
55#[async_trait]
56impl Tool for ActivateTool {
57    fn name(&self) -> &'static str {
58        "activate_tool"
59    }
60
61    fn description(&self) -> &'static str {
62        "Mount a tool whose schema is not loaded yet.\n\n\
63         Some tools are named in the system message but their schemas are NOT loaded — until\n\
64         they are, only the name is known, and calling one fails: there is no parameter\n\
65         schema to call it with. This tool loads it.\n\
66         Pass the tool's name exactly as the roster spells it. The result is that tool's full\n\
67         description and argument schema, and from your next turn on it is callable exactly\n\
68         like any tool already in your list — and it stays mounted for the rest of the\n\
69         session, so open it once and use it as often as you need.\n\
70         A name that is not mountable comes back with the ones that are. A name that is\n\
71         already mounted comes back saying so. Do not open a capability on the chance it\n\
72         comes in handy: every mounted tool is sent on every later request."
73    }
74
75    fn schema(&self) -> Value {
76        json!({
77            "type": "object",
78            "properties": {
79                "name": {
80                    "type": "string",
81                    "description": "The tool name exactly as the roster spells it."
82                }
83            },
84            "required": ["name"],
85            "additionalProperties": false,
86        })
87    }
88
89    /// Exposure is `Direct`: this one must always be on the wire, or nothing can
90    /// ever be opened.
91    fn exposure(&self) -> ToolExposure {
92        ToolExposure::Direct
93    }
94
95    async fn call(&self, args: &Value, _ctx: &ToolContext) -> AgentResult<Vec<Content>> {
96        let name = args
97            .get("name")
98            .and_then(Value::as_str)
99            .map(str::trim)
100            .filter(|s| !s.is_empty())
101            .ok_or_else(|| AgentError::ToolArgsInvalid {
102                name: self.name().to_string(),
103                raw: "missing field `name` — pass the tool name exactly as the roster spells it"
104                    .to_string(),
105            })?;
106
107        let Some((exposure, definition)) = self.candidates.get(name) else {
108            return Ok(vec![Content::text(format!(
109                "No tool named `{name}` is mountable. Mountable names: {}.",
110                self.candidate_names().join(", ")
111            ))]);
112        };
113
114        match exposure {
115            ToolExposure::Hidden => Ok(vec![Content::text(format!(
116                "`{name}` is internal and is not mountable. It is not in the roster."
117            ))]),
118            ToolExposure::Direct => Ok(vec![Content::text(format!(
119                "`{name}` is already mounted — call it directly."
120            ))]),
121            ToolExposure::Deferred => {
122                let first_open = self.activation.activate(name);
123                let status = if first_open {
124                    "mounted"
125                } else {
126                    "already mounted"
127                };
128                Ok(vec![Content::text(format!(
129                    "`{name}` {status}. Call it from the next turn on, with these arguments:\n{}",
130                    serde_json::to_string_pretty(definition).unwrap_or_default()
131                ))])
132            }
133        }
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use std::sync::atomic::AtomicBool;
140
141    use super::*;
142    use crate::engine::EventBus;
143    use crate::tool::ExecClock;
144    use crate::types::SessionId;
145    use serde_json::json;
146
147    fn test_context() -> ToolContext {
148        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
149        ToolContext {
150            session_id: SessionId::new(0),
151            user_event_tx: tx,
152            llm_client: None,
153            session_store: None,
154            language: crate::types::Language::En,
155            cancel_token: tokio_util::sync::CancellationToken::new(),
156            max_output_chars: None,
157            exec_clock: ExecClock::default(),
158            waiting_for_human: Arc::new(AtomicBool::new(false)),
159            event_bus: EventBus::new(1),
160        }
161    }
162
163    fn registry_free_tool() -> (ActivateTool, ToolActivation) {
164        let activation = ToolActivation::new();
165        let tool = ActivateTool::new(
166            activation.clone(),
167            vec![
168                (
169                    "browser_navigate".to_string(),
170                    ToolExposure::Deferred,
171                    json!({
172                        "name": "browser_navigate",
173                        "description": "Open a URL in the browser.",
174                        "parameters": {"type": "object", "properties": {"url": {"type": "string"}}},
175                    }),
176                ),
177                (
178                    "always_here".to_string(),
179                    ToolExposure::Direct,
180                    json!({"name": "always_here"}),
181                ),
182                (
183                    "internal".to_string(),
184                    ToolExposure::Hidden,
185                    json!({"name": "internal"}),
186                ),
187            ],
188        );
189        // `ActivateTool::new` returns Arc; unwrap for the tests to own the value.
190        let tool = Arc::try_unwrap(tool).ok().expect("single owner in tests");
191        (tool, activation)
192    }
193
194    async fn call(tool: &ActivateTool, args: Value) -> String {
195        let ctx = test_context();
196        let out = tool.call(&args, &ctx).await.expect("call succeeds");
197        out.iter()
198            .map(|c| match c {
199                Content::Text { text } => text.clone(),
200                _ => String::new(),
201            })
202            .collect()
203    }
204
205    /// Value: protects=the one thing the tool exists for — an opened tool must
206    /// be callable afterwards and its shape must come from us, not from the
207    /// model's reading of its name; fails_when=opening changes nothing, or
208    /// returns something other than the real definition. why_new=the tool is
209    /// new. seam=roster -> request; no_claim=that the model will read it.
210    #[tokio::test]
211    async fn opening_a_tool_mounts_it_and_hands_back_its_shape() {
212        let (tool, activation) = registry_free_tool();
213        let out = call(&tool, json!({"name": "browser_navigate"})).await;
214        assert!(
215            activation.is_active("browser_navigate"),
216            "opening must stick for the session"
217        );
218        assert!(out.contains("mounted"), "say what happened: {out}");
219        assert!(
220            out.contains("\"url\""),
221            "and hand back the real arguments, not just the name: {out}"
222        );
223    }
224
225    /// Value: protects=the model against a confidently wrong guess — a name
226    /// that is not mountable must come back with the list, because a silent
227    /// success leaves it calling a tool that never arrived; fails_when=an
228    /// unknown name is accepted. why_new=the tool is new. seam=roster; no_claim=
229    /// that the list is the only way to discover names.
230    #[tokio::test]
231    async fn an_unknown_name_is_refused_with_the_real_ones() {
232        let (tool, _activation) = registry_free_tool();
233        let out = call(&tool, json!({"name": "browser_nav"})).await;
234        assert!(out.contains("No tool named `browser_nav`"), "{out}");
235        assert!(
236            out.contains("browser_navigate"),
237            "the answer must name the tool it meant: {out}"
238        );
239    }
240
241    /// Value: protects=the reason `Hidden` exists — internal plumbing must stay
242    /// internal, and a roster-shaped hole must not become a way in;
243    /// fails_when=an internal tool can be mounted. why_new=the tool is new.
244    /// seam=exposure policy; no_claim=that no other path reaches a hidden tool.
245    #[tokio::test]
246    async fn an_internal_tool_cannot_be_mounted() {
247        let (tool, activation) = registry_free_tool();
248        let out = call(&tool, json!({"name": "internal"})).await;
249        assert!(out.contains("not mountable"), "{out}");
250        assert!(!activation.is_active("internal"), "and nothing was opened");
251    }
252
253    /// Value: protects=a turn the model could have spent working — a mounted
254    /// tool is already on the wire, so asking again must not read as success
255    /// and cost another round; fails_when=re-opening reports a fresh mount.
256    /// why_new=the tool is new. seam=session state; no_claim=about a session
257    /// where the tool was unmounted by other means.
258    #[tokio::test]
259    async fn opening_twice_is_reported_as_already_mounted() {
260        let (tool, _activation) = registry_free_tool();
261        call(&tool, json!({"name": "browser_navigate"})).await;
262        let out = call(&tool, json!({"name": "browser_navigate"})).await;
263        assert!(out.contains("already mounted"), "{out}");
264    }
265
266    /// Value: protects=the budget the roster exists to save — `Direct` tools
267    /// are already on every request, so "opening" one must not read as a win
268    /// and must not change the request; fails_when=a Direct tool is reported
269    /// mounted. why_new=the tool is new. seam=exposure policy.
270    #[tokio::test]
271    async fn an_already_mounted_tool_is_said_to_be() {
272        let (tool, activation) = registry_free_tool();
273        let out = call(&tool, json!({"name": "always_here"})).await;
274        assert!(out.contains("already mounted"), "{out}");
275        assert!(
276            !activation.is_active("always_here"),
277            "a Direct tool needs no activation entry"
278        );
279    }
280
281    /// Value: protects=the arg contract — a call with no name is a mistake the
282    /// model can correct if we say so, and an empty name is not a name;
283    /// fails_when=both are accepted and quietly do nothing.
284    /// why_new=the tool is new. seam=args.
285    #[tokio::test]
286    async fn a_missing_name_says_what_is_missing() {
287        let (tool, _activation) = registry_free_tool();
288        let err = tool.call(&json!({}), &test_context()).await;
289        let msg = format!("{:?}", err.expect_err("no name is an error"));
290        assert!(
291            msg.contains("`name`"),
292            "the error must name the field: {msg}"
293        );
294    }
295}