adk-browser 3.0.0

Browser automation tools for Rust Agent Development Kit (ADK-Rust) agents using WebDriver
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
//! Browser toolset that provides all browser tools as a collection.

use crate::pool::BrowserSessionPool;
use crate::session::BrowserSession;
use crate::tools::*;
use adk_core::{ReadonlyContext, Result, Tool, Toolset};
use async_trait::async_trait;
use std::path::PathBuf;
use std::sync::Arc;

/// Internal abstraction for session acquisition.
/// Not exposed in the public API.
enum SessionResolver {
    /// Fixed session — always returns the same session.
    Fixed(Arc<BrowserSession>),
    /// Pool-backed — resolves session from pool using user_id from context.
    Pool(Arc<BrowserSessionPool>),
}

impl SessionResolver {
    async fn resolve(&self, ctx: &Arc<dyn ReadonlyContext>) -> Result<Arc<BrowserSession>> {
        match self {
            SessionResolver::Fixed(session) => Ok(session.clone()),
            SessionResolver::Pool(pool) => pool.get_or_create(ctx.user_id()).await,
        }
    }
}

/// Pre-configured tool profiles for common use cases.
///
/// Instead of using every tool (which overwhelms LLM context windows),
/// select a profile that matches your agent's task. No profile includes
/// `browser_evaluate_js` or `browser_file_upload`; enable them with
/// [`BrowserToolset::with_evaluate_js`] and [`BrowserToolset::with_file_upload`].
///
/// # Example
///
/// ```rust,ignore
/// use adk_browser::{BrowserToolset, BrowserProfile, BrowserSession, BrowserConfig};
/// use std::sync::Arc;
///
/// let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
/// let toolset = BrowserToolset::with_profile(browser, BrowserProfile::FormFilling);
/// let tools = toolset.all_tools(); // 20 tools instead of 45
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BrowserProfile {
    /// 20 tools: navigation + interaction + extraction + wait + screenshot.
    /// Best for simple browsing tasks.
    Minimal,
    /// 20 tools: same categories as Minimal (navigation + interaction + extraction + wait + screenshot).
    /// Best for form-filling agents.
    FormFilling,
    /// 14 tools: navigation + extraction + screenshot + scroll, hover, and alert handling.
    /// Best for data extraction / scraping agents (no interaction tools).
    Scraping,
    /// 45 tools: every tool except `browser_evaluate_js` and `browser_file_upload`. Use
    /// only when the agent needs full browser control.
    Full,
}

/// A toolset that provides all browser automation tools.
///
/// Use this to add all browser tools to an agent at once, or use
/// individual tools for more control.
///
/// Four defaults limit what a model can reach through the browser:
///
/// - `browser_evaluate_js`, which runs model-written JavaScript in the page, is
///   off until [`with_evaluate_js`](Self::with_evaluate_js) or
///   [`with_js`](Self::with_js) enables it.
/// - `browser_file_upload` is off until [`with_file_upload`](Self::with_file_upload)
///   names the directories files may be uploaded from.
/// - Navigation accepts only `http` and `https` URLs until
///   [`with_allowed_schemes`](Self::with_allowed_schemes) says otherwise, so
///   `file:`, `javascript:`, `data:`, and browser-internal URLs are refused.
/// - Navigation refuses loopback, private, link-local, and cloud metadata
///   addresses until [`with_private_network_access`](Self::with_private_network_access)
///   permits them, checks the page it ends on after redirects, and refuses host
///   names that do not resolve on the agent host until
///   [`with_unresolved_hosts`](Self::with_unresolved_hosts) permits them.
pub struct BrowserToolset {
    resolver: SessionResolver,
    /// Include navigation tools (navigate, back, forward, refresh)
    include_navigation: bool,
    /// Include interaction tools (click, type, select)
    include_interaction: bool,
    /// Include extraction tools (extract text, attributes, links, page info)
    include_extraction: bool,
    /// Include wait tools
    include_wait: bool,
    /// Include screenshot tool
    include_screenshot: bool,
    /// Include the JavaScript helper tools (scroll, hover, alert handling)
    include_js: bool,
    /// Include `browser_evaluate_js`, which runs arbitrary model-written JavaScript
    include_evaluate_js: bool,
    /// Include cookie management tools
    include_cookies: bool,
    /// Include window/tab management tools
    include_windows: bool,
    /// Include frame/iframe management tools
    include_frames: bool,
    /// Include advanced action tools (drag-drop, focus, key presses, etc.)
    include_actions: bool,
    /// Directories `browser_file_upload` may read from; the tool is offered only when set
    upload_roots: Option<Vec<PathBuf>>,
    /// URL schemes the navigation and new-tab/window tools accept
    allowed_schemes: Vec<String>,
    /// Whether the navigation, history, and new-tab/window tools may open private network
    /// addresses
    allow_private_network: bool,
    /// Whether those tools may open host names that do not resolve on the agent host
    allow_unresolved_hosts: bool,
    /// With sources, the navigation and new-tab/window tools open only URLs that appeared in
    /// them
    url_sources: Option<adk_core::egress::UrlSources>,
}

impl BrowserToolset {
    /// Create a new toolset with every tool enabled except `browser_evaluate_js` and
    /// `browser_file_upload`.
    ///
    /// Equivalent to [`with_profile`](Self::with_profile) with [`BrowserProfile::Full`].
    pub fn new(browser: Arc<BrowserSession>) -> Self {
        Self::from_profile(SessionResolver::Fixed(browser), BrowserProfile::Full)
    }

    /// Create a pool-backed toolset with every tool enabled except `browser_evaluate_js`
    /// and `browser_file_upload`.
    ///
    /// Sessions are resolved per-user at runtime via `Toolset::tools(ctx)`.
    /// The pool calls `get_or_create(ctx.user_id())` to obtain an isolated
    /// browser session for each user.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_browser::{BrowserToolset, BrowserSessionPool, BrowserConfig};
    /// use std::sync::Arc;
    ///
    /// let pool = Arc::new(BrowserSessionPool::new(BrowserConfig::default(), 10));
    /// let toolset = BrowserToolset::with_pool(pool);
    /// ```
    pub fn with_pool(pool: Arc<BrowserSessionPool>) -> Self {
        Self::from_profile(SessionResolver::Pool(pool), BrowserProfile::Full)
    }

    /// Create a pool-backed toolset with a pre-configured profile.
    ///
    /// Combines pool-backed session resolution with profile-based tool
    /// category selection.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_browser::{BrowserToolset, BrowserProfile, BrowserSessionPool, BrowserConfig};
    /// use std::sync::Arc;
    ///
    /// let pool = Arc::new(BrowserSessionPool::new(BrowserConfig::default(), 10));
    /// let toolset = BrowserToolset::with_pool_and_profile(pool, BrowserProfile::Minimal);
    /// ```
    pub fn with_pool_and_profile(pool: Arc<BrowserSessionPool>, profile: BrowserProfile) -> Self {
        Self::from_profile(SessionResolver::Pool(pool), profile)
    }

    /// Create a toolset with a pre-configured profile.
    ///
    /// This is the recommended way to create a toolset for most agents.
    /// Using `BrowserProfile::Full` is equivalent to `BrowserToolset::new()`.
    pub fn with_profile(browser: Arc<BrowserSession>, profile: BrowserProfile) -> Self {
        Self::from_profile(SessionResolver::Fixed(browser), profile)
    }

    fn from_profile(resolver: SessionResolver, profile: BrowserProfile) -> Self {
        let (interaction, wait, js, extended) = match profile {
            BrowserProfile::Minimal | BrowserProfile::FormFilling => (true, true, false, false),
            BrowserProfile::Scraping => (false, false, true, false),
            BrowserProfile::Full => (true, true, true, true),
        };
        Self {
            resolver,
            include_navigation: true,
            include_interaction: interaction,
            include_extraction: true,
            include_wait: wait,
            include_screenshot: true,
            include_js: js,
            include_evaluate_js: false,
            include_cookies: extended,
            include_windows: extended,
            include_frames: extended,
            include_actions: extended,
            upload_roots: None,
            allowed_schemes: default_allowed_schemes(),
            allow_private_network: false,
            allow_unresolved_hosts: false,
            url_sources: None,
        }
    }

    /// Enable or disable navigation tools.
    pub fn with_navigation(mut self, enabled: bool) -> Self {
        self.include_navigation = enabled;
        self
    }

    /// Enable or disable interaction tools.
    pub fn with_interaction(mut self, enabled: bool) -> Self {
        self.include_interaction = enabled;
        self
    }

    /// Enable or disable extraction tools.
    pub fn with_extraction(mut self, enabled: bool) -> Self {
        self.include_extraction = enabled;
        self
    }

    /// Enable or disable wait tools.
    pub fn with_wait(mut self, enabled: bool) -> Self {
        self.include_wait = enabled;
        self
    }

    /// Enable or disable screenshot tool.
    pub fn with_screenshot(mut self, enabled: bool) -> Self {
        self.include_screenshot = enabled;
        self
    }

    /// Enable or disable every JavaScript tool: scroll, hover, alert handling, and
    /// `browser_evaluate_js`.
    ///
    /// `with_js(true)` is an explicit opt-in to `browser_evaluate_js`, which runs
    /// model-written JavaScript in the page. To keep the helpers without it, follow
    /// with `.with_evaluate_js(false)`.
    pub fn with_js(mut self, enabled: bool) -> Self {
        self.include_js = enabled;
        self.include_evaluate_js = enabled;
        self
    }

    /// Enable or disable `browser_evaluate_js`.
    ///
    /// Off by default. The tool runs arbitrary model-written JavaScript in the
    /// current page, with the page's cookies and session, so a prompt-injected page
    /// can steer it. Enable it only for agents that need it.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_browser::{BrowserConfig, BrowserSession, BrowserToolset};
    /// use std::sync::Arc;
    ///
    /// let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
    /// let toolset = BrowserToolset::new(browser).with_evaluate_js(true);
    /// ```
    pub fn with_evaluate_js(mut self, enabled: bool) -> Self {
        self.include_evaluate_js = enabled;
        self
    }

    /// Replace the URL schemes `browser_navigate`, `browser_new_tab`, and
    /// `browser_new_window` accept.
    ///
    /// Defaults to [`DEFAULT_ALLOWED_SCHEMES`](crate::DEFAULT_ALLOWED_SCHEMES)
    /// (`http`, `https`). Schemes are compared case-insensitively. Allowing `file`
    /// exposes the host filesystem to the model, and allowing `javascript` or `data`
    /// lets it run script without `browser_evaluate_js`.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_browser::{BrowserConfig, BrowserSession, BrowserToolset};
    /// use std::sync::Arc;
    ///
    /// let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
    /// // HTTPS only.
    /// let toolset = BrowserToolset::new(browser).with_allowed_schemes(["https"]);
    /// ```
    #[must_use]
    pub fn with_allowed_schemes<I, S>(mut self, schemes: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.allowed_schemes = schemes.into_iter().map(Into::into).collect();
        self
    }

    /// Permit or refuse navigation to loopback, private, link-local, and cloud
    /// metadata addresses.
    ///
    /// Refused by default, in `browser_navigate`, `browser_new_tab`, and
    /// `browser_new_window`, and for the page those tools and `browser_back`,
    /// `browser_forward`, and `browser_refresh` end on after redirects. Enable this
    /// only for an agent meant to browse an internal network; see
    /// [`NavigateTool::with_private_network_access`](crate::tools::NavigateTool::with_private_network_access).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_browser::{BrowserConfig, BrowserSession, BrowserToolset};
    /// use std::sync::Arc;
    ///
    /// let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
    /// let intranet = BrowserToolset::new(browser).with_private_network_access(true);
    /// ```
    #[must_use]
    pub fn with_private_network_access(mut self, enabled: bool) -> Self {
        self.allow_private_network = enabled;
        self
    }

    /// Permit or refuse navigation to host names that do not resolve on the agent host.
    ///
    /// Refused by default, since the agent cannot check where such a name leads. Enable
    /// this when the browser resolves names the agent host cannot, such as behind a proxy
    /// or on a remote WebDriver host; see
    /// [`NavigateTool::with_unresolved_hosts`](crate::tools::NavigateTool::with_unresolved_hosts).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_browser::{BrowserConfig, BrowserSession, BrowserToolset};
    /// use std::sync::Arc;
    ///
    /// let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
    /// let proxied = BrowserToolset::new(browser).with_unresolved_hosts(true);
    /// ```
    #[must_use]
    pub fn with_unresolved_hosts(mut self, enabled: bool) -> Self {
        self.allow_unresolved_hosts = enabled;
        self
    }

    /// Open only URLs that already appeared in the conversation's `sources`: a user message
    /// or a tool result, exactly as written there. Off by default.
    ///
    /// Applies to `browser_navigate`, `browser_new_tab` and `browser_new_window`; a URL the
    /// model composed, for example with data appended to a query string, is refused with
    /// [`URL_NOT_IN_CONTEXT_CODE`](crate::tools::URL_NOT_IN_CONTEXT_CODE) before the browser
    /// moves. See [`NavigateTool::with_url_provenance`](crate::tools::NavigateTool::with_url_provenance).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_browser::{BrowserConfig, BrowserSession, BrowserToolset};
    /// use adk_core::egress::UrlSources;
    /// use std::sync::Arc;
    ///
    /// let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
    /// let unattended = BrowserToolset::new(browser).with_url_provenance(UrlSources::default());
    /// ```
    #[must_use]
    pub fn with_url_provenance(mut self, sources: adk_core::egress::UrlSources) -> Self {
        self.url_sources = Some(sources);
        self
    }

    /// Offer `browser_file_upload`, limited to files inside `roots`.
    ///
    /// Off by default in every profile. The tool resolves each model-chosen path,
    /// symlinks included, and refuses anything that is not an existing file under a
    /// resolved root, so point `roots` at directories that hold only what the agent
    /// may hand to a web page.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_browser::{BrowserConfig, BrowserSession, BrowserToolset};
    /// use std::sync::Arc;
    ///
    /// let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
    /// let toolset = BrowserToolset::new(browser).with_file_upload(["/srv/agent/uploads"]);
    /// ```
    #[must_use]
    pub fn with_file_upload<I, P>(mut self, roots: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: Into<PathBuf>,
    {
        self.upload_roots = Some(roots.into_iter().map(Into::into).collect());
        self
    }

    /// Enable or disable cookie management tools.
    pub fn with_cookies(mut self, enabled: bool) -> Self {
        self.include_cookies = enabled;
        self
    }

    /// Enable or disable window/tab management tools.
    pub fn with_windows(mut self, enabled: bool) -> Self {
        self.include_windows = enabled;
        self
    }

    /// Enable or disable frame/iframe management tools.
    pub fn with_frames(mut self, enabled: bool) -> Self {
        self.include_frames = enabled;
        self
    }

    /// Enable or disable advanced action tools.
    pub fn with_actions(mut self, enabled: bool) -> Self {
        self.include_actions = enabled;
        self
    }

    /// Get all tools as a vector (synchronous version).
    ///
    /// Works for fixed-session toolsets. For pool-backed toolsets,
    /// returns an empty vec with a warning — use `Toolset::tools(ctx)` or
    /// `try_all_tools()` instead.
    pub fn all_tools(&self) -> Vec<Arc<dyn Tool>> {
        match &self.resolver {
            SessionResolver::Fixed(session) => self.build_tools(session.clone()),
            SessionResolver::Pool(_) => {
                tracing::warn!(
                    "BrowserToolset::all_tools() called on a pool-backed toolset. \
                     Returns empty vec. Use Toolset::tools(ctx) instead."
                );
                Vec::new()
            }
        }
    }

    /// Try to get all tools synchronously. Returns an error for pool-backed toolsets.
    ///
    /// Prefer `Toolset::tools(ctx)` for pool-backed toolsets.
    pub fn try_all_tools(&self) -> Result<Vec<Arc<dyn Tool>>> {
        match &self.resolver {
            SessionResolver::Fixed(session) => Ok(self.build_tools(session.clone())),
            SessionResolver::Pool(_) => Err(adk_core::AdkError::tool(
                "Cannot resolve tools synchronously for a pool-backed BrowserToolset. \
                 Use Toolset::tools(ctx) instead.",
            )),
        }
    }

    /// Internal: build tool instances from a resolved session.
    fn build_tools(&self, browser: Arc<BrowserSession>) -> Vec<Arc<dyn Tool>> {
        let mut tools: Vec<Arc<dyn Tool>> = Vec::new();

        if self.include_navigation {
            tools.push(Arc::new(
                NavigateTool::new(browser.clone())
                    .with_allowed_schemes(self.allowed_schemes.clone())
                    .with_private_network_access(self.allow_private_network)
                    .with_unresolved_hosts(self.allow_unresolved_hosts)
                    .with_url_provenance(self.url_sources.clone()),
            ));
            tools.push(Arc::new(
                BackTool::new(browser.clone())
                    .with_private_network_access(self.allow_private_network)
                    .with_unresolved_hosts(self.allow_unresolved_hosts),
            ));
            tools.push(Arc::new(
                ForwardTool::new(browser.clone())
                    .with_private_network_access(self.allow_private_network)
                    .with_unresolved_hosts(self.allow_unresolved_hosts),
            ));
            tools.push(Arc::new(
                RefreshTool::new(browser.clone())
                    .with_private_network_access(self.allow_private_network)
                    .with_unresolved_hosts(self.allow_unresolved_hosts),
            ));
        }

        if self.include_interaction {
            tools.push(Arc::new(ClickTool::new(browser.clone())));
            tools.push(Arc::new(DoubleClickTool::new(browser.clone())));
            tools.push(Arc::new(TypeTool::new(browser.clone())));
            tools.push(Arc::new(ClearTool::new(browser.clone())));
            tools.push(Arc::new(SelectTool::new(browser.clone())));
        }

        if self.include_extraction {
            tools.push(Arc::new(ExtractTextTool::new(browser.clone())));
            tools.push(Arc::new(ExtractAttributeTool::new(browser.clone())));
            tools.push(Arc::new(ExtractLinksTool::new(browser.clone())));
            tools.push(Arc::new(PageInfoTool::new(browser.clone())));
            tools.push(Arc::new(PageSourceTool::new(browser.clone())));
            tools.push(Arc::new(ElementsTool::new(browser.clone())));
        }

        if self.include_wait {
            tools.push(Arc::new(WaitForElementTool::new(browser.clone())));
            tools.push(Arc::new(WaitTool::new()));
            tools.push(Arc::new(WaitForPageLoadTool::new(browser.clone())));
            tools.push(Arc::new(WaitForTextTool::new(browser.clone())));
        }

        if self.include_screenshot {
            tools.push(Arc::new(ScreenshotTool::new(browser.clone())));
        }

        if self.include_evaluate_js {
            tools.push(Arc::new(EvaluateJsTool::new(browser.clone())));
        }

        if self.include_js {
            tools.push(Arc::new(ScrollTool::new(browser.clone())));
            tools.push(Arc::new(HoverTool::new(browser.clone())));
            tools.push(Arc::new(AlertTool::new(browser.clone())));
        }

        if self.include_cookies {
            tools.push(Arc::new(GetCookiesTool::new(browser.clone())));
            tools.push(Arc::new(GetCookieTool::new(browser.clone())));
            tools.push(Arc::new(AddCookieTool::new(browser.clone())));
            tools.push(Arc::new(DeleteCookieTool::new(browser.clone())));
            tools.push(Arc::new(DeleteAllCookiesTool::new(browser.clone())));
        }

        if self.include_windows {
            tools.push(Arc::new(ListWindowsTool::new(browser.clone())));
            tools.push(Arc::new(
                NewTabTool::new(browser.clone())
                    .with_allowed_schemes(self.allowed_schemes.clone())
                    .with_private_network_access(self.allow_private_network)
                    .with_unresolved_hosts(self.allow_unresolved_hosts)
                    .with_url_provenance(self.url_sources.clone()),
            ));
            tools.push(Arc::new(
                NewWindowTool::new(browser.clone())
                    .with_allowed_schemes(self.allowed_schemes.clone())
                    .with_private_network_access(self.allow_private_network)
                    .with_unresolved_hosts(self.allow_unresolved_hosts)
                    .with_url_provenance(self.url_sources.clone()),
            ));
            tools.push(Arc::new(SwitchWindowTool::new(browser.clone())));
            tools.push(Arc::new(CloseWindowTool::new(browser.clone())));
            tools.push(Arc::new(MaximizeWindowTool::new(browser.clone())));
            tools.push(Arc::new(MinimizeWindowTool::new(browser.clone())));
            tools.push(Arc::new(SetWindowSizeTool::new(browser.clone())));
        }

        if self.include_frames {
            tools.push(Arc::new(SwitchToFrameTool::new(browser.clone())));
            tools.push(Arc::new(SwitchToParentFrameTool::new(browser.clone())));
            tools.push(Arc::new(SwitchToDefaultContentTool::new(browser.clone())));
        }

        if self.include_actions {
            tools.push(Arc::new(DragAndDropTool::new(browser.clone())));
            tools.push(Arc::new(RightClickTool::new(browser.clone())));
            tools.push(Arc::new(FocusTool::new(browser.clone())));
            tools.push(Arc::new(ElementStateTool::new(browser.clone())));
            tools.push(Arc::new(PressKeyTool::new(browser.clone())));
            tools.push(Arc::new(PrintToPdfTool::new(browser.clone())));
        }

        if let Some(roots) = &self.upload_roots {
            tools.push(Arc::new(FileUploadTool::new(browser).with_allowed_roots(roots.clone())));
        }

        tools
    }
}

#[async_trait]
impl Toolset for BrowserToolset {
    fn name(&self) -> &str {
        "browser"
    }

    async fn tools(&self, ctx: Arc<dyn ReadonlyContext>) -> Result<Vec<Arc<dyn Tool>>> {
        let session = self.resolver.resolve(&ctx).await?;
        Ok(self.build_tools(session))
    }
}

/// Helper function to create a minimal browser toolset with only essential tools.
pub fn minimal_browser_tools(browser: Arc<BrowserSession>) -> Vec<Arc<dyn Tool>> {
    vec![
        Arc::new(NavigateTool::new(browser.clone())),
        Arc::new(ClickTool::new(browser.clone())),
        Arc::new(TypeTool::new(browser.clone())),
        Arc::new(ExtractTextTool::new(browser.clone())),
        Arc::new(WaitForElementTool::new(browser.clone())),
        Arc::new(ScreenshotTool::new(browser)),
    ]
}

/// Helper function to create a read-only browser toolset (no interaction).
pub fn readonly_browser_tools(browser: Arc<BrowserSession>) -> Vec<Arc<dyn Tool>> {
    vec![
        Arc::new(NavigateTool::new(browser.clone())),
        Arc::new(ExtractTextTool::new(browser.clone())),
        Arc::new(ExtractAttributeTool::new(browser.clone())),
        Arc::new(ExtractLinksTool::new(browser.clone())),
        Arc::new(PageInfoTool::new(browser.clone())),
        Arc::new(ScreenshotTool::new(browser.clone())),
        Arc::new(ScrollTool::new(browser)),
    ]
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::BrowserConfig;

    #[test]
    fn test_toolset_all_tools() {
        let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
        let toolset = BrowserToolset::new(browser);
        let tools = toolset.all_tools();

        // Every tool except browser_evaluate_js and browser_file_upload (45)
        assert_eq!(tools.len(), 45);

        // Check some tool names exist
        let tool_names: Vec<&str> = tools.iter().map(|t| t.name()).collect();
        assert!(tool_names.contains(&"browser_navigate"));
        assert!(tool_names.contains(&"browser_click"));
        assert!(tool_names.contains(&"browser_type"));
        assert!(tool_names.contains(&"browser_screenshot"));
        assert!(tool_names.contains(&"browser_elements"));
        // New tools
        assert!(tool_names.contains(&"browser_get_cookies"));
        assert!(tool_names.contains(&"browser_new_tab"));
        assert!(tool_names.contains(&"browser_switch_to_frame"));
        assert!(tool_names.contains(&"browser_drag_and_drop"));
    }

    #[test]
    fn test_toolset_selective() {
        let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
        let toolset = BrowserToolset::new(browser)
            .with_navigation(true)
            .with_interaction(false)
            .with_extraction(false)
            .with_wait(false)
            .with_screenshot(false)
            .with_js(false)
            .with_cookies(false)
            .with_windows(false)
            .with_frames(false)
            .with_actions(false);

        let tools = toolset.all_tools();

        // Should only have navigation tools
        assert_eq!(tools.len(), 4);
    }

    #[test]
    fn test_minimal_tools() {
        let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
        let tools = minimal_browser_tools(browser);

        assert_eq!(tools.len(), 6);
    }

    #[test]
    fn test_profile_form_filling() {
        let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
        let toolset = BrowserToolset::with_profile(browser, BrowserProfile::FormFilling);
        let tools = toolset.all_tools();

        // Navigation (4) + Interaction (5) + Extraction (6) + Wait (4) + Screenshot (1) = 20
        let tool_names: Vec<&str> = tools.iter().map(|t| t.name()).collect();
        assert!(tool_names.contains(&"browser_navigate"));
        assert!(tool_names.contains(&"browser_click"));
        assert!(tool_names.contains(&"browser_type"));
        assert!(tool_names.contains(&"browser_select"));
        assert!(tool_names.contains(&"browser_clear"));
        assert!(tool_names.contains(&"browser_screenshot"));
        // Should NOT include cookies, windows, frames, actions
        assert!(!tool_names.contains(&"browser_get_cookies"));
        assert!(!tool_names.contains(&"browser_new_tab"));
        assert!(!tool_names.contains(&"browser_switch_to_frame"));
        assert!(!tool_names.contains(&"browser_drag_and_drop"));
    }

    #[test]
    fn test_profile_scraping() {
        let browser = Arc::new(BrowserSession::new(BrowserConfig::default()));
        let toolset = BrowserToolset::with_profile(browser, BrowserProfile::Scraping);
        let tools = toolset.all_tools();

        let tool_names: Vec<&str> = tools.iter().map(|t| t.name()).collect();
        assert!(tool_names.contains(&"browser_navigate"));
        assert!(tool_names.contains(&"browser_extract_text"));
        assert!(tool_names.contains(&"browser_extract_links"));
        assert!(tool_names.contains(&"browser_screenshot"));
        assert!(tool_names.contains(&"browser_scroll"));
        // Should NOT include interaction tools
        assert!(!tool_names.contains(&"browser_click"));
        assert!(!tool_names.contains(&"browser_type"));
    }

    #[test]
    fn test_profile_full_matches_new() {
        let browser1 = Arc::new(BrowserSession::new(BrowserConfig::default()));
        let browser2 = Arc::new(BrowserSession::new(BrowserConfig::default()));
        let full = BrowserToolset::with_profile(browser1, BrowserProfile::Full);
        let default = BrowserToolset::new(browser2);
        assert_eq!(full.all_tools().len(), default.all_tools().len());
    }
}