Skip to main content

adk_browser/
toolset.rs

1//! Browser toolset that provides all browser tools as a collection.
2
3use crate::pool::BrowserSessionPool;
4use crate::session::BrowserSession;
5use crate::tools::*;
6use adk_core::{ReadonlyContext, Result, Tool, Toolset};
7use async_trait::async_trait;
8use std::path::PathBuf;
9use std::sync::Arc;
10
11/// Internal abstraction for session acquisition.
12/// Not exposed in the public API.
13enum SessionResolver {
14    /// Fixed session — always returns the same session.
15    Fixed(Arc<BrowserSession>),
16    /// Pool-backed — resolves session from pool using user_id from context.
17    Pool(Arc<BrowserSessionPool>),
18}
19
20impl SessionResolver {
21    async fn resolve(&self, ctx: &Arc<dyn ReadonlyContext>) -> Result<Arc<BrowserSession>> {
22        match self {
23            SessionResolver::Fixed(session) => Ok(session.clone()),
24            SessionResolver::Pool(pool) => pool.get_or_create(ctx.user_id()).await,
25        }
26    }
27}
28
29/// Pre-configured tool profiles for common use cases.
30///
31/// Instead of using every tool (which overwhelms LLM context windows),
32/// select a profile that matches your agent's task. No profile includes
33/// `browser_evaluate_js` or `browser_file_upload`; enable them with
34/// [`BrowserToolset::with_evaluate_js`] and [`BrowserToolset::with_file_upload`].
35///
36/// # Example
37///
38/// ```rust,ignore
39/// use adk_browser::{BrowserToolset, BrowserProfile, BrowserSession, BrowserConfig};
40/// use std::sync::Arc;
41///
42/// let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
43/// let toolset = BrowserToolset::with_profile(browser, BrowserProfile::FormFilling);
44/// let tools = toolset.all_tools(); // 20 tools instead of 45
45/// ```
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum BrowserProfile {
48    /// 20 tools: navigation + interaction + extraction + wait + screenshot.
49    /// Best for simple browsing tasks.
50    Minimal,
51    /// 20 tools: same categories as Minimal (navigation + interaction + extraction + wait + screenshot).
52    /// Best for form-filling agents.
53    FormFilling,
54    /// 14 tools: navigation + extraction + screenshot + scroll, hover, and alert handling.
55    /// Best for data extraction / scraping agents (no interaction tools).
56    Scraping,
57    /// 45 tools: every tool except `browser_evaluate_js` and `browser_file_upload`. Use
58    /// only when the agent needs full browser control.
59    Full,
60}
61
62/// A toolset that provides all browser automation tools.
63///
64/// Use this to add all browser tools to an agent at once, or use
65/// individual tools for more control.
66///
67/// Four defaults limit what a model can reach through the browser:
68///
69/// - `browser_evaluate_js`, which runs model-written JavaScript in the page, is
70///   off until [`with_evaluate_js`](Self::with_evaluate_js) or
71///   [`with_js`](Self::with_js) enables it.
72/// - `browser_file_upload` is off until [`with_file_upload`](Self::with_file_upload)
73///   names the directories files may be uploaded from.
74/// - Navigation accepts only `http` and `https` URLs until
75///   [`with_allowed_schemes`](Self::with_allowed_schemes) says otherwise, so
76///   `file:`, `javascript:`, `data:`, and browser-internal URLs are refused.
77/// - Navigation refuses loopback, private, link-local, and cloud metadata
78///   addresses until [`with_private_network_access`](Self::with_private_network_access)
79///   permits them, checks the page it ends on after redirects, and refuses host
80///   names that do not resolve on the agent host until
81///   [`with_unresolved_hosts`](Self::with_unresolved_hosts) permits them.
82pub struct BrowserToolset {
83    resolver: SessionResolver,
84    /// Include navigation tools (navigate, back, forward, refresh)
85    include_navigation: bool,
86    /// Include interaction tools (click, type, select)
87    include_interaction: bool,
88    /// Include extraction tools (extract text, attributes, links, page info)
89    include_extraction: bool,
90    /// Include wait tools
91    include_wait: bool,
92    /// Include screenshot tool
93    include_screenshot: bool,
94    /// Include the JavaScript helper tools (scroll, hover, alert handling)
95    include_js: bool,
96    /// Include `browser_evaluate_js`, which runs arbitrary model-written JavaScript
97    include_evaluate_js: bool,
98    /// Include cookie management tools
99    include_cookies: bool,
100    /// Include window/tab management tools
101    include_windows: bool,
102    /// Include frame/iframe management tools
103    include_frames: bool,
104    /// Include advanced action tools (drag-drop, focus, key presses, etc.)
105    include_actions: bool,
106    /// Directories `browser_file_upload` may read from; the tool is offered only when set
107    upload_roots: Option<Vec<PathBuf>>,
108    /// URL schemes the navigation and new-tab/window tools accept
109    allowed_schemes: Vec<String>,
110    /// Whether the navigation, history, and new-tab/window tools may open private network
111    /// addresses
112    allow_private_network: bool,
113    /// Whether those tools may open host names that do not resolve on the agent host
114    allow_unresolved_hosts: bool,
115    /// With sources, the navigation and new-tab/window tools open only URLs that appeared in
116    /// them
117    url_sources: Option<adk_core::egress::UrlSources>,
118}
119
120impl BrowserToolset {
121    /// Create a new toolset with every tool enabled except `browser_evaluate_js` and
122    /// `browser_file_upload`.
123    ///
124    /// Equivalent to [`with_profile`](Self::with_profile) with [`BrowserProfile::Full`].
125    pub fn new(browser: Arc<BrowserSession>) -> Self {
126        Self::from_profile(SessionResolver::Fixed(browser), BrowserProfile::Full)
127    }
128
129    /// Create a pool-backed toolset with every tool enabled except `browser_evaluate_js`
130    /// and `browser_file_upload`.
131    ///
132    /// Sessions are resolved per-user at runtime via `Toolset::tools(ctx)`.
133    /// The pool calls `get_or_create(ctx.user_id())` to obtain an isolated
134    /// browser session for each user.
135    ///
136    /// # Example
137    ///
138    /// ```rust,ignore
139    /// use adk_browser::{BrowserToolset, BrowserSessionPool, BrowserConfig};
140    /// use std::sync::Arc;
141    ///
142    /// let pool = Arc::new(BrowserSessionPool::new(BrowserConfig::default(), 10));
143    /// let toolset = BrowserToolset::with_pool(pool);
144    /// ```
145    pub fn with_pool(pool: Arc<BrowserSessionPool>) -> Self {
146        Self::from_profile(SessionResolver::Pool(pool), BrowserProfile::Full)
147    }
148
149    /// Create a pool-backed toolset with a pre-configured profile.
150    ///
151    /// Combines pool-backed session resolution with profile-based tool
152    /// category selection.
153    ///
154    /// # Example
155    ///
156    /// ```rust,ignore
157    /// use adk_browser::{BrowserToolset, BrowserProfile, BrowserSessionPool, BrowserConfig};
158    /// use std::sync::Arc;
159    ///
160    /// let pool = Arc::new(BrowserSessionPool::new(BrowserConfig::default(), 10));
161    /// let toolset = BrowserToolset::with_pool_and_profile(pool, BrowserProfile::Minimal);
162    /// ```
163    pub fn with_pool_and_profile(pool: Arc<BrowserSessionPool>, profile: BrowserProfile) -> Self {
164        Self::from_profile(SessionResolver::Pool(pool), profile)
165    }
166
167    /// Create a toolset with a pre-configured profile.
168    ///
169    /// This is the recommended way to create a toolset for most agents.
170    /// Using `BrowserProfile::Full` is equivalent to `BrowserToolset::new()`.
171    pub fn with_profile(browser: Arc<BrowserSession>, profile: BrowserProfile) -> Self {
172        Self::from_profile(SessionResolver::Fixed(browser), profile)
173    }
174
175    fn from_profile(resolver: SessionResolver, profile: BrowserProfile) -> Self {
176        let (interaction, wait, js, extended) = match profile {
177            BrowserProfile::Minimal | BrowserProfile::FormFilling => (true, true, false, false),
178            BrowserProfile::Scraping => (false, false, true, false),
179            BrowserProfile::Full => (true, true, true, true),
180        };
181        Self {
182            resolver,
183            include_navigation: true,
184            include_interaction: interaction,
185            include_extraction: true,
186            include_wait: wait,
187            include_screenshot: true,
188            include_js: js,
189            include_evaluate_js: false,
190            include_cookies: extended,
191            include_windows: extended,
192            include_frames: extended,
193            include_actions: extended,
194            upload_roots: None,
195            allowed_schemes: default_allowed_schemes(),
196            allow_private_network: false,
197            allow_unresolved_hosts: false,
198            url_sources: None,
199        }
200    }
201
202    /// Enable or disable navigation tools.
203    pub fn with_navigation(mut self, enabled: bool) -> Self {
204        self.include_navigation = enabled;
205        self
206    }
207
208    /// Enable or disable interaction tools.
209    pub fn with_interaction(mut self, enabled: bool) -> Self {
210        self.include_interaction = enabled;
211        self
212    }
213
214    /// Enable or disable extraction tools.
215    pub fn with_extraction(mut self, enabled: bool) -> Self {
216        self.include_extraction = enabled;
217        self
218    }
219
220    /// Enable or disable wait tools.
221    pub fn with_wait(mut self, enabled: bool) -> Self {
222        self.include_wait = enabled;
223        self
224    }
225
226    /// Enable or disable screenshot tool.
227    pub fn with_screenshot(mut self, enabled: bool) -> Self {
228        self.include_screenshot = enabled;
229        self
230    }
231
232    /// Enable or disable every JavaScript tool: scroll, hover, alert handling, and
233    /// `browser_evaluate_js`.
234    ///
235    /// `with_js(true)` is an explicit opt-in to `browser_evaluate_js`, which runs
236    /// model-written JavaScript in the page. To keep the helpers without it, follow
237    /// with `.with_evaluate_js(false)`.
238    pub fn with_js(mut self, enabled: bool) -> Self {
239        self.include_js = enabled;
240        self.include_evaluate_js = enabled;
241        self
242    }
243
244    /// Enable or disable `browser_evaluate_js`.
245    ///
246    /// Off by default. The tool runs arbitrary model-written JavaScript in the
247    /// current page, with the page's cookies and session, so a prompt-injected page
248    /// can steer it. Enable it only for agents that need it.
249    ///
250    /// # Example
251    ///
252    /// ```rust,ignore
253    /// use adk_browser::{BrowserConfig, BrowserSession, BrowserToolset};
254    /// use std::sync::Arc;
255    ///
256    /// let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
257    /// let toolset = BrowserToolset::new(browser).with_evaluate_js(true);
258    /// ```
259    pub fn with_evaluate_js(mut self, enabled: bool) -> Self {
260        self.include_evaluate_js = enabled;
261        self
262    }
263
264    /// Replace the URL schemes `browser_navigate`, `browser_new_tab`, and
265    /// `browser_new_window` accept.
266    ///
267    /// Defaults to [`DEFAULT_ALLOWED_SCHEMES`](crate::DEFAULT_ALLOWED_SCHEMES)
268    /// (`http`, `https`). Schemes are compared case-insensitively. Allowing `file`
269    /// exposes the host filesystem to the model, and allowing `javascript` or `data`
270    /// lets it run script without `browser_evaluate_js`.
271    ///
272    /// # Example
273    ///
274    /// ```rust,ignore
275    /// use adk_browser::{BrowserConfig, BrowserSession, BrowserToolset};
276    /// use std::sync::Arc;
277    ///
278    /// let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
279    /// // HTTPS only.
280    /// let toolset = BrowserToolset::new(browser).with_allowed_schemes(["https"]);
281    /// ```
282    #[must_use]
283    pub fn with_allowed_schemes<I, S>(mut self, schemes: I) -> Self
284    where
285        I: IntoIterator<Item = S>,
286        S: Into<String>,
287    {
288        self.allowed_schemes = schemes.into_iter().map(Into::into).collect();
289        self
290    }
291
292    /// Permit or refuse navigation to loopback, private, link-local, and cloud
293    /// metadata addresses.
294    ///
295    /// Refused by default, in `browser_navigate`, `browser_new_tab`, and
296    /// `browser_new_window`, and for the page those tools and `browser_back`,
297    /// `browser_forward`, and `browser_refresh` end on after redirects. Enable this
298    /// only for an agent meant to browse an internal network; see
299    /// [`NavigateTool::with_private_network_access`](crate::tools::NavigateTool::with_private_network_access).
300    ///
301    /// # Example
302    ///
303    /// ```rust,ignore
304    /// use adk_browser::{BrowserConfig, BrowserSession, BrowserToolset};
305    /// use std::sync::Arc;
306    ///
307    /// let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
308    /// let intranet = BrowserToolset::new(browser).with_private_network_access(true);
309    /// ```
310    #[must_use]
311    pub fn with_private_network_access(mut self, enabled: bool) -> Self {
312        self.allow_private_network = enabled;
313        self
314    }
315
316    /// Permit or refuse navigation to host names that do not resolve on the agent host.
317    ///
318    /// Refused by default, since the agent cannot check where such a name leads. Enable
319    /// this when the browser resolves names the agent host cannot, such as behind a proxy
320    /// or on a remote WebDriver host; see
321    /// [`NavigateTool::with_unresolved_hosts`](crate::tools::NavigateTool::with_unresolved_hosts).
322    ///
323    /// # Example
324    ///
325    /// ```rust,ignore
326    /// use adk_browser::{BrowserConfig, BrowserSession, BrowserToolset};
327    /// use std::sync::Arc;
328    ///
329    /// let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
330    /// let proxied = BrowserToolset::new(browser).with_unresolved_hosts(true);
331    /// ```
332    #[must_use]
333    pub fn with_unresolved_hosts(mut self, enabled: bool) -> Self {
334        self.allow_unresolved_hosts = enabled;
335        self
336    }
337
338    /// Open only URLs that already appeared in the conversation's `sources`: a user message
339    /// or a tool result, exactly as written there. Off by default.
340    ///
341    /// Applies to `browser_navigate`, `browser_new_tab` and `browser_new_window`; a URL the
342    /// model composed, for example with data appended to a query string, is refused with
343    /// [`URL_NOT_IN_CONTEXT_CODE`](crate::tools::URL_NOT_IN_CONTEXT_CODE) before the browser
344    /// moves. See [`NavigateTool::with_url_provenance`](crate::tools::NavigateTool::with_url_provenance).
345    ///
346    /// # Example
347    ///
348    /// ```rust,ignore
349    /// use adk_browser::{BrowserConfig, BrowserSession, BrowserToolset};
350    /// use adk_core::egress::UrlSources;
351    /// use std::sync::Arc;
352    ///
353    /// let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
354    /// let unattended = BrowserToolset::new(browser).with_url_provenance(UrlSources::default());
355    /// ```
356    #[must_use]
357    pub fn with_url_provenance(mut self, sources: adk_core::egress::UrlSources) -> Self {
358        self.url_sources = Some(sources);
359        self
360    }
361
362    /// Offer `browser_file_upload`, limited to files inside `roots`.
363    ///
364    /// Off by default in every profile. The tool resolves each model-chosen path,
365    /// symlinks included, and refuses anything that is not an existing file under a
366    /// resolved root, so point `roots` at directories that hold only what the agent
367    /// may hand to a web page.
368    ///
369    /// # Example
370    ///
371    /// ```rust,ignore
372    /// use adk_browser::{BrowserConfig, BrowserSession, BrowserToolset};
373    /// use std::sync::Arc;
374    ///
375    /// let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
376    /// let toolset = BrowserToolset::new(browser).with_file_upload(["/srv/agent/uploads"]);
377    /// ```
378    #[must_use]
379    pub fn with_file_upload<I, P>(mut self, roots: I) -> Self
380    where
381        I: IntoIterator<Item = P>,
382        P: Into<PathBuf>,
383    {
384        self.upload_roots = Some(roots.into_iter().map(Into::into).collect());
385        self
386    }
387
388    /// Enable or disable cookie management tools.
389    pub fn with_cookies(mut self, enabled: bool) -> Self {
390        self.include_cookies = enabled;
391        self
392    }
393
394    /// Enable or disable window/tab management tools.
395    pub fn with_windows(mut self, enabled: bool) -> Self {
396        self.include_windows = enabled;
397        self
398    }
399
400    /// Enable or disable frame/iframe management tools.
401    pub fn with_frames(mut self, enabled: bool) -> Self {
402        self.include_frames = enabled;
403        self
404    }
405
406    /// Enable or disable advanced action tools.
407    pub fn with_actions(mut self, enabled: bool) -> Self {
408        self.include_actions = enabled;
409        self
410    }
411
412    /// Get all tools as a vector (synchronous version).
413    ///
414    /// Works for fixed-session toolsets. For pool-backed toolsets,
415    /// returns an empty vec with a warning — use `Toolset::tools(ctx)` or
416    /// `try_all_tools()` instead.
417    pub fn all_tools(&self) -> Vec<Arc<dyn Tool>> {
418        match &self.resolver {
419            SessionResolver::Fixed(session) => self.build_tools(session.clone()),
420            SessionResolver::Pool(_) => {
421                tracing::warn!(
422                    "BrowserToolset::all_tools() called on a pool-backed toolset. \
423                     Returns empty vec. Use Toolset::tools(ctx) instead."
424                );
425                Vec::new()
426            }
427        }
428    }
429
430    /// Try to get all tools synchronously. Returns an error for pool-backed toolsets.
431    ///
432    /// Prefer `Toolset::tools(ctx)` for pool-backed toolsets.
433    pub fn try_all_tools(&self) -> Result<Vec<Arc<dyn Tool>>> {
434        match &self.resolver {
435            SessionResolver::Fixed(session) => Ok(self.build_tools(session.clone())),
436            SessionResolver::Pool(_) => Err(adk_core::AdkError::tool(
437                "Cannot resolve tools synchronously for a pool-backed BrowserToolset. \
438                 Use Toolset::tools(ctx) instead.",
439            )),
440        }
441    }
442
443    /// Internal: build tool instances from a resolved session.
444    fn build_tools(&self, browser: Arc<BrowserSession>) -> Vec<Arc<dyn Tool>> {
445        let mut tools: Vec<Arc<dyn Tool>> = Vec::new();
446
447        if self.include_navigation {
448            tools.push(Arc::new(
449                NavigateTool::new(browser.clone())
450                    .with_allowed_schemes(self.allowed_schemes.clone())
451                    .with_private_network_access(self.allow_private_network)
452                    .with_unresolved_hosts(self.allow_unresolved_hosts)
453                    .with_url_provenance(self.url_sources.clone()),
454            ));
455            tools.push(Arc::new(
456                BackTool::new(browser.clone())
457                    .with_private_network_access(self.allow_private_network)
458                    .with_unresolved_hosts(self.allow_unresolved_hosts),
459            ));
460            tools.push(Arc::new(
461                ForwardTool::new(browser.clone())
462                    .with_private_network_access(self.allow_private_network)
463                    .with_unresolved_hosts(self.allow_unresolved_hosts),
464            ));
465            tools.push(Arc::new(
466                RefreshTool::new(browser.clone())
467                    .with_private_network_access(self.allow_private_network)
468                    .with_unresolved_hosts(self.allow_unresolved_hosts),
469            ));
470        }
471
472        if self.include_interaction {
473            tools.push(Arc::new(ClickTool::new(browser.clone())));
474            tools.push(Arc::new(DoubleClickTool::new(browser.clone())));
475            tools.push(Arc::new(TypeTool::new(browser.clone())));
476            tools.push(Arc::new(ClearTool::new(browser.clone())));
477            tools.push(Arc::new(SelectTool::new(browser.clone())));
478        }
479
480        if self.include_extraction {
481            tools.push(Arc::new(ExtractTextTool::new(browser.clone())));
482            tools.push(Arc::new(ExtractAttributeTool::new(browser.clone())));
483            tools.push(Arc::new(ExtractLinksTool::new(browser.clone())));
484            tools.push(Arc::new(PageInfoTool::new(browser.clone())));
485            tools.push(Arc::new(PageSourceTool::new(browser.clone())));
486            tools.push(Arc::new(ElementsTool::new(browser.clone())));
487        }
488
489        if self.include_wait {
490            tools.push(Arc::new(WaitForElementTool::new(browser.clone())));
491            tools.push(Arc::new(WaitTool::new()));
492            tools.push(Arc::new(WaitForPageLoadTool::new(browser.clone())));
493            tools.push(Arc::new(WaitForTextTool::new(browser.clone())));
494        }
495
496        if self.include_screenshot {
497            tools.push(Arc::new(ScreenshotTool::new(browser.clone())));
498        }
499
500        if self.include_evaluate_js {
501            tools.push(Arc::new(EvaluateJsTool::new(browser.clone())));
502        }
503
504        if self.include_js {
505            tools.push(Arc::new(ScrollTool::new(browser.clone())));
506            tools.push(Arc::new(HoverTool::new(browser.clone())));
507            tools.push(Arc::new(AlertTool::new(browser.clone())));
508        }
509
510        if self.include_cookies {
511            tools.push(Arc::new(GetCookiesTool::new(browser.clone())));
512            tools.push(Arc::new(GetCookieTool::new(browser.clone())));
513            tools.push(Arc::new(AddCookieTool::new(browser.clone())));
514            tools.push(Arc::new(DeleteCookieTool::new(browser.clone())));
515            tools.push(Arc::new(DeleteAllCookiesTool::new(browser.clone())));
516        }
517
518        if self.include_windows {
519            tools.push(Arc::new(ListWindowsTool::new(browser.clone())));
520            tools.push(Arc::new(
521                NewTabTool::new(browser.clone())
522                    .with_allowed_schemes(self.allowed_schemes.clone())
523                    .with_private_network_access(self.allow_private_network)
524                    .with_unresolved_hosts(self.allow_unresolved_hosts)
525                    .with_url_provenance(self.url_sources.clone()),
526            ));
527            tools.push(Arc::new(
528                NewWindowTool::new(browser.clone())
529                    .with_allowed_schemes(self.allowed_schemes.clone())
530                    .with_private_network_access(self.allow_private_network)
531                    .with_unresolved_hosts(self.allow_unresolved_hosts)
532                    .with_url_provenance(self.url_sources.clone()),
533            ));
534            tools.push(Arc::new(SwitchWindowTool::new(browser.clone())));
535            tools.push(Arc::new(CloseWindowTool::new(browser.clone())));
536            tools.push(Arc::new(MaximizeWindowTool::new(browser.clone())));
537            tools.push(Arc::new(MinimizeWindowTool::new(browser.clone())));
538            tools.push(Arc::new(SetWindowSizeTool::new(browser.clone())));
539        }
540
541        if self.include_frames {
542            tools.push(Arc::new(SwitchToFrameTool::new(browser.clone())));
543            tools.push(Arc::new(SwitchToParentFrameTool::new(browser.clone())));
544            tools.push(Arc::new(SwitchToDefaultContentTool::new(browser.clone())));
545        }
546
547        if self.include_actions {
548            tools.push(Arc::new(DragAndDropTool::new(browser.clone())));
549            tools.push(Arc::new(RightClickTool::new(browser.clone())));
550            tools.push(Arc::new(FocusTool::new(browser.clone())));
551            tools.push(Arc::new(ElementStateTool::new(browser.clone())));
552            tools.push(Arc::new(PressKeyTool::new(browser.clone())));
553            tools.push(Arc::new(PrintToPdfTool::new(browser.clone())));
554        }
555
556        if let Some(roots) = &self.upload_roots {
557            tools.push(Arc::new(FileUploadTool::new(browser).with_allowed_roots(roots.clone())));
558        }
559
560        tools
561    }
562}
563
564#[async_trait]
565impl Toolset for BrowserToolset {
566    fn name(&self) -> &str {
567        "browser"
568    }
569
570    async fn tools(&self, ctx: Arc<dyn ReadonlyContext>) -> Result<Vec<Arc<dyn Tool>>> {
571        let session = self.resolver.resolve(&ctx).await?;
572        Ok(self.build_tools(session))
573    }
574}
575
576/// Helper function to create a minimal browser toolset with only essential tools.
577pub fn minimal_browser_tools(browser: Arc<BrowserSession>) -> Vec<Arc<dyn Tool>> {
578    vec![
579        Arc::new(NavigateTool::new(browser.clone())),
580        Arc::new(ClickTool::new(browser.clone())),
581        Arc::new(TypeTool::new(browser.clone())),
582        Arc::new(ExtractTextTool::new(browser.clone())),
583        Arc::new(WaitForElementTool::new(browser.clone())),
584        Arc::new(ScreenshotTool::new(browser)),
585    ]
586}
587
588/// Helper function to create a read-only browser toolset (no interaction).
589pub fn readonly_browser_tools(browser: Arc<BrowserSession>) -> Vec<Arc<dyn Tool>> {
590    vec![
591        Arc::new(NavigateTool::new(browser.clone())),
592        Arc::new(ExtractTextTool::new(browser.clone())),
593        Arc::new(ExtractAttributeTool::new(browser.clone())),
594        Arc::new(ExtractLinksTool::new(browser.clone())),
595        Arc::new(PageInfoTool::new(browser.clone())),
596        Arc::new(ScreenshotTool::new(browser.clone())),
597        Arc::new(ScrollTool::new(browser)),
598    ]
599}
600
601#[cfg(test)]
602mod tests {
603    use super::*;
604    use crate::config::BrowserConfig;
605
606    #[test]
607    fn test_toolset_all_tools() {
608        let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
609        let toolset = BrowserToolset::new(browser);
610        let tools = toolset.all_tools();
611
612        // Every tool except browser_evaluate_js and browser_file_upload (45)
613        assert_eq!(tools.len(), 45);
614
615        // Check some tool names exist
616        let tool_names: Vec<&str> = tools.iter().map(|t| t.name()).collect();
617        assert!(tool_names.contains(&"browser_navigate"));
618        assert!(tool_names.contains(&"browser_click"));
619        assert!(tool_names.contains(&"browser_type"));
620        assert!(tool_names.contains(&"browser_screenshot"));
621        assert!(tool_names.contains(&"browser_elements"));
622        // New tools
623        assert!(tool_names.contains(&"browser_get_cookies"));
624        assert!(tool_names.contains(&"browser_new_tab"));
625        assert!(tool_names.contains(&"browser_switch_to_frame"));
626        assert!(tool_names.contains(&"browser_drag_and_drop"));
627    }
628
629    #[test]
630    fn test_toolset_selective() {
631        let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
632        let toolset = BrowserToolset::new(browser)
633            .with_navigation(true)
634            .with_interaction(false)
635            .with_extraction(false)
636            .with_wait(false)
637            .with_screenshot(false)
638            .with_js(false)
639            .with_cookies(false)
640            .with_windows(false)
641            .with_frames(false)
642            .with_actions(false);
643
644        let tools = toolset.all_tools();
645
646        // Should only have navigation tools
647        assert_eq!(tools.len(), 4);
648    }
649
650    #[test]
651    fn test_minimal_tools() {
652        let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
653        let tools = minimal_browser_tools(browser);
654
655        assert_eq!(tools.len(), 6);
656    }
657
658    #[test]
659    fn test_profile_form_filling() {
660        let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
661        let toolset = BrowserToolset::with_profile(browser, BrowserProfile::FormFilling);
662        let tools = toolset.all_tools();
663
664        // Navigation (4) + Interaction (5) + Extraction (6) + Wait (4) + Screenshot (1) = 20
665        let tool_names: Vec<&str> = tools.iter().map(|t| t.name()).collect();
666        assert!(tool_names.contains(&"browser_navigate"));
667        assert!(tool_names.contains(&"browser_click"));
668        assert!(tool_names.contains(&"browser_type"));
669        assert!(tool_names.contains(&"browser_select"));
670        assert!(tool_names.contains(&"browser_clear"));
671        assert!(tool_names.contains(&"browser_screenshot"));
672        // Should NOT include cookies, windows, frames, actions
673        assert!(!tool_names.contains(&"browser_get_cookies"));
674        assert!(!tool_names.contains(&"browser_new_tab"));
675        assert!(!tool_names.contains(&"browser_switch_to_frame"));
676        assert!(!tool_names.contains(&"browser_drag_and_drop"));
677    }
678
679    #[test]
680    fn test_profile_scraping() {
681        let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
682        let toolset = BrowserToolset::with_profile(browser, BrowserProfile::Scraping);
683        let tools = toolset.all_tools();
684
685        let tool_names: Vec<&str> = tools.iter().map(|t| t.name()).collect();
686        assert!(tool_names.contains(&"browser_navigate"));
687        assert!(tool_names.contains(&"browser_extract_text"));
688        assert!(tool_names.contains(&"browser_extract_links"));
689        assert!(tool_names.contains(&"browser_screenshot"));
690        assert!(tool_names.contains(&"browser_scroll"));
691        // Should NOT include interaction tools
692        assert!(!tool_names.contains(&"browser_click"));
693        assert!(!tool_names.contains(&"browser_type"));
694    }
695
696    #[test]
697    fn test_profile_full_matches_new() {
698        let browser1 = Arc::new(BrowserSession::new(BrowserConfig::default()));
699        let browser2 = Arc::new(BrowserSession::new(BrowserConfig::default()));
700        let full = BrowserToolset::with_profile(browser1, BrowserProfile::Full);
701        let default = BrowserToolset::new(browser2);
702        assert_eq!(full.all_tools().len(), default.all_tools().len());
703    }
704}