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