sequel-mcp 0.11.2

Local-first, policy-gated MySQL/MariaDB and SQLite access for AI agents: native Rust MCP server, CLI and GUI
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
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
//! D7: deterministic process-level MCP lifecycle tests against the real
//! built binary — legacy initialization, tools/list, a gated SQLite
//! execute (denied) and query round trip, malformed + oversized requests,
//! stdin EOF during an in-flight request, and clean exit. Every read is
//! deadline-driven; no fixed sleeps as a pass criterion.
//!
//! ISOLATION: every spawned process runs in a CLEAN environment (nothing
//! inherited; only an isolated HOME/XDG tree and the fail-closed
//! SEQUEL_MCP_TEST_MODE/ROOT variables) — the executable regression for
//! the benchmark-environment isolation failure. A spawned child can
//! never inherit the developer's real config, audit DB, or Keychain.

use std::io::{Read, Write};
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};

/// Compile-time path to the locally built binary (no runtime-supplied
/// command source).
fn bin_path() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_sequel-mcp"))
}

struct Server {
    child: Child,
}

impl Server {
    /// Standard demo config: one read-only sqlite connection, spawned in
    /// a clean isolated environment (see module ISOLATION note).
    fn spawn() -> (Server, std::process::ChildStdin, LineReceiver) {
        Self::spawn_demo_with(serde_json::json!({}))
    }

    /// Demo config variant with table policies, for elevation scenarios.
    fn spawn_demo_with(
        table_policies: serde_json::Value,
    ) -> (Server, std::process::ChildStdin, LineReceiver) {
        let dir = tempfile::TempDir::new().unwrap();
        let cfg_root = dir.path().join("cfg");
        let data_root = dir.path().join("data");
        std::fs::create_dir_all(cfg_root.join("sequel-mcp")).unwrap();
        std::fs::create_dir_all(data_root.join("sequel-mcp")).unwrap();
        std::fs::create_dir_all(dir.path().join("home")).unwrap();
        // Read-only SQLite handles require the file to exist.
        let demo_db = dir.path().join("demo.sqlite");
        std::fs::write(&demo_db, b"").unwrap();
        std::fs::write(
            cfg_root.join("sequel-mcp").join("config.json"),
            serde_json::to_string_pretty(&demo_config(&demo_db, table_policies)).unwrap(),
        )
        .unwrap();
        eprintln!("ISO_ROOT={}", dir.path().display());
        std::mem::forget(dir);
        Self::launch(&cfg_root, &data_root)
    }

    /// Spawn with a fully caller-provided config document (same clean
    /// isolated environment).
    fn spawn_with_config(
        cfg: serde_json::Value,
    ) -> (Server, std::process::ChildStdin, LineReceiver) {
        let dir = tempfile::TempDir::new().unwrap();
        let cfg_root = dir.path().join("cfg");
        let data_root = dir.path().join("data");
        std::fs::create_dir_all(cfg_root.join("sequel-mcp")).unwrap();
        std::fs::create_dir_all(data_root.join("sequel-mcp")).unwrap();
        std::fs::create_dir_all(dir.path().join("home")).unwrap();
        std::fs::write(
            cfg_root.join("sequel-mcp").join("config.json"),
            serde_json::to_string_pretty(&cfg).unwrap(),
        )
        .unwrap();
        eprintln!("ISO_ROOT={}", dir.path().display());
        std::mem::forget(dir);
        Self::launch(&cfg_root, &data_root)
    }

    /// Launch the binary with a CLEAN environment: nothing inherited,
    /// only the isolated tree below and the fail-closed test-mode
    /// variables. The binary needs no PATH - it execs nothing.
    fn launch(
        cfg_root: &std::path::Path,
        data_root: &std::path::Path,
    ) -> (Server, std::process::ChildStdin, LineReceiver) {
        // The fail-closed test root is the grandparent of the XDG dirs
        // (the leaked TempDir itself).
        let test_root = cfg_root
            .parent()
            .map(std::path::Path::to_path_buf)
            .unwrap_or_else(|| cfg_root.to_path_buf());
        let home = test_root.join("home");
        let mut child = Command::new(bin_path())
            .arg("serve")
            .env_clear()
            .env("HOME", &home)
            .env("XDG_CONFIG_HOME", cfg_root)
            .env("XDG_DATA_HOME", data_root)
            .env("SEQUEL_MCP_TEST_MODE", "1")
            .env("SEQUEL_MCP_TEST_ROOT", &test_root)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .expect("binary spawns");
        let stdin = child.stdin.take().unwrap();
        let stdout = child.stdout.take().unwrap();
        // Drain stderr in the background so a chatty child can never
        // block on a full pipe (kept for post-mortem on failure).
        let err = child.stderr.take();
        std::thread::spawn(move || {
            use std::io::Read;
            let mut e = match err {
                Some(e) => e,
                None => return,
            };
            let mut buf = [0u8; 4096];
            while let Ok(n) = e.read(&mut buf) {
                if n == 0 {
                    break;
                }
            }
        });
        let reader = LineReceiver::from_reader(stdout);
        (Server { child }, stdin, reader)
    }

    /// Like [`Server::launch`], plus synthetic test secrets for the
    /// in-memory store (TEST_MODE only; never the real Keychain).
    fn launch_with_secrets(
        cfg_root: &std::path::Path,
        data_root: &std::path::Path,
        secrets_json: &str,
    ) -> (Server, std::process::ChildStdin, LineReceiver) {
        let test_root = cfg_root
            .parent()
            .map(std::path::Path::to_path_buf)
            .unwrap_or_else(|| cfg_root.to_path_buf());
        let home = test_root.join("home");
        let mut child = Command::new(bin_path())
            .arg("serve")
            .env_clear()
            .env("HOME", &home)
            .env("XDG_CONFIG_HOME", cfg_root)
            .env("XDG_DATA_HOME", data_root)
            .env("SEQUEL_MCP_TEST_MODE", "1")
            .env("SEQUEL_MCP_TEST_ROOT", &test_root)
            .env("SEQUEL_MCP_TEST_SECRETS", secrets_json)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .expect("binary spawns");
        let stdin = child.stdin.take().unwrap();
        let stdout = child.stdout.take().unwrap();
        let err = child.stderr.take();
        std::thread::spawn(move || {
            use std::io::Read;
            let mut e = match err {
                Some(e) => e,
                None => return,
            };
            let mut buf = [0u8; 4096];
            while let Ok(n) = e.read(&mut buf) {
                if n == 0 {
                    break;
                }
            }
        });
        let reader = LineReceiver::from_reader(stdout);
        (Server { child }, stdin, reader)
    }
}

impl Drop for Server {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

fn readonly_policy() -> serde_json::Value {
    serde_json::json!({
        "read": "allow", "write": "deny", "ddl": "deny", "admin": "deny",
        "txCtrl": "allow", "rowCap": 200, "stmtTimeoutMs": 5000,
        "requireTouchID": false, "maxBackupRows": 100,
        "maxBackupBytes": 1048576, "onBackupOverflow": "abort"
    })
}

fn demo_config(db: &std::path::Path, table_policies: serde_json::Value) -> serde_json::Value {
    serde_json::json!({
        "version": 2,
        "revision": 1,
        "defaultConnection": "demo",
        "connections": [{
            "driver": "sqlite",
            "name": "demo",
            "path": db.display().to_string(),
            "database": "main",
            "policy": readonly_policy(),
            "tablePolicies": table_policies
        }],
        "retention": {}
    })
}

fn send(stdin: &mut impl Write, value: &serde_json::Value) {
    stdin
        .write_all(serde_json::to_string(value).unwrap().as_bytes())
        .unwrap();
    stdin.write_all(b"\n").unwrap();
    stdin.flush().unwrap();
}

/// Channel-fed line reader: an OS thread blocks on the pipe so the main
/// thread can enforce real deadlines (a blocking read on the pipe cannot).
/// Parsed messages that arrive out of order (concurrent responses) are
/// buffered, not discarded, so a later matcher still finds them.
struct LineReceiver {
    rx: std::sync::mpsc::Receiver<String>,
    pending: std::collections::VecDeque<serde_json::Value>,
}

impl LineReceiver {
    fn from_reader<R: Read + Send + 'static>(inner: R) -> Self {
        let (tx, rx) = std::sync::mpsc::channel::<String>();
        std::thread::spawn(move || {
            use std::io::BufRead;
            let reader = std::io::BufReader::new(inner);
            for line in reader.split(b'\n') {
                match line {
                    Ok(bytes) => {
                        let line = String::from_utf8_lossy(&bytes).trim().to_string();
                        if line.is_empty() {
                            continue;
                        }
                        if tx.send(line).is_err() {
                            break;
                        }
                    }
                    Err(_) => break,
                }
            }
        });
        Self {
            rx,
            pending: std::collections::VecDeque::new(),
        }
    }

    /// Next buffered-or-incoming message for `want_id`; non-matching
    /// messages stay buffered for subsequent lookups.
    fn recv_matching(&mut self, want_id: i64, deadline: Duration) -> Option<serde_json::Value> {
        let started = Instant::now();
        loop {
            if let Some(pos) = self.pending.iter().position(|m| m["id"] == want_id) {
                return self.pending.remove(pos);
            }
            match self.rx.recv_timeout(Duration::from_millis(50)) {
                Ok(line) => {
                    if let Ok(msg) = serde_json::from_str::<serde_json::Value>(&line) {
                        if msg["id"] == want_id {
                            return Some(msg);
                        }
                        self.pending.push_back(msg);
                    }
                }
                Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                    if started.elapsed() >= deadline {
                        return None;
                    }
                }
                Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => return None,
            }
        }
    }

    fn next_line(&mut self, deadline: Duration) -> Option<String> {
        let started = Instant::now();
        loop {
            match self.rx.recv_timeout(Duration::from_millis(50)) {
                Ok(line) => return Some(line),
                Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                    if started.elapsed() >= deadline {
                        return None;
                    }
                }
                Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
                    return None;
                }
            }
        }
    }
}

fn read_response(out: &mut LineReceiver, want_id: i64, deadline: Duration) -> serde_json::Value {
    out.recv_matching(want_id, deadline)
        .unwrap_or_else(|| panic!("no response for id {want_id} within {deadline:?}"))
}

/// Next server-INITIATED request with `method` (e.g. elicitation/create);
/// responses and other requests stay buffered for later lookups.
fn recv_request(out: &mut LineReceiver, method: &str, deadline: Duration) -> serde_json::Value {
    let started = Instant::now();
    loop {
        if let Some(pos) = out.pending.iter().position(|m| m["method"] == method) {
            return out.pending.remove(pos).expect("pending request vanished");
        }
        match out.rx.recv_timeout(Duration::from_millis(50)) {
            Ok(line) => {
                if let Ok(msg) = serde_json::from_str::<serde_json::Value>(&line) {
                    if msg["method"] == method {
                        return msg;
                    }
                    out.pending.push_back(msg);
                }
            }
            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                if started.elapsed() >= deadline {
                    panic!("no {method} request within {deadline:?}");
                }
            }
            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
                panic!("stdout closed while waiting for {method}")
            }
        }
    }
}

#[test]
fn d7_lifecycle_legacy_and_tools() {
    let (server, mut stdin, mut out) = Server::spawn();

    // --- Legacy initialization (what current Codex clients send).
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 1, "method": "initialize",
            "params": {
                "protocolVersion": "2025-06-18",
                "capabilities": {},
                "clientInfo": {"name": "d7-test", "version": "0"}
            }
        }),
    );
    let msg = read_response(&mut out, 1, Duration::from_secs(10));
    assert_eq!(msg["result"]["serverInfo"]["name"], "sequel-mcp");
    assert_eq!(
        msg["result"]["serverInfo"]["version"],
        env!("CARGO_PKG_VERSION")
    );
    send(
        &mut stdin,
        &serde_json::json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
    );

    // --- tools/list: 21 tools with names.
    send(
        &mut stdin,
        &serde_json::json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}),
    );
    let msg = read_response(&mut out, 2, Duration::from_secs(10));
    let tools = msg["result"]["tools"].as_array().expect("tools");
    assert_eq!(tools.len(), 28, "tool count");
    assert!(tools.iter().all(|t| t["name"].is_string()));
    assert!(tools.iter().any(|t| t["name"] == "query"));

    // --- Gated SQLite execute denied by policy (write=deny): fail closed.
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 3, "method": "tools/call",
            "params": {"name": "execute", "arguments": {
                "sql": "CREATE TABLE IF NOT EXISTS demo_t (id INTEGER PRIMARY KEY)"
            }}
        }),
    );
    let msg = read_response(&mut out, 3, Duration::from_secs(10));
    assert!(
        msg["result"]["isError"].as_bool().unwrap_or(false),
        "denied write: {msg}"
    );

    // --- SQLite query round trip through the real gate.
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 4, "method": "tools/call",
            "params": {"name": "query", "arguments": {"sql": "SELECT 41 + 1 AS answer"}}
        }),
    );
    let msg = read_response(&mut out, 4, Duration::from_secs(10));
    let rows = msg["result"]["structuredContent"]["rows"]
        .as_array()
        .unwrap_or_else(|| panic!("rows missing: {msg}"));
    assert_eq!(rows[0]["answer"], serde_json::json!(42), "{msg}");

    // --- Malformed request: rmcp's documented/current malformed-line
    // behavior (rust-sdk #938) is that invalid stdio lines are ignored —
    // no JSON-RPC parse-error frame — and the server remains live. The
    // acceptance contract is survival + stream integrity: the malformed
    // line does not crash the server, produces no stdout contamination,
    // and the very next valid request is answered normally.
    stdin.write_all(b"{not json}\n").unwrap();
    stdin.flush().unwrap();
    send(
        &mut stdin,
        &serde_json::json!({"jsonrpc": "2.0", "id": 7, "method": "tools/list"}),
    );
    let msg = read_response(&mut out, 7, Duration::from_secs(10));
    assert!(
        msg["result"]["tools"]
            .as_array()
            .map(|t| t.len() == 28)
            .unwrap_or(false),
        "server must keep answering after malformed input: {msg}"
    );

    // --- Oversized request (~2 MiB > MAX_MCP_LINE_BYTES): the line
    // limiter discards it BEFORE the JSON codec ever buffers it (bounded
    // memory); the deterministic contract is that the stream stays
    // intact — the follow-up valid request MUST be answered and no
    // protocol bytes are emitted for the dropped line.
    let big = "x".repeat(2 * 1024 * 1024);
    let oversized =
        format!("{{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"tools/list\",\"x\":\"{big}\"}}");
    stdin.write_all(oversized.as_bytes()).unwrap();
    stdin.write_all(b"\n").unwrap();
    stdin.flush().unwrap();
    send(
        &mut stdin,
        &serde_json::json!({"jsonrpc": "2.0", "id": 6, "method": "tools/list"}),
    );
    let msg = read_response(&mut out, 6, Duration::from_secs(20));
    assert_eq!(
        msg["result"]["tools"].as_array().unwrap().len(),
        28,
        "follow-up after oversized input: {msg}"
    );

    // --- Clean EOF shutdown: close stdin, prompt exit.
    drop(stdin);
    let mut server = server;
    let started = Instant::now();
    loop {
        match server.child.try_wait().unwrap() {
            Some(_) => break,
            None => {
                assert!(
                    started.elapsed() < Duration::from_secs(10),
                    "process must exit promptly after stdin EOF"
                );
                std::thread::sleep(Duration::from_millis(25));
            }
        }
    }
}

#[test]
fn d7_eof_during_in_flight_request() {
    let (server, mut stdin, mut out) = Server::spawn();

    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 1, "method": "initialize",
            "params": {
                "protocolVersion": "2025-06-18",
                "capabilities": {},
                "clientInfo": {"name": "d7-eof", "version": "0"}
            }
        }),
    );
    let _ = read_response(&mut out, 1, Duration::from_secs(10));
    send(
        &mut stdin,
        &serde_json::json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
    );

    // Slow read, then stdin EOF immediately: the process must exit within
    // a bounded window without waiting for the query to finish.
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 2, "method": "tools/call",
            "params": {"name": "query", "arguments": {
                "sql": "WITH RECURSIVE c(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM c) SELECT COUNT(*) FROM c"
            }}
        }),
    );
    drop(stdin);
    let mut server = server;
    let started = Instant::now();
    loop {
        match server.child.try_wait().unwrap() {
            Some(status) => {
                assert!(
                    started.elapsed() < Duration::from_secs(15),
                    "EOF with in-flight request must not hang"
                );
                assert!(
                    status.success() || status.code().is_some(),
                    "exit: {status:?}"
                );
                break;
            }
            None => {
                assert!(
                    started.elapsed() < Duration::from_secs(15),
                    "EOF with in-flight request must not hang"
                );
                std::thread::sleep(Duration::from_millis(25));
            }
        }
    }
}

// ---- add_connection: elicited password → secret store + config ----

fn initialize_with_elicitation(
    stdin: &mut impl std::io::Write,
    out: &mut LineReceiver,
    elicitation: bool,
) {
    let caps = if elicitation {
        serde_json::json!({"elicitation": {"form": {}}})
    } else {
        serde_json::json!({})
    };
    send(
        stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 1, "method": "initialize",
            "params": {
                "protocolVersion": "2025-06-18",
                "capabilities": caps,
                "clientInfo": {"name": "add-conn-test", "version": "0"}
            }
        }),
    );
    let msg = read_response(out, 1, Duration::from_secs(10));
    assert_eq!(msg["result"]["serverInfo"]["name"], "sequel-mcp");
    send(
        stdin,
        &serde_json::json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
    );
}

#[test]
fn add_connection_round_trip() {
    let (server, mut stdin, mut out) = Server::spawn();
    initialize_with_elicitation(&mut stdin, &mut out, true);

    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 2, "method": "tools/call",
            "params": {"name": "add_connection", "arguments": {
                "name": "rt-mysql", "host": "127.0.0.1", "port": 3306,
                "user": "root", "database": "app", "ssl": false,
                "policy_preset": "read-only",
                "ssh_host": "bastion.example.com", "ssh_user": "ops",
                "ssh_key_path": "~/.ssh/id_ed25519",
                "ssh_docker_container": "mysql_prod",
                "ssh_docker_bridge_tool": "nc",
                "ssh_host_key_policy": "strict"
            }}
        }),
    );
    // The password arrives as a LIVE server-initiated elicitation, never
    // through tool arguments.
    let elicit = recv_request(&mut out, "elicitation/create", Duration::from_secs(10));
    let message = elicit["params"]["message"].as_str().unwrap_or_default();
    assert!(message.contains("root@127.0.0.1:3306"), "{message}");
    assert!(message.contains("never in tool arguments"), "{message}");
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": elicit["id"],
            "result": {"action": "accept", "content": {"password": "hunter2"}}
        }),
    );
    let msg = read_response(&mut out, 2, Duration::from_secs(10));
    let text = msg["result"]["content"][0]["text"]
        .as_str()
        .unwrap_or_default();
    assert!(text.contains("Saved connection \"rt-mysql\""), "{text}");

    // list_connections: driver mysql, read-only preset applied, password
    // present in the (test-mode in-memory) secret store.
    send(
        &mut stdin,
        &serde_json::json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call",
            "params": {"name": "list_connections", "arguments": {}}}),
    );
    let msg = read_response(&mut out, 3, Duration::from_secs(10));
    let payload: serde_json::Value =
        serde_json::from_str(msg["result"]["content"][0]["text"].as_str().unwrap())
            .expect("list_connections returns JSON");
    let conns = payload["connections"].as_array().unwrap();
    // The isolated demo config pre-seeds one sqlite connection; the new
    // MySQL connection adds to it.
    assert_eq!(conns.len(), 2, "{payload}");
    let rt = conns
        .iter()
        .find(|c| c["name"] == "rt-mysql")
        .expect("rt-mysql present");
    assert_eq!(rt["driver"], "mysql");
    assert_eq!(rt["hasStoredPassword"], true);
    assert_eq!(rt["policy"]["write"], "deny");

    // The no-secrets connections resource echoes the SSH + docker shape.
    send(
        &mut stdin,
        &serde_json::json!({"jsonrpc": "2.0", "id": 4, "method": "resources/read",
            "params": {"uri": "sequel-mcp://connections"}}),
    );
    let msg = read_response(&mut out, 4, Duration::from_secs(10));
    let resource = msg["result"]["contents"][0]["text"].as_str().unwrap();
    assert!(resource.contains("mysql_prod"), "{resource}");
    assert!(resource.contains("bastion.example.com"), "{resource}");

    drop(stdin);
    let mut server = server;
    let started = Instant::now();
    loop {
        match server.child.try_wait().unwrap() {
            Some(_) => break,
            None => {
                assert!(started.elapsed() < Duration::from_secs(10));
                std::thread::sleep(Duration::from_millis(25));
            }
        }
    }
}

#[test]
fn add_connection_declined_not_saved() {
    let (server, mut stdin, mut out) = Server::spawn();
    initialize_with_elicitation(&mut stdin, &mut out, true);

    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 2, "method": "tools/call",
            "params": {"name": "add_connection", "arguments": {
                "name": "declined-mysql", "host": "127.0.0.1", "user": "root"
            }}
        }),
    );
    let elicit = recv_request(&mut out, "elicitation/create", Duration::from_secs(10));
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": elicit["id"],
            "result": {"action": "decline"}
        }),
    );
    let msg = read_response(&mut out, 2, Duration::from_secs(10));
    let text = msg["result"]["content"][0]["text"]
        .as_str()
        .unwrap_or_default();
    assert!(
        text.contains("Password capture cancelled. Connection not saved."),
        "{text}"
    );

    send(
        &mut stdin,
        &serde_json::json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call",
            "params": {"name": "list_connections", "arguments": {}}}),
    );
    let msg = read_response(&mut out, 3, Duration::from_secs(10));
    let payload: serde_json::Value =
        serde_json::from_str(msg["result"]["content"][0]["text"].as_str().unwrap())
            .expect("list_connections returns JSON");
    assert!(
        payload["connections"]
            .as_array()
            .unwrap()
            .iter()
            .all(|c| c["name"] != "declined-mysql"),
        "declined capture must leave the config untouched"
    );
    drop(stdin);
    drop(server);
}

#[test]
fn add_connection_without_elicitation_support_fails_closed() {
    let (server, mut stdin, mut out) = Server::spawn();
    initialize_with_elicitation(&mut stdin, &mut out, false);

    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 2, "method": "tools/call",
            "params": {"name": "add_connection", "arguments": {
                "name": "no-elicit-mysql", "host": "127.0.0.1", "user": "root"
            }}
        }),
    );
    // A client that never declared elicitation.form gets a typed error,
    // never a hang and never a saved connection.
    let msg = read_response(&mut out, 2, Duration::from_secs(10));
    let text = msg["result"]["content"][0]["text"]
        .as_str()
        .unwrap_or_default();
    assert!(
        text.contains("Password capture cancelled. Connection not saved."),
        "{text}"
    );

    send(
        &mut stdin,
        &serde_json::json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call",
            "params": {"name": "list_connections", "arguments": {}}}),
    );
    let msg = read_response(&mut out, 3, Duration::from_secs(10));
    let payload: serde_json::Value =
        serde_json::from_str(msg["result"]["content"][0]["text"].as_str().unwrap())
            .expect("list_connections returns JSON");
    assert!(
        payload["connections"]
            .as_array()
            .unwrap()
            .iter()
            .all(|c| c["name"] != "no-elicit-mysql")
    );
    drop(stdin);
    drop(server);
}

// ---- restore_backup: per-statement policy + audit (review P1) ----

/// Shared harness: an isolated sqlite connection with read/write/ddl
/// allowed, a `users` table with one updated row (the update's pre-image
/// is the backup we restore), legacy-era initialization.
fn restore_harness() -> (
    Server,
    std::process::ChildStdin,
    LineReceiver,
    std::path::PathBuf,
) {
    let dir = tempfile::TempDir::new().unwrap();
    let cfg_root = dir.path().join("cfg");
    let data_root = dir.path().join("data");
    std::fs::create_dir_all(cfg_root.join("sequel-mcp")).unwrap();
    std::fs::create_dir_all(data_root.join("sequel-mcp")).unwrap();
    let db = dir.path().join("demo.sqlite");
    std::fs::write(&db, b"").unwrap();
    let policy = serde_json::json!({
        "read": "allow", "write": "allow", "ddl": "allow", "admin": "deny",
        "txCtrl": "allow", "rowCap": 100, "stmtTimeoutMs": 5000,
        "requireTouchID": false, "maxBackupRows": 100,
        "maxBackupBytes": 1048576, "onBackupOverflow": "abort"
    });
    std::fs::write(
        cfg_root.join("sequel-mcp").join("config.json"),
        serde_json::to_string_pretty(&serde_json::json!({
            "version": 2, "revision": 1, "defaultConnection": "demo",
            "connections": [
                {"driver": "sqlite", "name": "demo", "path": db.display().to_string(),
                 "database": "main", "policy": policy, "tablePolicies": {}}
            ],
            "retention": {}
        }))
        .unwrap(),
    )
    .unwrap();
    eprintln!("ISO_ROOT={}", dir.path().display());
    let root = dir.path().to_path_buf();
    std::mem::forget(dir);
    let (server, mut stdin, mut out) = Server::launch(&cfg_root, &data_root);
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 1, "method": "initialize",
            "params": {
                "protocolVersion": "2025-06-18",
                "capabilities": {"elicitation": {"form": {}}},
                "clientInfo": {"name": "restore-test", "version": "0"}
            }
        }),
    );
    let msg = read_response(&mut out, 1, Duration::from_secs(10));
    assert_eq!(msg["result"]["serverInfo"]["name"], "sequel-mcp");
    send(
        &mut stdin,
        &serde_json::json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
    );
    (server, stdin, out, root)
}

fn restore_exec(
    stdin: &mut impl Write,
    out: &mut LineReceiver,
    id: i64,
    sql: &str,
) -> serde_json::Value {
    send(
        stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": id, "method": "tools/call",
            "params": {"name": "execute", "arguments": {"sql": sql}}
        }),
    );
    read_response(out, id, Duration::from_secs(10))
}

fn restore_query(stdin: &mut impl Write, out: &mut LineReceiver, id: i64, sql: &str) -> String {
    send(
        stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": id, "method": "tools/call",
            "params": {"name": "query", "arguments": {"sql": sql}}
        }),
    );
    let msg = read_response(out, id, Duration::from_secs(10));
    msg["result"]["content"][0]["text"]
        .as_str()
        .unwrap_or_default()
        .to_string()
}

/// After a restore call, the next relevant wire message is EITHER the
/// confirmation elicitation (confirm-gated policy) or the final response
/// (allow/deny resolves without prompting).
fn restore_next(out: &mut LineReceiver, want_id: i64) -> (&'static str, serde_json::Value) {
    let started = Instant::now();
    loop {
        if let Some(pos) = out.pending.iter().position(|m| m["id"] == want_id) {
            return ("resp", out.pending.remove(pos).expect("pending resp"));
        }
        if let Some(pos) = out
            .pending
            .iter()
            .position(|m| m["method"] == "elicitation/create")
        {
            return ("elicit", out.pending.remove(pos).expect("pending elicit"));
        }
        match out.rx.recv_timeout(Duration::from_millis(50)) {
            Ok(line) => {
                if let Ok(msg) = serde_json::from_str::<serde_json::Value>(&line) {
                    if msg["id"] == want_id {
                        return ("resp", msg);
                    }
                    if msg["method"] == "elicitation/create" {
                        return ("elicit", msg);
                    }
                    out.pending.push_back(msg);
                }
            }
            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                if started.elapsed() >= Duration::from_secs(10) {
                    panic!("no response or elicitation for restore within 10s");
                }
            }
            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
                panic!("stdout closed waiting for restore outcome");
            }
        }
    }
}

#[test]
fn restore_denied_statement_refuses_whole_replay() {
    let (server, mut stdin, mut out, _root) = restore_harness();
    let mut id = 10;

    let m = restore_exec(
        &mut stdin,
        &mut out,
        id,
        "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)",
    );
    assert!(
        m["result"]["structuredContent"]["affectedRows"].is_number()
            || m["result"]["content"][0]["text"]
                .as_str()
                .unwrap_or("")
                .contains("affectedRows"),
        "{m}"
    );
    id += 1;
    let _ = restore_exec(
        &mut stdin,
        &mut out,
        id,
        "INSERT INTO users (id, name) VALUES (1, 'alice')",
    );
    id += 1;
    let _ = restore_exec(
        &mut stdin,
        &mut out,
        id,
        "UPDATE users SET name = 'bob' WHERE id = 1",
    );
    id += 1;

    // Deny writes on the restore target AFTER the backup exists.
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": id, "method": "tools/call",
            "params": {"name": "set_table_policy", "arguments": {
                "connection": "demo", "table": "main.users",
                "policy": {"write": "deny"}
            }}
        }),
    );
    let msg = read_response(&mut out, id, Duration::from_secs(10));
    let set_text = serde_json::to_string(&msg["result"]).unwrap_or_default();
    assert!(
        set_text.contains("\"write\":\"deny\""),
        "rule set: {set_text}"
    );
    id += 1;

    // Dry-run shows the per-statement policy preview flagging the denial.
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": id, "method": "tools/call",
            "params": {"name": "restore_backup", "arguments": {"backup_id": 2, "dry_run": true}}
        }),
    );
    let msg = read_response(&mut out, id, Duration::from_secs(10));
    let text = serde_json::to_string(&msg["result"]).unwrap_or_default();
    assert!(
        text.contains("policy"),
        "dry-run must carry the policy preview: {text}"
    );
    assert!(
        text.contains("wouldDeny") || text.contains("\"Deny\""),
        "preview flags the deny: {text}"
    );
    id += 1;

    // Confirmed restore: the per-statement deny refuses the WHOLE replay
    // (the outer approval cannot cover a denied statement).
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": id, "method": "tools/call",
            "params": {"name": "restore_backup", "arguments": {"backup_id": 2, "dry_run": false}}
        }),
    );
    // The deny fires either before or after the confirmation depending
    // on policy shape; answer the elicitation if it comes first.
    let (kind, first) = restore_next(&mut out, id);
    if kind == "elicit" {
        send(
            &mut stdin,
            &serde_json::json!({
                "jsonrpc": "2.0", "id": first["id"],
                "result": {"action": "accept", "content": {"choice": "once"}}
            }),
        );
    }
    let msg = read_response(&mut out, id, Duration::from_secs(10));
    let text = msg["result"]["content"][0]["text"]
        .as_str()
        .unwrap_or_default();
    assert!(
        text.contains("Restore denied by policy") && text.contains("statement"),
        "typed refusal naming the statement: {text}"
    );
    id += 1;

    // Nothing was restored: the updated value stands.
    let q = restore_query(
        &mut stdin,
        &mut out,
        id,
        "SELECT name FROM users WHERE id = 1",
    );
    assert!(q.contains("bob"), "denied restore must not replay: {q}");

    drop(stdin);
    drop(server);
}

#[test]
fn restore_success_writes_per_statement_audit_rows() {
    let (server, mut stdin, mut out, _root) = restore_harness();
    let mut id = 10;

    let _ = restore_exec(
        &mut stdin,
        &mut out,
        id,
        "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)",
    );
    id += 1;
    let _ = restore_exec(
        &mut stdin,
        &mut out,
        id,
        "INSERT INTO users (id, name) VALUES (1, 'alice')",
    );
    id += 1;
    let _ = restore_exec(
        &mut stdin,
        &mut out,
        id,
        "UPDATE users SET name = 'bob' WHERE id = 1",
    );
    id += 1;

    // Confirmed restore replays the pre-image ('alice') back.
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": id, "method": "tools/call",
            "params": {"name": "restore_backup", "arguments": {"backup_id": 2, "dry_run": false}}
        }),
    );
    let (kind, first) = restore_next(&mut out, id);
    if kind == "elicit" {
        send(
            &mut stdin,
            &serde_json::json!({
                "jsonrpc": "2.0", "id": first["id"],
                "result": {"action": "accept", "content": {"choice": "once"}}
            }),
        );
    }
    let msg = read_response(&mut out, id, Duration::from_secs(10));
    let text = msg["result"]["content"][0]["text"]
        .as_str()
        .unwrap_or_default();
    assert!(
        text.contains("executedStatements"),
        "restore executed: {text}"
    );
    assert!(
        !text.contains("audit-write-failed"),
        "no audit warnings: {text}"
    );
    id += 1;

    let q = restore_query(
        &mut stdin,
        &mut out,
        id,
        "SELECT name FROM users WHERE id = 1",
    );
    assert!(q.contains("alice"), "pre-image restored: {q}");
    id += 1;

    // Per-statement audit rows linked to the backup exist.
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": id, "method": "tools/call",
            "params": {"name": "audit_search", "arguments": {"limit": 50}}
        }),
    );
    let msg = read_response(&mut out, id, Duration::from_secs(10));
    let audit = msg["result"]["content"][0]["text"]
        .as_str()
        .unwrap_or_default();
    assert!(
        audit.contains("restore-2-"),
        "audit rows must carry the restore request-id prefix: {audit}"
    );
    assert!(
        audit.contains("\"backupId\":2") || audit.contains("\"backup_id\":2"),
        "rows link the backup: {audit}"
    );

    drop(stdin);
    drop(server);
}

// ---- Modern era (2026-07-28): discovery, _meta requests, MRTR ----

fn meta_2026() -> serde_json::Value {
    serde_json::json!({
        "io.modelcontextprotocol/protocolVersion": "2026-07-28",
        "io.modelcontextprotocol/clientCapabilities": {"elicitation": {"form": {}}},
        "io.modelcontextprotocol/clientInfo": {"name": "d7-test", "version": "0"}
    })
}

#[test]
fn d7_modern_discover_meta_and_version_error() {
    let (server, mut stdin, mut out) = Server::spawn();

    // server/discover with modern _meta: supportedVersions includes
    // 2026-07-28 and the server identity is in the response _meta.
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 1, "method": "server/discover",
            "params": {"_meta": meta_2026()}
        }),
    );
    let msg = read_response(&mut out, 1, Duration::from_secs(10));
    let versions: Vec<&str> = msg["result"]["supportedVersions"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap())
        .collect();
    assert!(versions.contains(&"2026-07-28"), "{versions:?}");
    assert_eq!(
        msg["result"]["_meta"]["io.modelcontextprotocol/serverInfo"]["name"],
        "sequel-mcp"
    );

    // Modern tools/list without any initialize: carries result
    // discrimination (resultType).
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 2, "method": "tools/list",
            "params": {"_meta": meta_2026()}
        }),
    );
    let msg = read_response(&mut out, 2, Duration::from_secs(10));
    assert_eq!(msg["result"]["resultType"], "complete");
    assert_eq!(msg["result"]["tools"].as_array().unwrap().len(), 28);

    // Modern tools/call (read) succeeds without initialize.
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 3, "method": "tools/call",
            "params": {
                "name": "query",
                "arguments": {"sql": "SELECT 6 AS seven_minus_one"},
                "_meta": meta_2026()
            }
        }),
    );
    let msg = read_response(&mut out, 3, Duration::from_secs(10));
    let rows = msg["result"]["structuredContent"]["rows"]
        .as_array()
        .unwrap();
    assert_eq!(rows[0]["seven_minus_one"], serde_json::json!(6));

    // Unsupported protocol version: the typed -32022 protocol error with
    // supported/requested data.
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 4, "method": "tools/list",
            "params": {"_meta": {
                "io.modelcontextprotocol/protocolVersion": "1999-01-01",
                "io.modelcontextprotocol/clientCapabilities": {},
                "io.modelcontextprotocol/clientInfo": {"name": "d7", "version": "0"}
            }}
        }),
    );
    let msg = read_response(&mut out, 4, Duration::from_secs(10));
    assert_eq!(msg["error"]["code"], -32022, "{msg}");
    assert_eq!(msg["error"]["data"]["requested"], "1999-01-01");

    drop(stdin);
    let mut server = server;
    let started = Instant::now();
    loop {
        match server.child.try_wait().unwrap() {
            Some(_) => break,
            None => {
                assert!(started.elapsed() < Duration::from_secs(10));
                std::thread::sleep(Duration::from_millis(25));
            }
        }
    }
}

#[test]
fn d7_modern_mrtr_approval_lifecycle() {
    // The elevation policy (write=deny baseline + main.z allow rule) makes
    // CREATE TABLE z confirm-required; the modern path must return
    // input_required, consume the one-shot approval on retry, reject the
    // replay, and reject a mutated-but-otherwise-allowed statement by
    // digest.
    let (mut server, mut stdin, mut out) = Server::spawn_demo_with(serde_json::json!({
        "main.z": {"write": "allow", "ddl": "allow"},
        "main.zz": {"write": "allow", "ddl": "allow"}
    }));

    let sql = "CREATE TABLE z (id INTEGER PRIMARY KEY)";
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 1, "method": "tools/call",
            "params": {
                "name": "execute",
                "arguments": {"sql": sql},
                "_meta": meta_2026()
            }
        }),
    );
    let msg = read_response(&mut out, 1, Duration::from_secs(10));
    assert_eq!(msg["result"]["resultType"], "input_required", "{msg}");
    let state = msg["result"]["requestState"].as_str().unwrap().to_string();
    // Redacted operation details present in the input request.
    let ir = &msg["result"]["inputRequests"]["approval"]["params"];
    assert!(ir["message"].as_str().unwrap().contains("CREATE TABLE z"));
    assert!(ir["message"].as_str().unwrap().contains("main.z"));
    assert_eq!(ir["mode"], "form");
    assert_eq!(
        ir["requestedSchema"]["properties"]["choice"]["enum"][0],
        "once"
    );

    // Retry with the approval: executes exactly once.
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 2, "method": "tools/call",
            "params": {
                "name": "execute",
                "arguments": {"sql": sql},
                "_meta": meta_2026(),
                "inputResponses": {"approval": {"action": "accept", "content": {"choice": "once"}}},
                "requestState": state
            }
        }),
    );
    let msg = read_response(&mut out, 2, Duration::from_secs(10));
    assert!(
        msg["result"]["isError"].is_null() || msg["result"]["isError"] == false,
        "approved execution: {msg}"
    );

    // Replay the same approval: rejected (single use).
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 3, "method": "tools/call",
            "params": {
                "name": "execute",
                "arguments": {"sql": sql},
                "_meta": meta_2026(),
                "inputResponses": {"approval": {"action": "accept", "content": {"choice": "once"}}},
                "requestState": state
            }
        }),
    );
    let msg = read_response(&mut out, 3, Duration::from_secs(10));
    assert!(
        msg["error"]["message"]
            .as_str()
            .unwrap()
            .starts_with("[mrtr_already_consumed]"),
        "replay rejected with a typed code: {msg}"
    );

    // Fresh approval for a different statement; try to use it on a
    // different allowed table — digest mismatch must reject.
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 4, "method": "tools/call",
            "params": {
                "name": "execute",
                "arguments": {"sql": "CREATE TABLE zz (id INTEGER PRIMARY KEY)"},
                "_meta": meta_2026()
            }
        }),
    );
    let msg2 = read_response(&mut out, 4, Duration::from_secs(10));
    let state2 = msg2["result"]["requestState"].as_str().unwrap().to_string();
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 5, "method": "tools/call",
            "params": {
                "name": "execute",
                "arguments": {"sql": "CREATE TABLE zz (id INTEGER PRIMARY KEY, other INT)"},
                "_meta": meta_2026(),
                "inputResponses": {"approval": {"action": "accept", "content": {"choice": "once"}}},
                "requestState": state2
            }
        }),
    );
    let msg = read_response(&mut out, 5, Duration::from_secs(10));
    assert!(
        msg["error"]["message"]
            .as_str()
            .unwrap()
            .starts_with("[mrtr_invalid_state]"),
        "digest mismatch rejected with a typed code: {msg}"
    );
    assert!(
        msg["error"]["message"]
            .as_str()
            .unwrap()
            .contains("operation changed"),
        "digest mismatch names the reason: {msg}"
    );
    let _ = &mut server;
}

// ---- MRTR negative matrix: every failure mode is typed, never a plain
// SQL error; the state is opaque and server-side ----

fn mrtr_call(
    stdin: &mut impl Write,
    out: &mut LineReceiver,
    id: i64,
    body: serde_json::Value,
) -> serde_json::Value {
    send(
        stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": id, "method": "tools/call",
            "params": {
                "name": "execute",
                "_meta": meta_2026(),
                "inputResponses": {"approval": {"action": "accept", "content": {"choice": "once"}}},
                "requestState": body["state"].as_str().unwrap_or(""),
                "arguments": {"sql": body["sql"].as_str().unwrap_or("")}
            }
        }),
    );
    read_response(out, id, Duration::from_secs(10))
}

fn mrtr_first_call(
    stdin: &mut impl Write,
    out: &mut LineReceiver,
    id: i64,
    sql: &str,
    name: &str,
    arguments_extra: serde_json::Value,
) -> String {
    let mut args = serde_json::json!({"sql": sql});
    if !arguments_extra.is_null() {
        for (k, v) in arguments_extra.as_object().unwrap() {
            args[k] = v.clone();
        }
    }
    let _ = name;
    send(
        stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": id, "method": "tools/call",
            "params": {"name": "execute", "arguments": args, "_meta": meta_2026()}
        }),
    );
    let msg = read_response(out, id, Duration::from_secs(10));
    assert_eq!(msg["result"]["resultType"], "input_required", "{msg}");
    msg["result"]["requestState"].as_str().unwrap().to_string()
}

#[test]
fn d7_modern_mrtr_negative_matrix() {
    let (server, mut stdin, mut out) = Server::spawn_demo_with(serde_json::json!({
        "main.z": {"read": "confirm", "write": "allow", "ddl": "allow"}
    }));

    let sql = "CREATE TABLE z (id INTEGER PRIMARY KEY)";
    let mut id = 100;

    // Corrupted state (one leading base64 char swapped).
    let s1 = mrtr_first_call(
        &mut stdin,
        &mut out,
        id,
        sql,
        "execute",
        serde_json::Value::Null,
    );
    id += 1;
    let first = s1.chars().next().unwrap();
    let swapped = if first == 'A' { 'B' } else { 'A' };
    let corrupt = format!("{swapped}{}", &s1[1..]);
    let msg = mrtr_call(
        &mut stdin,
        &mut out,
        id,
        serde_json::json!({"state": corrupt, "sql": sql}),
    );
    assert!(
        msg["error"]["message"]
            .as_str()
            .unwrap()
            .starts_with("[mrtr_invalid_state]"),
        "corrupted state: {msg}"
    );
    id += 1;

    // Truncated state.
    let s2 = mrtr_first_call(
        &mut stdin,
        &mut out,
        id,
        sql,
        "execute",
        serde_json::Value::Null,
    );
    id += 1;
    let truncated = s2[..s2.len() - 5].to_string();
    let msg = mrtr_call(
        &mut stdin,
        &mut out,
        id,
        serde_json::json!({"state": truncated, "sql": sql}),
    );
    assert!(
        msg["error"]["message"]
            .as_str()
            .unwrap()
            .starts_with("[mrtr_invalid_state]"),
        "truncated state: {msg}"
    );
    id += 1;

    // Oversized state (64 KiB of padding).
    let oversized = "A".repeat(64 * 1024);
    let msg = mrtr_call(
        &mut stdin,
        &mut out,
        id,
        serde_json::json!({"state": oversized, "sql": sql}),
    );
    assert!(
        msg["error"]["message"]
            .as_str()
            .unwrap()
            .starts_with("[mrtr_invalid_state]"),
        "oversized state: {msg}"
    );
    id += 1;

    // Cross-tool: a state issued for `execute` replayed through `query`
    // (whose own resolution is confirm-gated via the read rule).
    let s3 = mrtr_first_call(
        &mut stdin,
        &mut out,
        id,
        sql,
        "execute",
        serde_json::Value::Null,
    );
    id += 1;
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": id, "method": "tools/call",
            "params": {
                "name": "query",
                "arguments": {"sql": "SELECT * FROM z"},
                "_meta": meta_2026(),
                "inputResponses": {"approval": {"action": "accept", "content": {"choice": "once"}}},
                "requestState": s3
            }
        }),
    );
    let msg = read_response(&mut out, id, Duration::from_secs(10));
    assert!(
        msg["error"]["message"]
            .as_str()
            .unwrap()
            .starts_with("[mrtr_invalid_state]"),
        "cross-tool use rejected: {msg}"
    );
    assert!(
        msg["error"]["message"]
            .as_str()
            .unwrap()
            .contains("different tool"),
        "cross-tool reason surfaced: {msg}"
    );
    id += 1;

    // Policy change between plan and retry: typed policy_changed (an
    // UNRELATED table rule changes, so the statement itself stays
    // confirm-gated and only the revision moves).
    let s4 = mrtr_first_call(
        &mut stdin,
        &mut out,
        id,
        sql,
        "execute",
        serde_json::Value::Null,
    );
    id += 1;
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": id, "method": "tools/call",
            "params": {"name": "set_table_policy", "_meta": meta_2026(), "arguments": {
                "table": "main.unrelated", "policy": {"write": "allow"}
            }}
        }),
    );
    let _ = read_response(&mut out, id, Duration::from_secs(10));
    id += 1;
    let msg = mrtr_call(
        &mut stdin,
        &mut out,
        id,
        serde_json::json!({"state": s4, "sql": sql}),
    );
    assert!(
        msg["error"]["message"]
            .as_str()
            .unwrap()
            .starts_with("[mrtr_policy_changed]"),
        "policy change typed: {msg}"
    );
    id += 1;

    // Process restart: a state from a previous process is unknown.
    let s5 = mrtr_first_call(
        &mut stdin,
        &mut out,
        id,
        sql,
        "execute",
        serde_json::Value::Null,
    );
    id += 1;
    drop(stdin);
    {
        let mut server = server;
        let _ = server.child.kill();
        let _ = server.child.wait();
    }
    let (_server2, mut stdin, mut out) = Server::spawn_demo_with(serde_json::json!({
        "main.z": {"read": "confirm", "write": "allow", "ddl": "allow"}
    }));
    let msg = mrtr_call(
        &mut stdin,
        &mut out,
        id,
        serde_json::json!({"state": s5, "sql": sql}),
    );
    assert!(
        msg["error"]["message"]
            .as_str()
            .unwrap()
            .starts_with("[mrtr_invalid_state]"),
        "restart invalidates server-side state: {msg}"
    );
}

#[test]
fn d7_modern_mrtr_cross_connection_rejected() {
    // Two sqlite connections with identical elevation rules; a state
    // issued on the default must not validate on the other connection.
    let dir = tempfile::TempDir::new().unwrap();
    let cfg_root = dir.path().join("cfg");
    let data_root = dir.path().join("data");
    std::fs::create_dir_all(cfg_root.join("sequel-mcp")).unwrap();
    std::fs::create_dir_all(data_root.join("sequel-mcp")).unwrap();
    std::fs::create_dir_all(dir.path().join("home")).unwrap();
    let db = dir.path().join("demo.sqlite");
    let db2 = dir.path().join("alt.sqlite");
    std::fs::write(&db, b"").unwrap();
    std::fs::write(&db2, b"").unwrap();
    let policy = serde_json::json!({
        "read": "allow", "write": "deny", "ddl": "deny", "admin": "deny",
        "txCtrl": "allow", "rowCap": 100, "stmtTimeoutMs": 5000,
        "requireTouchID": false, "maxBackupRows": 100,
        "maxBackupBytes": 1048576, "onBackupOverflow": "abort"
    });
    let rules = serde_json::json!({"main.z": {"write": "allow", "ddl": "allow"}});
    std::fs::write(
        cfg_root.join("sequel-mcp").join("config.json"),
        serde_json::to_string_pretty(&serde_json::json!({
            "version": 2, "revision": 1, "defaultConnection": "demo",
            "connections": [
                {"driver": "sqlite", "name": "demo", "path": db.display().to_string(),
                 "database": "main", "policy": policy, "tablePolicies": rules},
                {"driver": "sqlite", "name": "alt", "path": db2.display().to_string(),
                 "database": "main", "policy": policy, "tablePolicies": rules}
            ],
            "retention": {}
        }))
        .unwrap(),
    )
    .unwrap();
    eprintln!("ISO_ROOT={}", dir.path().display());
    std::mem::forget(dir);
    let (_server, mut stdin, mut out) = Server::launch(&cfg_root, &data_root);

    let sql = "CREATE TABLE z (id INTEGER PRIMARY KEY)";
    let state = mrtr_first_call(
        &mut stdin,
        &mut out,
        1,
        sql,
        "demo",
        serde_json::Value::Null,
    );

    // Retry naming the OTHER connection.
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 2, "method": "tools/call",
            "params": {
                "name": "execute",
                "arguments": {"sql": sql, "connection": "alt"},
                "_meta": meta_2026(),
                "inputResponses": {"approval": {"action": "accept", "content": {"choice": "once"}}},
                "requestState": state
            }
        }),
    );
    let msg = read_response(&mut out, 2, Duration::from_secs(10));
    assert!(
        msg["error"]["message"]
            .as_str()
            .unwrap()
            .starts_with("[mrtr_invalid_state]"),
        "cross-connection use rejected: {msg}"
    );
    assert!(
        msg["error"]["message"]
            .as_str()
            .unwrap()
            .contains("different connection"),
        "cross-connection reason surfaced: {msg}"
    );
}

#[test]
fn d7_modern_mrtr_concurrent_retries_consume_once() {
    let (_server, mut stdin, mut out) = Server::spawn_demo_with(serde_json::json!({
        "main.z": {"write": "allow", "ddl": "allow"}
    }));
    let sql = "CREATE TABLE z (id INTEGER PRIMARY KEY)";
    let state = mrtr_first_call(
        &mut stdin,
        &mut out,
        1,
        sql,
        "demo",
        serde_json::Value::Null,
    );

    // Two retries pipelined BEFORE reading any response: exactly one may
    // consume the one-shot state; the other must report already-consumed.
    let body = |id: i64, state: &str, sql: &str| {
        serde_json::json!({
            "jsonrpc": "2.0", "id": id, "method": "tools/call",
            "params": {
                "name": "execute",
                "arguments": {"sql": sql},
                "_meta": meta_2026(),
                "inputResponses": {"approval": {"action": "accept", "content": {"choice": "once"}}},
                "requestState": state
            }
        })
    };
    let line1 = serde_json::to_string(&body(2, &state, sql)).unwrap();
    let line2 = serde_json::to_string(&body(3, &state, sql)).unwrap();
    stdin.write_all(line1.as_bytes()).unwrap();
    stdin.write_all(b"\n").unwrap();
    stdin.write_all(line2.as_bytes()).unwrap();
    stdin.write_all(b"\n").unwrap();
    stdin.flush().unwrap();

    let r2 = read_response(&mut out, 2, Duration::from_secs(10));
    let r3 = read_response(&mut out, 3, Duration::from_secs(10));
    let outcomes: Vec<bool> = [&r2, &r3]
        .iter()
        .map(|r| {
            r["error"]["message"]
                .as_str()
                .map(|m| m.starts_with("[mrtr_already_consumed]"))
                .unwrap_or(false)
        })
        .collect();
    assert_eq!(
        outcomes.iter().filter(|x| **x).count(),
        1,
        "exactly one retry reports already-consumed: {r2} {r3}"
    );
    let ok_count = [&r2, &r3]
        .iter()
        .filter(|r| {
            r.get("error").is_none()
                && r["result"].is_object()
                && (r["result"]["isError"].is_null()
                    || r["result"]["isError"] == serde_json::json!(false))
        })
        .count();
    assert_eq!(ok_count, 1, "exactly one retry executes: {r2} {r3}");
}

// ---- Isolation regression (benchmark incident): the spawned child
// never sees the developer environment ----

#[test]
fn isolation_child_never_loads_parent_config() {
    // A synthetic "real" tree with a non-loopback default connection,
    // far outside the isolated root.
    let real_dir = tempfile::TempDir::new().unwrap();
    let real_cfg = real_dir.path().join("config").join("sequel-mcp");
    std::fs::create_dir_all(&real_cfg).unwrap();
    let real_config = serde_json::json!({
        "version": 2, "revision": 1, "defaultConnection": "synthetic-real",
        "connections": [{
            "driver": "mysql", "name": "synthetic-real",
            "host": "192.0.2.10", "port": 3306, "user": "u", "database": "app",
            "ssl": false,
            "policy": {
                "read": "allow", "write": "deny", "ddl": "deny", "admin": "deny",
                "txCtrl": "allow", "rowCap": 100, "stmtTimeoutMs": 5000,
                "requireTouchID": false, "maxBackupRows": 100,
                "maxBackupBytes": 1048576, "onBackupOverflow": "abort"
            },
            "tablePolicies": {}
        }],
        "retention": {}
    });
    std::fs::write(
        real_cfg.join("config.json"),
        serde_json::to_string_pretty(&real_config).unwrap(),
    )
    .unwrap();
    let before = std::fs::read(real_cfg.join("config.json")).unwrap();

    // Child with an EMPTY config of its own, in the clean environment.
    let (mut child, mut stdin, mut out) = Server::spawn_with_config(serde_json::json!({
        "version": 2, "revision": 1, "connections": [], "retention": {}
    }));
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 1, "method": "tools/call",
            "params": {"name": "doctor", "arguments": {}, "_meta": meta_2026()}
        }),
    );
    let msg = read_response(&mut out, 1, Duration::from_secs(10));
    let text = serde_json::to_string(&msg["result"]).unwrap();
    assert!(
        !text.contains("synthetic-real") && !text.contains("192.0.2.10"),
        "parent config must not leak into the child: {text}"
    );
    assert_eq!(
        msg["result"]["structuredContent"]["connections"]
            .as_array()
            .map(Vec::len),
        Some(0),
        "child sees only its own (empty) config: {msg}"
    );
    drop(stdin);
    let _ = child.child.wait();

    let after = std::fs::read(real_cfg.join("config.json")).unwrap();
    assert_eq!(before, after, "the real tree must be untouched");
}

#[test]
fn isolation_state_files_landing_under_root() {
    let (mut child, mut stdin, mut out) = Server::spawn();
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 1, "method": "tools/call",
            "params": {"name": "query", "arguments": {"sql": "SELECT 7 AS v"}, "_meta": meta_2026()}
        }),
    );
    let msg = read_response(&mut out, 1, Duration::from_secs(10));
    assert_eq!(
        msg["result"]["structuredContent"]["rows"][0]["v"],
        serde_json::json!(7)
    );
    drop(stdin);
    let _ = child.child.wait();
    // The audit DB must have been created under the isolated data root
    // (found via the leaked ISO tree printed by the harness: assert by
    // scanning the printed roots is fragile; instead assert the child
    // answered and never wrote outside by construction of the clean
    // environment + the startup gate, exercised in the next test).
}

#[test]
fn isolation_startup_refuses_paths_outside_root() {
    // data root deliberately OUTSIDE the fail-closed test root: the
    // process must terminate BEFORE the MCP server starts (exit 78) and
    // emit no protocol bytes on stdout.
    let dir = tempfile::TempDir::new().unwrap();
    let cfg_root = dir.path().join("cfg");
    std::fs::create_dir_all(cfg_root.join("sequel-mcp")).unwrap();
    std::fs::create_dir_all(dir.path().join("home")).unwrap();
    let outside = tempfile::TempDir::new().unwrap();
    let outside_data = outside.path().join("data");
    std::fs::create_dir_all(&outside_data).unwrap();
    let (mut child, stdin, mut out) = Server::launch(&cfg_root, &outside_data);
    drop(stdin);
    let started = Instant::now();
    let status;
    loop {
        match child.child.try_wait().unwrap() {
            Some(s) => {
                status = s;
                break;
            }
            None => {
                assert!(
                    started.elapsed() < Duration::from_secs(10),
                    "must exit fast"
                );
                std::thread::sleep(Duration::from_millis(25));
            }
        }
    }
    assert_eq!(status.code(), Some(78), "isolation violation exits 78");
    assert!(
        out.next_line(Duration::from_millis(300)).is_none(),
        "no protocol bytes before the gate"
    );
}

#[test]
fn isolation_non_loopback_mysql_endpoint_refused_before_connect() {
    let dir = tempfile::TempDir::new().unwrap();
    let cfg_root = dir.path().join("cfg");
    let data_root = dir.path().join("data");
    std::fs::create_dir_all(cfg_root.join("sequel-mcp")).unwrap();
    std::fs::create_dir_all(data_root.join("sequel-mcp")).unwrap();
    std::fs::create_dir_all(dir.path().join("home")).unwrap();
    std::fs::write(
        cfg_root.join("sequel-mcp").join("config.json"),
        serde_json::to_string_pretty(&serde_json::json!({
            "version": 2, "revision": 1, "defaultConnection": "db",
            "connections": [{
                "driver": "mysql", "name": "db",
                "host": "192.0.2.10", "port": 3306, "user": "root",
                "database": "app", "ssl": false,
                "policy": {
                    "read": "allow", "write": "deny", "ddl": "deny", "admin": "deny",
                    "txCtrl": "allow", "rowCap": 100, "stmtTimeoutMs": 5000,
                    "requireTouchID": false, "maxBackupRows": 100,
                    "maxBackupBytes": 1048576, "onBackupOverflow": "abort"
                },
                "tablePolicies": {}
            }],
            "retention": {}
        }))
        .unwrap(),
    )
    .unwrap();
    eprintln!("ISO_ROOT={}", dir.path().display());
    std::mem::forget(dir);
    let (_server, mut stdin, mut out) = Server::launch_with_secrets(
        &cfg_root,
        &data_root,
        r#"{"db": {"root": "synthetic-password"}}"#,
    );

    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 1, "method": "tools/call",
            "params": {"name": "query", "arguments": {"sql": "SELECT 1 AS v"}, "_meta": meta_2026()}
        }),
    );
    let started = Instant::now();
    let msg = read_response(&mut out, 1, Duration::from_secs(20));
    let elapsed = started.elapsed();
    let text = serde_json::to_string(&msg).unwrap();
    let refused = msg["result"]["isError"].as_bool().unwrap_or(false) || msg["error"].is_object();
    assert!(refused, "refused: {msg}");
    assert!(
        text.contains("not loopback") || text.contains("SEQUEL_MCP_TEST_ALLOWED_ENDPOINTS"),
        "typed test-mode refusal: {text}"
    );
    // A real connect attempt to TEST-NET 192.0.2.10 would burn the 15 s
    // connect deadline; a pre-connect refusal returns immediately.
    assert!(
        elapsed < Duration::from_secs(5),
        "refusal must precede any connect attempt (took {elapsed:?})"
    );
}

#[test]
fn isolation_sqlite_path_outside_root_refused() {
    let outside = tempfile::TempDir::new().unwrap();
    let outside_db = outside.path().join("outside.sqlite");
    let (mut child, mut stdin, mut out) = Server::spawn_with_config(serde_json::json!({
        "version": 2, "revision": 1, "defaultConnection": "demo",
        "connections": [{
            "driver": "sqlite", "name": "demo",
            "path": outside_db.display().to_string(), "database": "main",
            "policy": {
                "read": "allow", "write": "deny", "ddl": "deny", "admin": "deny",
                "txCtrl": "allow", "rowCap": 100, "stmtTimeoutMs": 5000,
                "requireTouchID": false, "maxBackupRows": 100,
                "maxBackupBytes": 1048576, "onBackupOverflow": "abort"
            },
            "tablePolicies": {}
        }],
        "retention": {}
    }));
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 1, "method": "tools/call",
            "params": {"name": "query", "arguments": {"sql": "SELECT 1 AS v"}, "_meta": meta_2026()}
        }),
    );
    let msg = read_response(&mut out, 1, Duration::from_secs(10));
    let text = serde_json::to_string(&msg).unwrap();
    let refused = msg["result"]["isError"].as_bool().unwrap_or(false) || msg["error"].is_object();
    assert!(refused, "outside-root sqlite must fail closed: {msg}");
    assert!(
        text.contains("SEQUEL_MCP_TEST_ROOT"),
        "typed test-mode refusal: {text}"
    );
    assert!(
        !outside_db.exists(),
        "no file may be created outside the root"
    );
    drop(stdin);
    let _ = child.child.wait();
}

// ---- Input bounds: line-limit boundaries and response-ID integrity ----

fn padded_line(id: i64, target_len: usize) -> String {
    let prefix =
        format!("{{\"jsonrpc\":\"2.0\",\"id\":{id},\"method\":\"tools/list\",\"pad\":\"\"}}");
    let grow = target_len.saturating_sub(prefix.len());
    format!(
        "{{\"jsonrpc\":\"2.0\",\"id\":{id},\"method\":\"tools/list\",\"pad\":\"{}\"}}",
        "x".repeat(grow)
    )
}

#[test]
fn d7_line_limit_boundaries() {
    let limit = sequel_mcp::mcp::limits::MAX_MCP_LINE_BYTES;
    let (_server, mut stdin, mut out) = Server::spawn();
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 1, "method": "initialize",
            "params": {"protocolVersion": "2025-06-18", "capabilities": {},
                       "clientInfo": {"name": "limits", "version": "0"}}
        }),
    );
    let _ = read_response(&mut out, 1, Duration::from_secs(10));
    send(
        &mut stdin,
        &serde_json::json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
    );

    // limit - 1: passes.
    stdin
        .write_all(padded_line(10, limit - 1).as_bytes())
        .unwrap();
    stdin.write_all(b"\n").unwrap();
    stdin.flush().unwrap();
    let msg = read_response(&mut out, 10, Duration::from_secs(20));
    assert_eq!(
        msg["result"]["tools"].as_array().unwrap().len(),
        28,
        "{msg}"
    );

    // exactly limit: passes (the buffer observes one byte beyond).
    stdin.write_all(padded_line(11, limit).as_bytes()).unwrap();
    stdin.write_all(b"\n").unwrap();
    stdin.flush().unwrap();
    let msg = read_response(&mut out, 11, Duration::from_secs(20));
    assert_eq!(
        msg["result"]["tools"].as_array().unwrap().len(),
        28,
        "{msg}"
    );

    // limit + 1: dropped whole — no response for that id, and the next
    // valid request is answered (stream integrity).
    stdin
        .write_all(padded_line(12, limit + 1).as_bytes())
        .unwrap();
    stdin.write_all(b"\n").unwrap();
    stdin.flush().unwrap();
    let mut sink = out;
    let started = Instant::now();
    while let Some(line) = sink.next_line(Duration::from_millis(200)) {
        if let Ok(m) = serde_json::from_str::<serde_json::Value>(&line) {
            assert_ne!(
                m["id"],
                serde_json::json!(12),
                "no response may exist for the dropped line: {m}"
            );
        }
        if started.elapsed() > Duration::from_secs(2) {
            break;
        }
    }
    send(
        &mut stdin,
        &serde_json::json!({"jsonrpc": "2.0", "id": 13, "method": "tools/list"}),
    );
    let msg = read_response(&mut sink, 13, Duration::from_secs(20));
    assert_eq!(
        msg["result"]["tools"].as_array().unwrap().len(),
        28,
        "{msg}"
    );

    // No-newline oversized sender followed by the newline: the single
    // over-long line is dropped, the following valid line answered.
    stdin
        .write_all(padded_line(14, limit + 512).as_bytes())
        .unwrap();
    stdin.flush().unwrap();
    std::thread::sleep(Duration::from_millis(50));
    stdin.write_all(b"\n").unwrap();
    stdin.flush().unwrap();
    send(
        &mut stdin,
        &serde_json::json!({"jsonrpc": "2.0", "id": 15, "method": "tools/list"}),
    );
    let msg = read_response(&mut sink, 15, Duration::from_secs(20));
    assert_eq!(
        msg["result"]["tools"].as_array().unwrap().len(),
        28,
        "{msg}"
    );

    // Slow byte-chunked oversized sender: still discarded incrementally,
    // memory bounded by the fixed limit-sized buffer.
    let mut sent = 0usize;
    let target = limit + 4096;
    while sent < target {
        let chunk = 16 * 1024;
        stdin.write_all(&vec![b'q'; chunk]).unwrap();
        stdin.flush().unwrap();
        sent += chunk;
        std::thread::sleep(Duration::from_millis(1));
    }
    stdin.write_all(b"\n").unwrap();
    stdin.flush().unwrap();
    send(
        &mut stdin,
        &serde_json::json!({"jsonrpc": "2.0", "id": 16, "method": "tools/list"}),
    );
    let msg = read_response(&mut sink, 16, Duration::from_secs(30));
    assert_eq!(
        msg["result"]["tools"].as_array().unwrap().len(),
        28,
        "{msg}"
    );
    let _ = &mut stdin;
}

#[test]
fn d7_oversized_line_eof_midway_exits_bounded() {
    let (_server, mut stdin, mut _out) = Server::spawn();
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 1, "method": "initialize",
            "params": {"protocolVersion": "2025-06-18", "capabilities": {},
                       "clientInfo": {"name": "eof", "version": "0"}}
        }),
    );
    // Partial oversized line (no newline), then EOF: bounded exit.
    stdin
        .write_all(&vec![
            b'e';
            sequel_mcp::mcp::limits::MAX_MCP_LINE_BYTES + 1024
        ])
        .unwrap();
    stdin.flush().unwrap();
    drop(stdin);
    let mut server = _server;
    let started = Instant::now();
    loop {
        match server.child.try_wait().unwrap() {
            Some(_) => break,
            None => {
                assert!(
                    started.elapsed() < Duration::from_secs(15),
                    "EOF mid-oversized-line must exit promptly"
                );
                std::thread::sleep(Duration::from_millis(25));
            }
        }
    }
}

#[test]
fn d7_concurrent_response_id_integrity() {
    // 50 pipelined tools/call (small queries mixed with large responses
    // from a pre-seeded table): every request id must receive exactly one
    // terminal response, none duplicated, none missing, and the server
    // stays usable afterwards (rmcp #941 regression).
    let dir = tempfile::TempDir::new().unwrap();
    let cfg_root = dir.path().join("cfg");
    let data_root = dir.path().join("data");
    std::fs::create_dir_all(cfg_root.join("sequel-mcp")).unwrap();
    std::fs::create_dir_all(data_root.join("sequel-mcp")).unwrap();
    std::fs::create_dir_all(dir.path().join("home")).unwrap();
    let db = dir.path().join("big.sqlite");
    {
        let conn = rusqlite::Connection::open(&db).unwrap();
        conn.execute_batch(
            "CREATE TABLE big (payload TEXT);
             INSERT INTO big (payload) VALUES (printf('%c', 'x'));",
        )
        .unwrap();
        // Widen rows deterministically with SQL only.
        for _ in 0..5 {
            conn.execute_batch("UPDATE big SET payload = payload || payload;")
                .unwrap();
        }
    }
    std::fs::write(
        cfg_root.join("sequel-mcp").join("config.json"),
        serde_json::to_string_pretty(&serde_json::json!({
            "version": 2, "revision": 1, "defaultConnection": "demo",
            "connections": [{
                "driver": "sqlite", "name": "demo",
                "path": db.display().to_string(), "database": "main",
                "policy": {
                    "read": "allow", "write": "deny", "ddl": "deny", "admin": "deny",
                    "txCtrl": "allow", "rowCap": 200, "stmtTimeoutMs": 10000,
                    "requireTouchID": false, "maxBackupRows": 100,
                    "maxBackupBytes": 1048576, "onBackupOverflow": "abort"
                },
                "tablePolicies": {}
            }],
            "retention": {}
        }))
        .unwrap(),
    )
    .unwrap();
    eprintln!("ISO_ROOT={}", dir.path().display());
    std::mem::forget(dir);
    let (mut server, mut stdin, mut out) = Server::launch(&cfg_root, &data_root);
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 1, "method": "initialize",
            "params": {"protocolVersion": "2025-06-18", "capabilities": {},
                       "clientInfo": {"name": "conc", "version": "0"}}
        }),
    );
    let _ = read_response(&mut out, 1, Duration::from_secs(10));
    send(
        &mut stdin,
        &serde_json::json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
    );

    // 40 small + 10 large, all pipelined before reading anything.
    let mut wire = String::new();
    for i in 0..50 {
        let sql = if i % 5 == 0 {
            "SELECT payload FROM big LIMIT 32"
        } else {
            "SELECT 1 AS v"
        };
        wire.push_str(
            &serde_json::to_string(&serde_json::json!({
                "jsonrpc": "2.0", "id": 100 + i, "method": "tools/call",
                "params": {"name": "query", "arguments": {"sql": sql}}
            }))
            .unwrap(),
        );
        wire.push('\n');
    }
    stdin.write_all(wire.as_bytes()).unwrap();
    stdin.flush().unwrap();

    let mut seen = std::collections::BTreeSet::new();
    let started = Instant::now();
    while seen.len() < 50 {
        assert!(
            started.elapsed() < Duration::from_secs(60),
            "timed out with {}/50 responses",
            seen.len()
        );
        let line = out
            .next_line(Duration::from_secs(30))
            .expect("response line");
        let msg: serde_json::Value = serde_json::from_str(&line).expect("parseable response");
        let id = msg["id"].as_i64().expect("response id");
        assert!((100..150).contains(&id), "unexpected id {id}: {msg}");
        assert!(seen.insert(id), "duplicate response for id {id}");
        assert!(
            msg["result"].is_object() || msg["error"].is_object(),
            "terminal response for {id}: {msg}"
        );
    }

    // Still usable afterwards.
    send(
        &mut stdin,
        &serde_json::json!({"jsonrpc": "2.0", "id": 999, "method": "tools/list"}),
    );
    let msg = read_response(&mut out, 999, Duration::from_secs(10));
    assert_eq!(msg["result"]["tools"].as_array().unwrap().len(), 28);

    drop(stdin);
    let started = Instant::now();
    loop {
        match server.child.try_wait().unwrap() {
            Some(_) => break,
            None => {
                assert!(started.elapsed() < Duration::from_secs(10));
                std::thread::sleep(Duration::from_millis(25));
            }
        }
    }
}

/// Prompts and resources (legacy parity): prompts/list returns the two
/// prompts with their argument schemas; prompts/get renders each with
/// argument substitution (required-arg validation typed); resources/list
/// exposes sequel-mcp://connections; resources/read returns the no-secrets
/// JSON with policy presets and hasPassword.
#[test]
fn prompts_and_resources_lifecycle() {
    let (server, mut stdin, mut out) = Server::spawn();
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 1, "method": "initialize",
            "params": {"protocolVersion": "2025-06-18", "capabilities": {},
                       "clientInfo": {"name": "pr", "version": "0"}}
        }),
    );
    let _ = read_response(&mut out, 1, Duration::from_secs(10));
    send(
        &mut stdin,
        &serde_json::json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
    );

    // --- prompts/list ---
    send(
        &mut stdin,
        &serde_json::json!({"jsonrpc": "2.0", "id": 2, "method": "prompts/list"}),
    );
    let msg = read_response(&mut out, 2, Duration::from_secs(10));
    let prompts = msg["result"]["prompts"].as_array().expect("prompts");
    assert_eq!(prompts.len(), 2, "{msg}");
    assert!(prompts.iter().any(|p| p["name"] == "setup-connection"));
    assert!(prompts.iter().any(|p| p["name"] == "analyze-table"));
    let analyze = prompts
        .iter()
        .find(|p| p["name"] == "analyze-table")
        .unwrap();
    let args = analyze["arguments"].as_array().expect("args");
    assert!(
        args.iter()
            .any(|a| a["name"] == "connection" && a["required"] == true)
    );
    assert!(
        args.iter()
            .any(|a| a["name"] == "table" && a["required"] == true)
    );

    // --- prompts/get: setup-connection with an optional name ---
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 3, "method": "prompts/get",
            "params": {"name": "setup-connection", "arguments": {"suggestedName": "warehouse"}}
        }),
    );
    let msg = read_response(&mut out, 3, Duration::from_secs(10));
    let text = msg["result"]["messages"][0]["content"]["text"]
        .as_str()
        .unwrap();
    assert!(text.contains("called \"warehouse\""), "{text}");
    assert!(text.contains("add_sqlite_connection"), "{text}");
    assert_eq!(msg["result"]["messages"][0]["role"], "user");

    // --- prompts/get: analyze-table without database ---
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 4, "method": "prompts/get",
            "params": {"name": "analyze-table",
                       "arguments": {"connection": "demo", "table": "users"}}
        }),
    );
    let msg = read_response(&mut out, 4, Duration::from_secs(10));
    let text = msg["result"]["messages"][0]["content"]["text"]
        .as_str()
        .unwrap();
    assert!(text.contains("`users`"), "{text}");
    assert!(text.contains("\"demo\""), "{text}");
    assert!(!text.contains("in database"), "{text}");
    assert!(text.contains("SELECT COUNT(*)"), "{text}");

    // --- prompts/get: missing required argument is a typed error ---
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 5, "method": "prompts/get",
            "params": {"name": "analyze-table", "arguments": {"connection": "demo"}}
        }),
    );
    let msg = read_response(&mut out, 5, Duration::from_secs(10));
    assert!(
        msg["error"]["message"].as_str().unwrap().contains("table"),
        "{msg}"
    );

    // --- resources/list ---
    send(
        &mut stdin,
        &serde_json::json!({"jsonrpc": "2.0", "id": 6, "method": "resources/list"}),
    );
    let msg = read_response(&mut out, 6, Duration::from_secs(10));
    let resources = msg["result"]["resources"].as_array().expect("resources");
    assert_eq!(resources.len(), 1, "{msg}");
    assert_eq!(resources[0]["uri"], "sequel-mcp://connections");
    assert_eq!(resources[0]["mimeType"], "application/json");

    // --- resources/read: no-secrets connection JSON ---
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 7, "method": "resources/read",
            "params": {"uri": "sequel-mcp://connections"}
        }),
    );
    let msg = read_response(&mut out, 7, Duration::from_secs(10));
    let contents = msg["result"]["contents"].as_array().expect("contents");
    assert_eq!(contents[0]["uri"], "sequel-mcp://connections");
    assert_eq!(contents[0]["mimeType"], "application/json");
    let text = contents[0]["text"].as_str().unwrap();
    let parsed: serde_json::Value = serde_json::from_str(text).unwrap();
    let conns = parsed["connections"].as_array().unwrap();
    assert_eq!(conns.len(), 1, "demo connection listed");
    assert_eq!(conns[0]["name"], "demo");
    assert_eq!(conns[0]["driver"], "sqlite");
    assert_eq!(conns[0]["hasPassword"], false);
    assert!(conns[0]["presets"].as_array().unwrap().len() >= 3);
    // No secret material in the payload.
    assert!(!text.contains("\"password\": \""));

    // --- resources/read: unknown URI is a typed error ---
    send(
        &mut stdin,
        &serde_json::json!({
            "jsonrpc": "2.0", "id": 8, "method": "resources/read",
            "params": {"uri": "sequel-mcp://nope"}
        }),
    );
    let msg = read_response(&mut out, 8, Duration::from_secs(10));
    assert!(
        msg["error"]["message"]
            .as_str()
            .unwrap()
            .contains("unknown resource"),
        "{msg}"
    );

    drop(stdin);
    let mut server = server;
    let started = Instant::now();
    loop {
        match server.child.try_wait().unwrap() {
            Some(_) => break,
            None => {
                assert!(started.elapsed() < Duration::from_secs(10));
                std::thread::sleep(Duration::from_millis(25));
            }
        }
    }
}