poly-mcp 0.5.0

A comprehensive MCP server with filesystem, diagnostics, scripting, time, network, context, git, input, clipboard, transform, and screen control tools
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
mod cdp;

use anyhow::Context;
use serde_json::{json, Value};
use std::process::Command;
use std::sync::atomic::{AtomicBool, Ordering};

const DEFAULT_PORT: u16 = 9222;

/// Browser control module — headless browser automation via CDP.
pub struct BrowserModule {
    /// Cached session keyed by (port). Supports multi-port usage.
    sessions: tokio::sync::Mutex<std::collections::HashMap<u16, cdp::BrowserSession>>,
    needs_reconnect: AtomicBool,
}

impl BrowserModule {
    pub fn new() -> Self {
        Self {
            sessions: tokio::sync::Mutex::new(std::collections::HashMap::new()),
            needs_reconnect: AtomicBool::new(false),
        }
    }

    /// Mark session as potentially dead — next get_session will probe.
    fn mark_needs_reconnect(&self) {
        self.needs_reconnect.store(true, Ordering::Relaxed);
    }

    /// Get or create a persistent browser session for a specific port.
    /// If a previous call failed, probes the session before reusing it.
    async fn get_session(&self, port: u16) -> anyhow::Result<tokio::sync::MutexGuard<'_, std::collections::HashMap<u16, cdp::BrowserSession>>> {
        let mut guard = self.sessions.lock().await;

        // If flagged as potentially dead, probe the existing session for this port
        if guard.contains_key(&port) && self.needs_reconnect.swap(false, Ordering::Relaxed) {
            let healthy = if let Some(session) = guard.get_mut(&port) {
                tokio::time::timeout(
                    tokio::time::Duration::from_secs(1),
                    session.evaluate("1"),
                )
                .await
                .map(|r| r.is_ok())
                .unwrap_or(false)
            } else {
                false
            };
            if !healthy {
                guard.remove(&port);
            }
        }

        if !guard.contains_key(&port) {
            let session = cdp::BrowserSession::connect(port).await?;
            guard.insert(port, session);
        }
        Ok(guard)
    }

    pub fn get_tools(&self) -> Vec<Value> {
        vec![
            json!({
                "name": "browser_launch",
                "description": "Launch a browser (Firefox or Chrome) with remote debugging enabled. Returns the CDP port for use with other browser tools. The browser stays running until browser_close is called. Note: snap-packaged Firefox cannot bind debugging ports — use a native install or Chrome instead.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "headless": { "type": "boolean", "description": "Run without visible window (default true)" },
                        "url": { "type": "string", "description": "Initial URL to open" },
                        "port": { "type": "number", "description": "CDP debugging port (default 9222)" },
                        "browser": { "type": "string", "description": "Browser to use: 'firefox' or 'chrome' (auto-detected if omitted)", "enum": ["firefox", "chrome"] }
                    },
                    "required": []
                }
            }),
            json!({
                "name": "browser_navigate",
                "description": "Navigate to a URL in the browser. Waits for page load to complete.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "url": { "type": "string", "description": "URL to navigate to" },
                        "port": { "type": "number", "description": "CDP port (default 9222)" }
                    },
                    "required": ["url"]
                }
            }),
            json!({
                "name": "browser_screenshot",
                "description": "Take a screenshot of the current page. Returns an image. Much more reliable than screen_capture for web content since it captures the DOM directly.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "full_page": { "type": "boolean", "description": "Capture full scrollable page, not just viewport (default false)" },
                        "port": { "type": "number", "description": "CDP port (default 9222)" }
                    },
                    "required": []
                }
            }),
            json!({
                "name": "browser_content",
                "description": "Get the page content — title, URL, HTML, or extracted text.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "format": {
                            "type": "string",
                            "description": "'text' (visible text), 'html' (full HTML), 'title' (page title), 'url' (current URL)",
                            "enum": ["text", "html", "title", "url"]
                        },
                        "port": { "type": "number", "description": "CDP port (default 9222)" }
                    },
                    "required": []
                }
            }),
            json!({
                "name": "browser_query",
                "description": "Query DOM elements by CSS selector. Returns matching elements with text, attributes, and bounding boxes. Use this to find buttons, links, inputs — then click or fill them.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "selector": { "type": "string", "description": "CSS selector (e.g. 'button', '.submit-btn', '#email', 'a[href*=login]')" },
                        "port": { "type": "number", "description": "CDP port (default 9222)" }
                    },
                    "required": ["selector"]
                }
            }),
            json!({
                "name": "browser_click",
                "description": "Click a DOM element by CSS selector. More reliable than coordinate clicking — targets the element directly in the DOM.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "selector": { "type": "string", "description": "CSS selector of element to click" },
                        "port": { "type": "number", "description": "CDP port (default 9222)" }
                    },
                    "required": ["selector"]
                }
            }),
            json!({
                "name": "browser_fill",
                "description": "Fill a form input/textarea by CSS selector. Triggers input and change events.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "selector": { "type": "string", "description": "CSS selector of the input field" },
                        "value": { "type": "string", "description": "Value to fill" },
                        "port": { "type": "number", "description": "CDP port (default 9222)" }
                    },
                    "required": ["selector", "value"]
                }
            }),
            json!({
                "name": "browser_eval",
                "description": "Execute JavaScript in the page context. Returns the result. Can access DOM, make fetch calls, interact with page APIs.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "expression": { "type": "string", "description": "JavaScript code to execute" },
                        "port": { "type": "number", "description": "CDP port (default 9222)" }
                    },
                    "required": ["expression"]
                }
            }),
            json!({
                "name": "browser_tabs",
                "description": "List all open browser tabs with their titles, URLs, and IDs.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "port": { "type": "number", "description": "CDP port (default 9222)" }
                    },
                    "required": []
                }
            }),
            json!({
                "name": "browser_close",
                "description": "Close a browser tab or the entire browser.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "tab_id": { "type": "string", "description": "Tab ID to close. If omitted, closes all tabs and kills the browser." },
                        "port": { "type": "number", "description": "CDP port (default 9222)" }
                    },
                    "required": []
                }
            }),
            json!({
                "name": "browser_wait",
                "description": "Wait for a condition in the browser: element by CSS selector, text on page, URL match, or custom JS expression. Polls every 100ms. Essential for SPAs — call this after navigate to ensure content is rendered before interacting.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "selector": { "type": "string", "description": "CSS selector to wait for (e.g. '.loaded', '#content', 'button[data-action]')" },
                        "text": { "type": "string", "description": "Text to wait for on the page (substring match)" },
                        "url": { "type": "string", "description": "URL substring to wait for (e.g. '/dashboard')" },
                        "expression": { "type": "string", "description": "JS expression that should return truthy when condition is met" },
                        "visible": { "type": "boolean", "description": "For selector: also require element has non-zero size (default true)" },
                        "timeout_ms": { "type": "number", "description": "Timeout in ms (default 30000)" },
                        "port": { "type": "number", "description": "CDP port (default 9222)" }
                    },
                    "required": []
                }
            }),
            json!({
                "name": "browser_scroll",
                "description": "Scroll the page in a direction, by pixels, or scroll a specific element into view.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "direction": { "type": "string", "description": "Scroll direction: 'up', 'down', 'left', 'right' (default 'down')", "enum": ["up", "down", "left", "right"] },
                        "pixels": { "type": "number", "description": "Pixels to scroll (default 300)" },
                        "selector": { "type": "string", "description": "CSS selector of element to scroll into view (overrides direction/pixels)" },
                        "port": { "type": "number", "description": "CDP port (default 9222)" }
                    },
                    "required": []
                }
            }),
            json!({
                "name": "browser_hover",
                "description": "Hover over a DOM element to trigger CSS :hover styles and tooltip display.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "selector": { "type": "string", "description": "CSS selector of element to hover" },
                        "port": { "type": "number", "description": "CDP port (default 9222)" }
                    },
                    "required": ["selector"]
                }
            }),
            json!({
                "name": "browser_select",
                "description": "Select an option from a <select> dropdown by value or visible text.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "selector": { "type": "string", "description": "CSS selector of the <select> element" },
                        "value": { "type": "string", "description": "Option value to select" },
                        "text": { "type": "string", "description": "Option visible text to select (used if value not provided)" },
                        "port": { "type": "number", "description": "CDP port (default 9222)" }
                    },
                    "required": ["selector"]
                }
            }),
        ]
    }

    // ── Tool dispatch ─────────────────────────────────────────────

    pub async fn launch(&self, args: Value) -> anyhow::Result<Value> {
        let headless = args["headless"].as_bool().unwrap_or(true);
        let url = args["url"].as_str().unwrap_or("about:blank");
        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
        let browser_pref = args["browser"].as_str();

        let (browser_name, bin_path) = find_browser(browser_pref)?;

        let mut cmd_args: Vec<String> = Vec::new();

        match browser_name {
            "firefox" => {
                cmd_args.push(format!("--remote-debugging-port={}", port));
                if headless {
                    cmd_args.push("--headless".to_string());
                }
                cmd_args.push(url.to_string());
            }
            "chrome" => {
                cmd_args.push(format!("--remote-debugging-port={}", port));
                if headless {
                    cmd_args.push("--headless=new".to_string());
                }
                cmd_args.push("--no-first-run".to_string());
                cmd_args.push("--no-default-browser-check".to_string());
                cmd_args.push("--disable-gpu".to_string());
                cmd_args.push(url.to_string());
            }
            _ => unreachable!(),
        }

        // Launch browser process
        let child = Command::new(&bin_path)
            .args(&cmd_args)
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .spawn()
            .context(format!("Failed to launch {}", browser_name))?;

        let pid = child.id();

        // Wait for CDP to become available
        let start = std::time::Instant::now();
        let timeout = tokio::time::Duration::from_secs(15);

        loop {
            if start.elapsed() > timeout {
                return Err(anyhow::anyhow!(
                    "Browser launched but CDP port {} not responding after 15s",
                    port
                ));
            }

            // Try connecting — reset any stale session/cache first
            if let Ok(_) = cdp::BrowserSession::connect(port).await {
                self.sessions.lock().await.remove(&port);
                cdp::clear_browser_cache(port);
                return Ok(json!({
                    "success": true,
                    "browser": browser_name,
                    "pid": pid,
                    "port": port,
                    "headless": headless,
                    "startup_ms": start.elapsed().as_millis()
                }));
            }

            tokio::time::sleep(tokio::time::Duration::from_millis(300)).await;
        }
    }

    /// Check if an error is transient (worth retrying).
    fn is_transient_error(e: &anyhow::Error) -> bool {
        let msg = e.to_string();
        msg.contains("WebSocket") || msg.contains("timeout") || msg.contains("closed")
    }

    /// Handle a transient error: clear session and wait before retry.
    async fn handle_transient(&self, port: u16, attempt: usize) {
        let delays = [200u64, 400, 800];
        self.sessions.lock().await.remove(&port);
        self.needs_reconnect.store(false, Ordering::Relaxed);
        let delay = delays.get(attempt).copied().unwrap_or(800);
        tokio::time::sleep(tokio::time::Duration::from_millis(delay)).await;
    }

    pub async fn navigate(&self, args: Value) -> anyhow::Result<Value> {
        let url = args["url"].as_str().context("Missing 'url'")?;
        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;

        let result = async {
            let mut guard = self.get_session(port).await?;
            let session = guard.get_mut(&port).context("No browser session")?;
            session.navigate(url).await?;
            let title = session.get_title().await.unwrap_or_default();
            Ok(json!({ "success": true, "url": url, "title": title }))
        }.await;

        if result.is_err() { self.mark_needs_reconnect(); }
        result
    }

    pub async fn screenshot(&self, args: Value) -> anyhow::Result<Value> {
        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;

        let result: anyhow::Result<Value> = async {
            let mut guard = self.get_session(port).await?;
            let session = guard.get_mut(&port).context("No browser session")?;
            let b64_data = session.screenshot().await?;
            let byte_size = b64_data.len() * 3 / 4;
            Ok(json!({
                "content": [
                    { "type": "image", "data": b64_data, "mimeType": "image/png" },
                    { "type": "text", "text": serde_json::to_string_pretty(&json!({"bytes": byte_size}))? }
                ]
            }))
        }.await;

        if result.is_err() { self.mark_needs_reconnect(); }
        result
    }

    pub async fn content(&self, args: Value) -> anyhow::Result<Value> {
        let format = args["format"].as_str().unwrap_or("text");
        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;

        let result: anyhow::Result<Value> = async {
            let mut guard = self.get_session(port).await?;
            let session = guard.get_mut(&port).context("No browser session")?;
            match format {
                "html" => {
                    let html = session.get_content().await?;
                    Ok(json!({ "format": "html", "length": html.len(), "content": html }))
                }
                "title" => {
                    let title = session.get_title().await?;
                    Ok(json!({ "format": "title", "title": title }))
                }
                "url" => {
                    let url = session.evaluate("window.location.href").await?;
                    Ok(json!({ "format": "url", "url": url }))
                }
                _ => {
                    let text = session.evaluate("document.body?.innerText || ''").await?;
                    let text_str = text.as_str().unwrap_or("");
                    Ok(json!({ "format": "text", "length": text_str.len(), "content": text_str }))
                }
            }
        }.await;

        if result.is_err() { self.mark_needs_reconnect(); }
        result
    }

    pub async fn query(&self, args: Value) -> anyhow::Result<Value> {
        let selector = args["selector"].as_str().context("Missing 'selector'")?;
        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;

        for attempt in 0..3 {
            let result: anyhow::Result<Value> = async {
                let mut guard = self.get_session(port).await?;
                let session = guard.get_mut(&port).context("No browser session")?;
                let elements = session.query_selector_all(selector).await?;
                let count = elements.as_array().map(|a| a.len()).unwrap_or(0);
                Ok(json!({ "selector": selector, "count": count, "elements": elements }))
            }.await;
            match result {
                Ok(v) => return Ok(v),
                Err(e) if Self::is_transient_error(&e) && attempt < 2 => {
                    self.handle_transient(port, attempt).await;
                }
                Err(e) => { self.mark_needs_reconnect(); return Err(e); }
            }
        }
        unreachable!()
    }

    pub async fn click(&self, args: Value) -> anyhow::Result<Value> {
        let selector = args["selector"].as_str().context("Missing 'selector'")?;
        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;

        for attempt in 0..3 {
            let result: anyhow::Result<Value> = async {
                let mut guard = self.get_session(port).await?;
                let session = guard.get_mut(&port).context("No browser session")?;
                let r = session.click_selector(selector).await?;
                Ok(json!({ "selector": selector, "result": r }))
            }.await;
            match result {
                Ok(v) => return Ok(v),
                Err(e) if Self::is_transient_error(&e) && attempt < 2 => {
                    self.handle_transient(port, attempt).await;
                }
                Err(e) => { self.mark_needs_reconnect(); return Err(e); }
            }
        }
        unreachable!()
    }

    pub async fn fill(&self, args: Value) -> anyhow::Result<Value> {
        let selector = args["selector"].as_str().context("Missing 'selector'")?;
        let value = args["value"].as_str().context("Missing 'value'")?;
        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;

        for attempt in 0..3 {
            let result: anyhow::Result<Value> = async {
                let mut guard = self.get_session(port).await?;
                let session = guard.get_mut(&port).context("No browser session")?;
                let r = session.fill_selector(selector, value).await?;
                Ok(json!({ "selector": selector, "result": r }))
            }.await;
            match result {
                Ok(v) => return Ok(v),
                Err(e) if Self::is_transient_error(&e) && attempt < 2 => {
                    self.handle_transient(port, attempt).await;
                }
                Err(e) => { self.mark_needs_reconnect(); return Err(e); }
            }
        }
        unreachable!()
    }

    pub async fn eval(&self, args: Value) -> anyhow::Result<Value> {
        let expression = args["expression"].as_str().context("Missing 'expression'")?;
        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;

        let result: anyhow::Result<Value> = async {
            let mut guard = self.get_session(port).await?;
            let session = guard.get_mut(&port).context("No browser session")?;
            let r = session.evaluate(expression).await?;
            Ok(json!({ "expression": expression, "result": r }))
        }.await;

        if result.is_err() { self.mark_needs_reconnect(); }
        result
    }

    pub async fn wait(&self, args: Value) -> anyhow::Result<Value> {
        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
        let timeout_ms = args["timeout_ms"].as_u64().unwrap_or(30000);
        let visible = args["visible"].as_bool().unwrap_or(true);

        // Build JS condition from parameters
        let condition_js = if let Some(selector) = args["selector"].as_str() {
            let sel = cdp::js_escape(selector);
            if visible {
                format!(
                    "(function(){{ var el = document.querySelector('{}'); if (!el) return false; var r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0; }})()",
                    sel
                )
            } else {
                format!("!!document.querySelector('{}')", sel)
            }
        } else if let Some(text) = args["text"].as_str() {
            format!("(document.body?.innerText || '').includes('{}')", cdp::js_escape(text))
        } else if let Some(url_pat) = args["url"].as_str() {
            format!("window.location.href.includes('{}')", cdp::js_escape(url_pat))
        } else if let Some(expr) = args["expression"].as_str() {
            expr.to_string()
        } else {
            return Err(anyhow::anyhow!("Provide 'selector', 'text', 'url', or 'expression'"));
        };

        let result: anyhow::Result<Value> = async {
            let mut guard = self.get_session(port).await?;
            let session = guard.get_mut(&port).context("No browser session")?;
            session.wait_for(&condition_js, timeout_ms).await
        }.await;

        if result.is_err() { self.mark_needs_reconnect(); }
        result
    }

    pub async fn scroll(&self, args: Value) -> anyhow::Result<Value> {
        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
        let direction = args["direction"].as_str().unwrap_or("down");
        let pixels = args["pixels"].as_i64().unwrap_or(300);
        let selector = args["selector"].as_str();

        let result: anyhow::Result<Value> = async {
            let mut guard = self.get_session(port).await?;
            let session = guard.get_mut(&port).context("No browser session")?;
            session.scroll_page(direction, pixels, selector).await
        }.await;

        if result.is_err() { self.mark_needs_reconnect(); }
        result
    }

    pub async fn hover(&self, args: Value) -> anyhow::Result<Value> {
        let selector = args["selector"].as_str().context("Missing 'selector'")?;
        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;

        let result: anyhow::Result<Value> = async {
            let mut guard = self.get_session(port).await?;
            let session = guard.get_mut(&port).context("No browser session")?;
            session.hover_element(selector).await
        }.await;

        if result.is_err() { self.mark_needs_reconnect(); }
        result
    }

    pub async fn select(&self, args: Value) -> anyhow::Result<Value> {
        let selector = args["selector"].as_str().context("Missing 'selector'")?;
        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
        let value = args["value"].as_str();
        let text = args["text"].as_str();

        let result: anyhow::Result<Value> = async {
            let mut guard = self.get_session(port).await?;
            let session = guard.get_mut(&port).context("No browser session")?;
            session.select_option(selector, value, text).await
        }.await;

        if result.is_err() { self.mark_needs_reconnect(); }
        result
    }

    pub async fn tabs(&self, args: Value) -> anyhow::Result<Value> {
        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;

        // Try using cached session first (avoids opening a second connection that
        // hits Firefox's "one session" limit)
        let result: anyhow::Result<Value> = async {
            let mut guard = self.get_session(port).await?;
            let session = guard.get_mut(&port).context("No browser session")?;

            if session.browser_kind() == cdp::BrowserKind::Firefox {
                // Use BiDi browsingContext.getTree via cached session
                let tree = session.send_raw("browsingContext.getTree", json!({})).await?;
                let contexts = tree.get("contexts").and_then(|c| c.as_array()).cloned().unwrap_or_default();
                let tabs: Vec<Value> = contexts.iter().map(|c| json!({
                    "id": c["context"],
                    "title": c.get("url").and_then(|u| u.as_str()).unwrap_or(""),
                    "url": c.get("url").and_then(|u| u.as_str()).unwrap_or(""),
                })).collect();
                Ok(json!({ "count": tabs.len(), "tabs": tabs }))
            } else {
                // Chrome: use HTTP endpoint (doesn't require WebSocket session)
                drop(guard);
                let tabs = cdp::list_tabs(port).await?;
                Ok(json!({ "count": tabs.len(), "tabs": tabs }))
            }
        }.await;

        if result.is_err() { self.mark_needs_reconnect(); }
        result
    }

    pub async fn close(&self, args: Value) -> anyhow::Result<Value> {
        let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
        let tab_id = args["tab_id"].as_str();

        // Clear cached session and browser kind for this port
        self.sessions.lock().await.remove(&port);
        cdp::clear_browser_cache(port);

        if let Some(id) = tab_id {
            cdp::close_tab(port, id).await?;
            Ok(json!({ "success": true, "closed": "tab", "tab_id": id }))
        } else {
            // Close all tabs and kill browser
            if let Ok(tabs) = cdp::list_tabs(port).await {
                for tab in &tabs {
                    if let Some(id) = tab["id"].as_str() {
                        let _ = cdp::close_tab(port, id).await;
                    }
                }
            }

            // Kill browser processes listening on this port
            let _ = Command::new("fuser")
                .args(["-k", &format!("{}/tcp", port)])
                .output();

            Ok(json!({ "success": true, "closed": "browser", "port": port }))
        }
    }
}

// ── Helpers ────────────────────────────────────────────────────────

fn find_browser(preference: Option<&str>) -> anyhow::Result<(&'static str, String)> {
    let firefox_bins = ["firefox", "firefox-esr"];
    let chrome_bins = [
        "google-chrome-stable",
        "google-chrome",
        "chromium-browser",
        "chromium",
    ];

    if let Some(pref) = preference {
        let (label, bins): (&'static str, &[&str]) = if pref == "firefox" {
            ("firefox", &firefox_bins)
        } else {
            ("chrome", &chrome_bins)
        };
        for bin in bins {
            if let Some(path) = which(bin) {
                return Ok((label, path));
            }
        }
        return Err(anyhow::anyhow!(
            "{} not found. Install it or try the other browser.",
            pref
        ));
    }

    // Auto-detect: prefer Firefox (better CDP support on Linux)
    for bin in &firefox_bins {
        if let Some(path) = which(bin) {
            return Ok(("firefox", path));
        }
    }
    for bin in &chrome_bins {
        if let Some(path) = which(bin) {
            return Ok(("chrome", path));
        }
    }

    Err(anyhow::anyhow!(
        "No browser found. Install Firefox or Chrome."
    ))
}

fn which(name: &str) -> Option<String> {
    Command::new("which")
        .arg(name)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
}