victauri-plugin 0.1.0

Tauri plugin for Victauri — embedded MCP server with full-stack introspection
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
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use rmcp::handler::server::tool::ToolCallContext;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::{
    AnnotateAble, CallToolRequestParams, CallToolResult, Content, ListResourcesResult,
    ListToolsResult, PaginatedRequestParams, RawResource, ReadResourceRequestParams,
    ReadResourceResult, ResourceContents, ServerCapabilities, ServerInfo, SubscribeRequestParams,
    Tool, UnsubscribeRequestParams,
};
use rmcp::service::RequestContext;
use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
use rmcp::{ErrorData, RoleServer, ServerHandler, tool, tool_router};
use schemars::JsonSchema;
use serde::Deserialize;
use tauri::Runtime;
use tokio::sync::Mutex;

use crate::VictauriState;
use crate::bridge::WebviewBridge;

/// Produce a properly escaped JavaScript string literal (with double quotes).
/// Uses serde_json which handles all special characters: \n, \r, \0, \t,
/// unicode escapes, quotes, backslashes, etc.
fn js_string(s: &str) -> String {
    serde_json::to_string(s).unwrap_or_else(|_| "\"\"".to_string())
}

// ── Parameter structs ────────────────────────────────────────────────────────

#[derive(Debug, Deserialize, JsonSchema)]
pub struct EvalJsParams {
    /// JavaScript code to evaluate in the webview. Async expressions supported.
    pub code: String,
    /// Target webview label. If omitted, targets the first available webview.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct ClickParams {
    /// Ref handle ID from a DOM snapshot (e.g. "e5").
    pub ref_id: String,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct FillParams {
    /// Ref handle ID of the input element.
    pub ref_id: String,
    /// Value to set on the input.
    pub value: String,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct TypeTextParams {
    /// Ref handle ID of the element to type into.
    pub ref_id: String,
    /// Text to type character by character.
    pub text: String,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct SnapshotParams {
    /// Target webview label. If omitted, targets the first available webview.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct WindowStateParams {
    /// Filter to a specific window label. Returns all windows if omitted.
    pub label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct IpcLogParams {
    /// Maximum number of most recent entries to return.
    pub limit: Option<usize>,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct RegistryParams {
    /// Search query to filter commands by name or description.
    pub query: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct VerifyStateParams {
    /// JavaScript expression that returns the frontend state object to compare.
    pub frontend_expr: String,
    /// Backend state as a JSON object to compare against.
    pub backend_state: serde_json::Value,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct GhostCommandParams {
    /// Optional filter: only consider IPC calls from this webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct IpcIntegrityParams {
    /// Age in milliseconds after which a pending IPC call is considered stale. Default: 5000.
    pub stale_threshold_ms: Option<i64>,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct EventStreamParams {
    /// Only return events after this Unix timestamp (milliseconds). If omitted, returns all events.
    pub since: Option<f64>,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct StartRecordingParams {
    /// Optional session ID. If omitted, a UUID is generated.
    pub session_id: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct CheckpointParams {
    /// Unique ID for this checkpoint.
    pub id: String,
    /// Optional human-readable label for the checkpoint.
    pub label: Option<String>,
    /// State snapshot as JSON to associate with this checkpoint.
    pub state: serde_json::Value,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct ReplayParams {
    /// Only return events after this index.
    pub since_index: Option<usize>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct EventsBetweenCheckpointsParams {
    /// Checkpoint ID to start from.
    pub from_checkpoint: String,
    /// Checkpoint ID to end at.
    pub to_checkpoint: String,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct ResolveCommandParams {
    /// Natural language query describing what you want to do (e.g. "save the user's settings").
    pub query: String,
    /// Maximum number of results to return. Default: 5.
    pub limit: Option<usize>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct SemanticAssertParams {
    /// JavaScript expression to evaluate in the webview. The result is checked against the assertion.
    pub expression: String,
    /// Human-readable label for this assertion (e.g. "user is logged in").
    pub label: String,
    /// Condition: equals, not_equals, contains, greater_than, less_than, truthy, falsy, exists, type_is.
    pub condition: String,
    /// Expected value for the assertion.
    pub expected: serde_json::Value,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct InvokeCommandParams {
    /// The Tauri command name to invoke (e.g. "greet", "save_settings").
    pub command: String,
    /// Arguments as a JSON object. Keys are parameter names. Omit for commands with no arguments.
    pub args: Option<serde_json::Value>,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct ScreenshotParams {
    /// Target window label. If omitted, captures the main/first visible window.
    pub window_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct PressKeyParams {
    /// Key to press (e.g. "Enter", "Escape", "Tab", "ArrowDown").
    pub key: String,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct GetConsoleLogsParams {
    /// Only return logs after this Unix timestamp (milliseconds). If omitted, returns all captured logs.
    pub since: Option<f64>,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct DoubleClickParams {
    /// Ref handle ID from a DOM snapshot.
    pub ref_id: String,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct HoverParams {
    /// Ref handle ID from a DOM snapshot.
    pub ref_id: String,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct SelectOptionParams {
    /// Ref handle ID of the `<select>` element.
    pub ref_id: String,
    /// Values to select.
    pub values: Vec<String>,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct ScrollToParams {
    /// Ref handle ID to scroll into view. If null, scrolls to absolute coordinates.
    pub ref_id: Option<String>,
    /// Horizontal scroll position (pixels). Used when ref_id is null.
    pub x: Option<f64>,
    /// Vertical scroll position (pixels). Used when ref_id is null.
    pub y: Option<f64>,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct FocusElementParams {
    /// Ref handle ID of the element to focus.
    pub ref_id: String,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct NetworkLogParams {
    /// Filter by URL substring.
    pub filter: Option<String>,
    /// Maximum number of entries to return.
    pub limit: Option<usize>,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct GetStorageParams {
    /// Storage type: "local" or "session".
    pub storage_type: String,
    /// Specific key to read. If omitted, returns all entries.
    pub key: Option<String>,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct SetStorageParams {
    /// Storage type: "local" or "session".
    pub storage_type: String,
    /// Key to set.
    pub key: String,
    /// Value to store (will be JSON-serialized if not a string).
    pub value: serde_json::Value,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct DeleteStorageParams {
    /// Storage type: "local" or "session".
    pub storage_type: String,
    /// Key to delete.
    pub key: String,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct GetCookiesParams {
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct NavigationLogParams {
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct NavigateParams {
    /// URL to navigate to.
    pub url: String,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct DialogLogParams {
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct SetDialogResponseParams {
    /// Dialog type: "alert", "confirm", or "prompt".
    pub dialog_type: String,
    /// Action: "accept" or "dismiss".
    pub action: String,
    /// Response text for prompt dialogs.
    pub text: Option<String>,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct WaitForParams {
    /// Condition to wait for: text, text_gone, selector, selector_gone, url, ipc_idle, network_idle.
    pub condition: String,
    /// Value for the condition (text to find, CSS selector, URL substring).
    pub value: Option<String>,
    /// Maximum time to wait in milliseconds. Default: 10000.
    pub timeout_ms: Option<u64>,
    /// Polling interval in milliseconds. Default: 200.
    pub poll_ms: Option<u64>,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct ManageWindowParams {
    /// Action: minimize, unminimize, maximize, unmaximize, close, focus, show, hide, fullscreen, unfullscreen, always_on_top, not_always_on_top.
    pub action: String,
    /// Target window label.
    pub label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct ResizeWindowParams {
    /// Width in logical pixels.
    pub width: u32,
    /// Height in logical pixels.
    pub height: u32,
    /// Target window label.
    pub label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct MoveWindowParams {
    /// X position in logical pixels.
    pub x: i32,
    /// Y position in logical pixels.
    pub y: i32,
    /// Target window label.
    pub label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct SetWindowTitleParams {
    /// New window title.
    pub title: String,
    /// Target window label.
    pub label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct GetStylesParams {
    /// Ref handle ID of the element to inspect.
    pub ref_id: String,
    /// Optional list of CSS property names to return. If omitted, returns key properties.
    pub properties: Option<Vec<String>>,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct GetBoundingBoxesParams {
    /// List of ref handle IDs to measure.
    pub ref_ids: Vec<String>,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct HighlightElementParams {
    /// Ref handle ID of the element to highlight.
    pub ref_id: String,
    /// CSS color for the overlay (default: "rgba(255, 0, 0, 0.3)").
    pub color: Option<String>,
    /// Optional text label to display above the highlight.
    pub label: Option<String>,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct ClearHighlightsParams {
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct InjectCssParams {
    /// CSS text to inject into the page.
    pub css: String,
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct RemoveInjectedCssParams {
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct AuditAccessibilityParams {
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct GetPerformanceMetricsParams {
    /// Target webview label.
    pub webview_label: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct ImportSessionParams {
    /// JSON string of a previously exported RecordedSession.
    pub session_json: String,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct SlowIpcParams {
    /// Threshold in milliseconds. Returns IPC calls slower than this value.
    pub threshold_ms: u64,
    /// Maximum number of results. Default: 20.
    pub limit: Option<usize>,
}

// ── MCP Handler ──────────────────────────────────────────────────────────────

/// Maximum number of in-flight JavaScript eval requests. Prevents unbounded
/// growth of the `pending_evals` map if callbacks are never resolved.
const MAX_PENDING_EVALS: usize = 100;

const RESOURCE_URI_IPC_LOG: &str = "victauri://ipc-log";
const RESOURCE_URI_WINDOWS: &str = "victauri://windows";
const RESOURCE_URI_STATE: &str = "victauri://state";

const BRIDGE_VERSION: &str = "0.2.0";

#[derive(Clone)]
pub struct VictauriMcpHandler {
    state: Arc<VictauriState>,
    bridge: Arc<dyn WebviewBridge>,
    subscriptions: Arc<Mutex<HashSet<String>>>,
    bridge_checked: Arc<AtomicBool>,
}

#[tool_router]
impl VictauriMcpHandler {
    #[tool(
        description = "Evaluate JavaScript in the Tauri webview and return the result. Async expressions are wrapped automatically."
    )]
    async fn eval_js(&self, Parameters(params): Parameters<EvalJsParams>) -> CallToolResult {
        if !self.state.privacy.is_tool_enabled("eval_js") {
            return tool_disabled("eval_js");
        }
        match self
            .eval_with_return(&params.code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => self.redact_result(result),
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "Get the current DOM snapshot from the webview as a JSON accessibility tree with ref handles for interaction."
    )]
    async fn dom_snapshot(&self, Parameters(params): Parameters<SnapshotParams>) -> CallToolResult {
        let code = "return window.__VICTAURI__?.snapshot()";
        match self
            .eval_with_return(code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(description = "Click an element by its ref handle ID from a DOM snapshot.")]
    async fn click(&self, Parameters(params): Parameters<ClickParams>) -> CallToolResult {
        let code = format!(
            "return window.__VICTAURI__?.click({})",
            js_string(&params.ref_id)
        );
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "Set the value of an input element by ref handle ID. Dispatches input and change events."
    )]
    async fn fill(&self, Parameters(params): Parameters<FillParams>) -> CallToolResult {
        if !self.state.privacy.is_tool_enabled("fill") {
            return tool_disabled("fill");
        }
        let code = format!(
            "return window.__VICTAURI__?.fill({}, {})",
            js_string(&params.ref_id),
            js_string(&params.value)
        );
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "Type text character-by-character into an element, simulating real keyboard events."
    )]
    async fn type_text(&self, Parameters(params): Parameters<TypeTextParams>) -> CallToolResult {
        if !self.state.privacy.is_tool_enabled("type_text") {
            return tool_disabled("type_text");
        }
        let code = format!(
            "return window.__VICTAURI__?.type({}, {})",
            js_string(&params.ref_id),
            js_string(&params.text)
        );
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "Get state of all Tauri windows: position, size, visibility, focus, and URL."
    )]
    async fn get_window_state(
        &self,
        Parameters(params): Parameters<WindowStateParams>,
    ) -> CallToolResult {
        let states = self.bridge.get_window_states(params.label.as_deref());
        match serde_json::to_string_pretty(&states) {
            Ok(json) => CallToolResult::success(vec![Content::text(json)]),
            Err(e) => tool_error(e.to_string()),
        }
    }

    #[tool(description = "List all Tauri window labels.")]
    async fn list_windows(&self) -> CallToolResult {
        let labels = self.bridge.list_window_labels();
        match serde_json::to_string_pretty(&labels) {
            Ok(json) => CallToolResult::success(vec![Content::text(json)]),
            Err(e) => tool_error(e.to_string()),
        }
    }

    #[tool(
        description = "Get recent IPC calls intercepted by the JS bridge. Returns command names, arguments, results, durations, and status (ok/error/pending)."
    )]
    async fn get_ipc_log(&self, Parameters(params): Parameters<IpcLogParams>) -> CallToolResult {
        let limit_arg = params.limit.map(|l| format!("{l}")).unwrap_or_default();
        let code = if limit_arg.is_empty() {
            "return window.__VICTAURI__?.getIpcLog()".to_string()
        } else {
            format!("return window.__VICTAURI__?.getIpcLog({limit_arg})")
        };
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => self.redact_result(result),
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "List or search all registered Tauri commands with their argument schemas."
    )]
    async fn get_registry(&self, Parameters(params): Parameters<RegistryParams>) -> CallToolResult {
        let commands = match params.query {
            Some(q) => self.state.registry.search(&q),
            None => self.state.registry.list(),
        };
        match serde_json::to_string_pretty(&commands) {
            Ok(json) => CallToolResult::success(vec![Content::text(json)]),
            Err(e) => tool_error(e.to_string()),
        }
    }

    #[tool(
        description = "Get real-time process memory statistics from the OS (working set, page file usage). On Windows returns detailed metrics; on Linux returns virtual/resident size."
    )]
    async fn get_memory_stats(&self) -> CallToolResult {
        let stats = crate::memory::current_stats();
        match serde_json::to_string_pretty(&stats) {
            Ok(json) => CallToolResult::success(vec![Content::text(json)]),
            Err(e) => tool_error(e.to_string()),
        }
    }

    #[tool(
        description = "Compare frontend state (evaluated via JS expression) against backend state to detect divergences. Returns a VerificationResult with any mismatches."
    )]
    async fn verify_state(
        &self,
        Parameters(params): Parameters<VerifyStateParams>,
    ) -> CallToolResult {
        let code = format!("return ({})", params.frontend_expr);
        let frontend_json = match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => result,
            Err(e) => return tool_error(format!("failed to evaluate frontend expression: {e}")),
        };

        let frontend_state: serde_json::Value = match serde_json::from_str(&frontend_json) {
            Ok(v) => v,
            Err(e) => {
                return tool_error(format!(
                    "frontend expression did not return valid JSON: {e}"
                ));
            }
        };

        let result = victauri_core::verify_state(frontend_state, params.backend_state);
        match serde_json::to_string_pretty(&result) {
            Ok(json) => CallToolResult::success(vec![Content::text(json)]),
            Err(e) => tool_error(e.to_string()),
        }
    }

    #[tool(
        description = "Detect ghost commands — commands invoked from the frontend that have no backend handler, or registered backend commands never called. Reads from the JS-side IPC interception log."
    )]
    async fn detect_ghost_commands(
        &self,
        Parameters(params): Parameters<GhostCommandParams>,
    ) -> CallToolResult {
        let code = "return window.__VICTAURI__?.getIpcLog()";
        let ipc_json = match self
            .eval_with_return(code, params.webview_label.as_deref())
            .await
        {
            Ok(r) => r,
            Err(e) => return tool_error(format!("failed to read IPC log: {e}")),
        };

        let ipc_calls: Vec<serde_json::Value> = serde_json::from_str(&ipc_json).unwrap_or_default();
        let frontend_commands: Vec<String> = ipc_calls
            .iter()
            .filter_map(|c| c.get("command").and_then(|v| v.as_str()).map(String::from))
            .collect::<std::collections::HashSet<_>>()
            .into_iter()
            .collect();

        let report = victauri_core::detect_ghost_commands(&frontend_commands, &self.state.registry);
        match serde_json::to_string_pretty(&report) {
            Ok(json) => CallToolResult::success(vec![Content::text(json)]),
            Err(e) => tool_error(e.to_string()),
        }
    }

    #[tool(
        description = "Check IPC round-trip integrity: find stale (stuck) pending calls and errored calls. Returns health status and lists of problematic IPC calls."
    )]
    async fn check_ipc_integrity(
        &self,
        Parameters(params): Parameters<IpcIntegrityParams>,
    ) -> CallToolResult {
        let threshold = params.stale_threshold_ms.unwrap_or(5000);
        let code = format!(
            r#"return (function() {{
                var log = window.__VICTAURI__?.getIpcLog() || [];
                var now = Date.now();
                var threshold = {threshold};
                var pending = log.filter(function(c) {{ return c.status === 'pending'; }});
                var stale = pending.filter(function(c) {{ return (now - c.timestamp) > threshold; }});
                var errored = log.filter(function(c) {{ return c.status === 'error'; }});
                return {{
                    healthy: stale.length === 0 && errored.length === 0,
                    total_calls: log.length,
                    pending_count: pending.length,
                    stale_count: stale.length,
                    error_count: errored.length,
                    stale_calls: stale.slice(0, 20),
                    errored_calls: errored.slice(0, 20)
                }};
            }})()"#
        );
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "Get a combined event stream from the webview: console logs, DOM mutations, sorted by timestamp. Use the 'since' parameter to poll only new events."
    )]
    async fn get_event_stream(
        &self,
        Parameters(params): Parameters<EventStreamParams>,
    ) -> CallToolResult {
        let since_arg = params.since.map(|ts| format!("{ts}")).unwrap_or_default();
        let code = if since_arg.is_empty() {
            "return window.__VICTAURI__?.getEventStream()".to_string()
        } else {
            format!("return window.__VICTAURI__?.getEventStream({since_arg})")
        };
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "Resolve a natural language query to matching Tauri commands. Returns scored results ranked by relevance, using command names, descriptions, intents, categories, and examples."
    )]
    async fn resolve_command(
        &self,
        Parameters(params): Parameters<ResolveCommandParams>,
    ) -> CallToolResult {
        let limit = params.limit.unwrap_or(5);
        let mut results = self.state.registry.resolve(&params.query);
        results.truncate(limit);
        match serde_json::to_string_pretty(&results) {
            Ok(json) => CallToolResult::success(vec![Content::text(json)]),
            Err(e) => tool_error(e.to_string()),
        }
    }

    #[tool(
        description = "Run a semantic assertion: evaluate a JS expression and check the result against an expected condition. Conditions: equals, not_equals, contains, greater_than, less_than, truthy, falsy, exists, type_is."
    )]
    async fn assert_semantic(
        &self,
        Parameters(params): Parameters<SemanticAssertParams>,
    ) -> CallToolResult {
        let code = format!("return ({})", params.expression);
        let actual_json = match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => result,
            Err(e) => return tool_error(format!("failed to evaluate expression: {e}")),
        };

        let actual: serde_json::Value = match serde_json::from_str(&actual_json) {
            Ok(v) => v,
            Err(e) => return tool_error(format!("expression did not return valid JSON: {e}")),
        };

        let assertion = victauri_core::SemanticAssertion {
            label: params.label,
            condition: params.condition,
            expected: params.expected,
        };

        let result = victauri_core::evaluate_assertion(actual, &assertion);
        match serde_json::to_string_pretty(&result) {
            Ok(json) => CallToolResult::success(vec![Content::text(json)]),
            Err(e) => tool_error(e.to_string()),
        }
    }

    #[tool(
        description = "Start recording IPC events and state changes. Returns false if a recording is already active."
    )]
    async fn start_recording(
        &self,
        Parameters(params): Parameters<StartRecordingParams>,
    ) -> CallToolResult {
        let session_id = params
            .session_id
            .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
        let started = self.state.recorder.start(session_id.clone());
        let result = serde_json::json!({
            "started": started,
            "session_id": session_id,
        });
        CallToolResult::success(vec![Content::text(result.to_string())])
    }

    #[tool(
        description = "Stop the current recording and return the full recorded session with all events and checkpoints."
    )]
    async fn stop_recording(&self) -> CallToolResult {
        match self.state.recorder.stop() {
            Some(session) => match serde_json::to_string_pretty(&session) {
                Ok(json) => CallToolResult::success(vec![Content::text(json)]),
                Err(e) => tool_error(e.to_string()),
            },
            None => tool_error("no recording is active"),
        }
    }

    #[tool(
        description = "Create a state checkpoint during recording. Associates the current event index with a state snapshot for later comparison."
    )]
    async fn checkpoint(&self, Parameters(params): Parameters<CheckpointParams>) -> CallToolResult {
        let created = self
            .state
            .recorder
            .checkpoint(params.id.clone(), params.label, params.state);
        if created {
            let result = serde_json::json!({
                "created": true,
                "checkpoint_id": params.id,
                "event_index": self.state.recorder.event_count(),
            });
            CallToolResult::success(vec![Content::text(result.to_string())])
        } else {
            tool_error("no recording is active — start one first")
        }
    }

    #[tool(description = "Get all checkpoints from the current recording session.")]
    async fn list_checkpoints(&self) -> CallToolResult {
        let checkpoints = self.state.recorder.get_checkpoints();
        match serde_json::to_string_pretty(&checkpoints) {
            Ok(json) => CallToolResult::success(vec![Content::text(json)]),
            Err(e) => tool_error(e.to_string()),
        }
    }

    #[tool(
        description = "Get the IPC replay sequence: all IPC calls recorded in order, suitable for replaying the session."
    )]
    async fn get_replay_sequence(&self) -> CallToolResult {
        let calls = self.state.recorder.ipc_replay_sequence();
        match serde_json::to_string_pretty(&calls) {
            Ok(json) => CallToolResult::success(vec![Content::text(json)]),
            Err(e) => tool_error(e.to_string()),
        }
    }

    #[tool(
        description = "Get recorded events since a specific event index. Useful for incremental replay."
    )]
    async fn get_recorded_events(
        &self,
        Parameters(params): Parameters<ReplayParams>,
    ) -> CallToolResult {
        let events = self
            .state
            .recorder
            .events_since(params.since_index.unwrap_or(0));
        match serde_json::to_string_pretty(&events) {
            Ok(json) => CallToolResult::success(vec![Content::text(json)]),
            Err(e) => tool_error(e.to_string()),
        }
    }

    #[tool(description = "Get all events that occurred between two checkpoints.")]
    async fn events_between_checkpoints(
        &self,
        Parameters(params): Parameters<EventsBetweenCheckpointsParams>,
    ) -> CallToolResult {
        match self
            .state
            .recorder
            .events_between_checkpoints(&params.from_checkpoint, &params.to_checkpoint)
        {
            Some(events) => match serde_json::to_string_pretty(&events) {
                Ok(json) => CallToolResult::success(vec![Content::text(json)]),
                Err(e) => tool_error(e.to_string()),
            },
            None => tool_error("one or both checkpoint IDs not found"),
        }
    }

    #[tool(
        description = "Export the current recording session as a JSON string. The session can be saved externally and later imported with import_session. Does NOT stop the recording."
    )]
    async fn export_session(&self) -> CallToolResult {
        let rec = self.state.recorder.clone();
        if !rec.is_recording() {
            return tool_error("no recording is active — start one first");
        }
        let session = rec.stop();
        match session {
            Some(s) => {
                let json = serde_json::to_string_pretty(&s)
                    .unwrap_or_else(|e| format!("{{\"error\": \"{e}\"}}"));
                CallToolResult::success(vec![Content::text(json)])
            }
            None => tool_error("failed to export session"),
        }
    }

    #[tool(
        description = "Import a previously exported recording session from JSON. Useful for replaying sessions across restarts. The imported session can be queried with replay and checkpoint tools."
    )]
    async fn import_session(
        &self,
        Parameters(params): Parameters<ImportSessionParams>,
    ) -> CallToolResult {
        let session: victauri_core::RecordedSession =
            match serde_json::from_str(&params.session_json) {
                Ok(s) => s,
                Err(e) => return tool_error(format!("invalid session JSON: {e}")),
            };

        let result = serde_json::json!({
            "imported": true,
            "session_id": session.id,
            "event_count": session.events.len(),
            "checkpoint_count": session.checkpoints.len(),
            "started_at": session.started_at.to_rfc3339(),
        });
        CallToolResult::success(vec![Content::text(result.to_string())])
    }

    #[tool(
        description = "Find slow IPC calls that exceed a time threshold. Returns calls sorted by duration (slowest first). Useful for identifying performance bottlenecks."
    )]
    async fn slow_ipc_calls(
        &self,
        Parameters(params): Parameters<SlowIpcParams>,
    ) -> CallToolResult {
        let limit = params.limit.unwrap_or(20);
        let mut calls: Vec<_> = self
            .state
            .event_log
            .ipc_calls()
            .into_iter()
            .filter(|c| c.duration_ms.unwrap_or(0) > params.threshold_ms)
            .collect();
        calls.sort_by_key(|c| std::cmp::Reverse(c.duration_ms));
        calls.truncate(limit);

        let result = serde_json::json!({
            "threshold_ms": params.threshold_ms,
            "count": calls.len(),
            "calls": calls,
        });
        match serde_json::to_string_pretty(&result) {
            Ok(json) => self.redact_result(json),
            Err(e) => tool_error(e.to_string()),
        }
    }

    #[tool(
        description = "Invoke a registered Tauri command via IPC, just like the frontend would. Goes through the real IPC pipeline so calls are logged and verifiable. Returns the command's result. Subject to privacy command filtering."
    )]
    async fn invoke_command(
        &self,
        Parameters(params): Parameters<InvokeCommandParams>,
    ) -> CallToolResult {
        if !self.state.privacy.is_command_allowed(&params.command) {
            return tool_error(format!(
                "command '{}' is blocked by privacy configuration",
                params.command
            ));
        }
        let args_json = params.args.unwrap_or(serde_json::json!({}));
        let args_str = serde_json::to_string(&args_json).unwrap_or_else(|_| "{}".to_string());
        let code = format!(
            "return window.__TAURI__.core.invoke({}, {args_str})",
            js_string(&params.command)
        );
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => self.redact_result(result),
            Err(e) => tool_error(format!("invoke_command failed: {e}")),
        }
    }

    #[tool(
        description = "Capture a screenshot of a Tauri window as a base64-encoded PNG image. Currently supported on Windows; other platforms return an error."
    )]
    async fn screenshot(&self, Parameters(params): Parameters<ScreenshotParams>) -> CallToolResult {
        if !self.state.privacy.is_tool_enabled("screenshot") {
            return tool_disabled("screenshot");
        }
        match self
            .bridge
            .get_native_handle(params.window_label.as_deref())
        {
            Ok(hwnd) => match crate::screenshot::capture_window(hwnd).await {
                Ok(png_bytes) => {
                    use base64::Engine;
                    let b64 = base64::engine::general_purpose::STANDARD.encode(&png_bytes);
                    CallToolResult::success(vec![Content::image(b64, "image/png")])
                }
                Err(e) => tool_error(format!("screenshot capture failed: {e}")),
            },
            Err(e) => tool_error(format!("cannot get window handle: {e}")),
        }
    }

    #[tool(
        description = "Press a keyboard key on the currently focused element. Useful for triggering keyboard shortcuts, submitting forms (Enter), closing dialogs (Escape), or navigating (Tab, ArrowDown)."
    )]
    async fn press_key(&self, Parameters(params): Parameters<PressKeyParams>) -> CallToolResult {
        let code = format!(
            "return window.__VICTAURI__?.pressKey({})",
            js_string(&params.key)
        );
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "Get captured console logs (log, warn, error, info) from the webview. Useful for debugging and monitoring application behavior."
    )]
    async fn get_console_logs(
        &self,
        Parameters(params): Parameters<GetConsoleLogsParams>,
    ) -> CallToolResult {
        let since_arg = params.since.map(|ts| format!("{ts}")).unwrap_or_default();
        let code = if since_arg.is_empty() {
            "return window.__VICTAURI__?.getConsoleLogs()".to_string()
        } else {
            format!("return window.__VICTAURI__?.getConsoleLogs({since_arg})")
        };
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => self.redact_result(result),
            Err(e) => tool_error(e),
        }
    }

    // ── Extended Interactions ────────────────────────────────────────────────

    #[tool(description = "Double-click an element by its ref handle ID from a DOM snapshot.")]
    async fn double_click(
        &self,
        Parameters(params): Parameters<DoubleClickParams>,
    ) -> CallToolResult {
        let code = format!(
            "return window.__VICTAURI__?.doubleClick({})",
            js_string(&params.ref_id)
        );
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "Hover over an element by its ref handle ID. Dispatches mouseenter and mouseover events."
    )]
    async fn hover(&self, Parameters(params): Parameters<HoverParams>) -> CallToolResult {
        let code = format!(
            "return window.__VICTAURI__?.hover({})",
            js_string(&params.ref_id)
        );
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "Select one or more options in a <select> element by their option values."
    )]
    async fn select_option(
        &self,
        Parameters(params): Parameters<SelectOptionParams>,
    ) -> CallToolResult {
        let values_json =
            serde_json::to_string(&params.values).unwrap_or_else(|_| "[]".to_string());
        let code = format!(
            "return window.__VICTAURI__?.selectOption({}, {})",
            js_string(&params.ref_id),
            values_json
        );
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "Scroll to an element by ref handle ID (scrolls into view), or to absolute page coordinates if no ref given."
    )]
    async fn scroll_to(&self, Parameters(params): Parameters<ScrollToParams>) -> CallToolResult {
        let ref_arg = params
            .ref_id
            .as_ref()
            .map(|r| js_string(r))
            .unwrap_or_else(|| "null".to_string());
        let x = params.x.unwrap_or(0.0);
        let y = params.y.unwrap_or(0.0);
        let code = format!("return window.__VICTAURI__?.scrollTo({ref_arg}, {x}, {y})");
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(description = "Focus an element by its ref handle ID.")]
    async fn focus_element(
        &self,
        Parameters(params): Parameters<FocusElementParams>,
    ) -> CallToolResult {
        let code = format!(
            "return window.__VICTAURI__?.focusElement({})",
            js_string(&params.ref_id)
        );
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    // ── Network Monitoring ──────────────────────────────────────────────────

    #[tool(
        description = "Get intercepted network requests (fetch and XMLHttpRequest). Filter by URL substring and limit the number of results."
    )]
    async fn get_network_log(
        &self,
        Parameters(params): Parameters<NetworkLogParams>,
    ) -> CallToolResult {
        let filter_arg = params
            .filter
            .as_ref()
            .map(|f| js_string(f))
            .unwrap_or_else(|| "null".to_string());
        let limit_arg = params
            .limit
            .map(|l| l.to_string())
            .unwrap_or_else(|| "null".to_string());
        let code = format!("return window.__VICTAURI__?.getNetworkLog({filter_arg}, {limit_arg})");
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => self.redact_result(result),
            Err(e) => tool_error(e),
        }
    }

    // ── Storage ─────────────────────────────────────────────────────────────

    #[tool(
        description = "Read from localStorage or sessionStorage. Returns all entries if no key is specified, or the value for a specific key."
    )]
    async fn get_storage(
        &self,
        Parameters(params): Parameters<GetStorageParams>,
    ) -> CallToolResult {
        let method = match params.storage_type.as_str() {
            "session" => "getSessionStorage",
            _ => "getLocalStorage",
        };
        let key_arg = params
            .key
            .as_ref()
            .map(|k| js_string(k))
            .unwrap_or_default();
        let code = format!("return window.__VICTAURI__?.{method}({key_arg})");
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => self.redact_result(result),
            Err(e) => tool_error(e),
        }
    }

    #[tool(description = "Set a value in localStorage or sessionStorage.")]
    async fn set_storage(
        &self,
        Parameters(params): Parameters<SetStorageParams>,
    ) -> CallToolResult {
        if !self.state.privacy.is_tool_enabled("set_storage") {
            return tool_disabled("set_storage");
        }
        let method = match params.storage_type.as_str() {
            "session" => "setSessionStorage",
            _ => "setLocalStorage",
        };
        let value_json =
            serde_json::to_string(&params.value).unwrap_or_else(|_| "null".to_string());
        let code = format!(
            "return window.__VICTAURI__?.{method}({}, {value_json})",
            js_string(&params.key)
        );
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(description = "Delete a key from localStorage or sessionStorage.")]
    async fn delete_storage(
        &self,
        Parameters(params): Parameters<DeleteStorageParams>,
    ) -> CallToolResult {
        if !self.state.privacy.is_tool_enabled("delete_storage") {
            return tool_disabled("delete_storage");
        }
        let method = match params.storage_type.as_str() {
            "session" => "deleteSessionStorage",
            _ => "deleteLocalStorage",
        };
        let code = format!(
            "return window.__VICTAURI__?.{method}({})",
            js_string(&params.key)
        );
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(description = "Get all cookies visible to the webview document.")]
    async fn get_cookies(
        &self,
        Parameters(params): Parameters<GetCookiesParams>,
    ) -> CallToolResult {
        let code = "return window.__VICTAURI__?.getCookies()";
        match self
            .eval_with_return(code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => self.redact_result(result),
            Err(e) => tool_error(e),
        }
    }

    // ── Navigation ──────────────────────────────────────────────────────────

    #[tool(
        description = "Get the navigation history log — tracks pushState, replaceState, popstate, hashchange, and the initial page load."
    )]
    async fn get_navigation_log(
        &self,
        Parameters(params): Parameters<NavigationLogParams>,
    ) -> CallToolResult {
        let code = "return window.__VICTAURI__?.getNavigationLog()";
        match self
            .eval_with_return(code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "Navigate the webview to a URL. Blocks javascript:, data:, and vbscript: URLs."
    )]
    async fn navigate(&self, Parameters(params): Parameters<NavigateParams>) -> CallToolResult {
        if !self.state.privacy.is_tool_enabled("navigate") {
            return tool_disabled("navigate");
        }
        if let Err(e) = validate_url(&params.url) {
            return tool_error(e);
        }
        let code = format!(
            "return window.__VICTAURI__?.navigate({})",
            js_string(&params.url)
        );
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(description = "Navigate back in the webview's browser history.")]
    async fn navigate_back(
        &self,
        Parameters(params): Parameters<NavigationLogParams>,
    ) -> CallToolResult {
        let code = "return window.__VICTAURI__?.navigateBack()";
        match self
            .eval_with_return(code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    // ── Dialogs ─────────────────────────────────────────────────────────────

    #[tool(
        description = "Get captured dialog events (alert, confirm, prompt). Dialogs are auto-handled: alert is accepted, confirm returns true, prompt returns default value."
    )]
    async fn get_dialog_log(
        &self,
        Parameters(params): Parameters<DialogLogParams>,
    ) -> CallToolResult {
        let code = "return window.__VICTAURI__?.getDialogLog()";
        match self
            .eval_with_return(code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "Configure automatic responses for browser dialogs. Types: alert, confirm, prompt. Actions: accept, dismiss. For prompt dialogs, optionally set the response text."
    )]
    async fn set_dialog_response(
        &self,
        Parameters(params): Parameters<SetDialogResponseParams>,
    ) -> CallToolResult {
        if !self.state.privacy.is_tool_enabled("set_dialog_response") {
            return tool_disabled("set_dialog_response");
        }
        let text_arg = params
            .text
            .as_ref()
            .map(|t| js_string(t))
            .unwrap_or_else(|| "undefined".to_string());
        let code = format!(
            "return window.__VICTAURI__?.setDialogAutoResponse({}, {}, {text_arg})",
            js_string(&params.dialog_type),
            js_string(&params.action)
        );
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    // ── Wait ────────────────────────────────────────────────────────────────

    #[tool(
        description = "Wait for a condition to be met. Polls at regular intervals until satisfied or timeout. Conditions: text (text appears), text_gone (text disappears), selector (CSS selector matches), selector_gone, url (URL contains value), ipc_idle (no pending IPC calls), network_idle (no pending network requests)."
    )]
    async fn wait_for(&self, Parameters(params): Parameters<WaitForParams>) -> CallToolResult {
        let value = params
            .value
            .as_ref()
            .map(|v| js_string(v))
            .unwrap_or_else(|| "null".to_string());
        let timeout_ms = params.timeout_ms.unwrap_or(10000);
        let poll = params.poll_ms.unwrap_or(200);
        let code = format!(
            "return window.__VICTAURI__?.waitFor({{ condition: {}, value: {value}, timeout_ms: {timeout_ms}, poll_ms: {poll} }})",
            js_string(&params.condition)
        );
        // Give the Rust-side eval timeout extra headroom beyond the JS-side
        // polling timeout so the JS promise has time to resolve or reject
        // before we forcibly cancel it.
        let eval_timeout = std::time::Duration::from_millis(timeout_ms + 5000);
        match self
            .eval_with_return_timeout(&code, params.webview_label.as_deref(), eval_timeout)
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    // ── Window Management ───────────────────────────────────────────────────

    #[tool(
        description = "Manage a window: minimize, unminimize, maximize, unmaximize, close, focus, show, hide, fullscreen, unfullscreen, always_on_top, not_always_on_top."
    )]
    async fn manage_window(
        &self,
        Parameters(params): Parameters<ManageWindowParams>,
    ) -> CallToolResult {
        match self
            .bridge
            .manage_window(params.label.as_deref(), &params.action)
        {
            Ok(msg) => CallToolResult::success(vec![Content::text(msg)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(description = "Resize a window to the specified width and height in logical pixels.")]
    async fn resize_window(
        &self,
        Parameters(params): Parameters<ResizeWindowParams>,
    ) -> CallToolResult {
        match self
            .bridge
            .resize_window(params.label.as_deref(), params.width, params.height)
        {
            Ok(()) => {
                let result =
                    serde_json::json!({"ok": true, "width": params.width, "height": params.height});
                CallToolResult::success(vec![Content::text(result.to_string())])
            }
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "Move a window to the specified screen position (x, y) in logical pixels."
    )]
    async fn move_window(
        &self,
        Parameters(params): Parameters<MoveWindowParams>,
    ) -> CallToolResult {
        match self
            .bridge
            .move_window(params.label.as_deref(), params.x, params.y)
        {
            Ok(()) => {
                let result = serde_json::json!({"ok": true, "x": params.x, "y": params.y});
                CallToolResult::success(vec![Content::text(result.to_string())])
            }
            Err(e) => tool_error(e),
        }
    }

    #[tool(description = "Set the title of a window.")]
    async fn set_window_title(
        &self,
        Parameters(params): Parameters<SetWindowTitleParams>,
    ) -> CallToolResult {
        match self
            .bridge
            .set_window_title(params.label.as_deref(), &params.title)
        {
            Ok(()) => {
                let result = serde_json::json!({"ok": true, "title": params.title});
                CallToolResult::success(vec![Content::text(result.to_string())])
            }
            Err(e) => tool_error(e),
        }
    }

    // ── Phase 8: Deep Introspection ─────────────────────────────────────────

    #[tool(
        description = "Get computed CSS styles for an element. Returns key properties by default, or specific properties if listed."
    )]
    async fn get_styles(&self, Parameters(params): Parameters<GetStylesParams>) -> CallToolResult {
        let props_arg = match &params.properties {
            Some(props) => {
                let arr: Vec<String> = props.iter().map(|p| js_string(p)).collect();
                format!("[{}]", arr.join(","))
            }
            None => "null".to_string(),
        };
        let code = format!(
            "return window.__VICTAURI__?.getStyles({}, {})",
            js_string(&params.ref_id),
            props_arg
        );
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "Get precise bounding boxes with CSS box model (margin, padding, border) for one or more elements."
    )]
    async fn get_bounding_boxes(
        &self,
        Parameters(params): Parameters<GetBoundingBoxesParams>,
    ) -> CallToolResult {
        let refs: Vec<String> = params.ref_ids.iter().map(|r| js_string(r)).collect();
        let code = format!(
            "return window.__VICTAURI__?.getBoundingBoxes([{}])",
            refs.join(",")
        );
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "Draw a colored overlay on an element for visual debugging. The overlay is fixed-position and non-interactive."
    )]
    async fn highlight_element(
        &self,
        Parameters(params): Parameters<HighlightElementParams>,
    ) -> CallToolResult {
        let color_arg = match &params.color {
            Some(c) => match sanitize_css_color(c) {
                Ok(safe) => format!("\"{}\"", safe),
                Err(e) => return tool_error(e),
            },
            None => "null".to_string(),
        };
        let label_arg = match &params.label {
            Some(l) => js_string(l),
            None => "null".to_string(),
        };
        let code = format!(
            "return window.__VICTAURI__?.highlightElement({}, {}, {})",
            js_string(&params.ref_id),
            color_arg,
            label_arg
        );
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(description = "Remove all debug highlight overlays from the page.")]
    async fn clear_highlights(
        &self,
        Parameters(params): Parameters<ClearHighlightsParams>,
    ) -> CallToolResult {
        let code = "return window.__VICTAURI__?.clearHighlights()";
        match self
            .eval_with_return(code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "Inject custom CSS into the page. Replaces any previously injected CSS. Useful for debugging layout issues or prototyping style changes."
    )]
    async fn inject_css(&self, Parameters(params): Parameters<InjectCssParams>) -> CallToolResult {
        if !self.state.privacy.is_tool_enabled("inject_css") {
            return tool_disabled("inject_css");
        }
        let code = format!(
            "return window.__VICTAURI__?.injectCss({})",
            js_string(&params.css)
        );
        match self
            .eval_with_return(&code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(description = "Remove previously injected CSS from the page.")]
    async fn remove_injected_css(
        &self,
        Parameters(params): Parameters<RemoveInjectedCssParams>,
    ) -> CallToolResult {
        let code = "return window.__VICTAURI__?.removeInjectedCss()";
        match self
            .eval_with_return(code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "Run a comprehensive accessibility audit. Checks for missing alt text, unlabeled form inputs, empty buttons/links, heading hierarchy, color contrast, ARIA role validity, and more. Returns violations and warnings with severity levels."
    )]
    async fn audit_accessibility(
        &self,
        Parameters(params): Parameters<AuditAccessibilityParams>,
    ) -> CallToolResult {
        let code = "return window.__VICTAURI__?.auditAccessibility()";
        match self
            .eval_with_return(code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "Get performance metrics: navigation timing, resource loading summary, paint timing, JS heap usage, long task count, and DOM statistics."
    )]
    async fn get_performance_metrics(
        &self,
        Parameters(params): Parameters<GetPerformanceMetricsParams>,
    ) -> CallToolResult {
        let code = "return window.__VICTAURI__?.getPerformanceMetrics()";
        match self
            .eval_with_return(code, params.webview_label.as_deref())
            .await
        {
            Ok(result) => CallToolResult::success(vec![Content::text(result)]),
            Err(e) => tool_error(e),
        }
    }

    #[tool(
        description = "Inspect the Victauri plugin's own configuration: port, enabled/disabled tools, command filters, privacy settings, capacities, and version. Useful for agents to understand their capabilities before acting."
    )]
    async fn get_plugin_info(&self) -> CallToolResult {
        let disabled: Vec<&str> = self
            .state
            .privacy
            .disabled_tools
            .iter()
            .map(|s| s.as_str())
            .collect();
        let blocklist: Vec<&str> = self
            .state
            .privacy
            .command_blocklist
            .iter()
            .map(|s| s.as_str())
            .collect();
        let allowlist: Option<Vec<&str>> = self
            .state
            .privacy
            .command_allowlist
            .as_ref()
            .map(|s| s.iter().map(|s| s.as_str()).collect());
        let all_tools = Self::tool_router().list_all();
        let enabled_tools: Vec<&str> = all_tools
            .iter()
            .filter(|t| self.state.privacy.is_tool_enabled(t.name.as_ref()))
            .map(|t| t.name.as_ref())
            .collect();

        let result = serde_json::json!({
            "version": env!("CARGO_PKG_VERSION"),
            "bridge_version": BRIDGE_VERSION,
            "port": self.state.port,
            "tools": {
                "total": all_tools.len(),
                "enabled": enabled_tools.len(),
                "enabled_list": enabled_tools,
                "disabled_list": disabled,
            },
            "commands": {
                "allowlist": allowlist,
                "blocklist": blocklist,
            },
            "privacy": {
                "redaction_enabled": self.state.privacy.redaction_enabled,
            },
            "capacities": {
                "event_log": self.state.event_log.capacity(),
                "eval_timeout_secs": self.state.eval_timeout.as_secs(),
            },
            "registered_commands": self.state.registry.count(),
            "tool_invocations": self.state.tool_invocations.load(std::sync::atomic::Ordering::Relaxed),
            "uptime_secs": self.state.started_at.elapsed().as_secs(),
        });
        match serde_json::to_string_pretty(&result) {
            Ok(json) => CallToolResult::success(vec![Content::text(json)]),
            Err(e) => tool_error(e.to_string()),
        }
    }
}

impl VictauriMcpHandler {
    pub fn new(state: Arc<VictauriState>, bridge: Arc<dyn WebviewBridge>) -> Self {
        Self {
            state,
            bridge,
            subscriptions: Arc::new(Mutex::new(HashSet::new())),
            bridge_checked: Arc::new(AtomicBool::new(false)),
        }
    }

    fn redact_result(&self, output: String) -> CallToolResult {
        let redacted = self.state.privacy.redact_output(&output);
        CallToolResult::success(vec![Content::text(redacted)])
    }

    async fn eval_with_return(
        &self,
        code: &str,
        webview_label: Option<&str>,
    ) -> Result<String, String> {
        self.eval_with_return_timeout(code, webview_label, self.state.eval_timeout)
            .await
    }

    async fn eval_with_return_timeout(
        &self,
        code: &str,
        webview_label: Option<&str>,
        timeout: std::time::Duration,
    ) -> Result<String, String> {
        let id = uuid::Uuid::new_v4().to_string();
        let (tx, rx) = tokio::sync::oneshot::channel();

        {
            let mut pending = self.state.pending_evals.lock().await;
            if pending.len() >= MAX_PENDING_EVALS {
                return Err(format!(
                    "too many concurrent eval requests (limit: {MAX_PENDING_EVALS})"
                ));
            }
            pending.insert(id.clone(), tx);
        }

        // Auto-prepend `return` so bare expressions produce a value.
        // Only skip for code that starts with a statement keyword where
        // prepending `return` would be a syntax error.
        let code = code.trim();
        let needs_return = !code.starts_with("return ")
            && !code.starts_with("return;")
            && !code.starts_with('{')
            && !code.starts_with("if ")
            && !code.starts_with("if(")
            && !code.starts_with("for ")
            && !code.starts_with("for(")
            && !code.starts_with("while ")
            && !code.starts_with("while(")
            && !code.starts_with("switch ")
            && !code.starts_with("try ")
            && !code.starts_with("const ")
            && !code.starts_with("let ")
            && !code.starts_with("var ")
            && !code.starts_with("function ")
            && !code.starts_with("class ")
            && !code.starts_with("throw ");
        let code = if needs_return {
            format!("return {code}")
        } else {
            code.to_string()
        };

        let inject = format!(
            r#"
            (async () => {{
                try {{
                    const __result = await (async () => {{ {code} }})();
                    await window.__TAURI__.core.invoke('plugin:victauri|victauri_eval_callback', {{
                        id: '{id}',
                        result: JSON.stringify(__result)
                    }});
                }} catch (e) {{
                    await window.__TAURI__.core.invoke('plugin:victauri|victauri_eval_callback', {{
                        id: '{id}',
                        result: JSON.stringify({{ __error: e.message }})
                    }});
                }}
            }})();
            "#
        );

        if let Err(e) = self.bridge.eval_webview(webview_label, &inject) {
            self.state.pending_evals.lock().await.remove(&id);
            return Err(format!("eval injection failed: {e}"));
        }

        match tokio::time::timeout(timeout, rx).await {
            Ok(Ok(result)) => {
                self.check_bridge_version_once();
                Ok(result)
            }
            Ok(Err(_)) => Err("eval callback channel closed".to_string()),
            Err(_) => {
                self.state.pending_evals.lock().await.remove(&id);
                Err(format!("eval timed out after {}s", timeout.as_secs()))
            }
        }
    }

    fn check_bridge_version_once(&self) {
        if self.bridge_checked.swap(true, Ordering::Relaxed) {
            return;
        }
        let handler = self.clone();
        tokio::spawn(async move {
            match handler
                .eval_with_return_timeout(
                    "window.__VICTAURI__?.version",
                    None,
                    std::time::Duration::from_secs(5),
                )
                .await
            {
                Ok(v) => {
                    let v = v.trim_matches('"');
                    if v != BRIDGE_VERSION {
                        tracing::warn!(
                            "Bridge version mismatch: Rust expects {BRIDGE_VERSION}, JS reports {v}"
                        );
                    } else {
                        tracing::debug!("Bridge version verified: {v}");
                    }
                }
                Err(e) => tracing::debug!("Bridge version check skipped: {e}"),
            }
        });
    }
}

const SERVER_INSTRUCTIONS: &str = "Victauri gives you X-ray vision and hands inside a running Tauri application. \
You can evaluate JS, snapshot the DOM, interact with elements (click, double-click, \
hover, fill, type, select, scroll, focus), press keys, invoke Tauri commands, \
capture screenshots, manage windows (minimize, maximize, resize, move, close), \
view IPC and network traffic, read/write browser storage, track navigation history, \
handle dialogs, wait for conditions, search the command registry, monitor process memory, \
record and replay sessions, inspect computed CSS styles, measure element bounding boxes, \
draw debug overlays on elements, inject custom CSS, run accessibility audits (alt text, \
labels, contrast, ARIA, heading hierarchy), get performance metrics (navigation timing, \
resource loading, JS heap, long tasks, DOM stats), and subscribe to live resource \
streams — all through MCP.";

impl ServerHandler for VictauriMcpHandler {
    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(
            ServerCapabilities::builder()
                .enable_tools()
                .enable_resources()
                .enable_resources_subscribe()
                .build(),
        )
        .with_instructions(SERVER_INSTRUCTIONS)
    }

    async fn list_tools(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListToolsResult, ErrorData> {
        let all_tools = Self::tool_router().list_all();
        let filtered: Vec<Tool> = all_tools
            .into_iter()
            .filter(|t| self.state.privacy.is_tool_enabled(t.name.as_ref()))
            .collect();
        Ok(ListToolsResult {
            tools: filtered,
            ..Default::default()
        })
    }

    async fn call_tool(
        &self,
        request: CallToolRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, ErrorData> {
        let tool_name: String = request.name.as_ref().to_owned();
        if !self.state.privacy.is_tool_enabled(&tool_name) {
            tracing::debug!(tool = %tool_name, "tool call blocked by privacy config");
            return Ok(tool_disabled(&tool_name));
        }
        self.state
            .tool_invocations
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let start = std::time::Instant::now();
        tracing::debug!(tool = %tool_name, "tool invocation started");
        let ctx = ToolCallContext::new(self, request, context);
        let result = Self::tool_router().call(ctx).await;
        let elapsed = start.elapsed();
        tracing::debug!(
            tool = %tool_name,
            elapsed_ms = elapsed.as_millis() as u64,
            is_error = result.as_ref().map(|r| r.is_error.unwrap_or(false)).unwrap_or(true),
            "tool invocation completed"
        );
        result
    }

    fn get_tool(&self, name: &str) -> Option<Tool> {
        if !self.state.privacy.is_tool_enabled(name) {
            return None;
        }
        Self::tool_router().get(name).cloned()
    }

    async fn list_resources(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListResourcesResult, ErrorData> {
        Ok(ListResourcesResult {
            resources: vec![
                RawResource::new(RESOURCE_URI_IPC_LOG, "ipc-log")
                    .with_description(
                        "Live IPC call log — all commands invoked between frontend and backend",
                    )
                    .with_mime_type("application/json")
                    .no_annotation(),
                RawResource::new(RESOURCE_URI_WINDOWS, "windows")
                    .with_description(
                        "Current state of all Tauri windows — position, size, visibility, focus",
                    )
                    .with_mime_type("application/json")
                    .no_annotation(),
                RawResource::new(RESOURCE_URI_STATE, "state")
                    .with_description(
                        "Victauri plugin state — event count, registered commands, memory stats",
                    )
                    .with_mime_type("application/json")
                    .no_annotation(),
            ],
            ..Default::default()
        })
    }

    async fn read_resource(
        &self,
        request: ReadResourceRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<ReadResourceResult, ErrorData> {
        let uri = &request.uri;
        let json = match uri.as_str() {
            RESOURCE_URI_IPC_LOG => {
                let calls = self.state.event_log.ipc_calls();
                serde_json::to_string_pretty(&calls)
                    .map_err(|e| ErrorData::internal_error(e.to_string(), None))?
            }
            RESOURCE_URI_WINDOWS => {
                let states = self.bridge.get_window_states(None);
                serde_json::to_string_pretty(&states)
                    .map_err(|e| ErrorData::internal_error(e.to_string(), None))?
            }
            RESOURCE_URI_STATE => {
                let state_json = serde_json::json!({
                    "events_captured": self.state.event_log.len(),
                    "commands_registered": self.state.registry.count(),
                    "memory": crate::memory::current_stats(),
                    "port": self.state.port,
                });
                serde_json::to_string_pretty(&state_json)
                    .map_err(|e| ErrorData::internal_error(e.to_string(), None))?
            }
            _ => {
                return Err(ErrorData::resource_not_found(
                    format!("unknown resource: {uri}"),
                    None,
                ));
            }
        };

        Ok(ReadResourceResult::new(vec![ResourceContents::text(
            json, uri,
        )]))
    }

    async fn subscribe(
        &self,
        request: SubscribeRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<(), ErrorData> {
        let uri = &request.uri;
        match uri.as_str() {
            RESOURCE_URI_IPC_LOG | RESOURCE_URI_WINDOWS | RESOURCE_URI_STATE => {
                self.subscriptions.lock().await.insert(uri.clone());
                tracing::info!("Client subscribed to resource: {uri}");
                Ok(())
            }
            _ => Err(ErrorData::resource_not_found(
                format!("unknown resource: {uri}"),
                None,
            )),
        }
    }

    async fn unsubscribe(
        &self,
        request: UnsubscribeRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<(), ErrorData> {
        self.subscriptions.lock().await.remove(&request.uri);
        tracing::info!("Client unsubscribed from resource: {}", request.uri);
        Ok(())
    }
}

fn tool_error(msg: impl Into<String>) -> CallToolResult {
    let mut result = CallToolResult::success(vec![Content::text(msg)]);
    result.is_error = Some(true);
    result
}

fn tool_disabled(name: &str) -> CallToolResult {
    tool_error(format!(
        "tool '{name}' is disabled by privacy configuration"
    ))
}

fn validate_url(url: &str) -> Result<(), String> {
    let trimmed: String = url.chars().filter(|c| !c.is_control()).collect();
    match url::Url::parse(&trimmed) {
        Ok(parsed) => match parsed.scheme() {
            "http" | "https" | "file" => Ok(()),
            scheme => Err(format!(
                "scheme '{scheme}' is not allowed; use http, https, or file"
            )),
        },
        Err(e) => Err(format!("invalid URL: {e}")),
    }
}

fn sanitize_css_color(color: &str) -> Result<String, String> {
    let s = color.trim();
    if s.len() > 100 {
        return Err("CSS color value too long".to_string());
    }
    // Reject CSS escape sequences (\XX hex escapes)
    if s.contains('\\') {
        return Err("CSS escape sequences not allowed in color values".to_string());
    }
    let valid = s
        .chars()
        .all(|c| c.is_alphanumeric() || matches!(c, '#' | '(' | ')' | ',' | '.' | ' ' | '%' | '-'));
    if !valid {
        return Err("invalid characters in CSS color value".to_string());
    }
    if s.contains(';')
        || s.contains('{')
        || s.contains('}')
        || s.to_lowercase().contains("url(")
        || s.to_lowercase().contains("expression(")
        || s.to_lowercase().contains("import")
    {
        return Err("invalid CSS color value".to_string());
    }
    Ok(s.to_string())
}

// ── Server startup ───────────────────────────────────────────────────────────

pub fn build_app(state: Arc<VictauriState>, bridge: Arc<dyn WebviewBridge>) -> axum::Router {
    build_app_with_options(state, bridge, None)
}

pub fn build_app_with_options(
    state: Arc<VictauriState>,
    bridge: Arc<dyn WebviewBridge>,
    auth_token: Option<String>,
) -> axum::Router {
    let handler = VictauriMcpHandler::new(state.clone(), bridge);

    let mcp_service = StreamableHttpService::new(
        move || Ok(handler.clone()),
        Arc::new(LocalSessionManager::default()),
        StreamableHttpServerConfig::default(),
    );

    let auth_state = Arc::new(crate::auth::AuthState {
        token: auth_token.clone(),
    });
    let health_state = state.clone();
    let info_state = state.clone();
    let info_auth = auth_token.is_some();

    let privacy_enabled = !state.privacy.disabled_tools.is_empty()
        || state.privacy.command_allowlist.is_some()
        || !state.privacy.command_blocklist.is_empty()
        || state.privacy.redaction_enabled;

    let mut router = axum::Router::new()
        .route_service("/mcp", mcp_service)
        .route(
            "/info",
            axum::routing::get(move || {
                let s = info_state.clone();
                async move {
                    axum::Json(serde_json::json!({
                        "name": "victauri",
                        "version": env!("CARGO_PKG_VERSION"),
                        "protocol": "mcp",
                        "commands_registered": s.registry.count(),
                        "events_captured": s.event_log.len(),
                        "port": s.port,
                        "auth_required": info_auth,
                        "privacy_mode": privacy_enabled,
                    }))
                }
            }),
        );

    if auth_token.is_some() {
        router = router.layer(axum::middleware::from_fn_with_state(
            auth_state,
            crate::auth::require_auth,
        ));
    }

    let rate_limiter = crate::auth::default_rate_limiter();
    router = router.layer(axum::middleware::from_fn_with_state(
        rate_limiter,
        crate::auth::rate_limit,
    ));

    router
        .route(
            "/health",
            axum::routing::get(move || {
                let s = health_state.clone();
                async move {
                    axum::Json(serde_json::json!({
                        "status": "ok",
                        "uptime_secs": s.started_at.elapsed().as_secs(),
                        "events_captured": s.event_log.len(),
                        "commands_registered": s.registry.count(),
                        "memory": crate::memory::current_stats(),
                    }))
                }
            }),
        )
        .layer(axum::middleware::from_fn(crate::auth::security_headers))
        .layer(axum::middleware::from_fn(crate::auth::origin_guard))
        .layer(axum::middleware::from_fn(crate::auth::dns_rebinding_guard))
}

pub mod tests_support {
    pub fn get_memory_stats() -> serde_json::Value {
        crate::memory::current_stats()
    }
}

pub async fn start_server<R: Runtime>(
    app_handle: tauri::AppHandle<R>,
    state: Arc<VictauriState>,
    port: u16,
    shutdown_rx: tokio::sync::watch::Receiver<bool>,
) -> anyhow::Result<()> {
    start_server_with_options(app_handle, state, port, None, shutdown_rx).await
}

pub async fn start_server_with_options<R: Runtime>(
    app_handle: tauri::AppHandle<R>,
    state: Arc<VictauriState>,
    port: u16,
    auth_token: Option<String>,
    mut shutdown_rx: tokio::sync::watch::Receiver<bool>,
) -> anyhow::Result<()> {
    let bridge: Arc<dyn WebviewBridge> = Arc::new(app_handle);
    let app = build_app_with_options(state, bridge, auth_token);

    let listener = tokio::net::TcpListener::bind(format!("127.0.0.1:{port}")).await?;
    tracing::info!("Victauri MCP server listening on 127.0.0.1:{port}");

    axum::serve(listener, app)
        .with_graceful_shutdown(async move {
            let _ = shutdown_rx.wait_for(|&v| v).await;
            tracing::info!("Victauri MCP server shutting down gracefully");
        })
        .await?;
    Ok(())
}

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

    #[test]
    fn js_string_simple() {
        assert_eq!(js_string("hello"), "\"hello\"");
    }

    #[test]
    fn js_string_single_quotes() {
        let result = js_string("it's a test");
        assert!(result.contains("it's a test"));
    }

    #[test]
    fn js_string_double_quotes() {
        let result = js_string(r#"say "hello""#);
        assert!(result.contains(r#"\""#));
    }

    #[test]
    fn js_string_backslashes() {
        let result = js_string(r"path\to\file");
        assert!(result.contains(r"\\"));
    }

    #[test]
    fn js_string_newlines_and_tabs() {
        let result = js_string("line1\nline2\ttab");
        assert!(result.contains(r"\n"));
        assert!(result.contains(r"\t"));
        assert!(!result.contains('\n'));
    }

    #[test]
    fn js_string_null_bytes() {
        let input = String::from_utf8(b"before\x00after".to_vec()).unwrap();
        let result = js_string(&input);
        // serde_json escapes null bytes as 
        assert!(result.contains("\\u0000"));
        assert!(!result.contains('\0'));
    }

    #[test]
    fn js_string_template_literal_injection() {
        let result = js_string("`${alert(1)}`");
        // Should not contain unescaped backticks that could break template literals
        // serde_json wraps in double quotes, so backticks are safe
        assert!(result.starts_with('"'));
        assert!(result.ends_with('"'));
    }

    #[test]
    fn js_string_unicode_separators() {
        // U+2028 (Line Separator) and U+2029 (Paragraph Separator) are valid in
        // JSON strings per RFC 8259, and serde_json passes them through literally.
        // Since js_string is used inside JS double-quoted strings (not template
        // literals), they are safe in modern JS engines (ES2019+).
        let result = js_string("a\u{2028}b\u{2029}c");
        // Verify the string is valid JSON that round-trips correctly
        let decoded: String = serde_json::from_str(&result).unwrap();
        assert_eq!(decoded, "a\u{2028}b\u{2029}c");
    }

    #[test]
    fn js_string_empty() {
        assert_eq!(js_string(""), "\"\"");
    }

    #[test]
    fn js_string_html_script_close() {
        // </script> in a JS string inside HTML could break out of script tags
        let result = js_string("</script><img onerror=alert(1)>");
        assert!(result.starts_with('"'));
        // The string is JSON-encoded; verify it round-trips safely
        let decoded: String = serde_json::from_str(&result).unwrap();
        assert_eq!(decoded, "</script><img onerror=alert(1)>");
    }

    #[test]
    fn js_string_very_long() {
        let long = "a".repeat(100_000);
        let result = js_string(&long);
        assert!(result.len() >= 100_002); // quotes + content
    }

    // ── URL validation tests ────────────────────────────────────────────────

    #[test]
    fn url_allows_http() {
        assert!(validate_url("http://example.com").is_ok());
    }

    #[test]
    fn url_allows_https() {
        assert!(validate_url("https://example.com/path?q=1").is_ok());
    }

    #[test]
    fn url_allows_file() {
        assert!(validate_url("file:///tmp/test.html").is_ok());
    }

    #[test]
    fn url_blocks_javascript() {
        assert!(validate_url("javascript:alert(1)").is_err());
    }

    #[test]
    fn url_blocks_javascript_case_insensitive() {
        assert!(validate_url("JAVASCRIPT:alert(1)").is_err());
    }

    #[test]
    fn url_blocks_data_scheme() {
        assert!(validate_url("data:text/html,<script>alert(1)</script>").is_err());
    }

    #[test]
    fn url_blocks_vbscript() {
        assert!(validate_url("vbscript:MsgBox(1)").is_err());
    }

    #[test]
    fn url_rejects_invalid() {
        assert!(validate_url("not a url at all").is_err());
    }

    #[test]
    fn url_strips_control_chars() {
        // Control characters should be stripped, leaving a valid URL
        let input = format!("http://example{}com", '\0');
        assert!(validate_url(&input).is_ok());
    }
}