browser-control 1.1.1

CLI that manages browsers and exposes them over CDP/BiDi for agent-driven development. Includes an optional MCP server.
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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
//! MCP tools exposed by the `browser-control mcp` server.
//!
//! The tool surface is Playwright-shaped (`browser_*` prefix) plus
//! browser-control extensions (`browser_get_html`, `browser_fetch`,
//! `browser_eval`, `browser_select_element`, `browser_cookies`, `browser_storage_*`,
//! `browser_wait_for_cookie`) and the legacy CDP-shaped `list_targets`
//! kept for info-dense diagnostics.
//!
//! Tools that operate against a single tab accept optional `tab` (named)
//! and `target` (URL regex) arguments. The two are mutually exclusive;
//! omitting both routes to the server's in-memory active tab
//! (`current_tab`).

use anyhow::{anyhow, Result};
use regex::Regex;
use serde_json::{json, Value};
use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::cli::fetch::script_fetch_timeout_ms;
use crate::cli::storage::{build_get_expr, build_set_expr, ns_global};
use crate::cli::wait_for_cookie::cookie_matches;
use crate::detect::Engine;
use crate::dom::scripts::{FETCH_JS, GET_CLIP_RECT_JS, GET_DOM_JS, SELECT_ELEMENT_JS};
use crate::errors::SessionError;
use crate::mcp::server::{RegisteredTool, ServerState, ToolHandler, ToolRegistry};
use crate::session::backend::TabBackend;
use crate::session::freshness;
use crate::session::targets::TargetInfo;

/// Per-op timeout for read tools (`browser_get_html`,
/// `browser_select_element` short path, storage). 10 s is generous for
/// legitimate DOM work and tight enough that a wedged renderer
/// fast-fails.
const MCP_OP_TIMEOUT: Duration = Duration::from_secs(10);

/// Per-op timeout for `browser_fetch`. Slow HTTP fetches over real
/// networks can take many seconds; 60 s matches the CLI `fetch
/// --timeout-ms` default.
const MCP_FETCH_TIMEOUT: Duration = Duration::from_secs(60);

/// Per-op timeout for `browser_select_element`. The overlay waits for a
/// human click, so the bound has to be much longer than for automated
/// tools. Five minutes is plenty for an interactive selection without
/// leaking forever if the page is left abandoned.
const MCP_SELECT_ELEMENT_TIMEOUT: Duration = Duration::from_secs(300);

/// Probe budget for `browser_tab_select`: how long we give the selected
/// tab to answer `Runtime.evaluate("1")` / `script.evaluate("1")` before
/// returning `TabHung`. Matches `session::attach::PICK_PROBE_TIMEOUT`.
const TAB_SELECT_PROBE: Duration = Duration::from_millis(500);

/// Native wake/probe budget used only after a Playwright sidecar CDP failure.
const SIDECAR_WAKE_PROBE_TIMEOUT: Duration = Duration::from_secs(2);

/// Register the standard tool set onto the given registry.
pub fn register_all(registry: &ToolRegistry) {
    // Renamed-from-Playwright tools.
    registry.register(make_navigate());
    registry.register(make_eval());
    registry.register(make_get_html());
    registry.register(make_take_screenshot());
    registry.register(make_fetch());
    registry.register(make_curl());
    registry.register(make_select_element());
    registry.register(make_cookies());
    registry.register(make_storage_get());
    registry.register(make_storage_set());
    registry.register(make_wait_for_cookie());
    // Diagnostic enumeration (kept).
    registry.register(make_list_targets());
    // New tab-management tools.
    registry.register(make_tab_list());
    registry.register(make_tab_new());
    registry.register(make_tab_select());
    registry.register(make_tab_close());
    // New browser-management tools.
    registry.register(make_browser_start());
    registry.register(make_browser_select());
    registry.register(make_browser_list());
    registry.register(make_browser_show());
    // Playwright-only interaction tools — Chromium-family only (route
    // through the Node sidecar). Each errors with `EngineUnsupported`
    // when the active browser is BiDi.
    registry.register(make_snapshot());
    registry.register(make_click());
    registry.register(make_type());
    registry.register(make_hover());
    registry.register(make_drag());
    registry.register(make_press_key());
    registry.register(make_wait_for());
    registry.register(make_pdf_save());
}

// ---------------------------------------------------------------------------
// Helpers.
// ---------------------------------------------------------------------------

fn text_content(text: impl Into<String>) -> Value {
    json!({ "content": [ { "type": "text", "text": text.into() } ] })
}

fn image_content(data: String) -> Value {
    json!({
        "content": [ { "type": "image", "data": data, "mimeType": "image/png" } ]
    })
}

fn handler<F>(f: F) -> ToolHandler
where
    F: Fn(ServerState, Value) -> futures_util::future::BoxFuture<'static, Result<Value>>
        + Send
        + Sync
        + 'static,
{
    Arc::new(f)
}

/// Schema fragment for optional `tab` / `target` args. Inlined into
/// every per-tab tool's input schema so the agent-facing contract is
/// consistent.
fn tab_args_schema() -> Value {
    json!({
        "tab": {
            "type": "string",
            "description": "Optional named tab; mutually exclusive with `target`."
        },
        "target": {
            "type": "string",
            "description": "Optional URL regex selecting an existing tab; mutually exclusive with `tab`."
        }
    })
}

/// Canonical builder for a per-tab tool's `properties` object: the shared
/// `tab` / `target` schema merged with tool-specific `extra` fields. The
/// merge result is order-independent — `serde_json::Map` serializes keys
/// sorted — so callers may pass `extra` in any shape.
fn tab_args_properties(extra: Value) -> Value {
    let mut obj = extra.as_object().cloned().unwrap_or_default();
    if let Some(ta) = tab_args_schema().as_object() {
        for (k, v) in ta {
            obj.insert(k.clone(), v.clone());
        }
    }
    Value::Object(obj)
}

/// Canonical extraction of the optional `tab` (named) / `target` (URL
/// regex) routing args from a tool's `args`. Mirrors the parse in
/// [`ServerState::resolve_target_for_args`]; used by tools that need to
/// branch on whether explicit routing was given before resolving.
fn extract_tab_target(args: &Value) -> (Option<String>, Option<String>) {
    let tab = args.get("tab").and_then(|v| v.as_str()).map(String::from);
    let target = args
        .get("target")
        .and_then(|v| v.as_str())
        .map(String::from);
    (tab, target)
}

fn max_age_arg(args: &Value) -> Result<Duration> {
    match args.get("max_age") {
        None | Some(Value::Null) => Ok(freshness::DEFAULT_MAX_AGE),
        Some(Value::String(s)) => freshness::parse_max_age(s),
        Some(Value::Number(n)) => n
            .as_u64()
            .map(Duration::from_secs)
            .ok_or_else(|| anyhow!("`max_age` number must be non-negative seconds")),
        Some(_) => Err(anyhow!(
            "`max_age` must be a duration string, e.g. `10m` or `1h`"
        )),
    }
}

fn timeout_ms_arg(args: &Value, key: &str, default: Duration) -> Result<Duration> {
    match args.get(key) {
        None | Some(Value::Null) => Ok(default),
        Some(Value::Number(n)) => n
            .as_u64()
            .map(Duration::from_millis)
            .ok_or_else(|| anyhow!("`{key}` number must be non-negative milliseconds")),
        Some(_) => Err(anyhow!(
            "`{key}` must be a non-negative number of milliseconds"
        )),
    }
}

// ---------------------------------------------------------------------------
// browser_navigate
// ---------------------------------------------------------------------------

fn make_navigate() -> RegisteredTool {
    RegisteredTool {
        name: "browser_navigate".into(),
        description: "Navigate the active page to a URL.".into(),
        input_schema: json!({
            "type": "object",
            "properties": tab_args_properties(json!({ "url": { "type": "string" } })),
            "required": ["url"],
        }),
        handler: handler(|state, args| {
            Box::pin(async move {
                let url = args
                    .get("url")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| anyhow!("missing 'url'"))?
                    .to_string();
                let (backend, target_id) = state.resolve_target_for_args(&args).await?;
                backend.navigate(&target_id, &url).await?;
                Ok(text_content(format!("Navigated to {url}")))
            })
        }),
    }
}

// ---------------------------------------------------------------------------
// browser_eval
// ---------------------------------------------------------------------------

fn make_eval() -> RegisteredTool {
    RegisteredTool {
        name: "browser_eval".into(),
        description: "Evaluate a JavaScript expression in the active page.".into(),
        input_schema: json!({
            "type": "object",
            "properties": tab_args_properties(json!({
                "expression": {
                    "type": "string",
                    "description": "JavaScript expression to evaluate."
                },
                "await_promise": {
                    "type": "boolean",
                    "default": true,
                    "description": "Treat the expression as a Promise and await it."
                },
                "timeout_ms": {
                    "type": "number",
                    "description": "Per-call timeout in milliseconds (default 10000)."
                },
                "max_age": {
                    "type": "string",
                    "description": "Reload the page first if its document is older than this duration (default 10m)."
                }
            })),
            "required": ["expression"],
        }),
        handler: handler(|state, args| {
            Box::pin(async move {
                let expression = args
                    .get("expression")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| anyhow!("missing 'expression'"))?
                    .to_string();
                let await_promise = args
                    .get("await_promise")
                    .and_then(Value::as_bool)
                    .unwrap_or(true);
                let timeout = timeout_ms_arg(&args, "timeout_ms", MCP_OP_TIMEOUT)?;
                let max_age = max_age_arg(&args)?;
                let (backend, target_id) = state.resolve_target_for_args(&args).await?;
                backend.ensure_fresh(&target_id, max_age).await?;
                let value = backend
                    .evaluate(&target_id, &expression, await_promise, timeout)
                    .await?;
                Ok(text_content(serde_json::to_string_pretty(&value)?))
            })
        }),
    }
}

// ---------------------------------------------------------------------------
// browser_get_html
// ---------------------------------------------------------------------------

fn make_get_html() -> RegisteredTool {
    RegisteredTool {
        name: "browser_get_html".into(),
        description: "Get the rendered DOM as HTML, with shadow roots serialized when supported."
            .into(),
        input_schema: json!({
            "type": "object",
            "properties": tab_args_properties(json!({
                "selector": {
                    "type": "string",
                    "description": "Optional CSS selector; defaults to the document element."
                }
            })),
        }),
        handler: handler(|state, args| {
            Box::pin(async move {
                let selector_arg = args.get("selector").and_then(|v| v.as_str());
                let selector_literal = match selector_arg {
                    Some(s) => serde_json::to_string(s)?,
                    None => "null".to_string(),
                };
                let expr = format!("({GET_DOM_JS})({selector_literal})");
                let (backend, target_id) = state.resolve_target_for_args(&args).await?;
                let value = backend
                    .evaluate(&target_id, &expr, false, MCP_OP_TIMEOUT)
                    .await?;
                let html = value.as_str().unwrap_or("").to_string();
                Ok(text_content(html))
            })
        }),
    }
}

// ---------------------------------------------------------------------------
// browser_take_screenshot
// ---------------------------------------------------------------------------

fn make_take_screenshot() -> RegisteredTool {
    RegisteredTool {
        name: "browser_take_screenshot".into(),
        description: "Capture a PNG screenshot of the active page.".into(),
        input_schema: json!({
            "type": "object",
            "properties": tab_args_properties(json!({
                "full_page": { "type": "boolean", "default": false },
                "selector": { "type": "string" }
            })),
        }),
        handler: handler(|state, args| {
            Box::pin(async move {
                let full_page = args
                    .get("full_page")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false);
                let selector = args.get("selector").and_then(|v| v.as_str());
                let (backend, target_id) = state.resolve_target_for_args(&args).await?;
                // A selector clips the capture to that element's bounding box.
                let clip = match selector {
                    Some(sel) => {
                        let sel_literal = serde_json::to_string(sel)?;
                        let expr = format!("({GET_CLIP_RECT_JS})({sel_literal})");
                        let rect = backend
                            .evaluate(&target_id, &expr, false, MCP_OP_TIMEOUT)
                            .await?;
                        if rect.is_null() {
                            return Err(anyhow!("selector matched no visible element: {sel}"));
                        }
                        Some(rect)
                    }
                    None => None,
                };
                let b64 = backend.screenshot(&target_id, full_page, clip).await?;
                Ok(image_content(b64))
            })
        }),
    }
}

// ---------------------------------------------------------------------------
// browser_fetch
// ---------------------------------------------------------------------------

fn make_fetch() -> RegisteredTool {
    RegisteredTool {
        name: "browser_fetch".into(),
        description:
            "Perform an HTTP request from the page context. Preserves cookies and remains subject to browser CORS/CSP rules. Prefer `browser_curl` for large responses or direct file downloads."
                .into(),
        input_schema: json!({
            "type": "object",
            "properties": tab_args_properties(json!({
                "url": { "type": "string" },
                "method": { "type": "string" },
                "headers": { "type": "object" },
                "body": { "type": "string" },
                "timeout_ms": {
                    "type": "number",
                    "description": "Per-call timeout in milliseconds for the in-page fetch. Default 60s."
                },
                "max_age": {
                    "type": "string",
                    "description": "Reload the page first if its document is older than this duration (default 10m)."
                }
            })),
            "required": ["url"],
        }),
        handler: handler(|state, args| {
            Box::pin(async move {
                if args.get("url").and_then(|v| v.as_str()).is_none() {
                    return Err(anyhow!("missing 'url'"));
                }
                // Strip routing args before forwarding to the JS shim.
                let mut for_js = args.clone();
                if let Some(obj) = for_js.as_object_mut() {
                    obj.remove("tab");
                    obj.remove("target");
                    obj.remove("max_age");
                    obj.remove("timeout_ms");
                }
                let timeout = timeout_ms_arg(&args, "timeout_ms", MCP_FETCH_TIMEOUT)?;
                if let Some(obj) = for_js.as_object_mut() {
                    obj.insert(
                        "timeoutMs".to_string(),
                        json!(script_fetch_timeout_ms(timeout)),
                    );
                }
                let max_age = max_age_arg(&args)?;
                let args_json = serde_json::to_string(&for_js)?;
                let args_literal = serde_json::to_string(&args_json)?;
                let expr = format!("({FETCH_JS})({args_literal})");
                // Explicit `tab`/`target` routing is honoured verbatim. With
                // neither, route to a tab on the URL's origin rather than the
                // server's `about:blank` active tab — an opaque-origin fetch
                // silently drops cookies/credentials and trips CORS. Mirrors
                // `cli::fetch`'s origin-bound default path.
                let (tab, target) = extract_tab_target(&args);
                let has_route = tab.is_some() || target.is_some();
                let (backend, target_id) = if has_route {
                    state.resolve_target_for_args(&args).await?
                } else {
                    let url = args.get("url").and_then(|v| v.as_str()).unwrap();
                    state.resolve_or_create_for_origin(url).await?
                };
                backend.ensure_fresh(&target_id, max_age).await?;
                let value = backend.evaluate(&target_id, &expr, true, timeout).await?;
                let raw = value.as_str().unwrap_or("").to_string();
                let mut parsed: Value = serde_json::from_str(&raw)
                    .map_err(|e| anyhow!("invalid fetch response JSON: {e}"))?;
                if parsed.get("ok").and_then(Value::as_bool) == Some(false) {
                    let mut msg = parsed
                        .get("error")
                        .and_then(Value::as_str)
                        .unwrap_or("fetch failed")
                        .to_string();
                    if let Some(name) = parsed.get("errorName").and_then(Value::as_str) {
                        if !name.is_empty() {
                            msg.push_str(&format!(" ({name})"));
                        }
                    }
                    return Err(anyhow!(msg));
                }
                if let Some(obj) = parsed.as_object_mut() {
                    obj.remove("ok");
                }
                let pretty = serde_json::to_string_pretty(&parsed)?;
                Ok(text_content(pretty))
            })
        }),
    }
}

// ---------------------------------------------------------------------------
// browser_curl
// ---------------------------------------------------------------------------

fn make_curl() -> RegisteredTool {
    RegisteredTool {
        name: "browser_curl".into(),
        description: format!(
            "Run the real curl out of page context with cookies and User-Agent copied from the active browser, plus Origin and Referer derived from the selected source tab. Arguments use ordinary curl syntax and are forwarded unchanged. Omit `-o` to return up to {} MiB through MCP; use `-o <path>`/`--output <path>` for unrestricted streaming downloads. Unlike browser_fetch, curl is not subject to browser CORS/CSP and does not reproduce the browser TLS fingerprint.",
            crate::cli::curl::MCP_RESPONSE_LIMIT / (1024 * 1024)
        ),
        input_schema: json!({
            "type": "object",
            "properties": tab_args_properties(json!({
                "args": {
                    "type": "array",
                    "items": { "type": "string" },
                    "minItems": 1,
                    "description": "Exact curl arguments, including options and URL(s), e.g. [\"-L\", \"--fail-with-body\", \"-o\", \"/tmp/file.zip\", \"https://example.com/file.zip\"]."
                }
            })),
            "required": ["args"],
        }),
        handler: handler(|state, args| {
            Box::pin(async move {
                let curl_args = args
                    .get("args")
                    .and_then(Value::as_array)
                    .ok_or_else(|| anyhow!("missing or invalid 'args': expected an array of strings"))?
                    .iter()
                    .map(|arg| {
                        arg.as_str()
                            .map(String::from)
                            .ok_or_else(|| anyhow!("every curl argument must be a string"))
                    })
                    .collect::<Result<Vec<_>>>()?;
                if curl_args.is_empty() {
                    return Err(anyhow!(
                        "'args' must contain curl options and at least one URL"
                    ));
                }

                // Cookies are browser-wide. Explicit tab/target routing
                // selects the document used for navigator.userAgent, Origin,
                // and Referer. Otherwise prefer the MCP active tab, falling
                // back to any live tab inside `prepare`.
                let (tab, target) = extract_tab_target(&args);
                let has_route = tab.is_some() || target.is_some();
                let (backend, target_id) = if has_route {
                    let (backend, target_id) = state.resolve_target_for_args(&args).await?;
                    (backend, Some(target_id))
                } else {
                    let backend = state.ensure_backend().await?;
                    let target_id = state.active_target_id.lock().await.clone();
                    (backend, target_id)
                };
                let prepared = crate::cli::curl::prepare(&backend, target_id.as_deref()).await?;
                let output = crate::cli::curl::execute_mcp(&prepared, &curl_args).await?;
                Ok(crate::cli::curl::mcp_result(output))
            })
        }),
    }
}

// ---------------------------------------------------------------------------
// browser_select_element
// ---------------------------------------------------------------------------

fn make_select_element() -> RegisteredTool {
    RegisteredTool {
        name: "browser_select_element".into(),
        description:
            "Show an interactive overlay; resolve with the CSS selector for the clicked element."
                .into(),
        input_schema: json!({
            "type": "object",
            "properties": tab_args_properties(json!({})),
        }),
        handler: handler(|state, args| {
            Box::pin(async move {
                let expr = SELECT_ELEMENT_JS.to_string();
                let (backend, target_id) = state.resolve_target_for_args(&args).await?;
                // select_element shows an interactive overlay that the
                // human clicks — extend the bound generously so the
                // human has time to click.
                let value = backend
                    .evaluate(&target_id, &expr, true, MCP_SELECT_ELEMENT_TIMEOUT)
                    .await?;
                let selector = value.as_str().unwrap_or("").to_string();
                Ok(text_content(selector))
            })
        }),
    }
}

// ---------------------------------------------------------------------------
// list_targets (legacy, CDP-shaped info-dense diagnostic)
// ---------------------------------------------------------------------------

fn make_list_targets() -> RegisteredTool {
    RegisteredTool {
        name: "list_targets".into(),
        description: "List open page targets, optionally filtered by an unanchored URL regex. \
                      CDP-shaped diagnostic; agents typically want `browser_tab_list`."
            .into(),
        input_schema: json!({
            "type": "object",
            "properties": {
                "filter": {
                    "type": "string",
                    "description": "Optional unanchored URL regex."
                }
            },
        }),
        handler: handler(|state, args| {
            Box::pin(async move {
                let filter_re = args
                    .get("filter")
                    .and_then(|v| v.as_str())
                    .map(Regex::new)
                    .transpose()
                    .map_err(|e| anyhow!("invalid `filter` regex: {e}"))?;
                // Route through the server-owned backend rather than opening
                // a fresh BiDi session (which would fail/race on Firefox).
                // `live_targets` is the same primitive `browser_tab_list`
                // uses; re-shape it into the legacy CDP-style `TargetInfo`.
                let backend = state.ensure_backend().await?;
                let kind = match state.browser_snapshot().await.engine {
                    Engine::Cdp => "page",
                    Engine::Bidi => "context",
                };
                let targets: Vec<TargetInfo> = backend
                    .live_targets()
                    .await?
                    .into_iter()
                    .filter(|t| filter_re.as_ref().map_or(true, |re| re.is_match(&t.url)))
                    .map(|t| TargetInfo {
                        id: t.id,
                        url: t.url,
                        title: t.title,
                        kind: kind.to_string(),
                    })
                    .collect();
                Ok(text_content(serde_json::to_string_pretty(&targets)?))
            })
        }),
    }
}

// ---------------------------------------------------------------------------
// browser_cookies
// ---------------------------------------------------------------------------

fn make_cookies() -> RegisteredTool {
    RegisteredTool {
        name: "browser_cookies".into(),
        description: "Fetch cookies from the active browser. Returns full values (MCP is a \
                      trusted local channel). Optional unanchored regex filters."
            .into(),
        input_schema: json!({
            "type": "object",
            "properties": {
                "domain": { "type": "string", "description": "Unanchored regex on cookie domain." },
                "name":   { "type": "string", "description": "Unanchored regex on cookie name." }
            },
        }),
        handler: handler(|state, args| {
            Box::pin(async move {
                let domain_re = args
                    .get("domain")
                    .and_then(|v| v.as_str())
                    .map(Regex::new)
                    .transpose()
                    .map_err(|e| anyhow!("invalid `domain` regex: {e}"))?;
                let name_re = args
                    .get("name")
                    .and_then(|v| v.as_str())
                    .map(Regex::new)
                    .transpose()
                    .map_err(|e| anyhow!("invalid `name` regex: {e}"))?;
                // Route through the server-owned backend (reuses the open
                // session) instead of `fetch_cookies`, which opens a fresh
                // BiDi session and would fail/race on Firefox.
                let backend = state.ensure_backend().await?;
                let all = backend.cookies().await?;
                let filtered: Vec<_> = all
                    .into_iter()
                    .filter(|c| {
                        domain_re.as_ref().map_or(true, |re| re.is_match(&c.domain))
                            && name_re.as_ref().map_or(true, |re| re.is_match(&c.name))
                    })
                    .collect();
                Ok(text_content(serde_json::to_string_pretty(&filtered)?))
            })
        }),
    }
}

// ---------------------------------------------------------------------------
// browser_storage_get / browser_storage_set
// ---------------------------------------------------------------------------

fn make_storage_get() -> RegisteredTool {
    RegisteredTool {
        name: "browser_storage_get".into(),
        description: "Read a value from localStorage or sessionStorage on the active page.".into(),
        input_schema: json!({
            "type": "object",
            "properties": tab_args_properties(json!({
                "key": { "type": "string" },
                "namespace": {
                    "type": "string",
                    "enum": ["local", "session"],
                    "default": "local"
                },
                "max_age": {
                    "type": "string",
                    "description": "Reload the page first if its document is older than this duration (default 10m)."
                }
            })),
            "required": ["key"],
        }),
        handler: handler(|state, args| {
            Box::pin(async move {
                let key = args
                    .get("key")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| anyhow!("missing 'key'"))?
                    .to_string();
                let namespace = args
                    .get("namespace")
                    .and_then(|v| v.as_str())
                    .unwrap_or("local");
                let ns = ns_global(namespace)?;
                let expr = build_get_expr(ns, &key);
                let max_age = max_age_arg(&args)?;
                let (backend, target_id) = state.resolve_target_for_args(&args).await?;
                backend.ensure_fresh(&target_id, max_age).await?;
                let value = backend
                    .evaluate(&target_id, &expr, true, MCP_OP_TIMEOUT)
                    .await?;
                // `build_get_expr` wraps the result in JSON.stringify, so the
                // evaluator returns a JSON string. Unwrap one layer to surface
                // the raw value (or `null` when the key is absent).
                let text = match value {
                    Value::String(s) => s,
                    Value::Null => "null".to_string(),
                    other => other.to_string(),
                };
                Ok(text_content(text))
            })
        }),
    }
}

fn make_storage_set() -> RegisteredTool {
    RegisteredTool {
        name: "browser_storage_set".into(),
        description: "Write a value to localStorage or sessionStorage on the active page.".into(),
        input_schema: json!({
            "type": "object",
            "properties": tab_args_properties(json!({
                "key": { "type": "string" },
                "value": { "type": "string" },
                "namespace": {
                    "type": "string",
                    "enum": ["local", "session"],
                    "default": "local"
                }
            })),
            "required": ["key", "value"],
        }),
        handler: handler(|state, args| {
            Box::pin(async move {
                let key = args
                    .get("key")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| anyhow!("missing 'key'"))?
                    .to_string();
                let value = args
                    .get("value")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| anyhow!("missing 'value'"))?
                    .to_string();
                let namespace = args
                    .get("namespace")
                    .and_then(|v| v.as_str())
                    .unwrap_or("local");
                let ns = ns_global(namespace)?;
                let expr = build_set_expr(ns, &key, &value);
                let (backend, target_id) = state.resolve_target_for_args(&args).await?;
                let _ = backend
                    .evaluate(&target_id, &expr, true, MCP_OP_TIMEOUT)
                    .await?;
                Ok(text_content("ok"))
            })
        }),
    }
}

// ---------------------------------------------------------------------------
// browser_wait_for_cookie
// ---------------------------------------------------------------------------

fn make_wait_for_cookie() -> RegisteredTool {
    RegisteredTool {
        name: "browser_wait_for_cookie".into(),
        description: "Poll the browser until a cookie matching the regex filters appears, or \
                      timeout elapses."
            .into(),
        input_schema: json!({
            "type": "object",
            "properties": {
                "domain": { "type": "string", "description": "Unanchored regex on cookie domain." },
                "name":   { "type": "string", "description": "Unanchored regex on cookie name." },
                "timeout_seconds": { "type": "number", "default": 120 },
                "poll_interval_seconds": { "type": "number", "default": 1 }
            },
            "required": ["domain", "name"],
        }),
        handler: handler(|state, args| {
            Box::pin(async move {
                let domain = args
                    .get("domain")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| anyhow!("missing 'domain'"))?;
                let name = args
                    .get("name")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| anyhow!("missing 'name'"))?;
                let domain_re =
                    Regex::new(domain).map_err(|e| anyhow!("invalid `domain` regex: {e}"))?;
                let name_re = Regex::new(name).map_err(|e| anyhow!("invalid `name` regex: {e}"))?;
                let timeout_s = args
                    .get("timeout_seconds")
                    .and_then(|v| v.as_f64())
                    .unwrap_or(120.0)
                    .max(0.0);
                let interval_s = args
                    .get("poll_interval_seconds")
                    .and_then(|v| v.as_f64())
                    .unwrap_or(1.0)
                    .max(0.001);
                let deadline = Instant::now() + Duration::from_secs_f64(timeout_s);
                let interval = Duration::from_secs_f64(interval_s);
                // Acquire the server-owned backend once; reuse it each poll
                // rather than opening a fresh BiDi session per iteration
                // (which would fail/race on Firefox).
                let backend = state.ensure_backend().await?;
                loop {
                    let cookies = backend.cookies().await?;
                    if let Some(c) = cookies
                        .into_iter()
                        .find(|c| cookie_matches(c, &domain_re, &name_re))
                    {
                        return Ok(text_content(c.name));
                    }
                    let now = Instant::now();
                    if now >= deadline {
                        return Err(anyhow!("timed out waiting for cookie"));
                    }
                    let remaining = deadline.saturating_duration_since(now);
                    let nap = std::cmp::min(interval, remaining);
                    if nap.is_zero() {
                        return Err(anyhow!("timed out waiting for cookie"));
                    }
                    tokio::time::sleep(nap).await;
                }
            })
        }),
    }
}

// ---------------------------------------------------------------------------
// browser_tab_list / browser_tab_new / browser_tab_select / browser_tab_close
// ---------------------------------------------------------------------------

fn make_tab_list() -> RegisteredTool {
    RegisteredTool {
        name: "browser_tab_list".into(),
        description: "List open tabs in the active browser, Playwright-shaped \
                      (`[{target_id, url, title, active}]`)."
            .into(),
        input_schema: json!({"type": "object", "properties": {}}),
        handler: handler(|state, _args| {
            Box::pin(async move {
                let v = tab_list_value(&state).await?;
                Ok(text_content(serde_json::to_string_pretty(&v)?))
            })
        }),
    }
}

/// Build the `[{target_id, url, title, active}]` value for the current
/// browser. Shared between `browser_tab_list` and `browser_select`'s
/// response.
async fn tab_list_value(state: &ServerState) -> Result<Value> {
    let backend = state.ensure_backend().await?;
    let targets = backend.live_targets().await?;
    let active = state.active_target_id.lock().await.clone();
    let arr: Vec<Value> = targets
        .into_iter()
        .map(|t| {
            json!({
                "target_id": t.id,
                "url": t.url,
                "title": t.title,
                "active": active.as_deref() == Some(t.id.as_str()),
            })
        })
        .collect();
    Ok(Value::Array(arr))
}

fn make_tab_new() -> RegisteredTool {
    RegisteredTool {
        name: "browser_tab_new".into(),
        description: "Create a new tab and make it the active tab. Defaults to about:blank. \
                      Pass `name` to create or select a durable named tab addressable as \
                      `<browser>/<name>`."
            .into(),
        input_schema: json!({
            "type": "object",
            "properties": {
                "name": { "type": "string", "description": "Optional named-tab id (a-z, 0-9, '-', '_')." },
                "url": { "type": "string", "description": "Optional URL; defaults to about:blank." }
            },
        }),
        handler: handler(|state, args| {
            Box::pin(async move {
                if let Some(name) = args.get("name").and_then(|v| v.as_str()) {
                    let url = args.get("url").and_then(|v| v.as_str());
                    let opened = open_or_create_named_tab(&state, name, url).await?;
                    return Ok(text_content(serde_json::to_string_pretty(&opened)?));
                }
                let url = args
                    .get("url")
                    .and_then(|v| v.as_str())
                    .unwrap_or("about:blank")
                    .to_string();
                let backend = state.ensure_backend().await?;
                let tid = backend.create_tab(&url).await?;
                *state.active_target_id.lock().await = Some(tid.clone());
                Ok(text_content(serde_json::to_string_pretty(&json!({
                    "target_id": tid,
                    "url": url,
                    "active": true,
                }))?))
            })
        }),
    }
}

async fn open_or_create_named_tab(
    state: &ServerState,
    name: &str,
    url: Option<&str>,
) -> Result<Value> {
    crate::cli::env_resolver::validate_tab_name(name)?;
    let want_url = url.unwrap_or("about:blank").to_string();
    let backend = state.ensure_backend().await?;
    let browser_name = state.registered_browser_name().await?;

    let existing = {
        let bn = browser_name.clone();
        let n = name.to_string();
        crate::mcp::server::sync_registry_op(move |reg| reg.tab_get(&bn, &n)).await?
    };
    if let Some(row) = existing {
        let live = backend.live_target_ids().await?;
        if live.contains(&row.target_id) {
            if url.is_some() && row.last_url != want_url {
                backend.navigate(&row.target_id, &want_url).await?;
                let bn = browser_name.clone();
                let n = name.to_string();
                let u = want_url.clone();
                crate::mcp::server::sync_registry_op(move |reg| reg.tab_set_url(&bn, &n, &u))
                    .await?;
            } else {
                let bn = browser_name.clone();
                let n = name.to_string();
                crate::mcp::server::sync_registry_op(move |reg| reg.tab_touch(&bn, &n)).await?;
            }
            *state.active_target_id.lock().await = Some(row.target_id.clone());
            return Ok(json!({
                "name": name,
                "target_id": row.target_id,
                "url": if url.is_some() { want_url } else { row.last_url },
                "active": true,
                "created": false,
            }));
        }

        let _ = backend.close_tab(&row.target_id).await;
        let bn = browser_name.clone();
        let n = name.to_string();
        crate::mcp::server::sync_registry_op(move |reg| reg.tab_delete(&bn, &n)).await?;
    }

    let victim = {
        let bn = browser_name.clone();
        crate::mcp::server::sync_registry_op(
            move |reg| -> Result<Option<crate::registry::TabRow>> {
                if reg.tabs_count_daemon_created(&bn)? >= crate::session::tabs::HARD_CAP {
                    reg.tabs_lru_daemon_created(&bn)
                } else {
                    Ok(None)
                }
            },
        )
        .await?
    };
    if let Some(victim) = victim {
        let _ = backend.close_tab(&victim.target_id).await;
        let bn = victim.browser_name;
        let n = victim.name;
        crate::mcp::server::sync_registry_op(move |reg| reg.tab_delete(&bn, &n)).await?;
    }

    let target_id = backend.create_tab(&want_url).await?;
    let bn = browser_name;
    let n = name.to_string();
    let tid = target_id.clone();
    let u = want_url.clone();
    crate::mcp::server::sync_registry_op(move |reg| reg.tab_upsert(&bn, &n, &tid, &u, true))
        .await?;
    *state.active_target_id.lock().await = Some(target_id.clone());
    Ok(json!({
        "name": name,
        "target_id": target_id,
        "url": want_url,
        "active": true,
        "created": true,
    }))
}

fn make_tab_select() -> RegisteredTool {
    RegisteredTool {
        name: "browser_tab_select".into(),
        description: "Set the active tab. Probe-and-iterate: errors `TabHung` if the selected \
                      tab doesn't respond to a 500ms probe (agent should pick another or call \
                      `browser_tab_new`)."
            .into(),
        input_schema: json!({
            "type": "object",
            "properties": {
                "target_id": { "type": "string" }
            },
            "required": ["target_id"],
        }),
        handler: handler(|state, args| {
            Box::pin(async move {
                use crate::errors::SessionError;
                let tid = args
                    .get("target_id")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| anyhow!("missing 'target_id'"))?
                    .to_string();
                let backend = state.ensure_backend().await?;
                let live = backend.live_target_ids().await?;
                if !live.contains(&tid) {
                    return Err(SessionError::TabNotFound {
                        browser: state
                            .registered_browser_name()
                            .await
                            .unwrap_or_else(|_| "<external>".to_string()),
                        name: tid,
                    }
                    .into());
                }
                // Probe the tab. We don't auto-recreate on hang — the
                // agent asked for THIS tab; bubble up `TabHung` so they
                // can choose to `browser_tab_new` or pick a different
                // tab.
                let probed = tokio::time::timeout(
                    TAB_SELECT_PROBE,
                    backend.evaluate(&tid, "1", false, TAB_SELECT_PROBE),
                )
                .await;
                let ok = matches!(probed, Ok(Ok(_)));
                if !ok {
                    return Err(SessionError::TabHung {
                        target_id: Some(tid),
                        url: None,
                        timeout_ms: TAB_SELECT_PROBE.as_millis() as u64,
                        hint: "selected-tab-hung",
                    }
                    .into());
                }
                *state.active_target_id.lock().await = Some(tid.clone());
                Ok(text_content(serde_json::to_string_pretty(&json!({
                    "target_id": tid,
                    "active": true,
                }))?))
            })
        }),
    }
}

fn make_tab_close() -> RegisteredTool {
    RegisteredTool {
        name: "browser_tab_close".into(),
        description: "Close a tab. Defaults to the active tab; clears the active pointer if the \
                      closed tab was active."
            .into(),
        input_schema: json!({
            "type": "object",
            "properties": {
                "target_id": { "type": "string", "description": "Optional; defaults to active tab." }
            },
        }),
        handler: handler(|state, args| {
            Box::pin(async move {
                let backend = state.ensure_backend().await?;
                let explicit = args
                    .get("target_id")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string());
                let active = state.active_target_id.lock().await.clone();
                let tid = match (explicit, &active) {
                    (Some(e), _) => e,
                    (None, Some(a)) => a.clone(),
                    (None, None) => {
                        return Err(anyhow!("no `target_id` given and no active tab to close"));
                    }
                };
                backend.close_tab(&tid).await?;
                // If we just closed the active tab, clear the pointer.
                let mut ptr = state.active_target_id.lock().await;
                if ptr.as_deref() == Some(tid.as_str()) {
                    *ptr = None;
                }
                Ok(text_content(serde_json::to_string_pretty(&json!({
                    "closed": tid,
                }))?))
            })
        }),
    }
}

// ---------------------------------------------------------------------------
// browser_select / browser_list
// ---------------------------------------------------------------------------

fn make_browser_start() -> RegisteredTool {
    RegisteredTool {
        name: "browser_start".into(),
        description: "Start or reuse a browser, then make it the active MCP browser. \
                      Use this to recover after the active browser exits."
            .into(),
        input_schema: json!({
            "type": "object",
            "properties": {
                "browser": { "type": "string", "description": "Optional browser kind (chrome, edge, chromium, brave, firefox). Defaults to an already-running installed browser if any, otherwise the first installed Chromium-family browser." },
                "headless": { "type": "boolean", "default": false },
                "wait_timeout_seconds": { "type": "integer", "default": 30 }
            },
        }),
        handler: handler(|state, args| {
            Box::pin(async move {
                let browser = args
                    .get("browser")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string());
                let headless = args
                    .get("headless")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false);
                let wait_timeout = args
                    .get("wait_timeout_seconds")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(30);
                let started =
                    crate::cli::start::ensure_started(browser, headless, false, wait_timeout)
                        .await?;
                let resolved = crate::cli::env_resolver::ResolvedBrowser {
                    endpoint: started.endpoint.clone(),
                    engine: started.engine,
                    source: crate::cli::env_resolver::Source::Registered {
                        name: started.name.clone(),
                    },
                };
                state.switch_browser(resolved).await?;
                let tabs = tab_list_value(&state).await?;
                Ok(text_content(serde_json::to_string_pretty(&json!({
                    "name": started.name,
                    "kind": started.kind.as_str(),
                    "engine": match started.engine {
                        crate::detect::Engine::Cdp => "cdp",
                        crate::detect::Engine::Bidi => "bidi",
                    },
                    "endpoint": started.endpoint,
                    "reused": started.reused,
                    "selected": true,
                    "tabs": tabs,
                }))?))
            })
        }),
    }
}

fn make_browser_select() -> RegisteredTool {
    RegisteredTool {
        name: "browser_select".into(),
        description: "Switch the active browser by registered name, kind, URL, or CLI target \
                      syntax such as `chrome` or `brave/cart`. A kind selector starts or reuses \
                      that browser when none is live. The switch is committed before \
                      Firefox BiDi lock preparation; if preparation fails, the new browser remains \
                      active and the caller decides whether to retry, switch elsewhere, or switch back."
            .into(),
        input_schema: json!({
            "type": "object",
            "properties": {
                "name": { "type": "string", "description": "Browser selector, optionally `<browser>/<tab>`." }
            },
            "required": ["name"],
        }),
        handler: handler(|state, args| {
            Box::pin(async move {
                let name = args
                    .get("name")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| anyhow!("missing 'name'"))?
                    .to_string();
                let target = crate::cli::env_resolver::parse_target(&name)?;
                let resolved =
                    crate::mcp::server::resolve_browser_send(target.browser.clone()).await?;
                let resolved_clone = resolved.clone();
                state.switch_browser(resolved).await?;
                let selected_tab = if let Some(tab) = target.tab.as_deref() {
                    Some(open_or_create_named_tab(&state, tab, None).await?)
                } else {
                    None
                };
                let tabs = tab_list_value(&state).await?;
                Ok(text_content(serde_json::to_string_pretty(&json!({
                    "name": match &resolved_clone.source {
                        crate::cli::env_resolver::Source::Registered { name } => name.as_str(),
                        crate::cli::env_resolver::Source::External => "<external>",
                    },
                    "engine": match resolved_clone.engine {
                        crate::detect::Engine::Cdp => "cdp",
                        crate::detect::Engine::Bidi => "bidi",
                    },
                    "endpoint": resolved_clone.endpoint,
                    "selected_tab": selected_tab,
                    "tabs": tabs,
                }))?))
            })
        }),
    }
}

fn make_browser_list() -> RegisteredTool {
    RegisteredTool {
        name: "browser_list".into(),
        description: "List live registered browsers with `[{name, kind, engine, endpoint, alive}]`; dead-process rows are pruned."
            .into(),
        input_schema: json!({"type": "object", "properties": {}}),
        handler: handler(|_state, _args| {
            Box::pin(async move {
                // `Registry` is `!Send`; do the read on a blocking thread.
                let arr = tokio::task::spawn_blocking(|| -> Result<Vec<Value>> {
                    let registry = crate::registry::Registry::open()?;
                    let rows = registry.list_alive()?;
                    Ok(rows
                        .into_iter()
                        .map(|r| {
                            json!({
                                "name": r.name,
                                "kind": r.kind.as_str(),
                                "engine": match r.engine {
                                    crate::detect::Engine::Cdp => "cdp",
                                    crate::detect::Engine::Bidi => "bidi",
                                },
                                "endpoint": r.endpoint,
                                "alive": true,
                            })
                        })
                        .collect())
                })
                .await??;
                Ok(text_content(serde_json::to_string_pretty(&Value::Array(
                    arr,
                ))?))
            })
        }),
    }
}

fn make_browser_show() -> RegisteredTool {
    RegisteredTool {
        name: "browser_show".into(),
        description: "Explicitly reveal the active browser window for login or debugging. \
                      Normal automation keeps new tabs in the background."
            .into(),
        input_schema: json!({"type": "object", "properties": {}}),
        handler: handler(|state, _args| {
            Box::pin(async move {
                let backend = state.ensure_backend().await?;
                let target_id = backend.target_for_show().await?;
                let resolved = state.browser_snapshot().await;
                let source = resolved.source.clone();
                // External endpoints have no registered executable to
                // activate. Avoid opening the global registry in that case;
                // besides being unnecessary I/O, it could race a concurrent
                // browser switch or test-time data-directory override.
                let os_activated = match source {
                    crate::cli::env_resolver::Source::External => false,
                    source @ crate::cli::env_resolver::Source::Registered { .. } => {
                        tokio::task::spawn_blocking(move || -> Result<bool> {
                            let registry = crate::registry::Registry::open()?;
                            crate::cli::show::activate_resolved_app(&registry, &source)
                        })
                        .await??
                    }
                };
                backend.show_tab(&target_id).await?;
                Ok(text_content(serde_json::to_string_pretty(&json!({
                    "target_id": target_id,
                    "os_activated": os_activated,
                }))?))
            })
        }),
    }
}

// ---------------------------------------------------------------------------
// Playwright-only interaction tools (routed through the Node sidecar).
// ---------------------------------------------------------------------------
//
// Each tool:
//   1. Resolves the target tab via `state.resolve_target_for_args(args)`.
//   2. Acquires the sidecar via `state.ensure_sidecar(tool_name)`. On
//      BiDi browsers this errors with `EngineUnsupported`.
//   3. Forwards to the sidecar with `target_id` + tool-specific params.

/// Forward a sidecar call. Resolves the target natively first, ensures the
/// sidecar is up, then sends the RPC with `target_id` merged into the params.
/// If Playwright fails at the CDP attachment/connection layer, wake and probe
/// the tab through browser-control's native backend before returning a typed
/// sidecar-specific error. This prevents agents from misreading a sidecar CDP
/// timeout as evidence that the page itself is hung.
async fn forward_to_sidecar(
    state: &ServerState,
    tool_name: &str,
    args: &Value,
    sidecar_method: &str,
    mut params: serde_json::Map<String, Value>,
) -> Result<Value> {
    // Preflight: check engine support before resolving the target, but do not
    // spawn the sidecar yet. If Playwright attach fails, we still need a native
    // backend + target id for the wake/probe diagnostic.
    state.ensure_sidecar_supported(tool_name).await?;
    let (backend, target_id) = state.resolve_target_for_args(args).await?;
    params.insert("target_id".into(), Value::String(target_id));
    let sc = match state.ensure_sidecar(tool_name).await {
        Ok(sc) => sc,
        Err(e) if looks_like_sidecar_cdp_attach_failure(&e) => {
            return sidecar_cdp_failure_after_probe(
                state,
                &backend,
                tool_name,
                sidecar_method,
                params
                    .get("target_id")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default(),
                e,
            )
            .await;
        }
        Err(e) => return Err(e),
    };
    match sc.call(sidecar_method, Value::Object(params.clone())).await {
        Ok(v) => Ok(v),
        Err(e) if looks_like_sidecar_cdp_attach_failure(&e) => {
            sidecar_cdp_failure_after_probe(
                state,
                &backend,
                tool_name,
                sidecar_method,
                params
                    .get("target_id")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default(),
                e,
            )
            .await
        }
        Err(e) => Err(e),
    }
}

async fn sidecar_cdp_failure_after_probe(
    state: &ServerState,
    backend: &TabBackend,
    tool_name: &str,
    sidecar_method: &str,
    target_id: &str,
    err: anyhow::Error,
) -> Result<Value> {
    state.reset_sidecar().await;
    let url = wake_and_probe_target(backend, target_id).await?;
    Err(SessionError::SidecarConnectionFailed {
        tool: tool_name.to_string(),
        method: sidecar_method.to_string(),
        target_id: target_id.to_string(),
        url,
        details: format!("{err:#}"),
        hint: "retry the Playwright-sidecar tool or inspect with browser_get_html / browser_take_screenshot",
    }
    .into())
}

async fn wake_and_probe_target(backend: &TabBackend, target_id: &str) -> Result<Option<String>> {
    match tokio::time::timeout(SIDECAR_WAKE_PROBE_TIMEOUT, backend.show_tab(target_id)).await {
        Ok(r) => r?,
        Err(_) => {
            return Err(SessionError::TabHung {
                target_id: Some(target_id.to_string()),
                url: None,
                timeout_ms: SIDECAR_WAKE_PROBE_TIMEOUT.as_millis() as u64,
                hint: "sidecar-wake-timeout",
            }
            .into());
        }
    }

    match tokio::time::timeout(
        SIDECAR_WAKE_PROBE_TIMEOUT,
        backend.evaluate(target_id, "1", false, SIDECAR_WAKE_PROBE_TIMEOUT),
    )
    .await
    {
        Ok(r) => {
            let _ = r?;
        }
        Err(_) => {
            return Err(SessionError::TabHung {
                target_id: Some(target_id.to_string()),
                url: None,
                timeout_ms: SIDECAR_WAKE_PROBE_TIMEOUT.as_millis() as u64,
                hint: "sidecar-probe-timeout",
            }
            .into());
        }
    }

    match tokio::time::timeout(SIDECAR_WAKE_PROBE_TIMEOUT, backend.live_targets()).await {
        Ok(Ok(targets)) => Ok(targets
            .into_iter()
            .find(|t| t.id == target_id)
            .map(|t| t.url)),
        _ => Ok(None),
    }
}

fn looks_like_sidecar_cdp_attach_failure(err: &anyhow::Error) -> bool {
    let msg = format!("{err:#}").to_ascii_lowercase();
    msg.contains("<ws connecting>")
        || msg.contains("connectovercdp")
        || msg.contains("websocket")
        || msg.contains("browser has been closed")
        || msg.contains("browser closed")
        || msg.contains("browser disconnected")
        || msg.contains("target closed")
        || msg.contains("cdp session closed")
        || msg.contains("econnrefused")
        || msg.contains("econnreset")
        || msg.contains("socket hang up")
        || msg.contains("sidecar stdout closed")
        || msg.contains("sidecar writer closed")
        || msg.contains("sidecar response channel dropped")
}

fn make_snapshot() -> RegisteredTool {
    RegisteredTool {
        name: "browser_snapshot".into(),
        description: "Capture an accessibility-tree snapshot (YAML) of the active page. \
                      Chromium-only via Playwright sidecar."
            .into(),
        input_schema: json!({
            "type": "object",
            "properties": tab_args_schema(),
        }),
        handler: handler(|state, args| {
            Box::pin(async move {
                let v = forward_to_sidecar(
                    &state,
                    "browser_snapshot",
                    &args,
                    "snapshot",
                    serde_json::Map::new(),
                )
                .await?;
                let yaml = v
                    .get("snapshot")
                    .and_then(|s| s.as_str())
                    .unwrap_or_default();
                Ok(text_content(yaml))
            })
        }),
    }
}

// ---------------------------------------------------------------------------
// Table-driven sidecar interaction tools.
//
// click / type / hover / drag / press_key / wait_for all share one shape:
// build a param map from a fixed set of args, forward to the sidecar, return a
// fixed success string. Previously each tool declared its params *twice* — once
// in the input schema (`tab_args_properties`) and once in the handler (`copy_arg` per
// param) — with no compiler link, so a schema param missing a matching
// `copy_arg` was silently dropped before reaching the sidecar.
//
// `SidecarTool` is the single source of truth: each param's name + schema +
// required-ness is declared once in `params`, and BOTH the input schema and the
// param-forwarding are derived from it, so a param can't be in the schema but
// missing from the wire (or vice versa).
// ---------------------------------------------------------------------------

/// One sidecar-forwarded parameter, declared once. Drives both the JSON schema
/// (`schema`, `required`) and the runtime forwarding (`name`).
struct SidecarParam {
    name: &'static str,
    schema: Value,
    required: bool,
}

/// Declarative spec for a sidecar interaction tool. Both the input schema and
/// the param-forwarding are derived from the single `params` slice.
struct SidecarTool {
    name: &'static str,
    description: &'static str,
    /// The sidecar RPC method (e.g. `"click"`).
    method: &'static str,
    params: Vec<SidecarParam>,
    /// Fixed success message returned as text content.
    success: &'static str,
}

impl SidecarTool {
    fn build(self) -> RegisteredTool {
        let SidecarTool {
            name,
            description,
            method,
            params,
            success,
        } = self;

        // Schema: shared tab/target args plus this tool's params, with the
        // `required` list derived from the same table.
        let extra = Value::Object(
            params
                .iter()
                .map(|p| (p.name.to_string(), p.schema.clone()))
                .collect(),
        );
        let required: Vec<&str> = params
            .iter()
            .filter(|p| p.required)
            .map(|p| p.name)
            .collect();
        let mut input_schema = json!({
            "type": "object",
            "properties": tab_args_properties(extra),
        });
        if !required.is_empty() {
            input_schema["required"] = json!(required);
        }

        // Forwarding: copy exactly the params declared above — no second list
        // to drift out of sync.
        let param_names: Vec<&'static str> = params.iter().map(|p| p.name).collect();
        RegisteredTool {
            name: name.into(),
            description: description.into(),
            input_schema,
            handler: handler(move |state, args| {
                let param_names = param_names.clone();
                Box::pin(async move {
                    let mut params = serde_json::Map::new();
                    for key in &param_names {
                        copy_arg(&args, key, &mut params);
                    }
                    forward_to_sidecar(&state, name, &args, method, params).await?;
                    Ok(text_content(success))
                })
            }),
        }
    }
}

fn make_click() -> RegisteredTool {
    SidecarTool {
        name: "browser_click",
        description: "Click an element matched by CSS selector. Chromium-only.",
        method: "click",
        params: vec![
            SidecarParam {
                name: "selector",
                schema: json!({"type": "string"}),
                required: true,
            },
            SidecarParam {
                name: "timeout_ms",
                schema: json!({"type": "integer"}),
                required: false,
            },
        ],
        success: "clicked",
    }
    .build()
}

fn make_type() -> RegisteredTool {
    SidecarTool {
        name: "browser_type",
        description: "Type text into an input matched by CSS selector. \
                      `press_sequentially=true` simulates keystrokes; default uses fast `fill`. \
                      Chromium-only.",
        method: "type",
        params: vec![
            SidecarParam {
                name: "selector",
                schema: json!({"type": "string"}),
                required: true,
            },
            SidecarParam {
                name: "text",
                schema: json!({"type": "string"}),
                required: true,
            },
            SidecarParam {
                name: "press_sequentially",
                schema: json!({"type": "boolean"}),
                required: false,
            },
            SidecarParam {
                name: "timeout_ms",
                schema: json!({"type": "integer"}),
                required: false,
            },
        ],
        success: "typed",
    }
    .build()
}

fn make_hover() -> RegisteredTool {
    SidecarTool {
        name: "browser_hover",
        description: "Hover an element matched by CSS selector. Chromium-only.",
        method: "hover",
        params: vec![
            SidecarParam {
                name: "selector",
                schema: json!({"type": "string"}),
                required: true,
            },
            SidecarParam {
                name: "timeout_ms",
                schema: json!({"type": "integer"}),
                required: false,
            },
        ],
        success: "hovered",
    }
    .build()
}

fn make_drag() -> RegisteredTool {
    SidecarTool {
        name: "browser_drag",
        description: "Drag from one CSS-selected element to another. Chromium-only.",
        method: "drag",
        params: vec![
            SidecarParam {
                name: "source_selector",
                schema: json!({"type": "string"}),
                required: true,
            },
            SidecarParam {
                name: "target_selector",
                schema: json!({"type": "string"}),
                required: true,
            },
        ],
        success: "dragged",
    }
    .build()
}

fn make_press_key() -> RegisteredTool {
    SidecarTool {
        name: "browser_press_key",
        description: "Press a keyboard key (Playwright key name, e.g. 'Enter', 'Control+A'). \
                      Chromium-only.",
        method: "press_key",
        params: vec![SidecarParam {
            name: "key",
            schema: json!({"type": "string"}),
            required: true,
        }],
        success: "pressed",
    }
    .build()
}

fn make_wait_for() -> RegisteredTool {
    SidecarTool {
        name: "browser_wait_for",
        description: "Wait for a condition: a selector reaching `state`, a URL matching \
                      `url_regex`, or the page reaching `load_state` (`load` / \
                      `domcontentloaded` / `networkidle`). Chromium-only.",
        method: "wait_for",
        params: vec![
            SidecarParam { name: "selector", schema: json!({"type": "string"}), required: false },
            SidecarParam { name: "state", schema: json!({"type": "string", "enum": ["attached", "detached", "visible", "hidden"]}), required: false },
            SidecarParam { name: "url_regex", schema: json!({"type": "string"}), required: false },
            SidecarParam { name: "load_state", schema: json!({"type": "string", "enum": ["load", "domcontentloaded", "networkidle"]}), required: false },
            SidecarParam { name: "timeout_ms", schema: json!({"type": "integer"}), required: false },
        ],
        success: "ok",
    }
    .build()
}

fn make_pdf_save() -> RegisteredTool {
    RegisteredTool {
        name: "browser_pdf_save".into(),
        description: "Render the active page to PDF (base64 in `pdf_base64`). Chromium-only."
            .into(),
        input_schema: json!({
            "type": "object",
            "properties": tab_args_schema(),
        }),
        handler: handler(|state, args| {
            Box::pin(async move {
                let v = forward_to_sidecar(
                    &state,
                    "browser_pdf_save",
                    &args,
                    "pdf",
                    serde_json::Map::new(),
                )
                .await?;
                let b64 = v
                    .get("pdf_base64")
                    .and_then(|s| s.as_str())
                    .unwrap_or_default();
                Ok(json!({
                    "content": [{
                        "type": "resource",
                        "resource": { "mimeType": "application/pdf", "blob": b64 }
                    }]
                }))
            })
        }),
    }
}

/// Helper: copy a key from `args` into `dst` if present.
fn copy_arg(args: &Value, key: &str, dst: &mut serde_json::Map<String, Value>) {
    if let Some(v) = args.get(key) {
        dst.insert(key.into(), v.clone());
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures_util::{SinkExt, StreamExt};
    use tokio::sync::Mutex;
    use tokio_tungstenite::tungstenite::Message;

    /// All tools the registry exposes after `register_all`. Mirrors the
    /// registration order in `register_all`.
    const EXPECTED_TOOLS: &[&str] = &[
        "browser_navigate",
        "browser_eval",
        "browser_get_html",
        "browser_take_screenshot",
        "browser_fetch",
        "browser_curl",
        "browser_select_element",
        "browser_cookies",
        "browser_storage_get",
        "browser_storage_set",
        "browser_wait_for_cookie",
        "list_targets",
        "browser_tab_list",
        "browser_tab_new",
        "browser_tab_select",
        "browser_tab_close",
        "browser_start",
        "browser_select",
        "browser_list",
        "browser_show",
        "browser_snapshot",
        "browser_click",
        "browser_type",
        "browser_hover",
        "browser_drag",
        "browser_press_key",
        "browser_wait_for",
        "browser_pdf_save",
    ];

    fn schema_for(name: &str) -> Value {
        let registry = ToolRegistry::new();
        register_all(&registry);
        registry
            .list()
            .into_iter()
            .find(|t| t["name"] == name)
            .unwrap_or_else(|| panic!("tool {name} not registered"))["inputSchema"]
            .clone()
    }

    fn tool_description(name: &str) -> String {
        let registry = ToolRegistry::new();
        register_all(&registry);
        registry
            .list()
            .into_iter()
            .find(|t| t["name"] == name)
            .unwrap_or_else(|| panic!("tool {name} not registered"))["description"]
            .as_str()
            .unwrap_or("")
            .to_string()
    }

    struct ScreenshotMock {
        endpoint: String,
        capture_params: Arc<Mutex<Vec<Value>>>,
    }

    async fn spawn_screenshot_mock(selector_rect: Value) -> ScreenshotMock {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let capture_params = Arc::new(Mutex::new(Vec::new()));
        tokio::spawn({
            let capture_params = capture_params.clone();
            async move {
                let (stream, _) = listener.accept().await.unwrap();
                let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
                let mut next_session = 0u32;
                let mut eval_count = 0u32;
                while let Some(Ok(Message::Text(t))) = ws.next().await {
                    let req: Value = serde_json::from_str(&t).unwrap();
                    let id = req["id"].as_u64().unwrap();
                    let method = req["method"].as_str().unwrap_or("");
                    let result = match method {
                        "Target.getTargets" => json!({
                            "targetInfos": [{
                                "targetId": "T1",
                                "type": "page",
                                "url": "https://example.com/",
                                "title": "Example",
                            }]
                        }),
                        "Target.attachToTarget" => {
                            next_session += 1;
                            json!({"sessionId": format!("S{next_session}")})
                        }
                        "Target.detachFromTarget" => json!({}),
                        "Inspector.enable" => json!({}),
                        "Runtime.evaluate" => {
                            eval_count += 1;
                            if eval_count == 1 {
                                json!({"result": {"value": 1}})
                            } else {
                                json!({"result": {"value": selector_rect.clone()}})
                            }
                        }
                        "Page.captureScreenshot" => {
                            capture_params.lock().await.push(req["params"].clone());
                            json!({"data": "PNGDATA"})
                        }
                        _ => json!({}),
                    };
                    let resp = json!({"id": id, "result": result});
                    ws.send(Message::Text(resp.to_string())).await.unwrap();
                }
            }
        });
        ScreenshotMock {
            endpoint: format!("ws://{addr}"),
            capture_params,
        }
    }

    #[test]
    fn register_all_includes_expected_set() {
        let registry = ToolRegistry::new();
        register_all(&registry);
        let list = registry.list();
        let names: Vec<&str> = list.iter().map(|t| t["name"].as_str().unwrap()).collect();
        for expected in EXPECTED_TOOLS {
            assert!(
                names.contains(expected),
                "missing tool {expected} in {names:?}"
            );
        }
        assert_eq!(
            list.len(),
            EXPECTED_TOOLS.len(),
            "extra tools present: {names:?}"
        );
    }

    #[test]
    fn every_tool_has_object_input_schema() {
        let registry = ToolRegistry::new();
        register_all(&registry);
        for t in registry.list() {
            let schema = &t["inputSchema"];
            assert!(schema.is_object(), "schema not object: {schema}");
            assert_eq!(
                schema["type"], "object",
                "schema type != object for {}: {schema}",
                t["name"]
            );
        }
    }

    #[test]
    fn list_targets_schema_has_optional_filter() {
        let schema = schema_for("list_targets");
        assert_eq!(schema["properties"]["filter"]["type"], "string");
        assert!(
            schema.get("required").is_none() || schema["required"].as_array().unwrap().is_empty()
        );
    }

    #[test]
    fn browser_cookies_schema_has_optional_filters() {
        let schema = schema_for("browser_cookies");
        assert_eq!(schema["properties"]["domain"]["type"], "string");
        assert_eq!(schema["properties"]["name"]["type"], "string");
        assert!(
            schema.get("required").is_none() || schema["required"].as_array().unwrap().is_empty()
        );
    }

    #[test]
    fn browser_eval_requires_expression_and_supports_routing() {
        let schema = schema_for("browser_eval");
        let required = schema["required"].as_array().expect("required array");
        assert!(required.iter().any(|v| v == "expression"));
        assert_eq!(schema["properties"]["expression"]["type"], "string");
        assert_eq!(schema["properties"]["await_promise"]["type"], "boolean");
        assert_eq!(schema["properties"]["timeout_ms"]["type"], "number");
        assert_eq!(schema["properties"]["tab"]["type"], "string");
        assert_eq!(schema["properties"]["target"]["type"], "string");
    }

    #[test]
    fn browser_storage_get_requires_key() {
        let schema = schema_for("browser_storage_get");
        let required = schema["required"].as_array().expect("required array");
        assert!(required.iter().any(|v| v == "key"));
        assert_eq!(schema["properties"]["key"]["type"], "string");
        assert_eq!(schema["properties"]["namespace"]["type"], "string");
    }

    #[test]
    fn browser_storage_set_requires_key_and_value() {
        let schema = schema_for("browser_storage_set");
        let required: Vec<&str> = schema["required"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert!(required.contains(&"key"));
        assert!(required.contains(&"value"));
        assert_eq!(schema["properties"]["value"]["type"], "string");
    }

    #[test]
    fn browser_wait_for_cookie_requires_domain_and_name() {
        let schema = schema_for("browser_wait_for_cookie");
        let required: Vec<&str> = schema["required"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert!(required.contains(&"domain"));
        assert!(required.contains(&"name"));
        assert_eq!(schema["properties"]["timeout_seconds"]["type"], "number");
        assert_eq!(
            schema["properties"]["poll_interval_seconds"]["type"],
            "number"
        );
    }

    #[test]
    fn browser_navigate_schema_has_tab_and_target() {
        // Per-tab tools expose optional `tab`/`target` for routing.
        let schema = schema_for("browser_navigate");
        assert_eq!(schema["properties"]["tab"]["type"], "string");
        assert_eq!(schema["properties"]["target"]["type"], "string");
        let required: Vec<&str> = schema["required"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert!(required.contains(&"url"));
        assert!(!required.contains(&"tab"));
        assert!(!required.contains(&"target"));
    }

    #[test]
    fn browser_tab_select_requires_target_id() {
        let schema = schema_for("browser_tab_select");
        let required: Vec<&str> = schema["required"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert!(required.contains(&"target_id"));
    }

    #[test]
    fn browser_tab_close_target_id_is_optional() {
        // Default = close active tab; no required args.
        let schema = schema_for("browser_tab_close");
        assert!(
            schema.get("required").is_none() || schema["required"].as_array().unwrap().is_empty()
        );
        assert_eq!(schema["properties"]["target_id"]["type"], "string");
    }

    #[test]
    fn browser_select_requires_name() {
        let schema = schema_for("browser_select");
        let required: Vec<&str> = schema["required"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert!(required.contains(&"name"));
    }

    #[test]
    fn browser_select_description_documents_failed_lock_contract() {
        let desc = tool_description("browser_select");
        assert!(desc.contains("committed before"));
        assert!(desc.contains("new browser remains active"));
        assert!(desc.contains("switch back"));
    }

    #[test]
    fn browser_list_has_no_args() {
        let schema = schema_for("browser_list");
        assert_eq!(schema["properties"], json!({}));
    }

    #[test]
    fn browser_cookies_schema_has_no_tab_arg() {
        // Cookies are browser-wide; no per-tab routing.
        let schema = schema_for("browser_cookies");
        assert!(schema["properties"].get("tab").is_none());
        assert!(schema["properties"].get("target").is_none());
    }

    /// Sidecar-routed tools expose `tab`/`target` for the same routing
    /// surface as the other per-tab tools.
    #[test]
    fn sidecar_tools_expose_tab_and_target() {
        for name in &[
            "browser_snapshot",
            "browser_click",
            "browser_type",
            "browser_hover",
            "browser_drag",
            "browser_press_key",
            "browser_wait_for",
            "browser_pdf_save",
        ] {
            let schema = schema_for(name);
            assert_eq!(
                schema["properties"]["tab"]["type"], "string",
                "{name} missing tab arg"
            );
            assert_eq!(
                schema["properties"]["target"]["type"], "string",
                "{name} missing target arg"
            );
        }
    }

    /// `browser_click` / `browser_type` etc. require their selector
    /// args; `browser_snapshot` / `browser_pdf_save` / `browser_wait_for`
    /// don't (snapshot is page-wide, wait_for has multiple alternative
    /// conditions, pdf is page-wide).
    #[test]
    fn sidecar_tools_required_args() {
        let click = schema_for("browser_click");
        let req: Vec<&str> = click["required"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert!(req.contains(&"selector"));

        let t = schema_for("browser_type");
        let req: Vec<&str> = t["required"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert!(req.contains(&"selector"));
        assert!(req.contains(&"text"));

        // No required args on these.
        let snap = schema_for("browser_snapshot");
        assert!(snap.get("required").is_none() || snap["required"].as_array().unwrap().is_empty());
        let pdf = schema_for("browser_pdf_save");
        assert!(pdf.get("required").is_none() || pdf["required"].as_array().unwrap().is_empty());
    }

    /// Sidecar tool against a BiDi browser must error with
    /// `EngineUnsupported` BEFORE attempting to spawn the sidecar — so
    /// even systems without Node/Bun get a clean message.
    #[tokio::test]
    async fn sidecar_tool_on_bidi_returns_engine_unsupported() {
        use crate::cli::env_resolver::{ResolvedBrowser, Source};
        use crate::detect::Engine;
        use crate::errors::SessionError;

        // ServerState bound to a BiDi browser. Endpoint never gets hit
        // because the engine check short-circuits.
        let resolved = ResolvedBrowser {
            engine: Engine::Bidi,
            endpoint: "ws://127.0.0.1:0".into(),
            source: Source::External,
        };
        let state = ServerState::new(resolved);

        let err = match state.ensure_sidecar("browser_snapshot").await {
            Ok(_) => panic!("BiDi must error"),
            Err(e) => e,
        };
        let typed = err.downcast_ref::<SessionError>().expect("typed error");
        match typed {
            SessionError::EngineUnsupported { tool, hint, .. } => {
                assert_eq!(tool, "browser_snapshot");
                assert!(!hint.contains(concat!("browser_", "evaluate")));
                assert!(hint.contains("browser_get_html"));
                assert!(hint.contains("browser_select"));
            }
            other => panic!("expected EngineUnsupported, got {other:?}"),
        }
    }

    #[test]
    fn sidecar_cdp_attach_failure_classifier_matches_connect_layer_errors() {
        let err = anyhow::anyhow!(
            "browserType.connectOverCDP: Timeout 5000ms exceeded while <ws connecting> to ws://127.0.0.1:64767/devtools/browser/x"
        );
        assert!(looks_like_sidecar_cdp_attach_failure(&err));

        let err = anyhow::anyhow!("page.waitForLoadState: Timeout 30000ms exceeded");
        assert!(
            !looks_like_sidecar_cdp_attach_failure(&err),
            "normal page wait timeouts must not be reclassified as sidecar attach failures"
        );
    }

    #[test]
    fn sidecar_connection_failed_message_discourages_page_hang_inference() {
        let err = SessionError::SidecarConnectionFailed {
            tool: "browser_snapshot".into(),
            method: "snapshot".into(),
            target_id: "T1".into(),
            url: Some("http://localhost:5173/404".into()),
            details: "browserType.connectOverCDP: Timeout 5000ms exceeded".into(),
            hint: "retry the Playwright-sidecar tool or inspect with browser_get_html / browser_take_screenshot",
        };
        let msg = err.to_string();
        assert!(msg.contains("Playwright sidecar connection failed"));
        assert!(msg.contains("not evidence that the page is hung"));
        assert!(msg.contains("browser_get_html"));
    }

    #[tokio::test]
    async fn screenshot_selector_sends_cdp_clip() {
        let mock = spawn_screenshot_mock(json!({
            "x": 12.5,
            "y": 34.0,
            "width": 56.0,
            "height": 78.0,
        }))
        .await;
        let state = ServerState::new(ResolvedBrowser {
            engine: Engine::Cdp,
            endpoint: mock.endpoint,
            source: Source::External,
        });
        let h = handler_for("browser_take_screenshot");
        let out = h(
            state,
            json!({
                "target": "example\\.com",
                "selector": "#main",
            }),
        )
        .await
        .unwrap();
        assert_eq!(out["content"][0]["type"], "image");
        assert_eq!(out["content"][0]["data"], "PNGDATA");

        let captures = mock.capture_params.lock().await;
        assert_eq!(captures.len(), 1);
        assert_eq!(captures[0]["format"], "png");
        assert_eq!(captures[0]["captureBeyondViewport"], true);
        assert_eq!(captures[0]["clip"]["x"], json!(12.5));
        assert_eq!(captures[0]["clip"]["y"], json!(34.0));
        assert_eq!(captures[0]["clip"]["width"], json!(56.0));
        assert_eq!(captures[0]["clip"]["height"], json!(78.0));
        assert_eq!(captures[0]["clip"]["scale"], json!(1));
    }

    #[tokio::test]
    async fn screenshot_selector_null_rect_errors_clearly() {
        let mock = spawn_screenshot_mock(Value::Null).await;
        let state = ServerState::new(ResolvedBrowser {
            engine: Engine::Cdp,
            endpoint: mock.endpoint,
            source: Source::External,
        });
        let h = handler_for("browser_take_screenshot");
        let err = h(
            state,
            json!({
                "target": "example\\.com",
                "selector": "#missing",
            }),
        )
        .await
        .expect_err("null selector rect must error");
        assert!(
            err.to_string()
                .contains("selector matched no visible element: #missing"),
            "got: {err:#}"
        );
        assert!(mock.capture_params.lock().await.is_empty());
    }

    // -- Behavioral handler arg-validation -----------------------------------
    //
    // These invoke the real handler closures (not just the static schema)
    // against a `ServerState` whose endpoint is never reached, because the
    // arg-validation / mutual-exclusion checks fire *before* any backend
    // connection. No browser required.

    use crate::cli::env_resolver::{ResolvedBrowser, Source};
    use crate::detect::Engine;

    /// Fetch a registered tool's handler by name.
    fn handler_for(name: &str) -> ToolHandler {
        let registry = ToolRegistry::new();
        register_all(&registry);
        registry
            .handler(name)
            .unwrap_or_else(|| panic!("tool {name} not registered"))
    }

    /// A `ServerState` bound to an endpoint that is never reached (the
    /// handler errors during validation first). Marked CDP so we don't
    /// trip the BiDi-lock path.
    fn unreached_state() -> ServerState {
        ServerState::new(ResolvedBrowser {
            engine: Engine::Cdp,
            // Port 0 never accepts; any attempt to open a backend would
            // fail, but these tests assert the *validation* error fires
            // first.
            endpoint: "ws://127.0.0.1:0".into(),
            source: Source::External,
        })
    }

    #[tokio::test]
    async fn navigate_missing_url_errors_before_backend() {
        let h = handler_for("browser_navigate");
        let err = h(unreached_state(), json!({}))
            .await
            .expect_err("missing url must error");
        assert!(err.to_string().contains("missing 'url'"), "got: {err:#}");
    }

    #[tokio::test]
    async fn fetch_missing_url_errors_before_backend() {
        let h = handler_for("browser_fetch");
        let err = h(unreached_state(), json!({"method": "GET"}))
            .await
            .expect_err("missing url must error");
        assert!(err.to_string().contains("missing 'url'"), "got: {err:#}");
    }

    #[tokio::test]
    async fn curl_missing_args_errors_before_backend() {
        let h = handler_for("browser_curl");
        let err = h(unreached_state(), json!({}))
            .await
            .expect_err("missing args must error");
        assert!(err.to_string().contains("'args'"), "got: {err:#}");
    }

    #[tokio::test]
    async fn curl_rejects_non_string_args_before_backend() {
        let h = handler_for("browser_curl");
        let err = h(unreached_state(), json!({"args": ["-L", 7]}))
            .await
            .expect_err("non-string args must error");
        assert!(
            err.to_string()
                .contains("every curl argument must be a string"),
            "got: {err:#}"
        );
    }

    #[tokio::test]
    async fn storage_set_missing_value_errors_before_backend() {
        let h = handler_for("browser_storage_set");
        let err = h(unreached_state(), json!({"key": "k"}))
            .await
            .expect_err("missing value must error");
        assert!(err.to_string().contains("missing 'value'"), "got: {err:#}");
    }

    #[tokio::test]
    async fn storage_get_missing_key_errors_before_backend() {
        let h = handler_for("browser_storage_get");
        let err = h(unreached_state(), json!({}))
            .await
            .expect_err("missing key must error");
        assert!(err.to_string().contains("missing 'key'"), "got: {err:#}");
    }

    /// `tab` and `target` are mutually exclusive; the reject fires in
    /// `resolve_target_for_args` before any backend connection.
    #[tokio::test]
    async fn navigate_tab_and_target_mutually_exclusive() {
        let h = handler_for("browser_navigate");
        let err = h(
            unreached_state(),
            json!({"url": "https://e.test/", "tab": "a", "target": "b"}),
        )
        .await
        .expect_err("tab+target must error");
        assert!(
            err.to_string().contains("mutually exclusive"),
            "got: {err:#}"
        );
    }
}