Skip to main content

adk_tool/toolset/
compose.rs

1use adk_core::{ReadonlyContext, Result, Tool, ToolContext, ToolPredicate, Toolset};
2use async_trait::async_trait;
3use serde_json::Value;
4use std::sync::Arc;
5
6/// A toolset wrapper that filters tools from an inner toolset using a predicate.
7///
8/// Works with any `Toolset` implementation. Tools that do not satisfy the
9/// predicate are excluded from the resolved tool list.
10///
11/// # Example
12///
13/// ```rust,ignore
14/// use adk_tool::toolset::{FilteredToolset, string_predicate};
15///
16/// let browser = BrowserToolset::new(session);
17/// let filtered = FilteredToolset::new(
18///     Arc::new(browser),
19///     string_predicate(vec!["navigate".into(), "click".into()]),
20/// );
21/// // Only "navigate" and "click" tools will be exposed
22/// ```
23pub struct FilteredToolset {
24    inner: Arc<dyn Toolset>,
25    predicate: ToolPredicate,
26    name: String,
27}
28
29impl FilteredToolset {
30    /// Wrap `inner` and keep only tools that satisfy `predicate`.
31    pub fn new(inner: Arc<dyn Toolset>, predicate: ToolPredicate) -> Self {
32        let name = format!("{}_filtered", inner.name());
33        Self { inner, predicate, name }
34    }
35
36    /// Wrap `inner` with a custom name and keep only tools that satisfy `predicate`.
37    pub fn with_name(
38        inner: Arc<dyn Toolset>,
39        predicate: ToolPredicate,
40        name: impl Into<String>,
41    ) -> Self {
42        Self { inner, predicate, name: name.into() }
43    }
44}
45
46#[async_trait]
47impl Toolset for FilteredToolset {
48    fn name(&self) -> &str {
49        &self.name
50    }
51
52    async fn tools(&self, ctx: Arc<dyn ReadonlyContext>) -> Result<Vec<Arc<dyn Tool>>> {
53        let all = self.inner.tools(ctx).await?;
54        Ok(all.into_iter().filter(|t| (self.predicate)(t.as_ref())).collect())
55    }
56
57    /// Closes the inner toolset.
58    async fn close(&self) {
59        self.inner.close().await;
60    }
61}
62
63/// A toolset that merges tools from multiple inner toolsets into one.
64///
65/// Toolsets are resolved in registration order. If two inner toolsets
66/// provide a tool with the same name, the first one wins (last-registered
67/// duplicates are dropped with a `tracing::warn`).
68///
69/// # Example
70///
71/// ```rust,ignore
72/// use adk_tool::toolset::MergedToolset;
73///
74/// let merged = MergedToolset::new("all_tools", vec![
75///     Arc::new(browser_toolset),
76///     Arc::new(search_toolset),
77/// ]);
78/// ```
79pub struct MergedToolset {
80    name: String,
81    inner: Vec<Arc<dyn Toolset>>,
82}
83
84impl MergedToolset {
85    /// Create a merged toolset from multiple inner toolsets.
86    pub fn new(name: impl Into<String>, toolsets: Vec<Arc<dyn Toolset>>) -> Self {
87        Self { name: name.into(), inner: toolsets }
88    }
89
90    /// Append another toolset to the merge list.
91    pub fn with_toolset(mut self, toolset: Arc<dyn Toolset>) -> Self {
92        self.inner.push(toolset);
93        self
94    }
95}
96
97#[async_trait]
98impl Toolset for MergedToolset {
99    fn name(&self) -> &str {
100        &self.name
101    }
102
103    async fn tools(&self, ctx: Arc<dyn ReadonlyContext>) -> Result<Vec<Arc<dyn Tool>>> {
104        let mut seen = std::collections::HashSet::new();
105        let mut merged = Vec::new();
106
107        for toolset in &self.inner {
108            let tools = toolset.tools(ctx.clone()).await?;
109            for tool in tools {
110                let tool_name = tool.name().to_string();
111                if seen.contains(&tool_name) {
112                    tracing::warn!(
113                        tool.name = %tool_name,
114                        toolset.name = %toolset.name(),
115                        merged_toolset.name = %self.name,
116                        "duplicate tool name in MergedToolset, skipping"
117                    );
118                    continue;
119                }
120                seen.insert(tool_name);
121                merged.push(tool);
122            }
123        }
124
125        Ok(merged)
126    }
127
128    /// Closes every inner toolset, concurrently, so each one's close timeout runs at once.
129    async fn close(&self) {
130        futures::future::join_all(self.inner.iter().map(|toolset| toolset.close())).await;
131    }
132}
133
134/// A toolset wrapper that prefixes all tool names from an inner toolset.
135///
136/// Useful for namespacing tools when composing multiple toolsets that
137/// might have overlapping tool names.
138///
139/// # Example
140///
141/// ```rust,ignore
142/// use adk_tool::toolset::PrefixedToolset;
143///
144/// let browser = BrowserToolset::new(session);
145/// let prefixed = PrefixedToolset::new(Arc::new(browser), "browser");
146/// // Tools become "browser_navigate", "browser_click", etc.
147/// ```
148pub struct PrefixedToolset {
149    inner: Arc<dyn Toolset>,
150    prefix: String,
151    name: String,
152}
153
154impl PrefixedToolset {
155    /// Wrap `inner` and prefix all tool names with `prefix_`.
156    pub fn new(inner: Arc<dyn Toolset>, prefix: impl Into<String>) -> Self {
157        let prefix = prefix.into();
158        let name = format!("{}_{}", prefix, inner.name());
159        Self { inner, prefix, name }
160    }
161}
162
163#[async_trait]
164impl Toolset for PrefixedToolset {
165    fn name(&self) -> &str {
166        &self.name
167    }
168
169    async fn tools(&self, ctx: Arc<dyn ReadonlyContext>) -> Result<Vec<Arc<dyn Tool>>> {
170        let tools = self.inner.tools(ctx).await?;
171        Ok(tools
172            .into_iter()
173            .map(|t| -> Arc<dyn Tool> { Arc::new(PrefixedTool::new(t, &self.prefix)) })
174            .collect())
175    }
176
177    /// Closes the inner toolset.
178    async fn close(&self) {
179        self.inner.close().await;
180    }
181}
182
183/// Internal wrapper that presents a tool under a prefixed name.
184struct PrefixedTool {
185    inner: Arc<dyn Tool>,
186    prefixed_name: String,
187    prefixed_description: String,
188}
189
190impl PrefixedTool {
191    fn new(inner: Arc<dyn Tool>, prefix: &str) -> Self {
192        let prefixed_name = format!("{prefix}_{}", inner.name());
193        let prefixed_description = inner.description().to_string();
194        Self { inner, prefixed_name, prefixed_description }
195    }
196}
197
198#[async_trait]
199impl Tool for PrefixedTool {
200    fn name(&self) -> &str {
201        &self.prefixed_name
202    }
203
204    fn description(&self) -> &str {
205        &self.prefixed_description
206    }
207
208    fn enhanced_description(&self) -> String {
209        self.inner.enhanced_description()
210    }
211
212    fn is_long_running(&self) -> bool {
213        self.inner.is_long_running()
214    }
215
216    fn parameters_schema(&self) -> Option<Value> {
217        self.inner.parameters_schema()
218    }
219
220    fn response_schema(&self) -> Option<Value> {
221        self.inner.response_schema()
222    }
223
224    fn required_scopes(&self) -> &[&str] {
225        self.inner.required_scopes()
226    }
227
228    fn is_read_only(&self) -> bool {
229        self.inner.is_read_only()
230    }
231
232    fn is_concurrency_safe(&self) -> bool {
233        self.inner.is_concurrency_safe()
234    }
235
236    fn effect(&self) -> adk_core::ToolEffect {
237        self.inner.effect()
238    }
239
240    fn egress(&self, args: &serde_json::Value) -> adk_core::egress::ToolEgress {
241        self.inner.egress(args)
242    }
243
244    fn approval_evidence(&self, args: &serde_json::Value) -> Vec<adk_core::Evidence> {
245        self.inner.approval_evidence(args)
246    }
247
248    fn batch_group(&self) -> Option<adk_core::BatchGroup> {
249        self.inner.batch_group()
250    }
251
252    fn annotations(&self) -> Option<&Value> {
253        self.inner.annotations()
254    }
255
256    fn origin(&self) -> &str {
257        self.inner.origin()
258    }
259
260    fn timeout_override(&self) -> Option<Option<std::time::Duration>> {
261        self.inner.timeout_override()
262    }
263
264    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
265        self.inner.execute(ctx, args).await
266    }
267}