Skip to main content

adk_core/
tool.rs

1use crate::{CallbackContext, EventActions, MemoryEntry, Result};
2use async_trait::async_trait;
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5use std::sync::Arc;
6
7#[async_trait]
8pub trait Tool: Send + Sync {
9    fn name(&self) -> &str;
10    fn description(&self) -> &str;
11
12    /// Returns the tool declaration that should be exposed to model providers.
13    ///
14    /// The default implementation produces the standard ADK function-tool
15    /// declaration (`name`, `description`, optional `parameters`, optional
16    /// `response`). Provider-specific built-in tools may override this to attach
17    /// additional metadata that the provider adapters understand.
18    ///
19    /// # Example
20    ///
21    /// ```rust,ignore
22    /// fn declaration(&self) -> serde_json::Value {
23    ///     serde_json::json!({
24    ///         "name": self.name(),
25    ///         "description": self.description(),
26    ///         "x-adk-openai-tool": {
27    ///             "type": "web_search_2025_08_26"
28    ///         }
29    ///     })
30    /// }
31    /// ```
32    fn declaration(&self) -> Value {
33        let mut decl = serde_json::json!({
34            "name": self.name(),
35            "description": self.enhanced_description(),
36        });
37
38        if let Some(params) = self.parameters_schema() {
39            decl["parameters"] = params;
40        }
41
42        if let Some(response) = self.response_schema() {
43            decl["response"] = response;
44        }
45
46        decl
47    }
48
49    /// Returns an enhanced description that may include additional notes.
50    /// For long-running tools, this includes a warning not to call the tool
51    /// again if it has already returned a pending status.
52    /// Default implementation returns the base description.
53    fn enhanced_description(&self) -> String {
54        self.description().to_string()
55    }
56
57    /// Indicates whether the tool is a long-running operation.
58    /// Long-running tools typically return a task ID immediately and
59    /// complete the operation asynchronously.
60    fn is_long_running(&self) -> bool {
61        false
62    }
63
64    /// Indicates whether this tool is a built-in server-side tool (e.g., `google_search`, `url_context`).
65    ///
66    /// Built-in tools are executed server-side by the model provider and should not be
67    /// executed locally by the agent. The default implementation returns `false`.
68    fn is_builtin(&self) -> bool {
69        false
70    }
71
72    fn parameters_schema(&self) -> Option<Value> {
73        None
74    }
75    fn response_schema(&self) -> Option<Value> {
76        None
77    }
78
79    /// Returns the scopes required to execute this tool.
80    ///
81    /// When non-empty, the framework can enforce that the calling user
82    /// possesses **all** listed scopes before dispatching `execute()`.
83    /// The default implementation returns an empty slice (no scopes required).
84    ///
85    /// # Example
86    ///
87    /// ```rust,ignore
88    /// fn required_scopes(&self) -> &[&str] {
89    ///     &["finance:write", "verified"]
90    /// }
91    /// ```
92    fn required_scopes(&self) -> &[&str] {
93        &[]
94    }
95
96    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value>;
97}
98
99#[async_trait]
100pub trait ToolContext: CallbackContext {
101    fn function_call_id(&self) -> &str;
102    /// Get the current event actions. Returns an owned copy for thread safety.
103    fn actions(&self) -> EventActions;
104    /// Set the event actions (e.g., to trigger escalation or skip summarization).
105    fn set_actions(&self, actions: EventActions);
106    async fn search_memory(&self, query: &str) -> Result<Vec<MemoryEntry>>;
107
108    /// Returns the scopes granted to the current user for this invocation.
109    ///
110    /// Implementations may resolve scopes from session state, JWT claims,
111    /// or an external identity provider. The default returns an empty set
112    /// (no scopes granted), which means scope-protected tools will be denied
113    /// unless the implementation is overridden.
114    fn user_scopes(&self) -> Vec<String> {
115        vec![]
116    }
117}
118
119/// Configuration for automatic tool retry on failure.
120///
121/// Controls how many times a failed tool execution is retried before
122/// propagating the error. Applied as a flat delay between attempts
123/// (no exponential backoff in V1).
124///
125/// # Example
126///
127/// ```rust
128/// use std::time::Duration;
129/// use adk_core::RetryBudget;
130///
131/// // Retry up to 2 times with 500ms between attempts (3 total attempts)
132/// let budget = RetryBudget::new(2, Duration::from_millis(500));
133/// assert_eq!(budget.max_retries, 2);
134/// ```
135#[derive(Debug, Clone)]
136pub struct RetryBudget {
137    /// Maximum number of retry attempts (not counting the initial attempt).
138    /// E.g., `max_retries: 2` means up to 3 total attempts.
139    pub max_retries: u32,
140    /// Delay between retries. Applied as a flat delay (no backoff in V1).
141    pub delay: std::time::Duration,
142}
143
144impl RetryBudget {
145    /// Create a new retry budget.
146    ///
147    /// # Arguments
148    ///
149    /// * `max_retries` - Maximum retry attempts (not counting the initial attempt)
150    /// * `delay` - Flat delay between retry attempts
151    pub fn new(max_retries: u32, delay: std::time::Duration) -> Self {
152        Self { max_retries, delay }
153    }
154}
155
156#[async_trait]
157pub trait Toolset: Send + Sync {
158    fn name(&self) -> &str;
159    async fn tools(&self, ctx: Arc<dyn crate::ReadonlyContext>) -> Result<Vec<Arc<dyn Tool>>>;
160}
161
162/// Controls how the framework handles skills/agents that request unavailable tools.
163#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
164pub enum ValidationMode {
165    /// Reject the operation entirely if any requested tool is missing from the registry.
166    #[default]
167    Strict,
168    /// Bind available tools, omit missing ones, and log a warning.
169    Permissive,
170}
171
172/// A registry that maps tool names to concrete tool instances.
173///
174/// Implementations resolve string identifiers (e.g. from a skill or config)
175/// into executable `Arc<dyn Tool>` instances.
176pub trait ToolRegistry: Send + Sync {
177    /// Resolve a tool name to a concrete tool instance.
178    /// Returns `None` if the tool is not available in this registry.
179    fn resolve(&self, tool_name: &str) -> Option<Arc<dyn Tool>>;
180
181    /// Returns a list of all tool names available in this registry.
182    fn available_tools(&self) -> Vec<String> {
183        vec![]
184    }
185}
186
187pub type ToolPredicate = Box<dyn Fn(&dyn Tool) -> bool + Send + Sync>;
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192    use crate::{Content, EventActions, ReadonlyContext, RunConfig};
193    use std::sync::Mutex;
194
195    struct TestTool {
196        name: String,
197    }
198
199    #[allow(dead_code)]
200    struct TestContext {
201        content: Content,
202        config: RunConfig,
203        actions: Mutex<EventActions>,
204    }
205
206    impl TestContext {
207        fn new() -> Self {
208            Self {
209                content: Content::new("user"),
210                config: RunConfig::default(),
211                actions: Mutex::new(EventActions::default()),
212            }
213        }
214    }
215
216    #[async_trait]
217    impl ReadonlyContext for TestContext {
218        fn invocation_id(&self) -> &str {
219            "test"
220        }
221        fn agent_name(&self) -> &str {
222            "test"
223        }
224        fn user_id(&self) -> &str {
225            "user"
226        }
227        fn app_name(&self) -> &str {
228            "app"
229        }
230        fn session_id(&self) -> &str {
231            "session"
232        }
233        fn branch(&self) -> &str {
234            ""
235        }
236        fn user_content(&self) -> &Content {
237            &self.content
238        }
239    }
240
241    #[async_trait]
242    impl CallbackContext for TestContext {
243        fn artifacts(&self) -> Option<Arc<dyn crate::Artifacts>> {
244            None
245        }
246    }
247
248    #[async_trait]
249    impl ToolContext for TestContext {
250        fn function_call_id(&self) -> &str {
251            "call-123"
252        }
253        fn actions(&self) -> EventActions {
254            self.actions.lock().unwrap().clone()
255        }
256        fn set_actions(&self, actions: EventActions) {
257            *self.actions.lock().unwrap() = actions;
258        }
259        async fn search_memory(&self, _query: &str) -> Result<Vec<crate::MemoryEntry>> {
260            Ok(vec![])
261        }
262    }
263
264    #[async_trait]
265    impl Tool for TestTool {
266        fn name(&self) -> &str {
267            &self.name
268        }
269
270        fn description(&self) -> &str {
271            "test tool"
272        }
273
274        async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
275            Ok(Value::String("result".to_string()))
276        }
277    }
278
279    #[test]
280    fn test_tool_trait() {
281        let tool = TestTool { name: "test".to_string() };
282        assert_eq!(tool.name(), "test");
283        assert_eq!(tool.description(), "test tool");
284        assert!(!tool.is_long_running());
285    }
286
287    #[tokio::test]
288    async fn test_tool_execute() {
289        let tool = TestTool { name: "test".to_string() };
290        let ctx = Arc::new(TestContext::new()) as Arc<dyn ToolContext>;
291        let result = tool.execute(ctx, Value::Null).await.unwrap();
292        assert_eq!(result, Value::String("result".to_string()));
293    }
294}