Skip to main content

gemini_adk_rs/tool/
mod.rs

1//! Tool dispatch — regular, streaming, and input-streaming tools.
2
3pub mod commit;
4pub mod context;
5pub mod dispatcher;
6pub mod policy;
7pub mod schema;
8pub mod simple;
9pub mod typed;
10
11pub use commit::CommitGuard;
12pub use context::{ContextTool, ToolContext};
13pub use dispatcher::*;
14pub use policy::*;
15pub use schema::wire_schema;
16pub use simple::*;
17pub use typed::*;
18
19use std::sync::Arc;
20use std::time::Duration;
21
22pub mod media;
23
24use async_trait::async_trait;
25use tokio::sync::{broadcast, mpsc};
26use tokio::task::JoinHandle;
27use tokio_util::sync::CancellationToken;
28
29use crate::agent_session::InputEvent;
30use crate::error::ToolError;
31
32/// A regular tool — called once, returns a result.
33///
34/// # Examples
35///
36/// ```rust,ignore
37/// use async_trait::async_trait;
38/// use gemini_adk_rs::tool::ToolFunction;
39/// use gemini_adk_rs::error::ToolError;
40///
41/// struct MyTool;
42///
43/// #[async_trait]
44/// impl ToolFunction for MyTool {
45///     fn name(&self) -> &str { "my_tool" }
46///     fn description(&self) -> &str { "Does something useful" }
47///     fn parameters(&self) -> Option<serde_json::Value> { None }
48///     async fn call(&self, args: serde_json::Value) -> Result<serde_json::Value, ToolError> {
49///         Ok(serde_json::json!({"status": "ok"}))
50///     }
51/// }
52/// ```
53#[async_trait]
54pub trait ToolFunction: Send + Sync + 'static {
55    /// The unique name of this tool.
56    fn name(&self) -> &str;
57    /// Human-readable description of what this tool does.
58    fn description(&self) -> &str;
59    /// JSON Schema for the tool's input parameters, or `None` if parameterless.
60    fn parameters(&self) -> Option<serde_json::Value>;
61    /// Execute the tool with the given arguments and return the result.
62    async fn call(&self, args: serde_json::Value) -> Result<serde_json::Value, ToolError>;
63
64    /// Execute the tool knowing the session it runs in: its [`State`], the
65    /// call's id, and a cancellation token (see [`ToolContext`]).
66    ///
67    /// The runtime always calls this. The default ignores the context and
68    /// runs [`call`](Self::call), so a tool that needs no context implements
69    /// only `call`. A tool that does overrides this, and implements `call` as
70    /// `self.call_with_context(args, ToolContext::detached())`. A wrapper
71    /// must forward it, or the context is lost.
72    ///
73    /// [`State`]: crate::state::State
74    async fn call_with_context(
75        &self,
76        args: serde_json::Value,
77        ctx: ToolContext,
78    ) -> Result<serde_json::Value, ToolError> {
79        let _ = ctx;
80        self.call(args).await
81    }
82
83    /// Whether this tool must be confirmed before it runs. Defaults to `false`.
84    ///
85    /// Tools built with `T::confirm(..)` (a [`PolicyTool`] with a confirm
86    /// policy) return `true`, prompting the [`ToolDispatcher`] to consult its
87    /// configured `ConfirmationProvider` before executing.
88    fn requires_confirmation(&self) -> bool {
89        false
90    }
91
92    /// Optional hint shown when confirmation is requested.
93    fn confirmation_message(&self) -> Option<&str> {
94        None
95    }
96}
97
98/// An `Arc<dyn ToolFunction>` (or `Arc<SomeTool>`) is itself a tool, so a
99/// setter that takes `impl ToolFunction` accepts a shared handle as readily as
100/// a fresh value.
101#[async_trait]
102impl<T: ToolFunction + ?Sized> ToolFunction for Arc<T> {
103    fn name(&self) -> &str {
104        (**self).name()
105    }
106    fn description(&self) -> &str {
107        (**self).description()
108    }
109    fn parameters(&self) -> Option<serde_json::Value> {
110        (**self).parameters()
111    }
112    async fn call(&self, args: serde_json::Value) -> Result<serde_json::Value, ToolError> {
113        (**self).call(args).await
114    }
115    async fn call_with_context(
116        &self,
117        args: serde_json::Value,
118        ctx: ToolContext,
119    ) -> Result<serde_json::Value, ToolError> {
120        (**self).call_with_context(args, ctx).await
121    }
122    fn requires_confirmation(&self) -> bool {
123        (**self).requires_confirmation()
124    }
125    fn confirmation_message(&self) -> Option<&str> {
126        (**self).confirmation_message()
127    }
128}
129
130/// A streaming tool — runs in background, yields multiple results.
131#[async_trait]
132pub trait StreamingTool: Send + Sync + 'static {
133    /// The unique name of this tool.
134    fn name(&self) -> &str;
135    /// Human-readable description of what this tool does.
136    fn description(&self) -> &str;
137    /// JSON Schema for the tool's input parameters, or `None` if parameterless.
138    fn parameters(&self) -> Option<serde_json::Value>;
139    /// Execute the tool, sending intermediate results via `yield_tx`.
140    async fn run(
141        &self,
142        args: serde_json::Value,
143        yield_tx: mpsc::Sender<serde_json::Value>,
144    ) -> Result<(), ToolError>;
145}
146
147/// An input-streaming tool — receives duplicated live input while running.
148#[async_trait]
149pub trait InputStreamingTool: Send + Sync + 'static {
150    /// The unique name of this tool.
151    fn name(&self) -> &str;
152    /// Human-readable description of what this tool does.
153    fn description(&self) -> &str;
154    /// JSON Schema for the tool's input parameters, or `None` if parameterless.
155    fn parameters(&self) -> Option<serde_json::Value>;
156    /// Execute the tool, receiving live input via `input_rx` and sending results via `yield_tx`.
157    async fn run(
158        &self,
159        args: serde_json::Value,
160        input_rx: broadcast::Receiver<InputEvent>,
161        yield_tx: mpsc::Sender<serde_json::Value>,
162    ) -> Result<(), ToolError>;
163}
164
165/// Classification of a registered tool.
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
167pub enum ToolClass {
168    /// A one-shot tool that returns a single result.
169    Regular,
170    /// A tool that yields multiple results over time.
171    Streaming,
172    /// A tool that receives live input while producing results.
173    InputStream,
174}
175
176/// Unified tool storage.
177pub enum ToolKind {
178    /// A regular one-shot function tool.
179    Function(Arc<dyn ToolFunction>),
180    /// A streaming tool that yields multiple results.
181    Streaming(Arc<dyn StreamingTool>),
182    /// An input-streaming tool that receives live input.
183    InputStream(Arc<dyn InputStreamingTool>),
184}
185
186/// Handle to a running streaming tool.
187pub struct ActiveStreamingTool {
188    /// The spawned task handle.
189    pub task: JoinHandle<()>,
190    /// Token to cancel this streaming tool.
191    pub cancel: CancellationToken,
192}
193
194/// Default timeout for tool execution (30 seconds).
195pub(crate) const DEFAULT_TOOL_TIMEOUT: Duration = Duration::from_secs(30);
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200    use gemini_genai_rs::prelude::FunctionCall;
201    use serde_json::json;
202
203    struct MockTool;
204
205    #[async_trait]
206    impl ToolFunction for MockTool {
207        fn name(&self) -> &str {
208            "mock_tool"
209        }
210        fn description(&self) -> &str {
211            "A mock tool"
212        }
213        fn parameters(&self) -> Option<serde_json::Value> {
214            None
215        }
216        async fn call(&self, _args: serde_json::Value) -> Result<serde_json::Value, ToolError> {
217            Ok(json!({"result": "ok"}))
218        }
219    }
220
221    #[tokio::test]
222    async fn register_and_call_function_tool() {
223        let mut dispatcher = ToolDispatcher::new();
224        dispatcher.register_function(Arc::new(MockTool));
225        let result = dispatcher
226            .call_function("mock_tool", json!({}))
227            .await
228            .unwrap();
229        assert_eq!(result["result"], "ok");
230    }
231
232    #[tokio::test]
233    async fn call_unknown_tool_returns_error() {
234        let dispatcher = ToolDispatcher::new();
235        let result = dispatcher.call_function("nonexistent", json!({})).await;
236        assert!(result.is_err());
237    }
238
239    #[test]
240    fn to_tool_declarations() {
241        let mut dispatcher = ToolDispatcher::new();
242        dispatcher.register_function(Arc::new(MockTool));
243        let decls = dispatcher.to_tool_declarations();
244        assert_eq!(decls.len(), 1);
245    }
246
247    #[test]
248    fn classify_tool() {
249        let mut dispatcher = ToolDispatcher::new();
250        dispatcher.register_function(Arc::new(MockTool));
251        assert_eq!(dispatcher.classify("mock_tool"), Some(ToolClass::Regular));
252        assert_eq!(dispatcher.classify("nonexistent"), None);
253    }
254
255    #[test]
256    fn empty_dispatcher() {
257        let dispatcher = ToolDispatcher::new();
258        assert!(dispatcher.is_empty());
259        assert_eq!(dispatcher.len(), 0);
260        assert!(dispatcher.to_tool_declarations().is_empty());
261    }
262
263    #[test]
264    fn build_response_success() {
265        let call = FunctionCall {
266            name: "test".to_string(),
267            args: json!({}),
268            id: Some("call-1".to_string()),
269            thought_signature: None,
270        };
271        let resp = ToolDispatcher::build_response(&call, Ok(json!({"ok": true})));
272        assert_eq!(resp.name, "test");
273        assert_eq!(resp.response["ok"], true);
274    }
275
276    #[test]
277    fn build_response_error() {
278        let call = FunctionCall {
279            name: "test".to_string(),
280            args: json!({}),
281            id: Some("call-1".to_string()),
282            thought_signature: None,
283        };
284        let resp = ToolDispatcher::build_response(
285            &call,
286            Err(ToolError::ExecutionFailed("boom".to_string())),
287        );
288        assert!(resp.response["error"].as_str().unwrap().contains("boom"));
289    }
290
291    #[test]
292    fn tool_dispatcher_implements_tool_provider() {
293        use gemini_genai_rs::prelude::ToolProvider;
294        let mut dispatcher = ToolDispatcher::new();
295        dispatcher.register_function(Arc::new(MockTool));
296        let decls = dispatcher.declarations();
297        assert_eq!(decls.len(), 1);
298    }
299
300    #[tokio::test]
301    async fn simple_tool_closure() {
302        let tool = SimpleTool::new(
303            "add",
304            "Add two numbers",
305            Some(
306                json!({"type": "object", "properties": {"a": {"type": "number"}, "b": {"type": "number"}}}),
307            ),
308            |args| async move {
309                let a = args["a"].as_f64().unwrap_or(0.0);
310                let b = args["b"].as_f64().unwrap_or(0.0);
311                Ok(json!({"sum": a + b}))
312            },
313        );
314
315        let mut dispatcher = ToolDispatcher::new();
316        dispatcher.register_function(Arc::new(tool));
317        let result = dispatcher
318            .call_function("add", json!({"a": 3, "b": 4}))
319            .await
320            .unwrap();
321        assert_eq!(result["sum"], 7.0);
322    }
323
324    // --- TypedTool tests ---
325
326    #[derive(serde::Deserialize, schemars::JsonSchema)]
327    struct WeatherArgs {
328        /// The city to get weather for
329        city: String,
330        /// Temperature units (celsius or fahrenheit)
331        #[serde(default = "default_units")]
332        units: String,
333    }
334
335    fn default_units() -> String {
336        "celsius".to_string()
337    }
338
339    #[test]
340    fn typed_tool_auto_generates_schema() {
341        let tool = TypedTool::new(
342            "get_weather",
343            "Get current weather for a city",
344            |_args: WeatherArgs| async move { Ok(json!({})) },
345        );
346
347        let params = tool.parameters().expect("should have parameters");
348
349        // The schema should be an object type with "city" and "units" properties
350        let props = &params["properties"];
351        assert!(
352            props.get("city").is_some(),
353            "schema should contain 'city' property"
354        );
355        assert!(
356            props.get("units").is_some(),
357            "schema should contain 'units' property"
358        );
359
360        // "city" should be required (no default), "units" has a default so may not be
361        let required = params["required"]
362            .as_array()
363            .expect("should have required array");
364        let required_names: Vec<&str> = required.iter().filter_map(|v| v.as_str()).collect();
365        assert!(required_names.contains(&"city"), "city should be required");
366    }
367
368    #[tokio::test]
369    async fn typed_tool_deserializes_args() {
370        let tool = TypedTool::new(
371            "get_weather",
372            "Get current weather for a city",
373            |args: WeatherArgs| async move {
374                Ok(json!({
375                    "temp": 22,
376                    "city": args.city,
377                    "units": args.units,
378                }))
379            },
380        );
381
382        let result = tool
383            .call(json!({"city": "London", "units": "fahrenheit"}))
384            .await
385            .unwrap();
386        assert_eq!(result["city"], "London");
387        assert_eq!(result["units"], "fahrenheit");
388        assert_eq!(result["temp"], 22);
389    }
390
391    #[tokio::test]
392    async fn typed_tool_invalid_args_returns_error() {
393        let tool = TypedTool::new(
394            "get_weather",
395            "Get current weather for a city",
396            |_args: WeatherArgs| async move { Ok(json!({})) },
397        );
398
399        // Missing required field "city"
400        let result = tool.call(json!({"units": "celsius"})).await;
401        assert!(result.is_err(), "should fail with missing required field");
402        let err = result.unwrap_err();
403        match &err {
404            ToolError::InvalidArgs(msg) => {
405                assert!(
406                    msg.contains("city"),
407                    "error message should mention the missing field: {msg}"
408                );
409            }
410            other => panic!("expected ToolError::InvalidArgs, got: {other:?}"),
411        }
412
413        // Wrong type for "city" (number instead of string)
414        let result = tool.call(json!({"city": 12345})).await;
415        assert!(result.is_err(), "should fail with wrong type");
416    }
417
418    #[tokio::test]
419    async fn typed_tool_registers_in_dispatcher() {
420        let tool = TypedTool::new(
421            "get_weather",
422            "Get current weather for a city",
423            |args: WeatherArgs| async move { Ok(json!({"city": args.city})) },
424        );
425
426        let mut dispatcher = ToolDispatcher::new();
427        dispatcher.register_function(Arc::new(tool));
428
429        assert_eq!(dispatcher.classify("get_weather"), Some(ToolClass::Regular));
430        assert_eq!(dispatcher.len(), 1);
431
432        let result = dispatcher
433            .call_function("get_weather", json!({"city": "Paris"}))
434            .await
435            .unwrap();
436        assert_eq!(result["city"], "Paris");
437
438        // Verify it appears in tool declarations
439        let decls = dispatcher.to_tool_declarations();
440        assert_eq!(decls.len(), 1);
441    }
442
443    // --- Timeout and cancellation tests ---
444
445    /// A tool that sleeps forever (until cancelled/timed out).
446    struct SlowTool;
447
448    #[async_trait]
449    impl ToolFunction for SlowTool {
450        fn name(&self) -> &str {
451            "slow_tool"
452        }
453        fn description(&self) -> &str {
454            "A tool that never completes"
455        }
456        fn parameters(&self) -> Option<serde_json::Value> {
457            None
458        }
459        async fn call(&self, _args: serde_json::Value) -> Result<serde_json::Value, ToolError> {
460            // Sleep effectively forever
461            tokio::time::sleep(Duration::from_secs(3600)).await;
462            Ok(json!({"result": "should never reach here"}))
463        }
464    }
465
466    #[tokio::test]
467    async fn tool_timeout_returns_error() {
468        let mut dispatcher = ToolDispatcher::new();
469        dispatcher.register_function(Arc::new(SlowTool));
470
471        let timeout = Duration::from_millis(50);
472        let result = dispatcher
473            .call_function_with_timeout("slow_tool", json!({}), timeout)
474            .await;
475
476        match result {
477            Err(ToolError::Timeout(d)) => assert_eq!(d, timeout),
478            other => panic!("expected ToolError::Timeout, got: {other:?}"),
479        }
480    }
481
482    #[tokio::test]
483    async fn tool_completes_before_timeout() {
484        let mut dispatcher = ToolDispatcher::new();
485        dispatcher.register_function(Arc::new(MockTool));
486
487        let result = dispatcher
488            .call_function_with_timeout("mock_tool", json!({}), Duration::from_secs(5))
489            .await
490            .unwrap();
491        assert_eq!(result["result"], "ok");
492    }
493
494    #[tokio::test]
495    async fn tool_cancelled_returns_error() {
496        let mut dispatcher = ToolDispatcher::new();
497        dispatcher.register_function(Arc::new(SlowTool));
498
499        let cancel = CancellationToken::new();
500        let cancel_clone = cancel.clone();
501
502        // Cancel after a short delay
503        tokio::spawn(async move {
504            tokio::time::sleep(Duration::from_millis(50)).await;
505            cancel_clone.cancel();
506        });
507
508        let result = dispatcher
509            .call_function_with_cancel("slow_tool", json!({}), cancel)
510            .await;
511
512        match result {
513            Err(ToolError::Cancelled) => {} // expected
514            other => panic!("expected ToolError::Cancelled, got: {other:?}"),
515        }
516    }
517
518    #[test]
519    fn default_timeout_is_30s() {
520        let dispatcher = ToolDispatcher::new();
521        assert_eq!(dispatcher.default_timeout(), Duration::from_secs(30));
522    }
523
524    #[test]
525    fn with_timeout_overrides_default() {
526        let dispatcher = ToolDispatcher::new().with_timeout(Duration::from_secs(10));
527        assert_eq!(dispatcher.default_timeout(), Duration::from_secs(10));
528    }
529
530    #[tokio::test]
531    async fn call_function_uses_default_timeout() {
532        // Set a very short default timeout so the slow tool times out
533        let mut dispatcher = ToolDispatcher::new().with_timeout(Duration::from_millis(50));
534        dispatcher.register_function(Arc::new(SlowTool));
535
536        let result = dispatcher.call_function("slow_tool", json!({})).await;
537
538        match result {
539            Err(ToolError::Timeout(d)) => assert_eq!(d, Duration::from_millis(50)),
540            other => panic!("expected ToolError::Timeout, got: {other:?}"),
541        }
542    }
543}