hyperdb-mcp 0.4.0

MCP server for Hyper database — instant SQL analytics for LLM workflows
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
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
// Copyright (c) 2026, Salesforce, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! MCP server implementation and tool parameter types.
//!
//! The [`HyperMcpServer`] is the top-level struct registered with the `rmcp`
//! framework. It lazily initializes the [`Engine`] on first tool call and
//! routes each MCP tool invocation to the appropriate ingest / query / export
//! function.
//!
//! Parameter structs derive `JsonSchema` so the MCP `tools/list` response
//! includes full JSON Schema descriptions for each tool's inputs.

use crate::attach::{self, AttachRegistry, AttachRequest, AttachSource, LOCAL_ALIAS};
use crate::chart::{render_chart, ChartFormat, ChartOptions, ChartType};
use crate::engine::{classify_statement, is_read_only_sql, Engine, StatementKind};
use crate::error::{ErrorCode, McpError};
use crate::export::{export_to_file, ExportOptions};
use crate::ingest::{
    detect_file_format, ingest_csv, ingest_csv_file, ingest_csv_file_async, ingest_json,
    ingest_json_file, ingest_json_file_async, InferredFileFormat, IngestOptions,
};
use crate::ingest_arrow::{
    ingest_arrow_ipc_file, ingest_arrow_ipc_file_async, ingest_parquet_file,
    ingest_parquet_file_async,
};
use crate::saved_queries::{build_store, SavedQuery, SavedQueryStore};
use crate::subscriptions::{
    uris_for_table_change, uris_for_workspace_change, SubscriptionRegistry,
};
use base64::Engine as _;
use rmcp::handler::server::router::prompt::PromptRouter;
use rmcp::handler::server::router::tool::ToolRouter;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::{
    AnnotateAble, CallToolResult, Content, GetPromptRequestParams, GetPromptResult, Implementation,
    InitializeRequestParams, InitializeResult, ListPromptsResult, ListResourceTemplatesResult,
    ListResourcesResult, PaginatedRequestParams, PromptMessage, PromptMessageRole, RawResource,
    RawResourceTemplate, ReadResourceRequestParams, ReadResourceResult, ResourceContents,
    ServerCapabilities, ServerInfo, SubscribeRequestParams, UnsubscribeRequestParams,
};
use rmcp::service::RequestContext;
use rmcp::{
    prompt, prompt_handler, prompt_router, tool, tool_handler, tool_router, RoleServer,
    ServerHandler,
};
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::{json, Value};
use sqlformat::{FormatOptions, Indent, QueryParams as SqlQueryParams};
use std::fmt::Write as _;
use std::sync::{Arc, Mutex};

#[expect(
    unused_imports,
    reason = "imported for use in doc comments that reference the type path"
)]
use rmcp::model::RawTextContent;

/// Number of rows returned by the `hyper://tables/{name}/sample` JSON
/// resource. Kept small so an MCP client can prefetch every table's sample
/// into the LLM context without blowing up the prompt budget.
const TABLE_SAMPLE_ROWS: u64 = 5;

/// Number of rows returned by the `hyper://tables/{name}/csv-sample` CSV
/// resource. Slightly larger than the JSON sample because CSV is a much
/// more compact wire format and the extra rows help LLMs see patterns.
const TABLE_CSV_SAMPLE_ROWS: u64 = 20;

// --- Parameter structs ---
// Field-level doc comments become JSON Schema `description` fields in the
// MCP `tools/list` response, so they are written for the LLM caller.

/// Schema override shape shared by `query_data`, `query_file`, `load_data`,
/// and `load_file`. Documented here once so all four tools can reference it
/// without duplicating the prose in every field doc.
///
/// Pass a JSON object mapping **column name → Hyper type string**, for example:
///
/// ```json
/// { "year": "INT", "population": "BIGINT", "entity": "TEXT" }
/// ```
///
/// Override semantics (applied inside ingest):
/// * Keys are matched to columns **by name** (case-sensitive). Column ordering
///   in the JSON object does not need to match the file; the inferred order
///   from the file is preserved.
/// * Columns *not* listed in the override keep their inferred type — you only
///   need to specify the columns you want to correct.
/// * Types are the Hyper SQL type spellings: `INT`, `BIGINT`, `NUMERIC(38,0)`,
///   `DOUBLE PRECISION`, `TEXT`, `BOOL`, `DATE`, `TIMESTAMP`.
/// * If you get a `SchemaMismatch` with suggestion to widen an integer column,
///   the typical fix is `{ "col": "BIGINT" }` or `{ "col": "NUMERIC(38,0)" }`.
///
/// Before ingesting an unfamiliar file, prefer calling `inspect_file` first —
/// it returns the inferred schema plus per-column min / max / `null_count` so
/// you can build a minimal, correct override in one shot.
///
/// Parameters for the `query_data` one-shot tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct QueryDataParams {
    /// JSON array of objects or CSV text.
    pub data: String,
    /// SQL query to run against the data. Reference the table by
    /// `table_name` (default `data`).
    pub sql: String,
    /// Data format: `"json"` or `"csv"`. Auto-detected from the first byte
    /// when omitted (`[`/`{` → JSON, otherwise CSV).
    pub format: Option<String>,
    /// Table name exposed to the SQL query (default: `data`).
    pub table_name: Option<String>,
    /// Partial schema override keyed by column name: `{"col": "BIGINT", ...}`.
    /// Only the listed columns are overridden; the rest keep their inferred
    /// type. See the struct-level docs on `QueryDataParams` and the
    /// `inspect_file` tool for type choices and diagnostics.
    pub schema: Option<Value>,
}

/// Parameters for the `query_file` one-shot tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct QueryFileParams {
    /// Absolute path to a CSV, Parquet, or Arrow IPC file.
    pub path: String,
    /// SQL query to run. Reference the table by `table_name` (default:
    /// filename stem).
    pub sql: String,
    /// Table name exposed to the SQL query (default: filename stem).
    pub table_name: Option<String>,
    /// Partial schema override keyed by column name: `{"col": "BIGINT", ...}`.
    /// See the docs on `QueryDataParams` for the full spec. Call
    /// `inspect_file` first if you are unsure of the correct types.
    pub schema: Option<Value>,
    /// Optional dot-separated path to extract a nested data array from the
    /// JSON file. Numeric segments index into arrays (e.g., `content.0`).
    /// String values encountered during navigation are automatically parsed
    /// as JSON, handling the common pattern where MCP tool responses contain
    /// stringified JSON payloads.
    pub json_extract_path: Option<String>,
}

/// Parameters for the `load_data` workspace tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct LoadDataParams {
    /// Target table name.
    pub table: String,
    /// JSON array of objects or CSV text.
    pub data: String,
    /// Data format: `"json"` or `"csv"`. Auto-detected when omitted.
    pub format: Option<String>,
    /// `"replace"` (default — drops and recreates the table) or
    /// `"append"` (adds rows to an existing table).
    pub mode: Option<String>,
    /// Partial schema override keyed by column name: `{"col": "BIGINT", ...}`.
    /// See the docs on `QueryDataParams` for the full spec.
    pub schema: Option<Value>,
    /// Target database alias. Omit (or pass `"local"`) to write to the
    /// ephemeral primary. Pass `"persistent"` to write to the durable
    /// database that survives across sessions. Other values target a
    /// user-attached database (must be writable).
    pub database: Option<String>,
    /// Shorthand for `database: "persistent"`. When true, data is written
    /// to the persistent database. If both `database` and `persist` are
    /// set, `database` wins.
    pub persist: Option<bool>,
}

/// Parameters for the `load_file` workspace tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct LoadFileParams {
    /// Target table name.
    pub table: String,
    /// Absolute path to a CSV, Parquet, or Arrow IPC file.
    pub path: String,
    /// `"replace"` (default — drops and recreates the table),
    /// `"append"` (adds rows to an existing table), or `"merge"`
    /// (upserts rows by `merge_key`; new columns in the incoming file
    /// are auto-added via `ALTER TABLE ADD COLUMN`).
    pub mode: Option<String>,
    /// Partial schema override keyed by column name: `{"col": "BIGINT", ...}`.
    /// Only the listed columns are overridden; the rest keep their inferred
    /// type. Call `inspect_file` first if you are unsure — it reports
    /// min / max / `null_count` per column using the exact same inference this
    /// tool uses, so the override you build from its output is guaranteed to
    /// align with the file's actual columns.
    pub schema: Option<Value>,
    /// Optional dot-separated path to extract a nested data array from the
    /// JSON file. Numeric segments index into arrays (e.g., `content.0`).
    /// String values encountered during navigation are automatically parsed
    /// as JSON, handling the common pattern where MCP tool responses contain
    /// stringified JSON payloads.
    pub json_extract_path: Option<String>,
    /// When `mode = "merge"`, the column(s) used to match incoming rows to
    /// existing rows for upsert. Pass a single name (`"job_id"`) or a list
    /// (`["cell", "job_id"]`). Required for merge; rejected with a clear
    /// error if set for `replace` or `append`.
    pub merge_key: Option<MergeKey>,
    /// Target database alias. Omit (or pass `"local"`) to write to the
    /// ephemeral primary. Pass `"persistent"` to write to the durable
    /// database. Other values target a user-attached writable database.
    pub database: Option<String>,
    /// Shorthand for `database: "persistent"`. If both `database` and
    /// `persist` are set, `database` wins.
    pub persist: Option<bool>,
}

/// One or many column names. Accepts either a JSON string `"col"` or
/// a JSON array `["col1", "col2"]` for ergonomics — the tool layer
/// normalizes to `Vec<String>` before passing into the ingest code.
///
/// A custom [`serde::Deserialize`] implementation produces clear
/// errors for wrong shapes (`null`, numbers, objects) instead of
/// the default untagged-enum message ("data did not match any
/// variant of untagged enum MergeKey"), which is opaque from the
/// MCP-tool-call side.
#[derive(Debug, JsonSchema)]
#[schemars(
    title = "MergeKey",
    description = "Either a single column name (string) or a list of column names (array of strings)",
    untagged
)]
pub enum MergeKey {
    Single(String),
    Multi(Vec<String>),
}

impl<'de> Deserialize<'de> for MergeKey {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::Error;
        let v = serde_json::Value::deserialize(deserializer)?;
        match v {
            serde_json::Value::String(s) => Ok(Self::Single(s)),
            serde_json::Value::Array(arr) => {
                let mut names = Vec::with_capacity(arr.len());
                for (i, item) in arr.into_iter().enumerate() {
                    match item {
                        serde_json::Value::String(s) => names.push(s),
                        other => {
                            return Err(D::Error::custom(format!(
                                "merge_key array element [{i}] must be a string \
                                 (column name); got {other}"
                            )));
                        }
                    }
                }
                Ok(Self::Multi(names))
            }
            other => Err(D::Error::custom(format!(
                "merge_key must be a column name (string) or list of column names \
                 (array of strings); got {other}"
            ))),
        }
    }
}

impl MergeKey {
    /// Materialize as a non-empty `Vec<String>`, or return `None` for the
    /// empty case so callers can convert it into an `InvalidArgument`
    /// error with a context-appropriate message.
    pub fn into_vec(self) -> Option<Vec<String>> {
        let v = match self {
            Self::Single(s) => vec![s],
            Self::Multi(v) => v,
        };
        if v.is_empty() || v.iter().any(String::is_empty) {
            None
        } else {
            Some(v)
        }
    }
}

/// One file entry within a [`LoadFilesParams`] batch. Same shape as
/// [`LoadFileParams`] minus cross-cutting concerns handled at the batch
/// level (the batch-level concurrency knob, etc.).
#[derive(Debug, Deserialize, JsonSchema)]
pub struct LoadFilesEntry {
    /// Target table name.
    pub table: String,
    /// Absolute path to a CSV, Parquet, Arrow IPC, or JSON file.
    pub path: String,
    /// `"replace"` (default), `"append"`, or `"merge"` — see
    /// [`LoadFileParams::mode`] for semantics.
    pub mode: Option<String>,
    /// Partial schema override keyed by column name.
    pub schema: Option<Value>,
    /// Optional JSON extract path — see `LoadFileParams::json_extract_path`.
    pub json_extract_path: Option<String>,
    /// When `mode = "merge"`, the column(s) to match on for upsert. See
    /// [`LoadFileParams::merge_key`].
    pub merge_key: Option<MergeKey>,
}

/// Parameters for the `load_files` workspace tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct LoadFilesParams {
    /// Batch of files to ingest in parallel. Each entry targets its own
    /// table and runs independently — one entry's failure does not abort
    /// the others.
    pub files: Vec<LoadFilesEntry>,
    /// Maximum number of concurrent ingest tasks. Each task checks out
    /// its own connection from a pool sized to match. Default:
    /// `min(files.len(), 8)`. Large parquet ingests are I/O-bound on
    /// hyperd's side; more connections don't help past a certain point
    /// and can starve the primary connection.
    pub concurrency: Option<u32>,
    /// Target database alias. Omit (or pass `"local"`) to write to the
    /// ephemeral primary. Pass `"persistent"` to write to the durable
    /// database. Other values target a user-attached writable database.
    /// Applies to every entry in the batch — multi-target batches are
    /// not supported.
    pub database: Option<String>,
    /// Shorthand for `database: "persistent"`. If both `database` and
    /// `persist` are set, `database` wins.
    pub persist: Option<bool>,
}

/// Validate the (`mode`, `merge_key`) combination at the tool boundary.
/// Returns the normalized `Vec<String>` for merge mode (or `None` for
/// replace/append). Rejects:
///
/// - `mode = "merge"` without `merge_key` → `InvalidArgument`.
/// - `mode = "merge"` with empty / blank-element `merge_key` →
///   `InvalidArgument`.
/// - `mode != "merge"` with `merge_key` set → `InvalidArgument`
///   (catches "I added merge_key but forgot mode" mistakes loudly).
fn validate_merge_args(
    mode: &str,
    merge_key: Option<MergeKey>,
) -> Result<Option<Vec<String>>, McpError> {
    match (mode, merge_key) {
        ("merge", None) => Err(McpError::new(
            ErrorCode::InvalidArgument,
            "mode=merge requires merge_key (a column name or list of column names)",
        )),
        ("merge", Some(mk)) => mk.into_vec().map(Some).ok_or_else(|| {
            McpError::new(
                ErrorCode::InvalidArgument,
                "merge_key must be a non-empty list of non-empty column names",
            )
        }),
        (_, Some(_)) => Err(McpError::new(
            ErrorCode::InvalidArgument,
            "merge_key is only valid with mode=merge",
        )),
        (_, None) => Ok(None),
    }
}

/// Parameters for the `load_iceberg` workspace tool.
///
/// An Iceberg table on disk is a *directory* containing a `metadata/`
/// subdir and one or more `data/` parquet files — hyperd reads the
/// metadata JSON to find the right snapshot and then the data files.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct LoadIcebergParams {
    /// Target Hyper table name.
    pub table: String,
    /// Absolute path to the Iceberg table root (the directory that
    /// contains `metadata/` and `data/`).
    pub path: String,
    /// `"replace"` (default) or `"append"`.
    pub mode: Option<String>,
    /// Optional specific metadata filename to pin a snapshot, e.g.
    /// `"v2.metadata.json"`. If omitted, hyperd uses the latest.
    pub metadata_filename: Option<String>,
    /// Optional snapshot version to read as of.
    pub version_as_of: Option<i64>,
}

/// Parameters for the read-only `query` workspace tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct QueryParams {
    /// SQL SELECT / WITH / EXPLAIN / SHOW / VALUES statement (read-only)
    pub sql: String,
    /// Target database alias for unqualified name resolution. Omit to
    /// query the ephemeral primary. Pass `"persistent"` to route to the
    /// durable database, or any user-attached alias.
    pub database: Option<String>,
}

/// Parameters for the mutating `execute` workspace tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ExecuteParams {
    /// One or more DDL/DML SQL statements (CREATE, INSERT, UPDATE, DELETE,
    /// DROP, ALTER, COPY, etc.) to execute as an atomic batch.
    ///
    /// Pass a single-element array `["UPDATE …"]` for one statement, or
    /// multiple elements for an atomic upsert / multi-table mutation.
    /// Multi-element batches run inside a transaction — every statement
    /// commits together or all roll back. Each element must be exactly
    /// one statement (no embedded `;`-separated multi-statements).
    ///
    /// Restrictions enforced before any SQL hits the server:
    /// - The array must be non-empty and no element may be empty/whitespace.
    /// - No element may be read-only (use `query` for SELECT/WITH/EXPLAIN).
    /// - DDL and DML cannot be mixed in one batch (Hyper aborts the
    ///   transaction with SQLSTATE 0A000).
    /// - Multi-element all-DDL batches are rejected because Hyper
    ///   auto-commits CREATE/DROP/ALTER even inside a transaction —
    ///   issue each DDL in its own `execute` call.
    pub sql: Vec<String>,
    /// Target database alias for unqualified name resolution. Omit to
    /// run against the ephemeral primary. Pass `"persistent"` to write
    /// to the durable database (or a writable user-attached alias).
    pub database: Option<String>,
}

/// Parameters for the `sample` convenience tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct SampleParams {
    /// Table name to sample from
    pub table: String,
    /// Number of rows to return (default: 5, max: 100)
    pub n: Option<u64>,
    /// Target database alias. Omit to sample from the ephemeral primary;
    /// pass `"persistent"` or a user-attached alias to sample from there.
    pub database: Option<String>,
}

/// Parameters for the `describe` tool. Both fields are optional to preserve
/// backward compatibility with callers that invoke `describe` with no args
/// to get the full workspace listing.
#[derive(Debug, Default, Deserialize, JsonSchema)]
pub struct DescribeParams {
    /// If set, return the schema and row count for just this table. Omit to
    /// list every public table in the workspace.
    pub table: Option<String>,
    /// Target database alias. Omit to describe tables in the ephemeral
    /// primary; pass `"persistent"` or a user-attached alias to describe
    /// tables in another database.
    pub database: Option<String>,
}

/// Parameters for the `chart` tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ChartParams {
    /// SQL query returning the data to plot (read-only SELECT/WITH/EXPLAIN/SHOW/VALUES)
    pub sql: String,
    /// Chart type: bar, line, scatter, or histogram
    pub chart_type: String,
    /// X-axis column name (required for bar/line/scatter; histogram uses this as the value column)
    pub x: Option<String>,
    /// Y-axis column name (required for bar/line/scatter)
    pub y: Option<String>,
    /// Optional series/grouping column for colored/grouped multi-series charts
    pub series: Option<String>,
    /// Chart title
    pub title: Option<String>,
    /// Output format: "png" (default) or "svg"
    pub format: Option<String>,
    /// Width in pixels (default 800)
    pub width: Option<u32>,
    /// Height in pixels (default 480)
    pub height: Option<u32>,
    /// Number of bins for histograms (default 20)
    pub bins: Option<u32>,
    /// Treat the x column as categorical rather than numeric. Auto-detected
    /// from the first row's x value for line/scatter charts: DATE, TIMESTAMP,
    /// TEXT, and other non-numeric types flip to categorical automatically.
    /// Set explicitly to override auto-detection. Bar charts are always
    /// categorical regardless of this flag.
    pub x_as_category: Option<bool>,
    /// Fix the x-axis range as [min, max]. Omit to auto-scale. Useful when
    /// comparing multiple charts at a consistent scale (e.g. [0, 1500] for
    /// population in millions) or when an outlier would distort auto-scaling.
    /// Ignored for bar charts (which use categorical x positions).
    pub x_range: Option<[f64; 2]>,
    /// Fix the y-axis range as [min, max]. Omit to auto-scale.
    /// Example: [0.0, 1.0] to pin a 0–1 index axis regardless of the data.
    pub y_range: Option<[f64; 2]>,
    /// Map series names to hex colors ("#rrggbb"). Series not listed here
    /// fall back to the default color palette. Example:
    /// {"India": "#e41a1c", "China": "#ff7f0e"}. Only meaningful when a
    /// `series` column is set.
    pub color_map: Option<std::collections::HashMap<String, String>>,
    /// When true, draw the series name as a text label next to each dot
    /// (scatter) or point (line) and suppress the legend box. Best when
    /// each series has exactly one point (e.g. one country per dot).
    /// Defaults to false (legend shown).
    pub label_points: Option<bool>,
    /// Where to write the rendered image. Parent directory is created
    /// automatically. If omitted, a file is auto-generated under the
    /// system temp dir (`<temp>/hyperdb-charts/chart-<ts>-<pid>-<n>.<ext>`).
    /// Combine with `inline=true` to receive the bytes inline AND write
    /// a file; otherwise the file is the sole output.
    pub output_path: Option<String>,
    /// When true, include the PNG/SVG bytes inline in the tool result.
    /// Without `output_path` this also skips the disk write entirely
    /// (pure inline). With `output_path` the file is written *and* the
    /// image is returned inline. Defaults to false — i.e. disk write
    /// only, with a short stats blob that carries the path.
    pub inline: Option<bool>,
    /// When false, refuse to overwrite an existing file at `output_path`
    /// and return `PERMISSION_DENIED` without touching it. Defaults to
    /// true (overwrite silently), matching the `export` tool.
    pub overwrite: Option<bool>,
    /// Target database alias for unqualified name resolution in the
    /// chart's SQL. Omit to query the ephemeral primary. Pass
    /// `"persistent"` or a user-attached alias to chart from there.
    pub database: Option<String>,
}

/// Parameters for the `watch_directory` tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct WatchDirectoryParams {
    /// Absolute path to the directory to watch
    pub path: String,
    /// Target table name — all files in the directory are appended to this table
    pub table: String,
    /// Maximum number of files ingested in parallel. Defaults to 4; capped at 32.
    /// Each in-flight ingest holds one connection to hyperd plus a transaction.
    #[serde(default)]
    pub max_concurrent: Option<u32>,
    /// Target database alias. Omit (or pass `"local"`) for the ephemeral
    /// primary. Pass `"persistent"` for the durable database, or any
    /// user-attached writable alias. The watcher's connection pool is
    /// built against the resolved target, so subsequent ingests land
    /// in the right database without per-file routing.
    ///
    /// Detaching the alias while a watcher is active is rejected — call
    /// `unwatch_directory` first.
    pub database: Option<String>,
    /// Shorthand for `database: "persistent"`. If both `database` and
    /// `persist` are set, `database` wins.
    pub persist: Option<bool>,
}

/// Parameters for the `unwatch_directory` tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct UnwatchDirectoryParams {
    /// Path of a currently watched directory
    pub path: String,
}

/// Parameters for the `inspect_file` tool.
///
/// Dry-run a file against the same schema inference + numeric-widening pipeline
/// that `load_file` uses, returning the inferred schema plus per-column
/// diagnostics. Call this *before* `load_file` whenever you are unsure about
/// types — especially for wide CSVs with large numbers, mixed integer/float
/// columns, or values that only appear near the end of the file. Use the
/// returned `type` + `min` / `max` to construct an explicit `schema` override
/// for the subsequent `load_file` / `load_data` call.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct InspectFileParams {
    /// Absolute path to the CSV, Parquet, or Arrow IPC file to inspect.
    /// Nothing is written to Hyper and no engine is started.
    pub path: String,
    /// Maximum number of sample rows / values per column to return (default
    /// 5, max 50). Useful for checking that an override would produce the
    /// expected types before ingesting a large file.
    pub sample_rows: Option<u32>,
    /// Optional dot-separated path to extract a nested data array from a
    /// JSON file before inspecting. See `LoadFileParams::json_extract_path`
    /// for the full path syntax and stringified-JSON handling.
    pub json_extract_path: Option<String>,
}

/// Parameters for the `export` tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ExportParams {
    /// SQL query to export (if omitted, exports whole table)
    pub sql: Option<String>,
    /// Table name (used if sql omitted)
    pub table: Option<String>,
    /// Output file path
    pub path: String,
    /// Format: csv, parquet, `arrow_ipc`, iceberg, or hyper. For `iceberg`
    /// the `path` is a *directory* that hyperd will create (the table
    /// root with a `metadata/` and `data/` subdir); for all other
    /// formats it is a single file.
    pub format: String,
    /// If false, refuse to overwrite an existing file at `path` and return
    /// a `PERMISSION_DENIED` error instead. Defaults to true (overwrite
    /// silently) to match pre-flag behavior.
    pub overwrite: Option<bool>,
    /// Optional per-format options passed through into hyperd's `COPY
    /// (query) TO '…' WITH (…)` clause. Keys must match hyperd's own
    /// option names exactly; values must be strings, numbers, or
    /// booleans (null / nested object / array are rejected). Common
    /// knobs:
    ///
    /// * **parquet** — `codec` (`"snappy"` default, `"zstd"`, `"gzip"`,
    ///   `"uncompressed"`, ...), `rows_per_row_group` (int).
    /// * **iceberg** — everything Parquet accepts, plus `table_scheme`
    ///   (`"metastore"` default, `"filesystem"`), `max_file_size`
    ///   (bytes; split data across multiple parquet files).
    /// * **csv** — `header` (bool, default true), `delimiter` (1-char
    ///   string, default `","`), `null` (string printed for NULL,
    ///   default `""`), `quote` (1-char string).
    /// * **`arrow_ipc`** — none commonly needed.
    ///
    /// Ignored for `format = "hyper"` (which isn't a `COPY`).
    pub format_options: Option<Value>,
    /// Source database alias. Omit to read from the ephemeral primary.
    /// Pass `"persistent"` or a user-attached alias to export from there.
    /// In `table` mode, the table name is fully qualified against this
    /// database. In `sql` mode, unqualified names in the SQL resolve
    /// against this database for the duration of the call.
    pub database: Option<String>,
}

/// Parameters for the `save_query` tool.
///
/// Persists a named read-only SQL query. After saving, the query is
/// available as two MCP resources:
///
/// * `hyper://queries/{name}/definition` — JSON metadata (sql, description,
///   `created_at`).
/// * `hyper://queries/{name}/result` — re-runs the SQL on every read and
///   returns the rows + query stats.
///
/// In ephemeral workspaces (no `--workspace`) saved queries live only for
/// the life of the server process; in persistent workspaces they are
/// stored in the `_hyperdb_saved_queries` meta-table and survive restarts.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct SaveQueryParams {
    /// Unique name identifying the query. Becomes the path component of
    /// the resource URIs — pick something URL-safe and human-readable.
    pub name: String,
    /// The SQL to store. Must be a read-only statement (`SELECT` / `WITH`
    /// / `EXPLAIN` / `SHOW` / `VALUES`); destructive statements are
    /// rejected at save time.
    pub sql: String,
    /// Optional free-form description — what does this query answer?
    pub description: Option<String>,
}

/// Parameters for the `delete_query` tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct DeleteQueryParams {
    /// Name of the saved query to remove. No-op when the name doesn't
    /// exist; the tool returns `{"deleted": false}` in that case.
    pub name: String,
}

/// One database to attach for the duration of a single `copy_query`
/// call. Same kind-tagged shape as `AttachDatabaseParams` so the
/// vocabulary stays consistent once remote kinds (`tcp` / `grpc`)
/// arrive.
#[derive(Debug, Deserialize, JsonSchema, Clone)]
pub struct AttachSpec {
    /// Alias used to qualify tables from this attachment (e.g. `src`
    /// lets you reference `src.public.customers`). Must be a SQL
    /// identifier and cannot be `local`.
    pub alias: String,
    /// Attachment kind. Only `"local_file"` is supported today; `"tcp"`
    /// (standard remote hyperd) and `"grpc"` (Data 360 read-only Hyper)
    /// are planned.
    pub kind: String,
    /// Absolute path to a `.hyper` file. Required when `kind ==
    /// "local_file"`; ignored otherwise.
    pub path: Option<String>,
    /// If `true`, allow writes into this attachment. Defaults to
    /// `false`. Must also satisfy the server's `--read-only` flag (it
    /// always wins).
    pub writable: Option<bool>,
    /// What to do when `kind == "local_file"` and `path` does not yet
    /// exist. `"error"` (default) returns `FILE_NOT_FOUND`; `"create"`
    /// issues `CREATE DATABASE IF NOT EXISTS` first and then attaches
    /// the resulting empty file. `"create"` requires `writable: true`
    /// and is rejected when the server is `--read-only`.
    pub on_missing: Option<String>,
}

/// Parameters for the `attach_database` tool. Mirrors [`AttachSpec`]
/// except that these attachments live for the rest of the MCP session
/// (or until `detach_database` is called).
#[derive(Debug, Deserialize, JsonSchema)]
pub struct AttachDatabaseParams {
    /// Alias to register the attachment under. Must be a SQL identifier
    /// (`[A-Za-z_][A-Za-z0-9_]{0,62}`) and cannot be `local` (reserved
    /// for the primary workspace).
    pub alias: String,
    /// Attachment kind. Only `"local_file"` is supported today.
    pub kind: String,
    /// Absolute path to a `.hyper` file. Required when `kind ==
    /// "local_file"`. The file must be idle — another MCP server or
    /// `hyperd` instance holding it will cause a `RESOURCE_BUSY` error.
    pub path: Option<String>,
    /// If `true`, `copy_query` (and raw `execute`) may target this
    /// attachment. Defaults to `false` so sources stay safe from
    /// accidental mutation.
    pub writable: Option<bool>,
    /// What to do when `kind == "local_file"` and `path` does not yet
    /// exist:
    ///
    /// * `"error"` (default) — return `FILE_NOT_FOUND`. Matches the
    ///   pre-existing contract.
    /// * `"create"` — issue `CREATE DATABASE IF NOT EXISTS` against the
    ///   path first, then attach the resulting empty file. Requires
    ///   `writable: true` (otherwise the empty DB would be unusable)
    ///   and is rejected when the server is running with `--read-only`.
    ///   The parent directory must already exist.
    pub on_missing: Option<String>,
}

/// Parameters for the `detach_database` tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct DetachDatabaseParams {
    /// Alias of a previously attached database.
    pub alias: String,
}

/// Parameters for the `copy_query` tool. Runs a read-only SELECT / WITH
/// / VALUES statement and lands the result into a target table.
///
/// The inner `sql` may reference tables in the primary workspace
/// (unqualified) as well as tables in any attachment by its fully
/// qualified form — e.g. `src.public.customers`. The destination is
/// resolved via `target_database` (main workspace by default).
#[derive(Debug, Deserialize, JsonSchema)]
pub struct CopyQueryParams {
    /// Read-only SQL statement whose result rows will be inserted into
    /// `target_table`. Must begin with `SELECT`, `WITH`, or `VALUES`.
    /// `EXPLAIN` / `SHOW` are rejected because their output shape isn't
    /// row-compatible with a target table.
    pub sql: String,
    /// Unqualified destination table name. Always lands in the
    /// `public` schema of the database identified by `target_database`.
    pub target_table: String,
    /// How to reconcile with any existing target table:
    ///
    /// * `"create"` — error if the target already exists; create from
    ///   the query's result schema via `CREATE TABLE AS`.
    /// * `"append"` — error if the target does not exist; rows are
    ///   appended via `INSERT INTO ... SELECT`.
    /// * `"replace"` — drop (if any) and recreate, atomically.
    pub mode: String,
    /// Alias of the destination database. `None` and `"local"` both
    /// mean the server's primary workspace. Any other value must refer
    /// to an attachment registered with `writable: true`.
    pub target_database: Option<String>,
    /// Optional list of databases to attach for the duration of this
    /// call only. Detached automatically even if the query fails.
    /// Aliases used here must not already be in use.
    pub temp_attach: Option<Vec<AttachSpec>>,
}

/// Parameters for the `set_table_metadata` tool.
///
/// Writes prose fields to the `_table_catalog` row for `table`. Unset
/// fields are left unchanged; passing an explicit empty string (`""`)
/// clears a field. Mechanical fields (`loaded_at`, `last_refreshed_at`,
/// `row_count`, `load_tool`, `load_params`) are managed by the server
/// and cannot be set through this tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct SetTableMetadataParams {
    /// Target table name. Must already exist in the workspace and have a
    /// catalog entry — load the table first (or run `execute CREATE
    /// TABLE`) so the server auto-stubs the row.
    pub table: String,
    /// Where the data came from (URL, S3 path, internal system name).
    pub source_url: Option<String>,
    /// Short description of the dataset (what's in the table, how to
    /// interpret it).
    pub source_description: Option<String>,
    /// Why this data is in the workspace — what questions it's intended
    /// to answer.
    pub purpose: Option<String>,
    /// License or attribution requirements for the source data.
    pub license: Option<String>,
    /// Free-form notes: refresh instructions, known gotchas, caveats.
    pub notes: Option<String>,
    /// Target database alias for the catalog write. Omit (or pass
    /// `"local"` / `"persistent"`) to update the persistent catalog —
    /// matches the default for the ephemeral primary's tables.
    /// Pass any user-attached writable alias to update that DB's
    /// per-database `_table_catalog` instead. Read-only attachments
    /// are rejected with a clear "re-attach with writable:true"
    /// message.
    pub database: Option<String>,
}

// --- Prompt argument structs ---

/// Arguments for the `analyze-table` prompt.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct AnalyzeTableArgs {
    /// Name of the table to analyze
    pub table: String,
}

/// Arguments for the `compare-tables` prompt.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct CompareTablesArgs {
    /// First table to compare
    pub table_a: String,
    /// Second table to compare
    pub table_b: String,
}

/// Arguments for the `data-quality` prompt.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct DataQualityArgs {
    /// Name of the table to assess
    pub table: String,
}

/// Arguments for the `suggest-queries` prompt.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct SuggestQueriesArgs {
    /// Name of the table to suggest queries for
    pub table: String,
    /// Optional goal or focus area (e.g. "find top customers", "detect anomalies")
    pub goal: Option<String>,
}

// --- Server ---

/// The MCP server that registers all Hyper tools and routes invocations.
///
/// The `Engine` is lazily initialized behind a `Mutex<Option<Engine>>` so that
/// the expensive `HyperProcess` startup only happens on the first actual tool
/// call, not during MCP handshake. This keeps `initialize` fast and avoids
/// starting `hyperd` if the client never calls a tool.
pub struct HyperMcpServer {
    engine: Arc<Mutex<Option<Engine>>>,
    /// `true` once [`Self::ensure_catalog_ready`] has successfully run on
    /// the current engine, so we only try to create / reconcile
    /// `_table_catalog` once per process. Reset to `false` if the
    /// underlying engine is torn down (e.g. connection lost) so the next
    /// call re-bootstraps.
    catalog_ready: Arc<Mutex<bool>>,
    watchers: Arc<crate::watcher::WatcherRegistry>,
    saved_queries: Arc<dyn SavedQueryStore>,
    subscriptions: Arc<SubscriptionRegistry>,
    /// Registry of `ATTACH DATABASE`s requested via `attach_database`.
    /// Lives at the server level (not the engine level) so the list
    /// survives `ConnectionLost` reconnects: [`Self::with_engine`]
    /// calls [`AttachRegistry::replay_all`] after building a fresh
    /// engine.
    attachments: Arc<AttachRegistry>,
    /// Path to the persistent `.hyper` file, or `None` for `--ephemeral-only`.
    /// Threaded into `Engine::new` so the engine can attach it under the
    /// reserved `"persistent"` alias.
    workspace_path: Option<String>,
    read_only: bool,
    /// Skip the shared daemon and spawn a private `hyperd` (legacy behavior).
    no_daemon: bool,
    /// Last time a heartbeat was sent to the daemon (debounced to avoid per-call TCP overhead).
    last_heartbeat: std::sync::Mutex<std::time::Instant>,
    /// MCP client name from the `initialize` handshake (e.g. "Claude Code",
    /// "cursor-mcp-client"). Populated once per session; used for catalog
    /// provenance tracking (`created_by` / `last_modified_by`).
    client_name: std::sync::Mutex<Option<String>>,
    // Under rmcp 1.x the router fields are constructed for downstream
    // macro-generated dispatch but not read through a direct field access
    // that the compiler can see. Keep them; the `#[tool_router]` /
    // `#[prompt_router]` attribute macros on impl blocks wire the routing.
    #[expect(dead_code, reason = "constructed for rmcp 1.x macro-based dispatch")]
    tool_router: ToolRouter<Self>,
    #[expect(dead_code, reason = "constructed for rmcp 1.x macro-based dispatch")]
    prompt_router: PromptRouter<Self>,
}

impl std::fmt::Debug for HyperMcpServer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HyperMcpServer")
            .field("persistent_path", &self.workspace_path)
            .field("read_only", &self.read_only)
            .field("no_daemon", &self.no_daemon)
            .finish_non_exhaustive()
    }
}

impl HyperMcpServer {
    /// Create a server instance. Pass `Some(path)` for persistent workspace,
    /// `None` for ephemeral (temp directory, auto-cleaned).
    ///
    /// The saved-queries store is chosen to match the workspace mode:
    /// persistent workspaces get a [`crate::saved_queries::WorkspaceStore`]
    /// (backed by a meta-table in the `.hyper` file so queries survive
    /// restarts), ephemeral workspaces get an in-memory
    /// [`crate::saved_queries::SessionStore`].
    ///
    /// When `read_only` is `true`, the `execute`, `load_data`, `load_file`,
    /// `save_query`, `delete_query`, and `set_table_metadata` tools return
    /// a `ReadOnlyViolation` error, and exporting to the `hyper` format
    /// (which is a raw file copy, harmless) remains allowed.
    ///
    /// When `bare` is `true`, the server does not create or maintain the
    /// `_table_catalog` table, and saved queries fall back to the in-memory
    /// [`crate::saved_queries::SessionStore`] regardless of `workspace_path`
    /// `persistent_path` is the resolved path to the persistent database
    /// (`Some`) or `None` for `--ephemeral-only` mode.
    pub fn new(persistent_path: Option<String>, read_only: bool) -> Self {
        Self::with_options(persistent_path, read_only, false)
    }

    /// Create a server instance with explicit daemon control.
    pub fn with_no_daemon(
        persistent_path: Option<String>,
        read_only: bool,
        no_daemon: bool,
    ) -> Self {
        Self::with_options(persistent_path, read_only, no_daemon)
    }

    fn with_options(persistent_path: Option<String>, read_only: bool, no_daemon: bool) -> Self {
        // Saved queries persist when a persistent database is available;
        // session storage takes over for `--ephemeral-only` sessions.
        let saved_queries: Arc<dyn SavedQueryStore> = build_store(persistent_path.as_deref());
        Self {
            engine: Arc::new(Mutex::new(None)),
            catalog_ready: Arc::new(Mutex::new(false)),
            watchers: Arc::new(crate::watcher::WatcherRegistry::new()),
            saved_queries,
            subscriptions: Arc::new(SubscriptionRegistry::new()),
            // The catalog policy is now uniform: seed `_table_catalog`
            // whenever MCP creates a fresh `.hyper` file. The opt-out
            // `--bare` path was removed; users wanting a pristine file
            // can `DROP TABLE _table_catalog` after creation.
            attachments: Arc::new(AttachRegistry::new()),
            workspace_path: persistent_path,
            read_only,
            no_daemon,
            last_heartbeat: std::sync::Mutex::new(std::time::Instant::now()),
            client_name: std::sync::Mutex::new(None),
            tool_router: Self::tool_router(),
            prompt_router: Self::prompt_router(),
        }
    }

    /// Return a clone of the subscription registry so background tasks
    /// (notably the directory watcher) can fire resource updates after
    /// their own ingest completes.
    #[must_use]
    pub fn subscriptions_handle(&self) -> Arc<SubscriptionRegistry> {
        Arc::clone(&self.subscriptions)
    }

    /// Fire resource-updated notifications for every URI affected by a
    /// change to the given table. Targets the workspace/table-list/readme
    /// summary resources plus the three per-table URIs (schema, sample,
    /// csv-sample). Callers that have just added or dropped a table
    /// should also call [`Self::notify_resource_list_changed`] so
    /// subscribers refresh their resource catalog.
    pub(crate) fn notify_table_changed(&self, table: &str) {
        for uri in uris_for_table_change(table) {
            self.subscriptions.notify_updated(&uri);
        }
    }

    /// Fire updates for every URI that summarises the workspace as a
    /// whole (workspace, tables list, readme). Used after watcher-style
    /// bulk mutations where the single-table helper isn't specific
    /// enough.
    pub(crate) fn notify_workspace_changed(&self) {
        for uri in uris_for_workspace_change() {
            self.subscriptions.notify_updated(uri);
        }
    }

    /// Fire a `notifications/resources/list_changed` broadcast. Call
    /// after any operation that adds or removes resources from the
    /// `resources/list` catalog — dropped tables, saved queries
    /// created / deleted, watcher ingest of a brand-new table.
    pub(crate) fn notify_resource_list_changed(&self) {
        self.subscriptions.notify_list_changed();
    }

    /// The MCP client name from the `initialize` handshake, or `None` if
    /// the handshake hasn't completed yet. Used for catalog provenance.
    fn client_name(&self) -> Option<String> {
        self.client_name.lock().ok().and_then(|g| g.clone())
    }

    /// Return a clone of the engine Arc so background tasks (watchers) can
    /// share access to the same lazy-initialized engine instance.
    #[must_use]
    pub fn engine_handle(&self) -> Arc<Mutex<Option<Engine>>> {
        Arc::clone(&self.engine)
    }

    /// Return a clone of the watcher registry handle for tool handlers.
    #[must_use]
    pub fn watchers_handle(&self) -> Arc<crate::watcher::WatcherRegistry> {
        Arc::clone(&self.watchers)
    }

    /// Return a clone of the attachments registry handle for tool
    /// handlers and the `with_engine` replay path.
    #[must_use]
    pub fn attachments_handle(&self) -> Arc<AttachRegistry> {
        Arc::clone(&self.attachments)
    }

    /// Whether the server is running in read-only mode.
    #[must_use]
    pub fn is_read_only(&self) -> bool {
        self.read_only
    }

    /// Return a `ReadOnlyViolation` error if the server is in read-only mode.
    /// Used as an early guard at the top of mutating tool handlers.
    fn check_writable(&self, operation: &str) -> Result<(), McpError> {
        if self.read_only {
            Err(McpError::new(
                ErrorCode::ReadOnlyViolation,
                format!("Operation '{operation}' is not permitted in read-only mode"),
            ))
        } else {
            Ok(())
        }
    }

    /// Resolve the effective database alias from a tool's `database` and
    /// `persist` parameters. Returns `None` when the target is the primary
    /// (ephemeral) — callers should leave SQL unqualified. Returns
    /// `Some(alias)` when targeting a non-primary database.
    ///
    /// When `require_writable` is true, verifies the target alias is
    /// either the primary, `"persistent"` (always writable), or a
    /// user-attached database with `writable: true`.
    fn resolve_db(
        &self,
        engine: &Engine,
        database: Option<&str>,
        persist: Option<bool>,
        require_writable: bool,
    ) -> Result<Option<String>, McpError> {
        let effective = match (database, persist) {
            (Some(db), _) => Some(db),
            (None, Some(true)) => Some(Engine::PERSISTENT_ALIAS),
            _ => None,
        };
        // Filter LOCAL_ALIAS ("local") — treat as primary
        let effective = effective.filter(|s| !s.eq_ignore_ascii_case(crate::attach::LOCAL_ALIAS));

        let resolved = engine.resolve_target_db(effective)?;
        let primary = engine.primary_db_name();

        if resolved == primary {
            return Ok(None);
        }

        if require_writable && resolved != Engine::PERSISTENT_ALIAS {
            match self.attachments.get(&resolved) {
                None => {
                    return Err(McpError::new(
                        ErrorCode::InvalidArgument,
                        format!(
                            "database '{resolved}' is not attached. \
                             Call attach_database first, or use \"persistent\"."
                        ),
                    ));
                }
                Some(entry) if !entry.writable => {
                    return Err(McpError::new(
                        ErrorCode::InvalidArgument,
                        format!(
                            "database '{resolved}' was attached read-only. \
                             Re-attach with writable:true to write to it."
                        ),
                    ));
                }
                _ => {}
            }
        }

        Ok(Some(resolved))
    }

    /// Lazily start the Hyper engine on first use, returning a mutex guard
    /// that holds a reference to the initialized `Engine`.
    ///
    /// When the engine was just created, resets the
    /// [`Self::catalog_ready`] flag so the subsequent `with_engine` call
    /// runs the catalog bootstrap. We can't run the bootstrap here
    /// because it needs to issue SQL back through `Engine`, and we're
    /// still holding the outer lock.
    fn ensure_engine(&self) -> Result<std::sync::MutexGuard<'_, Option<Engine>>, McpError> {
        let mut guard = self
            .engine
            .lock()
            .map_err(|_| McpError::new(ErrorCode::InternalError, "Lock poisoned"))?;
        if guard.is_none() {
            tracing::info!(
                persistent_db = self.workspace_path.as_deref().unwrap_or("<ephemeral-only>"),
                no_daemon = self.no_daemon,
                "initializing hyper engine"
            );
            let engine = if self.no_daemon {
                Engine::new_no_daemon(self.workspace_path.clone())?
            } else {
                Engine::new(self.workspace_path.clone())?
            };
            tracing::info!(
                ephemeral_path = %engine.ephemeral_path().display(),
                persistent_path = ?engine.persistent_path(),
                log_dir = %engine.log_dir().display(),
                "engine ready"
            );
            // Replay any attachments tracked across the previous
            // engine's lifetime *before* handing the engine out to a
            // tool — otherwise the first post-reconnect tool call
            // would see the attachments missing from Hyper's view even
            // though the registry still lists them. Logs replay
            // failures; those entries are dropped from the registry
            // inside `replay_all` so a single stale attachment doesn't
            // block recovery.
            if let Err(e) = self.attachments.replay_all(&engine) {
                tracing::warn!(err = %e.message, "failed to replay attachments on new engine");
            }
            *guard = Some(engine);
            // New engine → catalog may need to be created/reconciled
            // even if we already did it against a prior (now-dead)
            // engine.
            if let Ok(mut ready) = self.catalog_ready.lock() {
                *ready = false;
            }
        }
        Ok(guard)
    }

    /// Idempotently create and reconcile `_table_catalog` on first call
    /// per engine. No-op in bare or read-only mode (read-only can't
    /// mutate; bare callers never wanted the catalog in the first place).
    ///
    /// Catalog failures during bootstrap are logged at WARN but do not
    /// fail the outer tool call — a broken catalog should never block a
    /// legitimate query. The `catalog_ready` flag still flips to `true`
    /// so we don't retry the same failing bootstrap on every call.
    fn ensure_catalog_ready(&self, engine: &Engine) {
        if self.read_only {
            return;
        }
        let Ok(mut ready) = self.catalog_ready.lock() else {
            return;
        };
        if *ready {
            return;
        }
        if let Err(e) = crate::table_catalog::ensure_exists(engine) {
            tracing::warn!(err = %e.message, "failed to ensure _table_catalog exists");
        }
        if let Err(e) = crate::table_catalog::reconcile(engine) {
            tracing::warn!(err = %e.message, "failed to reconcile _table_catalog on startup");
        }
        *ready = true;
    }

    /// Best-effort catalog upsert after a successful ingest. Logs and
    /// swallows errors — a bookkeeping failure should never fail an
    /// otherwise-successful load.
    ///
    /// Routes the upsert to `target_db`'s `_table_catalog`. The
    /// catalog is lazily seeded if absent. `target_db = None` and
    /// `target_db = Some("persistent")` both write to the persistent
    /// catalog (the single-engine ephemeral primary stubs survive
    /// there for the session). User-attached writable aliases get
    /// their own per-DB catalog. Read-only attachments are rejected
    /// upstream by `resolve_db(require_writable=true)` so this helper
    /// never sees them.
    fn after_ingest_catalog_update(
        &self,
        engine: &Engine,
        table_name: &str,
        load_tool: &'static str,
        load_params: Option<&str>,
        row_count: Option<i64>,
        target_db: Option<&str>,
    ) {
        if let Err(e) = crate::table_catalog::upsert_stub_in(
            engine,
            table_name,
            load_tool,
            load_params,
            row_count,
            true,
            target_db,
            self.client_name().as_deref(),
        ) {
            tracing::warn!(
                table = %table_name,
                target_db = ?target_db,
                err = %e.message,
                "failed to update _table_catalog after ingest"
            );
        }
    }

    /// Best-effort catalog reconcile after a DDL/DML `execute`. Same
    /// error-swallowing rationale as [`Self::after_ingest_catalog_update`].
    ///
    /// Reconciles persistent first, then the user-attached writable
    /// target if one was passed and it isn't persistent. Without the
    /// second pass, raw DDL like `DROP TABLE` against a user-attached
    /// alias leaves the dropped table's row stranded in that DB's
    /// `_table_catalog` indefinitely (bootstrap reconcile only walks
    /// persistent, and tools like `describe` would keep listing it).
    #[expect(
        clippy::unused_self,
        reason = "&self required for method-call dispatch; body uses only engine + target_db"
    )]
    fn after_execute_catalog_update(&self, engine: &Engine, target_db: Option<&str>) {
        if let Err(e) = crate::table_catalog::reconcile_in(engine, None) {
            tracing::warn!(
                err = %e.message,
                "failed to reconcile persistent _table_catalog after execute"
            );
        }
        if let Some(alias) = target_db {
            if !alias.eq_ignore_ascii_case(Engine::PERSISTENT_ALIAS) {
                if let Err(e) = crate::table_catalog::reconcile_in(engine, Some(alias)) {
                    tracing::warn!(
                        target_db = alias,
                        err = %e.message,
                        "failed to reconcile user-DB _table_catalog after execute"
                    );
                }
            }
        }
    }

    /// Convenience wrapper: acquire the engine and run a closure against it.
    ///
    /// If the closure returns an error classified as
    /// [`ErrorCode::ConnectionLost`], the engine is dropped from the mutex
    /// before the error is returned to the caller. The next tool call will
    /// observe `engine.is_none()` and transparently re-spawn `hyperd` via
    /// [`Self::ensure_engine`]. Callers then just retry and the server
    /// heals itself.
    fn with_engine<F, R>(&self, f: F) -> Result<R, McpError>
    where
        F: FnOnce(&Engine) -> Result<R, McpError>,
    {
        let mut guard = self.ensure_engine()?;
        let engine = guard.as_ref().expect("ensure_engine guarantees Some");
        // Bootstrap the catalog exactly once per engine. Intentionally
        // runs *inside* `with_engine` (not `ensure_engine`) so the
        // catalog SQL can see errors classified via the normal error
        // path. No-op in bare or read-only mode.
        self.ensure_catalog_ready(engine);
        // In daemon mode, send a heartbeat so the daemon knows we're still active.
        // Debounced to avoid per-call TCP overhead (only sends if >60s since last).
        if !self.no_daemon {
            self.maybe_send_heartbeat();
        }
        let result = f(engine);
        if let Err(e) = &result {
            tracing::debug!(code = ?e.code, message = %e.message, "tool call returned error");
            if e.code == ErrorCode::ConnectionLost {
                tracing::warn!(
                    // Matches both the "hyperd crashed / socket closed" family
                    // and the "wire desynchronized" family — see
                    // [`crate::error::is_connection_lost`] for the full
                    // classifier and both triggers.
                    "connection to hyperd lost or desynchronized ({}); \
                     dropping engine so next call reconnects",
                    e.message
                );
                *guard = None;
                // Reset so the next call re-bootstraps the catalog
                // against the fresh engine.
                if let Ok(mut ready) = self.catalog_ready.lock() {
                    *ready = false;
                }
                // Tell the daemon hyperd looks dead from over here. The daemon
                // will pick up the flag on its next monitor tick and restart.
                // Skipped in --no-daemon mode because there's no daemon to tell.
                if !self.no_daemon {
                    crate::daemon::health::report_hyperd_error_to_daemon();
                }
            }
        }
        result
    }

    /// Best-effort heartbeat to keep the daemon alive while this client is active.
    /// Debounced: only sends if more than 60 seconds have elapsed since the last heartbeat,
    /// avoiding a new TCP connection on every tool call.
    fn maybe_send_heartbeat(&self) {
        const HEARTBEAT_INTERVAL: std::time::Duration = std::time::Duration::from_secs(60);
        let should_send = self
            .last_heartbeat
            .lock()
            .is_ok_and(|guard| guard.elapsed() >= HEARTBEAT_INTERVAL);
        if should_send {
            let port = crate::daemon::discovery::resolve_port();
            let _ = crate::daemon::health::send_command(port, "HEARTBEAT");
            if let Ok(mut guard) = self.last_heartbeat.lock() {
                *guard = std::time::Instant::now();
            }
        }
    }

    /// Run a closure that accesses the saved-query store.
    ///
    /// Some store variants (notably
    /// [`crate::saved_queries::WorkspaceStore`]) need an `Engine` handle
    /// to run SQL against the meta-table; others
    /// ([`crate::saved_queries::SessionStore`]) ignore the engine entirely.
    /// For persistent workspaces we spin the engine up lazily (same path
    /// as every tool call), for ephemeral workspaces we skip it so the
    /// session-only store doesn't pay a `hyperd` startup tax.
    fn with_saved_query_store<F, R>(&self, f: F) -> Result<R, McpError>
    where
        F: FnOnce(Option<&Engine>) -> Result<R, McpError>,
    {
        if self.workspace_path.is_some() {
            self.with_engine(|engine| f(Some(engine)))
        } else {
            f(None)
        }
    }

    #[expect(
        clippy::unnecessary_wraps,
        reason = "signature retained for API symmetry / future fallibility; returning Result/Option keeps callers from breaking when the function later grows failure cases"
    )]
    /// Wrap a successful JSON value as an MCP `CallToolResult` with both
    /// `structuredContent` (for spec-2025-06-18 typed clients) and a
    /// pretty-printed `text` block (for older clients that don't yet read
    /// `structuredContent`). Both representations carry the same JSON.
    fn ok_content(val: Value) -> Result<CallToolResult, rmcp::ErrorData> {
        let text = serde_json::to_string_pretty(&val).unwrap_or_default();
        let mut result = CallToolResult::structured(val);
        // CallToolResult::structured includes a stringified copy in `content`;
        // replace it with a pretty-printed version for human-readable display
        // in older clients.
        result.content = vec![Content::text(text)];
        Ok(result)
    }

    /// Pretty-print a SQL string using the `PostgreSQL` dialect formatter.
    /// Falls back to the original string if formatting fails or produces empty output.
    fn fmt_sql(sql: &str) -> String {
        let opts = FormatOptions {
            indent: Indent::Spaces(2),
            uppercase: Some(true),
            lines_between_queries: 1,
            ..FormatOptions::default()
        };
        let formatted = sqlformat::format(sql, &SqlQueryParams::None, &opts);
        if formatted.trim().is_empty() {
            sql.to_owned()
        } else {
            formatted
        }
    }

    #[expect(
        clippy::unnecessary_wraps,
        reason = "signature retained for API symmetry / future fallibility; returning Result/Option keeps callers from breaking when the function later grows failure cases"
    )]
    #[expect(
        clippy::needless_pass_by_value,
        reason = "call-site ergonomics: function consumes logically-owned parameters, refactoring signatures is not worth per-site churn"
    )]
    /// Wrap an `McpError` as an MCP `CallToolResult` with `isError: true`.
    /// The structured error (code + message + suggestion) is exposed both as
    /// `structuredContent` (spec 2025-06-18) and as a pretty-printed text block
    /// for older clients.
    fn err_content(e: McpError) -> Result<CallToolResult, rmcp::ErrorData> {
        let err_val = serde_json::to_value(&e).unwrap_or(Value::String(e.to_string()));
        let body = json!({"error": err_val});
        let text = serde_json::to_string_pretty(&body).unwrap_or_default();
        let mut result = CallToolResult::structured_error(body);
        result.content = vec![Content::text(text)];
        Ok(result)
    }
}

#[tool_router]
impl HyperMcpServer {
    /// Ingest inline data (JSON or CSV) and run a SQL query in one call. Creates a temp table, queries, discards.
    #[tool(
        description = "Ingest inline data (JSON or CSV) and run a SQL query in one call. Creates a temp table, queries, discards."
    )]
    fn query_data(
        &self,
        Parameters(params): Parameters<QueryDataParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        let result = self.with_engine(|engine| {
            let tname = params.table_name.unwrap_or_else(|| "data".into());
            let temp_table = format!("_tmp_{}_{}", tname, rand_suffix());
            let fmt = params.format.unwrap_or_else(|| detect_format(&params.data));
            let schema_override = crate::schema::normalize_schema_param(params.schema.as_ref())?;
            let opts = IngestOptions {
                table: temp_table.clone(),
                mode: "replace".into(),
                schema_override,
                merge_key: None,
                target_db: None,
            };

            let ingest_result = match fmt.as_str() {
                "csv" => ingest_csv(engine, &params.data, &opts),
                _ => ingest_json(engine, &params.data, &opts),
            }?;

            let query_sql = params.sql.replace(&tname, &temp_table);
            let rows = engine.execute_query_to_json(&query_sql)?;
            let _ = engine.execute_command(&format!("DROP TABLE IF EXISTS \"{temp_table}\""));

            Ok(json!({
                "sql": Self::fmt_sql(&params.sql),
                "result": rows,
                "stats": ingest_result.stats.to_json(),
            }))
        });

        match result {
            Ok(val) => Self::ok_content(val),
            Err(e) => Self::err_content(e),
        }
    }

    /// Ingest a file (CSV, JSON, JSONL, Parquet, Arrow IPC) and run a SQL query in one call.
    #[tool(
        description = "Ingest a file (CSV, JSON, JSONL / NDJSON, Parquet, Arrow IPC) and run a SQL query in one call. JSON files may be either a top-level array of objects or newline-delimited JSON (JSONL); the format is auto-detected from the first byte. Use `json_extract_path` to extract a nested data array from a JSON wrapper file (e.g., MCP tool responses saved to disk). The path is dot-separated; numeric segments index into arrays; string values are automatically parsed as JSON."
    )]
    fn query_file(
        &self,
        Parameters(params): Parameters<QueryFileParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        let result = self.with_engine(|engine| {
            crate::attach::validate_input_path(&params.path, "data file")?;
            let stem = std::path::Path::new(&params.path)
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("file")
                .to_string();
            let tname = params.table_name.unwrap_or_else(|| stem.clone());
            let temp_table = format!("_tmp_{}_{}", tname, rand_suffix());
            let schema_override = crate::schema::normalize_schema_param(params.schema.as_ref())?;
            let opts = IngestOptions {
                table: temp_table.clone(),
                mode: "replace".into(),
                schema_override,
                merge_key: None,
                target_db: None,
            };

            let ingest_result = if let Some(ref json_path) = params.json_extract_path {
                let raw = std::fs::read_to_string(&params.path).map_err(|e| {
                    McpError::new(
                        ErrorCode::FileNotFound,
                        format!("Cannot read file '{}': {e}", params.path),
                    )
                })?;
                let extracted = crate::ingest::extract_json_path(&raw, json_path)?;
                let array_text = crate::ingest::normalize_json_or_jsonl(&extracted)?;
                let mut result = ingest_json(engine, &array_text, &opts)?;
                result.stats.operation = "query_file".into();
                result.stats.bytes_read = std::fs::metadata(&params.path).map_or(0, |m| m.len());
                result.stats.file_format = Some("json".into());
                result
            } else {
                match detect_file_format(std::path::Path::new(&params.path)) {
                    InferredFileFormat::Parquet => ingest_parquet_file(engine, &params.path, &opts),
                    InferredFileFormat::ArrowIpc => {
                        ingest_arrow_ipc_file(engine, &params.path, &opts)
                    }
                    InferredFileFormat::Json => ingest_json_file(engine, &params.path, &opts),
                    InferredFileFormat::Csv => ingest_csv_file(engine, &params.path, &opts),
                }?
            };

            let query_sql = params.sql.replace(&tname, &temp_table);
            let rows = engine.execute_query_to_json(&query_sql)?;
            let _ = engine.execute_command(&format!("DROP TABLE IF EXISTS \"{temp_table}\""));

            Ok(json!({
                "sql": Self::fmt_sql(&params.sql),
                "result": rows,
                "stats": ingest_result.stats.to_json(),
            }))
        });

        match result {
            Ok(val) => Self::ok_content(val),
            Err(e) => Self::err_content(e),
        }
    }

    /// Load inline data (JSON or CSV) into a named workspace table.
    #[tool(
        description = "Load inline data (JSON or CSV) into a named workspace table. Supports partial `schema` overrides keyed by column name — only list the columns you want to correct, the rest keep their inferred type. On SchemaMismatch / numeric overflow, follow the error's suggestion (typically widen an INT column to BIGINT or NUMERIC(38,0))."
    )]
    fn load_data(
        &self,
        Parameters(params): Parameters<LoadDataParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        if let Err(e) = self.check_writable("load_data") {
            return Self::err_content(e);
        }
        let table_name = params.table.clone();
        // Replace-mode creates the table from scratch (or replaces an
        // existing one), which is a resource-list-changing event; append
        // mode only changes row content. Captured before the move-into
        // closure so we can pick the right notifications after success.
        let mode = params.mode.clone().unwrap_or_else(|| "replace".into());
        let result = self.with_engine(|engine| {
            let target_db =
                self.resolve_db(engine, params.database.as_deref(), params.persist, true)?;
            let fmt = params.format.unwrap_or_else(|| detect_format(&params.data));
            let schema_override = crate::schema::normalize_schema_param(params.schema.as_ref())?;
            let opts = IngestOptions {
                table: params.table.clone(),
                mode: mode.clone(),
                schema_override,
                merge_key: None,
                target_db: target_db.clone(),
            };

            let ingest_result = match fmt.as_str() {
                "csv" => ingest_csv(engine, &params.data, &opts),
                _ => ingest_json(engine, &params.data, &opts),
            }?;

            let schema_json: Vec<Value> = ingest_result
                .schema
                .iter()
                .map(|c| {
                    json!({
                        "name": c.name,
                        "type": c.hyper_type,
                        "nullable": c.nullable,
                    })
                })
                .collect();

            // Catalog bookkeeping: the helper routes the upsert to
            // target_db's per-DB _table_catalog (lazily seeded on
            // first ingest). Persistent and ephemeral primary share
            // persistent's catalog; user-attached writable DBs each
            // get their own.
            {
                let load_params = serde_json::to_string(&json!({
                    "mode": mode,
                    "format": fmt,
                    "database": target_db.as_deref().unwrap_or("local"),
                }))
                .ok();
                self.after_ingest_catalog_update(
                    engine,
                    &params.table,
                    "load_data",
                    load_params.as_deref(),
                    i64::try_from(ingest_result.rows).ok(),
                    target_db.as_deref(),
                );
            }

            Ok(json!({
                "rows": ingest_result.rows,
                "schema": schema_json,
                "stats": ingest_result.stats.to_json(),
            }))
        });

        match result {
            Ok(val) => {
                self.notify_table_changed(&table_name);
                if mode == "replace" {
                    // Replace either created a new table or recreated an
                    // existing one — either way the resource catalog
                    // moved.
                    self.notify_resource_list_changed();
                }
                Self::ok_content(val)
            }
            Err(e) => Self::err_content(e),
        }
    }

    /// Load a file (CSV, JSON, JSONL, Parquet, Arrow IPC) into a named workspace table.
    #[tool(
        description = "Load a CSV / JSON / JSONL / NDJSON / Parquet / Arrow IPC file into a named workspace table. Format is auto-detected from extension (or content for JSON vs CSV).\n\nWhen choosing a format for *new* data going into Hyper, prefer in this order:\n  1. **Parquet** (fastest, server-side): hyperd reads the file directly via `external()`. Types, NUMERIC precision, DATE / TIMESTAMP, and Snappy/ZSTD compression all preserved. This is the recommended format for large imports.\n  2. **CSV**: server-side `COPY FROM` — also fast, but types are inferred from a header + full-file numeric widening pass (CSV has no embedded type info), and empty unquoted cells load as SQL NULL per PostgreSQL CSV default.\n  3. **Arrow IPC** (.arrow / .ipc / .feather, File or Stream format, auto-detected): read in Rust and streamed into hyperd via the binary COPY protocol with zero value-level decoding. Fast but not quite as fast as Parquet, and schema overrides are rejected (the Arrow schema is authoritative).\n  4. **JSON / JSONL / NDJSON**: parsed in Rust (hyperd has no native JSON reader), with per-row insertion. Use for small / irregular data; large JSON should be converted to Parquet first.\n\nFor Apache Iceberg tables use `load_iceberg` instead — it takes a directory path rather than a single file.\n\nSupports partial `schema` overrides keyed by column name (`{\"col\":\"BIGINT\"}`) — only list columns you want to correct; unlisted columns keep their inferred type. Overrides are supported for Parquet, CSV, and JSON; rejected for Arrow IPC. Call `inspect_file` first when unsure about types or to debug a prior failure; the inspector reports per-column min/max/null_count using the exact same inference logic. Use `json_extract_path` to extract a nested data array from a JSON wrapper file — dot-separated path, numeric segments index into arrays, string values are parsed as JSON.\n\n**Mode**: `replace` (default — drops + recreates the table), `append` (adds rows to an existing table), or `merge` (upserts rows by `merge_key`). In merge mode, set `merge_key` to a column name (`\"job_id\"`) or list of names (`[\"cell\",\"job_id\"]`); rows with a matching key are replaced, rows with no match are inserted. New columns in the incoming file are auto-added via `ALTER TABLE ADD COLUMN`. Type changes on existing columns are rejected — use `replace` for breaking schema changes."
    )]
    fn load_file(
        &self,
        Parameters(params): Parameters<LoadFileParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        if let Err(e) = self.check_writable("load_file") {
            return Self::err_content(e);
        }
        let table_name = params.table.clone();
        let mode = params.mode.clone().unwrap_or_else(|| "replace".into());
        // Validate (mode, merge_key) combination at the tool boundary so the
        // ingest layer can stay focused on the load mechanics. `merge_key`
        // is required for merge and rejected for replace/append.
        let merge_key_vec = match validate_merge_args(&mode, params.merge_key) {
            Ok(v) => v,
            Err(e) => return Self::err_content(e),
        };
        // The closure returns `(payload, schema_changed)` so the
        // notify branch below can fire correctly for merges that ran
        // an `ALTER TABLE ADD COLUMN`. `replace` always changes shape;
        // `merge` only does conditionally; `append` never does.
        let result = self.with_engine(|engine| {
            let target_db =
                self.resolve_db(engine, params.database.as_deref(), params.persist, true)?;
            crate::attach::validate_input_path(&params.path, "data file")?;
            let schema_override = crate::schema::normalize_schema_param(params.schema.as_ref())?;
            let opts = IngestOptions {
                table: params.table.clone(),
                mode: mode.clone(),
                schema_override,
                merge_key: merge_key_vec.clone(),
                target_db: target_db.clone(),
            };

            let ingest_result = if let Some(ref json_path) = params.json_extract_path {
                let raw = std::fs::read_to_string(&params.path).map_err(|e| {
                    McpError::new(
                        ErrorCode::FileNotFound,
                        format!("Cannot read file '{}': {e}", params.path),
                    )
                })?;
                let extracted = crate::ingest::extract_json_path(&raw, json_path)?;
                let array_text = crate::ingest::normalize_json_or_jsonl(&extracted)?;
                let mut result = ingest_json(engine, &array_text, &opts)?;
                result.stats.operation = "load_file".into();
                result.stats.bytes_read = std::fs::metadata(&params.path).map_or(0, |m| m.len());
                result.stats.file_format = Some("json".into());
                result
            } else {
                match detect_file_format(std::path::Path::new(&params.path)) {
                    InferredFileFormat::Parquet => ingest_parquet_file(engine, &params.path, &opts),
                    InferredFileFormat::ArrowIpc => {
                        ingest_arrow_ipc_file(engine, &params.path, &opts)
                    }
                    InferredFileFormat::Json => ingest_json_file(engine, &params.path, &opts),
                    InferredFileFormat::Csv => ingest_csv_file(engine, &params.path, &opts),
                }?
            };

            // Capture the schema-changed flag before consuming
            // `ingest_result` so the closure can return it alongside
            // the JSON payload.
            let schema_changed = ingest_result.stats.schema_changed;

            let schema_json: Vec<Value> = ingest_result
                .schema
                .iter()
                .map(|c| {
                    json!({
                        "name": c.name,
                        "type": c.hyper_type,
                        "nullable": c.nullable,
                    })
                })
                .collect();

            // Catalog: helper routes to target_db's per-DB catalog.
            {
                let load_params = serde_json::to_string(&json!({
                    "source_path": params.path,
                    "mode": mode,
                    "schema": params.schema,
                    "json_extract_path": params.json_extract_path,
                    "merge_key": merge_key_vec,
                    "database": target_db.as_deref().unwrap_or("local"),
                }))
                .ok();
                self.after_ingest_catalog_update(
                    engine,
                    &params.table,
                    "load_file",
                    load_params.as_deref(),
                    i64::try_from(ingest_result.rows).ok(),
                    target_db.as_deref(),
                );
            }

            Ok((
                json!({
                    "rows": ingest_result.rows,
                    "schema": schema_json,
                    "stats": ingest_result.stats.to_json(),
                }),
                schema_changed,
            ))
        });

        match result {
            Ok((val, schema_changed)) => {
                self.notify_table_changed(&table_name);
                // Notify when the resource list's *shape* actually
                // changed: `replace` always (table dropped/recreated),
                // and `merge` only when it ran an `ALTER TABLE ADD
                // COLUMN` (or created the target via the rename short-
                // circuit). A merge that only updated existing rows
                // leaves the schema untouched, so we skip the
                // broadcast — same precedent as `append`.
                if mode == "replace" || schema_changed {
                    self.notify_resource_list_changed();
                }
                Self::ok_content(val)
            }
            Err(e) => Self::err_content(e),
        }
    }

    /// Ingest multiple files in parallel across a pool of async connections.
    /// Each entry behaves like a standalone `load_file` call; failures are
    /// reported per-file rather than aborting the whole batch.
    #[tool(
        description = "Ingest multiple files in parallel. Each entry is equivalent to a standalone `load_file` call (same formats and same format-selection guidance: prefer Parquet > CSV > Arrow IPC > JSON for large imports). The batch runs across a pool of async connections sized by `concurrency` (default `min(files.len(), 8)`), so independent files finish roughly in max-time rather than sum-time. Per-file errors are captured in the response and do not abort the rest of the batch; the top-level call still returns Ok. For Apache Iceberg tables, call `load_iceberg` per table instead — this tool only handles single-file formats.\n\nUse `database` (or shorthand `persist: true`) to target a non-primary database; the same value applies to every entry in the batch. **Note: `mode = \"merge\"` is not supported here — use `load_file` once per file when you need merge/upsert semantics.**"
    )]
    fn load_files(
        &self,
        Parameters(params): Parameters<LoadFilesParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        use hyperdb_api::pool::{create_pool, PoolConfig};
        use hyperdb_api::CreateMode;

        if let Err(e) = self.check_writable("load_files") {
            return Self::err_content(e);
        }
        if params.files.is_empty() {
            return Self::err_content(McpError::new(
                ErrorCode::EmptyData,
                "load_files: `files` must not be empty",
            ));
        }

        // Reject `mode = "merge"` (or stray `merge_key`) up front, before
        // we spin up the connection pool and dispatch the parallel batch.
        // The async ingest paths driven from this batch loader don't
        // carry the merge-via-temp-table branch, and rejecting per-entry
        // would produce a confusing N-rejection result for a uniform
        // merge call. One top-level error is the clearer contract.
        for (idx, entry) in params.files.iter().enumerate() {
            if let Err(mut e) = crate::attach::validate_input_path(&entry.path, "data file") {
                e.message = format!("entry {idx} (table '{}'): {}", entry.table, e.message);
                return Self::err_content(e);
            }
            let mode = entry.mode.as_deref().unwrap_or("replace");
            if mode == "merge" || entry.merge_key.is_some() {
                return Self::err_content(McpError::new(
                    ErrorCode::InvalidArgument,
                    format!(
                        "load_files does not support mode=merge yet (entry {idx}, table \
                         '{}'). Call load_file once per file when you need merge semantics.",
                        entry.table
                    ),
                ));
            }
        }

        // Resolve hyperd endpoint + the workspace path matching the
        // resolved target database. The pool opens that .hyper file
        // directly (under the same alias the engine uses) so qualified
        // SQL routes correctly. Read-only attachments are rejected by
        // resolve_db.
        let (endpoint, workspace, target_db) = match self.with_engine(|engine| {
            let target_db =
                self.resolve_db(engine, params.database.as_deref(), params.persist, true)?;
            let endpoint = engine.hyperd_endpoint()?;
            let workspace = match target_db.as_deref() {
                None => engine.ephemeral_path().to_string_lossy().to_string(),
                Some(alias) if alias.eq_ignore_ascii_case(Engine::PERSISTENT_ALIAS) => engine
                    .persistent_path()
                    .ok_or_else(|| {
                        McpError::new(
                            ErrorCode::InvalidArgument,
                            "target 'persistent' but the server is in --ephemeral-only mode",
                        )
                    })?
                    .to_string_lossy()
                    .to_string(),
                Some(alias) => {
                    let entry = self.attachments.get(alias).ok_or_else(|| {
                        McpError::new(
                            ErrorCode::InvalidArgument,
                            format!("database '{alias}' is not attached"),
                        )
                    })?;
                    let crate::attach::AttachSource::LocalFile { path } = &entry.source;
                    path.to_string_lossy().to_string()
                }
            };
            Ok((endpoint, workspace, target_db))
        }) {
            Ok(v) => v,
            Err(e) => return Self::err_content(e),
        };

        // Pool size: cap at files.len() and an absolute ceiling of 16 to
        // avoid starving the primary connection hyperd is already servicing.
        let file_count = params.files.len();
        let concurrency = params
            .concurrency
            .map_or(8, |n| n as usize)
            .min(file_count)
            .clamp(1, 16);

        let pool = match create_pool(
            PoolConfig::new(endpoint, workspace)
                .create_mode(CreateMode::DoNotCreate)
                .max_size(concurrency),
        ) {
            Ok(p) => Arc::new(p),
            Err(e) => {
                return Self::err_content(McpError::new(
                    ErrorCode::InternalError,
                    format!("Failed to build connection pool for load_files: {e}"),
                ))
            }
        };

        // Drive the async fan-out from this sync tool handler using the
        // same pattern as `start_watching`: block_in_place + block_on.
        let Ok(rt) = tokio::runtime::Handle::try_current() else {
            return Self::err_content(McpError::new(
                ErrorCode::InternalError,
                "load_files must run inside a tokio runtime",
            ));
        };

        // Per-entry result payload. Successful entries carry rows/schema/stats;
        // failures carry error code + message. Order matches input `files`.
        #[derive(Default)]
        struct EntryOutcome {
            table: String,
            ok: Option<(u64, Vec<Value>, Value)>,
            err: Option<(ErrorCode, String)>,
            replace_mode: bool,
        }

        let outcomes: Vec<EntryOutcome> = tokio::task::block_in_place(|| {
            rt.block_on(async {
                let mut set = tokio::task::JoinSet::new();
                for (idx, entry) in params.files.into_iter().enumerate() {
                    let pool = Arc::clone(&pool);
                    let entry_target_db = target_db.clone();
                    set.spawn(async move {
                        let mode = entry.mode.clone().unwrap_or_else(|| "replace".into());
                        let replace_mode = mode == "replace";
                        let mut out = EntryOutcome {
                            table: entry.table.clone(),
                            replace_mode,
                            ..Default::default()
                        };

                        // `merge` mode is rejected up front in the
                        // top-level handler; per-entry guard would be
                        // dead code here.

                        let schema_override =
                            match crate::schema::normalize_schema_param(entry.schema.as_ref()) {
                                Ok(v) => v,
                                Err(e) => {
                                    out.err = Some((e.code, e.message));
                                    return (idx, out);
                                }
                            };
                        // The pool was built against the resolved target's
                        // .hyper file as its workspace, so from these
                        // connections' perspective the target IS the primary
                        // database. Keep target_db unqualified (None) so SQL
                        // routes into the pool's primary instead of trying
                        // to qualify against an alias that doesn't exist on
                        // these connections. The `entry_target_db` is still
                        // used downstream for the catalog gate.
                        let _ = &entry_target_db;
                        let opts = IngestOptions {
                            table: entry.table.clone(),
                            mode: mode.clone(),
                            schema_override,
                            merge_key: None,
                            target_db: None,
                        };

                        // Check out a connection from the pool. Held only
                        // for the duration of this one ingest, then released.
                        let mut conn = match pool.get().await {
                            Ok(c) => c,
                            Err(e) => {
                                out.err = Some((
                                    ErrorCode::InternalError,
                                    format!("Failed to check out connection: {e}"),
                                ));
                                return (idx, out);
                            }
                        };

                        // `json_extract_path` only makes sense for JSON; the
                        // sync loader wraps the file read + normalize step
                        // around `ingest_json`. Mirror that here using the
                        // async ingest_json on the pooled connection.
                        let ingest_res = if let Some(ref json_path) = entry.json_extract_path {
                            let raw = match std::fs::read_to_string(&entry.path) {
                                Ok(s) => s,
                                Err(e) => {
                                    out.err = Some((
                                        ErrorCode::FileNotFound,
                                        format!("Cannot read file '{}': {e}", entry.path),
                                    ));
                                    return (idx, out);
                                }
                            };
                            let extracted = match crate::ingest::extract_json_path(&raw, json_path)
                            {
                                Ok(v) => v,
                                Err(e) => {
                                    out.err = Some((e.code, e.message));
                                    return (idx, out);
                                }
                            };
                            let array_text =
                                match crate::ingest::normalize_json_or_jsonl(&extracted) {
                                    Ok(v) => v,
                                    Err(e) => {
                                        out.err = Some((e.code, e.message));
                                        return (idx, out);
                                    }
                                };
                            crate::ingest::ingest_json_async(&mut conn, &array_text, &opts)
                                .await
                                .map(|mut r| {
                                    r.stats.operation = "load_file".into();
                                    r.stats.bytes_read =
                                        std::fs::metadata(&entry.path).map_or(0, |m| m.len());
                                    r.stats.file_format = Some("json".into());
                                    r
                                })
                        } else {
                            match detect_file_format(std::path::Path::new(&entry.path)) {
                                InferredFileFormat::Parquet => {
                                    ingest_parquet_file_async(&mut conn, &entry.path, &opts).await
                                }
                                InferredFileFormat::ArrowIpc => {
                                    ingest_arrow_ipc_file_async(&mut conn, &entry.path, &opts).await
                                }
                                InferredFileFormat::Json => {
                                    ingest_json_file_async(&mut conn, &entry.path, &opts).await
                                }
                                InferredFileFormat::Csv => {
                                    ingest_csv_file_async(&mut conn, &entry.path, &opts).await
                                }
                            }
                        };

                        match ingest_res {
                            Ok(r) => {
                                let schema_json: Vec<Value> = r
                                    .schema
                                    .iter()
                                    .map(|c| {
                                        json!({
                                            "name": c.name,
                                            "type": c.hyper_type,
                                            "nullable": c.nullable,
                                        })
                                    })
                                    .collect();
                                out.ok = Some((r.rows, schema_json, r.stats.to_json()));
                            }
                            Err(e) => {
                                out.err = Some((e.code, e.message));
                            }
                        }

                        (idx, out)
                    });
                }

                // Preserve input order when flattening the join set so the
                // response mirrors the caller's `files` array 1-for-1.
                let mut collected: Vec<Option<EntryOutcome>> =
                    (0..file_count).map(|_| None).collect();
                while let Some(joined) = set.join_next().await {
                    match joined {
                        Ok((idx, outcome)) => collected[idx] = Some(outcome),
                        Err(e) => {
                            // A task panicked — surface it as an error on a
                            // synthetic slot so the caller sees something.
                            tracing::warn!("load_files task join error: {e}");
                        }
                    }
                }
                collected.into_iter().flatten().collect()
            })
        });

        // Catalog bookkeeping + notifications for successful loads. Runs
        // back on the sync engine connection. Best-effort; errors are
        // logged but don't fail the batch response.
        let mut any_replace_succeeded = false;
        let mut tables_to_notify: Vec<String> = Vec::new();
        let results_json: Vec<Value> = outcomes
            .iter()
            .map(|o| match (&o.ok, &o.err) {
                (Some((rows, schema, stats)), _) => {
                    tables_to_notify.push(o.table.clone());
                    if o.replace_mode {
                        any_replace_succeeded = true;
                    }
                    json!({
                        "table": o.table,
                        "rows": rows,
                        "schema": schema,
                        "stats": stats,
                    })
                }
                (None, Some((code, msg))) => json!({
                    "table": o.table,
                    "error": {
                        "code": format!("{:?}", code),
                        "message": msg,
                    }
                }),
                // Shouldn't happen (exactly one of ok/err is set) but be
                // defensive — emit a placeholder rather than panicking.
                (None, None) => json!({
                    "table": o.table,
                    "error": {
                        "code": "InternalError",
                        "message": "load_files task produced no outcome",
                    }
                }),
            })
            .collect();

        // Update the per-table catalog stubs for every success. Requires
        // the engine, so we run this inside `with_engine`. The helper
        // routes the upsert to target_db's per-DB _table_catalog.
        if let Err(e) = self.with_engine(|engine| {
            for o in &outcomes {
                if let Some((rows, _, _)) = &o.ok {
                    self.after_ingest_catalog_update(
                        engine,
                        &o.table,
                        "load_file",
                        None,
                        i64::try_from(*rows).ok(),
                        target_db.as_deref(),
                    );
                }
            }
            Ok(())
        }) {
            tracing::warn!("load_files: catalog update batch failed: {}", e.message);
        }

        for t in &tables_to_notify {
            self.notify_table_changed(t);
        }
        if any_replace_succeeded {
            self.notify_resource_list_changed();
        }

        let success_count = outcomes.iter().filter(|o| o.ok.is_some()).count();
        let failure_count = outcomes.len() - success_count;

        Self::ok_content(json!({
            "results": results_json,
            "summary": {
                "total": outcomes.len(),
                "succeeded": success_count,
                "failed": failure_count,
                "concurrency": concurrency,
            }
        }))
    }

    /// Ingest an Apache Iceberg table directory into a workspace table
    /// using hyperd's native `external(..., format => 'iceberg')` reader.
    #[tool(
        description = "Ingest an Apache Iceberg table into a workspace table using hyperd's native Iceberg reader. `path` must be an absolute path to the Iceberg table *root directory* (the one containing the `metadata/` and `data/` subdirs). Hyperd resolves the latest snapshot by default; pass `metadata_filename` (e.g. `v2.metadata.json`) or `version_as_of` to pin a specific snapshot or version. Mode is `replace` (default) or `append`. Single SQL statement under the hood — no Rust-side Arrow decode, no per-row INSERTs."
    )]
    fn load_iceberg(
        &self,
        Parameters(params): Parameters<LoadIcebergParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        if let Err(e) = self.check_writable("load_iceberg") {
            return Self::err_content(e);
        }
        let table_name = params.table.clone();
        let mode = params.mode.clone().unwrap_or_else(|| "replace".into());
        let opts = crate::lakehouse::IcebergIngestOptions {
            table: params.table.clone(),
            mode: mode.clone(),
            metadata_filename: params.metadata_filename.clone(),
            version_as_of: params.version_as_of,
        };

        let result = self.with_engine(|engine| {
            // Iceberg "path" is a directory, not a file — validate as input path.
            crate::attach::validate_input_path(&params.path, "iceberg table")?;
            let ingest_result =
                crate::lakehouse::ingest_iceberg_table(engine, &params.path, &opts)?;

            let schema_json: Vec<Value> = ingest_result
                .schema
                .iter()
                .map(|c| {
                    json!({
                        "name": c.name,
                        "type": c.hyper_type,
                        "nullable": c.nullable,
                    })
                })
                .collect();

            let load_params = serde_json::to_string(&json!({
                "source_path": params.path,
                "mode": mode,
                "format": "iceberg",
                "metadata_filename": params.metadata_filename,
                "version_as_of": params.version_as_of,
            }))
            .ok();
            self.after_ingest_catalog_update(
                engine,
                &params.table,
                "load_iceberg",
                load_params.as_deref(),
                i64::try_from(ingest_result.rows).ok(),
                None,
            );

            Ok(json!({
                "rows": ingest_result.rows,
                "schema": schema_json,
                "stats": ingest_result.stats.to_json(),
            }))
        });

        match result {
            Ok(val) => {
                self.notify_table_changed(&table_name);
                if mode == "replace" {
                    self.notify_resource_list_changed();
                }
                Self::ok_content(val)
            }
            Err(e) => Self::err_content(e),
        }
    }

    /// Run a read-only SQL query (SELECT, WITH, EXPLAIN, SHOW, VALUES).
    #[tool(
        description = "Run a read-only SQL query (SELECT, WITH, EXPLAIN, SHOW, VALUES) against the workspace. For DDL/DML use the execute tool."
    )]
    fn query(
        &self,
        Parameters(params): Parameters<QueryParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        let result = self.with_engine(|engine| {
            if !is_read_only_sql(&params.sql) {
                return Err(McpError::new(
                    ErrorCode::SqlError,
                    "The query tool only accepts read-only SQL (SELECT, WITH, EXPLAIN, SHOW, VALUES). Use the execute tool for DDL/DML.",
                ));
            }
            // Optional database routing — temporarily redirect search_path
            // for the duration of this call. Restored on guard drop.
            let target_db = self.resolve_db(engine, params.database.as_deref(), None, false)?;
            let _search_guard = match target_db {
                Some(ref alias) => Some(engine.scoped_search_path(alias)?),
                None => None,
            };
            // Cap result-set size sent back to the LLM. Larger result sets blow
            // the model's context window and stall the conversation. Users who
            // need full scans should use `export` to write to a file.
            const MAX_QUERY_ROWS: usize = 10_000;

            let timer = crate::stats::StatsTimer::start();
            let mut rows = engine.execute_query_to_json(&params.sql)?;
            let total_rows = rows.len();
            let truncated = total_rows > MAX_QUERY_ROWS;
            if truncated {
                rows.truncate(MAX_QUERY_ROWS);
            }
            let elapsed = timer.elapsed_ms();
            let stats = crate::stats::QueryStats {
                operation: "query".into(),
                rows_returned: rows.len() as u64,
                rows_scanned: 0,
                elapsed_ms: elapsed,
                result_size_bytes: serde_json::to_string(&rows).map_or(0, |s| s.len() as u64),
                tables_touched: vec![],
            };
            let payload = if truncated {
                json!({
                    "result": rows,
                    "stats": stats.to_json(),
                    "truncated": true,
                    "total_rows": total_rows,
                    "rows_returned": MAX_QUERY_ROWS,
                    "hint": format!(
                        "Result set has {total_rows} rows; only the first {MAX_QUERY_ROWS} \
                         are shown. Add a LIMIT clause, aggregate with GROUP BY, or use \
                         the `export` tool to write the full result to a file."
                    ),
                })
            } else {
                json!({
                    "result": rows,
                    "stats": stats.to_json(),
                })
            };
            Ok((params.sql.clone(), payload))
        });

        match result {
            Ok((sql, val)) => {
                let formatted_sql = Self::fmt_sql(&sql);
                let json_text = serde_json::to_string_pretty(&val).unwrap_or_default();
                Ok(CallToolResult::success(vec![
                    Content::text(format!("```sql\n{formatted_sql}\n```")),
                    Content::text(json_text),
                ]))
            }
            Err(e) => Self::err_content(e),
        }
    }

    /// Execute one or more DDL/DML statements as an atomic batch.
    #[tool(
        description = "Execute one or more DDL/DML statements as an atomic batch. `sql` is an array of statements; pass `[\"SQL\"]` for a single statement or `[\"UPDATE …\", \"INSERT …\"]` for an atomic upsert. Multi-statement batches run inside a transaction — if any statement fails, all are rolled back. Mixing DDL with DML in one batch is rejected (Hyper aborts such transactions). Disabled in read-only mode."
    )]
    fn execute(
        &self,
        Parameters(params): Parameters<ExecuteParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        if let Err(e) = self.check_writable("execute") {
            return Self::err_content(e);
        }
        // Validation runs outside `with_engine` so a malformed batch
        // doesn't tie up an engine handle. All checks short-circuit on
        // the first failure with an InvalidArgument / SqlError carrying
        // an LLM-actionable suggestion.
        if let Err(e) = validate_execute_batch(&params.sql) {
            return Self::err_content(e);
        }
        let any_structural = params
            .sql
            .iter()
            .any(|s| matches!(classify_statement(s), StatementKind::Ddl));
        let result = self.with_engine(|engine| {
            // Optional database routing — temporarily redirect search_path.
            // require_writable=true ensures non-primary aliases must be writable.
            // Held for the entire batch (and transaction, if multi-statement).
            let target_db = self.resolve_db(engine, params.database.as_deref(), None, true)?;
            let _search_guard = match target_db {
                Some(ref alias) => Some(engine.scoped_search_path(alias)?),
                None => None,
            };
            let total_timer = crate::stats::StatsTimer::start();
            let (per_statement, affected_total, operation): (Vec<Value>, u64, &'static str) =
                if params.sql.len() == 1 {
                    // Singletons skip BEGIN/COMMIT — same auto-commit behavior
                    // as the pre-batch `execute` tool, and DDL singletons stay
                    // legal (Hyper auto-commits DDL anyway).
                    let stmt = &params.sql[0];
                    let t = crate::stats::StatsTimer::start();
                    let affected = engine.execute_command(stmt)?;
                    (
                        vec![json!({
                            "sql": Self::fmt_sql(stmt),
                            "affected_rows": affected,
                            "elapsed_ms": t.elapsed_ms(),
                        })],
                        affected,
                        "command",
                    )
                } else {
                    let stmts = &params.sql;
                    let (results, total) = engine.execute_in_transaction(|engine| {
                        let mut out = Vec::with_capacity(stmts.len());
                        let mut total: u64 = 0;
                        for (idx, stmt) in stmts.iter().enumerate() {
                            let t = crate::stats::StatsTimer::start();
                            let affected = engine.execute_command(stmt).map_err(|e| {
                                // Preserve the original error's code AND its
                                // suggestion (e.g. Hyper's "did you mean
                                // <column>?") — append the rollback context
                                // rather than replacing it.
                                let rollback_note = format!(
                                    "Failing SQL: {sql}. All previous statements in this batch were rolled back.",
                                    sql = Self::fmt_sql(stmt)
                                );
                                let combined = match e.suggestion.as_deref() {
                                    Some(orig) => format!("{orig} | {rollback_note}"),
                                    None => rollback_note,
                                };
                                McpError::new(
                                    e.code,
                                    format!(
                                        "statement {} of {} failed: {}",
                                        idx + 1,
                                        stmts.len(),
                                        e.message
                                    ),
                                )
                                .with_suggestion(combined)
                            })?;
                            // saturating_add: a single batch summing to >2^64 rows
                            // is implausible, but clamp rather than wrap on the
                            // off chance — wrap-around would silently undercount.
                            total = total.saturating_add(affected);
                            out.push(json!({
                                "sql": Self::fmt_sql(stmt),
                                "affected_rows": affected,
                                "elapsed_ms": t.elapsed_ms(),
                            }));
                        }
                        Ok((out, total))
                    })?;
                    (results, total, "transaction")
                };
            let elapsed = total_timer.elapsed_ms();
            // Reconcile only when the batch contains a statement that
            // could have changed the set of tables (CREATE / DROP /
            // ALTER / TRUNCATE / RENAME). Pure DML can't add or remove
            // tables, so running `reconcile_in` on every row-level
            // execute would do `2N + 2` SQL round-trips of pure waste.
            // Same gate as `notify_resource_list_changed` below; both
            // fire on the same set of statements.
            //
            // Threads `target_db` so a structural DDL against a
            // user-attached alias also reconciles that DB's catalog
            // (otherwise the dropped table's row stays stranded —
            // bootstrap reconcile only walks persistent).
            if any_structural {
                self.after_execute_catalog_update(engine, target_db.as_deref());
            }
            Ok(json!({
                "statements": per_statement.len(),
                "affected_rows": affected_total,
                "per_statement": per_statement,
                "stats": { "operation": operation, "elapsed_ms": elapsed },
            }))
        });

        match result {
            Ok(val) => {
                // Arbitrary DDL/DML may have touched any table — fire the
                // workspace-wide summary updates, and a list_changed to
                // nudge subscribers to refresh their resource catalog for
                // CREATE / DROP style statements.
                self.notify_workspace_changed();
                if any_structural {
                    self.notify_resource_list_changed();
                }
                Self::ok_content(val)
            }
            Err(e) => Self::err_content(e),
        }
    }

    /// Return the schema, total row count, and the first N rows of a table.
    #[tool(
        description = "Return the schema, total row count, and first N rows of a table. Combines describe + sample query in one call. N defaults to 5, max 100."
    )]
    fn sample(
        &self,
        Parameters(params): Parameters<SampleParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        let result = self.with_engine(|engine| {
            let target_db = self.resolve_db(engine, params.database.as_deref(), None, false)?;
            let timer = crate::stats::StatsTimer::start();
            let n = params.n.unwrap_or(5);
            let mut sample = engine.sample_table_in(target_db.as_deref(), &params.table, n)?;
            let elapsed = timer.elapsed_ms();
            if let Some(obj) = sample.as_object_mut() {
                obj.insert(
                    "stats".into(),
                    json!({ "operation": "sample", "elapsed_ms": elapsed }),
                );
            }
            Ok(sample)
        });

        match result {
            Ok(val) => Self::ok_content(val),
            Err(e) => Self::err_content(e),
        }
    }

    /// Render a chart (PNG or SVG) from a SQL query.
    #[tool(
        description = "Render a chart (bar, line, scatter, or histogram) from a SQL query. Writes the image to disk by default and returns a short stats blob with the path — use `Read(path)` to display it (this keeps the MCP transcript small). Set `inline=true` to also receive the PNG/SVG bytes inline in the tool result; combine with `output_path` to get both.\n\n**Data shape:** The query must return long-format data with one numeric `y` column. For multi-series charts, use a `series` column to split by category. If your data is wide-format (multiple value columns), reshape it with `UNION ALL` into (label, series, value) tuples before charting.\n\n**DATE/TIMESTAMP x-axis:** Line and scatter charts auto-detect non-numeric x columns. DATE, TIMESTAMP, and TIMESTAMPTZ values render with a **proportional time axis** — gaps between data points reflect real wall-clock time (4.5 h gap and 17 h gap don't look the same). Tick labels are formatted in the input kind: `%Y-%m-%d` for DATE, `%Y-%m-%d %H:%M:%S` for TIMESTAMP, with the originating timezone offset preserved for TIMESTAMPTZ. TEXT x columns fall back to evenly-spaced categorical mode. Set `x_as_category: true` to force categorical layout on temporal data (useful when even spacing reads better than proportional gaps).\n\n- `output_path`: explicit destination file path. Parent directory is created automatically (no need to pre-create it). If omitted, a file is auto-generated under the system temp dir as `hyperdb-charts/chart-<ts>-<pid>-<n>.<ext>`.\n- `inline`: when true, return the image bytes inline. Without `output_path`, suppresses the disk write entirely. With `output_path`, writes to disk AND returns inline. Defaults to false.\n- `format`: \"png\" (default) or \"svg\". Auto-derived from `output_path` extension when omitted. A mismatch between `format` and the path extension returns `INVALID_ARGUMENT`.\n- `overwrite`: default true. Set false to refuse overwriting an existing file (returns `PERMISSION_DENIED`).\n- `x_range` / `y_range`: fix axis extents across multiple charts (e.g. x_range=[0,1500], y_range=[0,1]).\n- `color_map`: stable per-series hex colors (e.g. {\"India\":\"#e41a1c\",\"China\":\"#ff7f0e\"}).\n- `label_points=true`: annotate each point with its series name instead of showing a legend — best when each series has exactly one point."
    )]
    fn chart(
        &self,
        Parameters(params): Parameters<ChartParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        let result = self.with_engine(|engine| {
            if !is_read_only_sql(&params.sql) {
                return Err(McpError::new(
                    ErrorCode::SqlError,
                    "The chart tool only accepts read-only SQL (SELECT, WITH, EXPLAIN, SHOW, VALUES).",
                ));
            }

            // If the caller passed an explicit output path, validate it.
            // Auto-generated paths land in a temp dir and don't need this gate.
            if let Some(out) = params.output_path.as_deref() {
                crate::attach::validate_output_path(out, "chart output")?;
            }
            // Resolve format up front — the path extension may imply it,
            // and we need the format before we can auto-generate a path.
            let format = crate::chart::resolve_chart_format(
                params.format.as_deref(),
                params.output_path.as_deref(),
            )?;

            // Optional database routing — temporarily redirect search_path
            // so unqualified names in the chart SQL resolve there.
            let target_db = self.resolve_db(engine, params.database.as_deref(), None, false)?;
            let _search_guard = match target_db {
                Some(ref alias) => Some(engine.scoped_search_path(alias)?),
                None => None,
            };

            let timer = crate::stats::StatsTimer::start();
            let rows = engine.execute_query_to_json(&params.sql)?;

            // Parse color_map: skip entries whose hex string is malformed,
            // logging them via the description rather than hard-failing.
            let color_map = params
                .color_map
                .as_ref()
                .map(|m| {
                    m.iter()
                        .filter_map(|(k, v)| {
                            crate::chart::parse_hex_color(v)
                                .map(|c| (k.clone(), c))
                        })
                        .collect::<std::collections::HashMap<_, _>>()
                })
                .unwrap_or_default();

            let opts = ChartOptions {
                chart_type: ChartType::parse(&params.chart_type)?,
                x_column: params.x.clone(),
                y_column: params.y.clone(),
                series_column: params.series.clone(),
                title: params.title.clone(),
                format,
                width: params.width.unwrap_or(800).clamp(200, 4096),
                height: params.height.unwrap_or(480).clamp(150, 4096),
                bins: params.bins.unwrap_or(20).clamp(1, 500),
                x_as_category: params.x_as_category,
                x_range: params.x_range,
                y_range: params.y_range,
                color_map,
                label_points: params.label_points.unwrap_or(false),
            };

            let chart = render_chart(&rows, &opts)?;

            // Decide disk vs inline vs both. Write to disk *before*
            // building the content vec so an I/O failure surfaces as a
            // tool error instead of a half-delivered response.
            let disposition = crate::chart::resolve_chart_disposition(
                params.inline.unwrap_or(false),
                params.output_path.as_deref(),
                opts.format,
            );
            let overwrite = params.overwrite.unwrap_or(true);
            if let Some(path) = disposition.path() {
                crate::chart::write_chart_to_disk(path, &chart.bytes, overwrite)?;
            }

            let elapsed = timer.elapsed_ms();
            Ok((chart, elapsed, opts, disposition))
        });

        match result {
            Ok((chart, elapsed_ms, opts, disposition)) => {
                let format_str = match opts.format {
                    ChartFormat::Png => "png",
                    ChartFormat::Svg => "svg",
                };
                let wants_inline = disposition.wants_inline();
                let output_path_str = disposition.path().map(|p| p.to_string_lossy().into_owned());

                let mut stats = serde_json::Map::new();
                stats.insert("operation".into(), json!("chart"));
                stats.insert("rows_plotted".into(), json!(chart.rows_plotted));
                stats.insert("elapsed_ms".into(), json!(elapsed_ms));
                stats.insert("format".into(), json!(format_str));
                stats.insert("bytes".into(), json!(chart.bytes.len()));
                stats.insert("width".into(), json!(opts.width));
                stats.insert("height".into(), json!(opts.height));
                stats.insert("inline".into(), json!(wants_inline));
                if let Some(p) = output_path_str {
                    stats.insert("output_path".into(), json!(p));
                }
                let stats_text =
                    serde_json::to_string_pretty(&Value::Object(stats)).unwrap_or_default();

                let mut content = Vec::with_capacity(2);
                if wants_inline {
                    let b64 = base64::engine::general_purpose::STANDARD.encode(&chart.bytes);
                    content.push(Content::image(b64, chart.mime_type.to_string()));
                }
                content.push(Content::text(stats_text));
                Ok(CallToolResult::success(content))
            }
            Err(e) => Self::err_content(e),
        }
    }

    /// Begin watching a directory for `.ready` sentinel files. See
    /// [`crate::watcher`] for the full producer/consumer protocol.
    #[tool(
        description = "Watch a directory for files to auto-ingest. Producers write data file + companion <name>.ready sentinel; the watcher appends the data file to the given table and deletes both on success. Use `database` (or shorthand `persist: true`) to target a non-primary database — the watcher's connection pool opens that file directly. `detach_database` rejects while a watcher is active; call `unwatch_directory` first. Disabled in read-only mode."
    )]
    fn watch_directory(
        &self,
        Parameters(params): Parameters<WatchDirectoryParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        if let Err(e) = self.check_writable("watch_directory") {
            return Self::err_content(e);
        }
        let canonical = match crate::attach::validate_input_path(&params.path, "watch directory") {
            Ok(p) => p,
            Err(e) => return Self::err_content(e),
        };
        // Eagerly initialize the engine so the background watcher thread can
        // assume `engine.as_ref()` is Some without needing workspace_path.
        match self.ensure_engine() {
            Ok(guard) => drop(guard),
            Err(e) => return Self::err_content(e),
        }

        // Resolve the target database once, under the engine lock. Read-only
        // attachments are rejected here (require_writable=true) so the
        // watcher can't be pointed at a destination it can't write to.
        let target_db = match self.with_engine(|engine| {
            self.resolve_db(engine, params.database.as_deref(), params.persist, true)
        }) {
            Ok(v) => v,
            Err(e) => return Self::err_content(e),
        };

        let path = canonical;
        let engine_handle = self.engine_handle();
        let attachments = self.attachments_handle();
        let registry = self.watchers_handle();
        let options = crate::watcher::WatchOptions {
            max_concurrent: params.max_concurrent.unwrap_or(0) as usize,
        };
        let result = crate::watcher::start_watching(
            engine_handle,
            attachments,
            registry,
            Some(self.subscriptions_handle()),
            path.clone(),
            params.table.clone(),
            target_db,
            options,
        );
        match result {
            Ok(stats) => {
                let body = json!({
                    "directory": path.to_string_lossy(),
                    "table": params.table,
                    "status": "watching",
                    "max_concurrent": stats.max_concurrent,
                    "initial_sweep": {
                        "files_ingested": stats.files_ingested,
                        "files_failed": stats.files_failed,
                    },
                });
                Self::ok_content(body)
            }
            Err(e) => Self::err_content(e),
        }
    }

    /// Stop watching a directory.
    #[tool(
        description = "Stop watching a directory previously registered with watch_directory. Pending .ready files are left in place."
    )]
    fn unwatch_directory(
        &self,
        Parameters(params): Parameters<UnwatchDirectoryParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        let path = std::path::PathBuf::from(&params.path);
        let result = crate::watcher::stop_watching(&self.watchers_handle(), &path);
        match result {
            Ok(summary) => Self::ok_content(summary),
            Err(e) => Self::err_content(e),
        }
    }

    /// Describe workspace tables. With `table` set, returns just that
    /// table's columns and row count; without it, lists every public table.
    #[tool(
        description = "Describe workspace tables. With `table` set, returns that single table's columns and row count (TABLE_NOT_FOUND if missing). Without `table`, lists every public table."
    )]
    fn describe(
        &self,
        Parameters(params): Parameters<DescribeParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        let result = self.with_engine(|engine| {
            let target_db = self.resolve_db(engine, params.database.as_deref(), None, false)?;
            match params.table.as_deref() {
                Some(name) => engine
                    .describe_table_in(target_db.as_deref(), name)
                    .map(|t| vec![t]),
                None => engine.describe_tables_in(target_db.as_deref()),
            }
        });

        match result {
            Ok(tables) => Self::ok_content(json!({"tables": tables})),
            Err(e) => Self::err_content(e),
        }
    }

    /// Dry-run schema inference on a file (CSV, Parquet, Arrow IPC) without
    /// ingesting it. Returns the inferred schema plus per-column diagnostics
    /// (`null_count`, `min`, `max`, `sample_values`) so an LLM can construct
    /// a safer `schema` override for `load_file` / `load_data`.
    #[tool(
        description = "Dry-run schema inference on a CSV / Parquet / Arrow IPC file without ingesting. Returns the schema load_file would use (including the full-file numeric widening pass), plus per-column null_count, min, max, and sample_values. Use this BEFORE load_file if you are unsure about types or ran into a SchemaMismatch / numeric overflow — then pass an explicit `schema` override on the subsequent load_file call. Use `json_extract_path` to inspect a nested data array inside a JSON wrapper file (e.g., MCP tool responses saved to disk)."
    )]
    #[expect(
        clippy::unused_self,
        reason = "method retained on the type for API symmetry; implementation currently does not need state"
    )]
    fn inspect_file(
        &self,
        Parameters(params): Parameters<InspectFileParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        if let Err(e) = crate::attach::validate_input_path(&params.path, "data file") {
            return Self::err_content(e);
        }
        let sample_rows = params.sample_rows.unwrap_or(5).clamp(1, 50) as usize;
        let result = if let Some(ref json_path) = params.json_extract_path {
            (|| -> Result<_, McpError> {
                let raw = std::fs::read_to_string(&params.path).map_err(|e| {
                    McpError::new(
                        ErrorCode::FileNotFound,
                        format!("Cannot read file '{}': {e}", params.path),
                    )
                })?;
                let file_size = std::fs::metadata(&params.path).map_or(0, |m| m.len());
                let extracted = crate::ingest::extract_json_path(&raw, json_path)?;
                crate::inspect::inspect_json_from_text(&extracted, file_size, sample_rows)
            })()
        } else {
            crate::inspect::inspect_source(&params.path, sample_rows)
        };
        match result {
            Ok(report) => Self::ok_content(report.to_json()),
            Err(e) => Self::err_content(e),
        }
    }

    /// Export query results or a table to CSV, Parquet, Arrow IPC,
    /// Apache Iceberg, or a new `.hyper` file.
    #[tool(
        description = "Export query results or a table to a file via hyperd's native writers. Every format listed here is server-side — hyperd writes the file directly, with zero per-row work in the MCP process — and every format round-trips cleanly through the matching loader (`load_file` or `load_iceberg`).\n\nWhen choosing a format for *data leaving* Hyper, prefer in this order:\n  1. **Parquet** (recommended default): smallest output, fastest write, preserves every type (NUMERIC precision/scale, DATE, TIMESTAMP, etc.). `path` is a single file.\n  2. **Iceberg**: produces a full Apache Iceberg table directory (`metadata/` + `data/`). Use when the consumer is a data-lake tool (Spark, Trino, DuckDB, etc.). `path` is a directory that hyperd creates.\n  3. **Arrow IPC Stream** (`arrow_ipc`): same wire shape Hyper uses internally; great for handing data to another Arrow-aware process. Larger than Parquet (no compression) but extremely fast to read back. `path` is a single file.\n  4. **CSV**: portable and human-readable but the largest output and types are lost (everything becomes text). Use for spreadsheet / shell-pipeline interop. Includes header row.\n  5. **Hyper**: an entire `.hyper` database file openable directly in Tableau Desktop. `sql`/`table` are ignored — every user table is copied.\n\nAll formats except Iceberg and Hyper require either `sql` or `table`. Iceberg output is a directory; all others are single files.\n\nUse `database` to read from a non-primary source: for `format=\"hyper\"` it selects which database is snapshotted; for the row-oriented formats it routes the SELECT through the named database (when `table` is set) or pins `schema_search_path` for the call (when `sql` is set)."
    )]
    fn export(
        &self,
        Parameters(params): Parameters<ExportParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        let result = self.with_engine(|engine| {
            // Validate output path: must be absolute, no `..` components.
            // (Iceberg "exports" to a directory; the same rules apply.)
            crate::attach::validate_output_path(&params.path, "export")?;
            // `format_options` must be a JSON object if supplied. Anything
            // else (array, string, number, null) is a caller error — reject
            // with a clear message rather than silently dropping it.
            let format_options = match params.format_options.clone() {
                None => None,
                Some(Value::Object(m)) => Some(m),
                Some(other) => {
                    return Err(McpError::new(
                        ErrorCode::SchemaMismatch,
                        format!("export: format_options must be a JSON object, got: {other}"),
                    ));
                }
            };
            // Database routing. Three strategies:
            // - `hyper` format + non-primary: source_db plumbed through
            //   into populate_export_target so the snapshot reads from
            //   the requested database (no need to redirect anything;
            //   the cross-DB CREATE TABLE AS handles it natively).
            // - `table` mode + non-primary: synthesize a fully-qualified
            //   SELECT and pass it as `sql` so export.rs's name-quoting
            //   doesn't double-quote our identifier.
            // - `sql` mode + non-primary: redirect search_path for the
            //   call duration so unqualified names resolve correctly.
            let target_db = self.resolve_db(engine, params.database.as_deref(), None, false)?;
            let (effective_sql, effective_table) = match (&params.sql, &params.table, &target_db) {
                (None, Some(t), Some(db)) => {
                    let esc_db = db.replace('"', "\"\"");
                    let esc_tbl = t.replace('"', "\"\"");
                    (
                        Some(format!(
                            "SELECT * FROM \"{esc_db}\".\"public\".\"{esc_tbl}\""
                        )),
                        None,
                    )
                }
                _ => (params.sql.clone(), params.table.clone()),
            };
            let _search_guard = match (&effective_sql, &target_db, &params.sql) {
                // Only pin search_path when the user supplied raw SQL
                // (not when we synthesized a fully-qualified SELECT).
                (Some(_), Some(alias), Some(_)) => Some(engine.scoped_search_path(alias)?),
                _ => None,
            };
            let opts = ExportOptions {
                sql: effective_sql,
                table: effective_table,
                path: params.path,
                format: params.format,
                overwrite: params.overwrite.unwrap_or(true),
                format_options,
                source_db: target_db.clone(),
            };
            let export_result = export_to_file(engine, &opts)?;
            Ok(json!({
                "output_path": export_result.stats.output_path,
                "rows": export_result.rows,
                "file_size_bytes": export_result.stats.file_size_bytes,
                "stats": export_result.stats.to_json(),
            }))
        });

        match result {
            Ok(val) => Self::ok_content(val),
            Err(e) => Self::err_content(e),
        }
    }

    /// Save a named read-only SQL query. After saving, the query is
    /// exposed as two MCP resources — see the struct-level docs on
    /// [`SaveQueryParams`] for the full URI pattern.
    #[tool(
        description = "Save a named read-only SQL query. Creates two resources: `hyper://queries/{name}/definition` (sql + metadata JSON) and `hyper://queries/{name}/result` (re-runs the SQL on every read). Persisted in the workspace when `--workspace` is set; session-only otherwise. Rejects non-read-only SQL and duplicate names; delete first to overwrite."
    )]
    fn save_query(
        &self,
        Parameters(params): Parameters<SaveQueryParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        if let Err(e) = self.check_writable("save_query") {
            return Self::err_content(e);
        }
        // Enforce read-only SQL at save time. This is belt-and-braces: the
        // result resource runs via `execute_query_to_json` which would
        // reject DDL/DML anyway, but rejecting here produces a clearer
        // error and prevents the row landing in the meta-table at all.
        if !is_read_only_sql(&params.sql) {
            return Self::err_content(McpError::new(
                ErrorCode::SqlError,
                "save_query only accepts read-only SQL (SELECT / WITH / EXPLAIN / SHOW / VALUES). \
                 Use the execute tool for DDL/DML, not save_query.",
            ));
        }
        if params.name.is_empty() {
            return Self::err_content(McpError::new(
                ErrorCode::SchemaMismatch,
                "Saved query name must not be empty.",
            ));
        }
        let query = SavedQuery {
            name: params.name.clone(),
            sql: params.sql,
            description: params.description,
            created_at: chrono::Utc::now(),
        };
        let store = Arc::clone(&self.saved_queries);
        let result = self.with_saved_query_store(|engine| store.save(engine, query.clone()));
        match result {
            Ok(()) => {
                // Both resources for this query name are new — nudge
                // clients to refresh their catalog so they see the new
                // `hyper://queries/{name}/...` entries.
                self.notify_resource_list_changed();
                Self::ok_content(json!({
                    "saved": true,
                    "name": query.name,
                    "resources": [
                        format!("hyper://queries/{}/definition", query.name),
                        format!("hyper://queries/{}/result", query.name),
                    ],
                    "created_at": query.created_at.to_rfc3339(),
                }))
            }
            Err(e) => Self::err_content(e),
        }
    }

    /// Delete a named saved query and its two resources.
    #[tool(
        description = "Delete a named saved query. Removes the underlying entry and both `hyper://queries/{name}/...` resources. Returns `{deleted: true}` when the query existed, `{deleted: false}` when it did not (no error)."
    )]
    fn delete_query(
        &self,
        Parameters(params): Parameters<DeleteQueryParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        if let Err(e) = self.check_writable("delete_query") {
            return Self::err_content(e);
        }
        let store = Arc::clone(&self.saved_queries);
        let name = params.name.clone();
        let result = self.with_saved_query_store(|engine| store.delete(engine, &name));
        match result {
            Ok(deleted) => {
                if deleted {
                    // Two resources just disappeared — fan out a
                    // list_changed and targeted updates so any subscriber
                    // holding stale `hyper://queries/{name}/...` state
                    // drops it.
                    self.notify_resource_list_changed();
                    self.subscriptions
                        .notify_updated(&format!("hyper://queries/{name}/definition"));
                    self.subscriptions
                        .notify_updated(&format!("hyper://queries/{name}/result"));
                }
                Self::ok_content(json!({
                    "deleted": deleted,
                    "name": params.name,
                }))
            }
            Err(e) => Self::err_content(e),
        }
    }

    /// Update prose metadata for a table in the `_table_catalog`.
    #[tool(
        description = "Update prose metadata for a table in the `_table_catalog`: source_url, source_description, purpose, license, notes. Fields you omit stay unchanged; pass an explicit empty string (\"\") to clear a field. Mechanical fields (load_tool, load_params, loaded_at, last_refreshed_at, row_count) are managed by the server. Requires an existing catalog entry — load the table first (load_file / load_data / execute CREATE TABLE) so the stub row is created automatically. Use `database` to target the metadata for a table in a non-primary writable database; read-only attachments are rejected with a clear re-attach-with-writable message. Disabled in read-only mode."
    )]
    fn set_table_metadata(
        &self,
        Parameters(params): Parameters<SetTableMetadataParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        if let Err(e) = self.check_writable("set_table_metadata") {
            return Self::err_content(e);
        }
        let fields = crate::table_catalog::MetadataFields {
            source_url: params.source_url,
            source_description: params.source_description,
            purpose: params.purpose,
            license: params.license,
            notes: params.notes,
        };
        let table_name = params.table.clone();
        let result = self.with_engine(|engine| {
            // Resolve target with require_writable=true so read-only
            // attachments are rejected BEFORE any catalog write
            // (defense-in-depth: ensure_exists_in's CREATE TABLE
            // would also fail at the Hyper layer, but the resolve_db
            // error is more actionable).
            let target_db = self.resolve_db(engine, params.database.as_deref(), None, true)?;
            crate::table_catalog::set_metadata_in(
                engine,
                &table_name,
                &fields,
                target_db.as_deref(),
            )
        });
        match result {
            Ok(entry) => Self::ok_content(entry.to_json()),
            Err(e) => Self::err_content(e),
        }
    }

    /// Returns plugin health, workspace info, table count, total rows, disk
    /// usage, and the list of active directory watchers with their stats.
    #[tool(
        description = "Returns plugin health, workspace info, table count, total rows, disk usage, and active directory watchers."
    )]
    fn status(&self) -> Result<CallToolResult, rmcp::ErrorData> {
        let result = self.with_engine(super::engine::Engine::status);

        match result {
            Ok(mut val) => {
                if let Some(obj) = val.as_object_mut() {
                    obj.insert("watchers".into(), self.watchers.to_json());
                    obj.insert("read_only".into(), json!(self.read_only));
                    let attachments: Vec<Value> = self
                        .attachments
                        .list()
                        .iter()
                        .map(super::attach::AttachedDb::to_json)
                        .collect();
                    obj.insert("attachments".into(), Value::Array(attachments));
                }
                Self::ok_content(val)
            }
            Err(e) => Self::err_content(e),
        }
    }

    /// Returns a concise LLM-facing README. Stateless — works
    /// identically in read-only mode. The text itself documents
    /// read-only restrictions, so the tool doesn't branch on
    /// `self.read_only`.
    #[tool(
        description = "Returns a concise LLM-facing README explaining what this MCP does, which tool to use for what, key parameter rules, SQL dialect quirks, and usage examples. Call this once at the start of a session to ground the model in the surface area before issuing other tool calls."
    )]
    #[expect(
        clippy::unused_self,
        reason = "the #[tool] macro dispatches on &self; signature must match the rest of the tool surface even though this tool is stateless"
    )]
    #[expect(
        clippy::unnecessary_wraps,
        reason = "uniform Result<CallToolResult, rmcp::ErrorData> across all tools so the #[tool_router] dispatcher has one signature shape"
    )]
    fn get_readme(&self) -> Result<CallToolResult, rmcp::ErrorData> {
        Ok(CallToolResult::success(vec![Content::text(
            crate::readme::README,
        )]))
    }

    /// Attach an additional `.hyper` database under a user-chosen
    /// alias so its tables can participate in cross-database queries.
    #[tool(
        description = "Attach an additional .hyper database under a chosen alias. Tables in the attachment are addressable as `{alias}.public.{table}` in any subsequent SELECT; tables in the primary workspace remain addressable as `local.public.{table}` or by their file stem. Default is read-only; pass writable:true to allow mutations (still respects --read-only). Set on_missing='create' (with writable:true) to create an empty .hyper file at the target path first and then attach it — useful for scratch databases without a separate file-creation step; the parent directory must already exist. Only kind='local_file' is supported today; 'tcp' and 'grpc' (Data 360) are planned. The alias 'local' is reserved for the primary workspace."
    )]
    fn attach_database(
        &self,
        Parameters(params): Parameters<AttachDatabaseParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        let writable = params.writable.unwrap_or(false);
        if writable {
            if let Err(e) = self.check_writable("attach_database(writable)") {
                return Self::err_content(e);
            }
        }
        let on_missing = match attach::OnMissing::parse(params.on_missing.as_deref()) {
            Ok(v) => v,
            Err(e) => return Self::err_content(e),
        };
        if on_missing == attach::OnMissing::Create && !writable {
            return Self::err_content(McpError::new(
                ErrorCode::InvalidArgument,
                "on_missing='create' requires writable:true — an empty .hyper file that cannot be written to cannot be populated.",
            ));
        }
        let source = match params.kind.as_str() {
            "local_file" => {
                let Some(raw) = params.path.as_deref() else {
                    return Self::err_content(McpError::new(
                        ErrorCode::InvalidArgument,
                        "kind='local_file' requires a 'path' argument",
                    ));
                };
                let resolved = match on_missing {
                    attach::OnMissing::Error => attach::validate_local_path(raw),
                    attach::OnMissing::Create => attach::validate_local_path_for_create(raw),
                };
                match resolved {
                    Ok(canonical) => AttachSource::LocalFile { path: canonical },
                    Err(e) => return Self::err_content(e),
                }
            }
            other => {
                return Self::err_content(McpError::new(
                    ErrorCode::InvalidArgument,
                    format!(
                        "Unsupported attach kind '{other}'. Only 'local_file' is supported today; \
                         'tcp' (remote hyperd) and 'grpc' (Data 360) are planned."
                    ),
                ));
            }
        };
        let req = AttachRequest {
            alias: params.alias.clone(),
            source,
            writable,
            on_missing,
        };
        let registry = self.attachments_handle();
        let alias_for_probe = req.alias.clone();
        let result = self.with_engine(|engine| {
            let entry = registry.attach(engine, req.clone())?;
            // Best-effort probe for a table count against the new
            // alias so the LLM sees what just came online without a
            // separate round-trip. Failures here don't invalidate the
            // attach — log and return `null` instead.
            let tables_visible = probe_table_count(engine, &alias_for_probe);
            Ok(json!({
                "alias": entry.alias,
                "kind": entry.source.kind_str(),
                "source": entry.source.to_json(),
                "writable": entry.writable,
                "tables_visible": tables_visible,
            }))
        });
        match result {
            Ok(val) => Self::ok_content(val),
            Err(e) => Self::err_content(e),
        }
    }

    /// Detach a previously attached database.
    #[tool(
        description = "Detach a database previously registered with attach_database. No-op when the alias is unknown. Returns {detached: true/false}."
    )]
    fn detach_database(
        &self,
        Parameters(params): Parameters<DetachDatabaseParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        // Canonicalize to the registry's stored form. Aliases are
        // lowercased at attach time; watcher `target_db` is also stored
        // canonicalized (via `Engine::resolve_target_db`), so an exact
        // `==` comparison suffices below.
        let alias = params.alias.to_ascii_lowercase();
        // Reject if any active watcher targets this alias. Otherwise the
        // watcher's pool would keep ingesting into the now-detached
        // workspace path; or, if the user re-attached the same alias to
        // a different file, into the wrong database. Fixed by stopping
        // the watcher first via `unwatch_directory`.
        if let Ok(watchers) = self.watchers.watchers.lock() {
            let conflict = watchers
                .values()
                .find(|h| h.target_db.as_deref() == Some(alias.as_str()));
            if let Some(h) = conflict {
                return Self::err_content(McpError::new(
                    ErrorCode::InvalidArgument,
                    format!(
                        "cannot detach '{alias}': an active watcher on directory '{}' targets it. \
                         Call unwatch_directory(\"{}\") first.",
                        h.directory.display(),
                        h.directory.display()
                    ),
                ));
            }
        }
        let registry = self.attachments_handle();
        let result = self.with_engine(|engine| {
            let outcome = registry.detach(engine, &alias)?;
            if outcome {
                // Drop any cached "_table_catalog exists in this alias"
                // probe so a re-attach to a different file or with
                // different writability won't reuse a stale entry.
                engine.clear_catalog_cache_for(&alias);
            }
            Ok(outcome)
        });
        match result {
            Ok(detached) => {
                Self::ok_content(json!({ "alias": params.alias, "detached": detached }))
            }
            Err(e) => Self::err_content(e),
        }
    }

    /// List currently attached databases.
    ///
    /// Named `list_attached_databases` (not `list_attached`) so it
    /// sits alongside `attach_database` / `detach_database` as a
    /// symmetric verb-database trio. The earlier `list_attached`
    /// name broke the pattern and consistently misled LLM callers
    /// into hallucinating `list_attached_databases` anyway, so the
    /// tool now matches the name the models were already reaching
    /// for.
    #[tool(
        description = "List every database currently attached under an alias: kind, path/endpoint, writable flag, attach time, and (best-effort) a count of visible public-schema tables."
    )]
    fn list_attached_databases(&self) -> Result<CallToolResult, rmcp::ErrorData> {
        let result = self.with_engine(|engine| {
            let entries = self.attachments.list();
            let attachments: Vec<Value> = entries
                .iter()
                .map(|entry| {
                    let mut obj = entry.to_json();
                    let tables_visible = probe_table_count(engine, &entry.alias);
                    if let Some(map) = obj.as_object_mut() {
                        map.insert("tables_visible".into(), json!(tables_visible));
                    }
                    obj
                })
                .collect();
            Ok(json!({ "attachments": attachments }))
        });
        match result {
            Ok(val) => Self::ok_content(val),
            Err(e) => Self::err_content(e),
        }
    }

    /// Run a SELECT across local + attached databases and land the
    /// result into a target table. All three modes (`create`,
    /// `append`, `replace`) are explicit — the target's actual
    /// existence must match the chosen mode.
    #[tool(
        description = "Run a SELECT (or WITH / VALUES) across local and attached databases and insert the result into a target table. Required `mode`: 'create' (target must not exist, creates via CREATE TABLE AS), 'append' (target must exist, INSERT INTO ... SELECT), or 'replace' (drops and recreates atomically). `target_database` defaults to the primary workspace ('local' also accepted); any other value must be an attachment registered with writable:true. Optional `temp_attach` attaches additional databases for this call only and detaches them on exit (even on failure). Disabled in read-only mode."
    )]
    fn copy_query(
        &self,
        Parameters(params): Parameters<CopyQueryParams>,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        if let Err(e) = self.check_writable("copy_query") {
            return Self::err_content(e);
        }
        let mode = match params.mode.as_str() {
            "create" | "append" | "replace" => params.mode.clone(),
            other => {
                return Self::err_content(McpError::new(
                    ErrorCode::InvalidArgument,
                    format!(
                        "copy_query mode '{other}' is not supported. Use 'create', 'append', or 'replace'."
                    ),
                ));
            }
        };
        if !is_read_only_sql(&params.sql) {
            return Self::err_content(McpError::new(
                ErrorCode::SqlError,
                "copy_query's `sql` must be a read-only statement (SELECT / WITH / VALUES). \
                 Use the execute tool for raw DDL/DML.",
            ));
        }
        // `target_database = None` and `"local"` both map to the
        // primary workspace (unqualified target name). Anything else
        // must refer to an attached writable database.
        //
        // Canonicalize to the registry's lowercase storage form before
        // both the registry lookup AND the qualified-SQL build path
        // (`perform_copy` → `qualified_name`). Hyper is case-sensitive
        // on quoted identifiers; without canonicalization here, a user
        // attaching as `"My_DB"` (which the registry stores as
        // `"my_db"`) and calling `copy_query(target_database="My_DB")`
        // would fail with "database does not exist" once SQL renders.
        let target_db_owned = params
            .target_database
            .as_deref()
            .filter(|s| !s.eq_ignore_ascii_case(LOCAL_ALIAS))
            .map(str::to_ascii_lowercase);
        let target_db = target_db_owned.as_deref();
        if let Some(alias) = target_db {
            match self.attachments.get(alias) {
                None => {
                    return Self::err_content(McpError::new(
                        ErrorCode::InvalidArgument,
                        format!(
                            "target_database '{alias}' is not attached. Call attach_database first."
                        ),
                    ));
                }
                Some(entry) if !entry.writable => {
                    return Self::err_content(McpError::new(
                        ErrorCode::InvalidArgument,
                        format!(
                            "target_database '{alias}' was attached read-only. Re-attach with writable:true to use it as a copy target."
                        ),
                    ));
                }
                Some(_) => {}
            }
        }

        // Pre-validate any temp_attach requests *before* we touch the
        // engine so a bad spec aborts cleanly without a partial attach.
        let temp_specs = params.temp_attach.clone().unwrap_or_default();
        let prepared_temps = match prepare_temp_attachments(&temp_specs, self.is_read_only()) {
            Ok(v) => v,
            Err(e) => return Self::err_content(e),
        };

        let target_table = params.target_table.clone();
        let sql_body = params.sql.clone();
        let load_params = serde_json::to_string(&json!({
            "mode": mode,
            "target_database": params.target_database,
            "target_table": target_table,
            "sql": Self::fmt_sql(&sql_body),
        }))
        .ok();

        let registry = self.attachments_handle();
        let result = self.with_engine(|engine| {
            // Phase 1: install temp attachments.
            let mut temp_aliases: Vec<String> = Vec::new();
            for req in &prepared_temps {
                match registry.attach(engine, req.clone()) {
                    Ok(entry) => temp_aliases.push(entry.alias),
                    Err(e) => {
                        // Roll back attachments installed so far.
                        for alias in &temp_aliases {
                            let _ = registry.detach(engine, alias);
                        }
                        return Err(e);
                    }
                }
            }

            // Phase 2: run the actual copy inside a helper so the
            // cleanup path is unified.
            let copy_outcome = perform_copy(engine, &mode, target_db, &target_table, &sql_body);

            // Phase 3: always detach the temp attachments, even on
            // error — they were installed only for the duration of
            // this call.
            for alias in &temp_aliases {
                if let Err(e) = registry.detach(engine, alias) {
                    tracing::warn!(
                        alias = %alias,
                        err = %e.message,
                        "failed to detach temp attachment after copy_query",
                    );
                }
            }

            // Phase 4: stamp `_table_catalog` inside the same engine
            // borrow the copy just ran under. Kept next to the copy
            // (rather than spun off in a second `with_engine`) so the
            // stub and the data it describes can't diverge — a new
            // engine might not even have the catalog materialized yet.
            // Skipped when the destination is an attached database
            // (their catalog isn't ours) or when the server is bare /
            // read-only. `after_ingest_catalog_update` logs WARN on
            // failure, matching how `load_file` / `load_data` /
            // `execute` register their provenance.
            if copy_outcome.is_ok() && target_db.is_none() {
                let row_count = copy_outcome
                    .as_ref()
                    .ok()
                    .and_then(|v| v.get("row_count").and_then(serde_json::Value::as_i64));
                self.after_ingest_catalog_update(
                    engine,
                    &target_table,
                    "copy_query",
                    load_params.as_deref(),
                    row_count,
                    target_db,
                );
            }

            copy_outcome
        });

        match result {
            Ok(outcome) => {
                // Fan out resource updates so subscribers refresh.
                if target_db.is_none() {
                    self.notify_table_changed(&target_table);
                }
                self.notify_workspace_changed();
                if mode != "append" {
                    // `create` / `replace` add or recreate the table,
                    // which is a resource-list-changing event.
                    self.notify_resource_list_changed();
                }
                Self::ok_content(outcome)
            }
            Err(e) => Self::err_content(e),
        }
    }
}

// --- Prompts ---

#[prompt_router]
impl HyperMcpServer {
    /// Deep analysis of a single table: schema, sample, column statistics, data quality flags.
    #[prompt(
        name = "analyze-table",
        description = "Deep analysis of a single table: schema, sample, column stats, data quality"
    )]
    pub async fn analyze_table(
        &self,
        Parameters(args): Parameters<AnalyzeTableArgs>,
    ) -> Vec<PromptMessage> {
        let context = self.build_analyze_context(&args.table);
        vec![
            PromptMessage::new_text(
                PromptMessageRole::User,
                format!(
                    "Analyze the `{}` table thoroughly.\n\n{}\n\nPlease:\n\
                    1. Describe each column (what it likely represents based on name and sample values)\n\
                    2. Compute basic statistics using the query tool: min/max/avg for numeric columns, distinct count and top values for text columns\n\
                    3. Flag any data quality issues: unexpected NULLs, suspicious outliers, inconsistent formats\n\
                    4. Summarize your findings in plain English",
                    args.table, context
                ),
            ),
            PromptMessage::new_text(
                PromptMessageRole::Assistant,
                format!(
                    "I'll analyze the `{}` table systematically. Let me start by examining the schema and sample, then run targeted queries for statistics and data quality.",
                    args.table
                ),
            ),
        ]
    }

    /// Compare two tables side-by-side: schema alignment, common keys, JOIN suggestions.
    #[prompt(
        name = "compare-tables",
        description = "Compare two tables: schema alignment, common keys, JOIN opportunities"
    )]
    pub async fn compare_tables(
        &self,
        Parameters(args): Parameters<CompareTablesArgs>,
    ) -> Vec<PromptMessage> {
        let ctx_a = self.build_brief_context(&args.table_a);
        let ctx_b = self.build_brief_context(&args.table_b);
        vec![
            PromptMessage::new_text(
                PromptMessageRole::User,
                format!(
                    "Compare these two tables:\n\n## Table A: `{}`\n{}\n\n## Table B: `{}`\n{}\n\nPlease:\n\
                    1. Identify columns that appear in both tables (by name or semantic match)\n\
                    2. Suggest likely JOIN keys and the JOIN type (inner, left, etc.)\n\
                    3. Highlight schema differences (column types, nullability)\n\
                    4. Propose 3-5 analytical queries that combine both tables and explain what each reveals",
                    args.table_a, ctx_a, args.table_b, ctx_b
                ),
            ),
            PromptMessage::new_text(
                PromptMessageRole::Assistant,
                format!(
                    "I'll compare `{}` and `{}` systematically — schema alignment first, then join keys, then analytical opportunities.",
                    args.table_a, args.table_b
                ),
            ),
        ]
    }

    /// Systematic data quality assessment: nulls, duplicates, cardinality, outliers.
    #[prompt(
        name = "data-quality",
        description = "Systematic data quality assessment: NULL rates, duplicates, low cardinality, outliers"
    )]
    pub async fn data_quality(
        &self,
        Parameters(args): Parameters<DataQualityArgs>,
    ) -> Vec<PromptMessage> {
        let context = self.build_brief_context(&args.table);
        vec![
            PromptMessage::new_text(
                PromptMessageRole::User,
                format!(
                    "Run a data quality assessment on the `{}` table.\n\n{}\n\nPlease use the query tool to check:\n\
                    1. NULL rate per column — run SELECT COUNT(*) FILTER (WHERE col IS NULL) / COUNT(*) for each column\n\
                    2. Duplicate rows — compare COUNT(*) vs COUNT(DISTINCT *) or use GROUP BY\n\
                    3. Low-cardinality columns — columns with suspiciously few distinct values\n\
                    4. Numeric outliers — values more than 3 stddev from the mean\n\
                    5. Date sanity — future dates or impossibly old dates in date/timestamp columns\n\n\
                    Summarize findings with severity (critical / warning / info) and suggest remediation for each issue.",
                    args.table, context
                ),
            ),
            PromptMessage::new_text(
                PromptMessageRole::Assistant,
                format!(
                    "I'll perform a systematic data quality assessment on `{}`. Let me run targeted queries for each check category.",
                    args.table
                ),
            ),
        ]
    }

    /// Propose useful analytical queries for a table, optionally guided by a goal.
    #[prompt(
        name = "suggest-queries",
        description = "Suggest analytical SQL queries for a table, optionally guided by a goal"
    )]
    pub async fn suggest_queries(
        &self,
        Parameters(args): Parameters<SuggestQueriesArgs>,
    ) -> Vec<PromptMessage> {
        let context = self.build_analyze_context(&args.table);
        let goal_section = match args.goal.as_deref() {
            Some(g) if !g.is_empty() => format!("\n\nSpecific goal: {g}"),
            _ => String::new(),
        };
        vec![
            PromptMessage::new_text(
                PromptMessageRole::User,
                format!(
                    "Given the `{}` table:\n\n{}{}\n\nSuggest 5 analytical SQL queries that would be useful for exploring this data. \
                    For each query, provide:\n\
                    - A descriptive title\n\
                    - The exact SQL (valid for Hyper / PostgreSQL-compatible syntax)\n\
                    - One sentence explaining what insight it reveals\n\n\
                    Prefer queries that use aggregations, GROUP BY, window functions, or CTEs to demonstrate the power of SQL analytics.",
                    args.table, context, goal_section
                ),
            ),
            PromptMessage::new_text(
                PromptMessageRole::Assistant,
                format!(
                    "Based on the schema and sample of `{}`, here are 5 analytical queries.",
                    args.table
                ),
            ),
        ]
    }
}

/// The payload of a resource read, carrying both MIME type and serialized
/// content. Different resources speak different formats (JSON for metadata,
/// markdown for human overviews, CSV for spreadsheet consumers), so the
/// resource layer needs to pass both along to the MCP client.
///
/// `Json` variants are pretty-printed when rendered; `Text` variants are
/// emitted verbatim. Tests and prompt helpers can still access the
/// underlying JSON via [`ResourceBody::as_json`] when it's a JSON payload.
#[derive(Debug, Clone)]
pub enum ResourceBody {
    /// Structured JSON — rendered as pretty-printed `application/json`.
    Json(Value),
    /// Free-form text with an explicit MIME type (e.g. `text/markdown`,
    /// `text/csv`).
    Text {
        /// IANA media type, e.g. `text/markdown` or `text/csv`.
        mime_type: String,
        /// The literal text to return to the client, verbatim.
        content: String,
    },
}

impl ResourceBody {
    /// Return the MIME type this body will be served with.
    #[must_use]
    pub fn mime_type(&self) -> &str {
        match self {
            ResourceBody::Json(_) => "application/json",
            ResourceBody::Text { mime_type, .. } => mime_type,
        }
    }

    /// Render the body to the text payload the client will receive.
    /// JSON variants are pretty-printed; text variants return as-is.
    #[must_use]
    pub fn to_text(&self) -> String {
        match self {
            ResourceBody::Json(v) => {
                serde_json::to_string_pretty(v).unwrap_or_else(|_| v.to_string())
            }
            ResourceBody::Text { content, .. } => content.clone(),
        }
    }

    /// Borrow the underlying `Value` when this body is JSON. Useful for
    /// tests that want to assert on individual fields without reparsing.
    #[must_use]
    pub fn as_json(&self) -> Option<&Value> {
        match self {
            ResourceBody::Json(v) => Some(v),
            ResourceBody::Text { .. } => None,
        }
    }
}

impl HyperMcpServer {
    /// Produce the body for a resource URI without constructing an MCP
    /// `RequestContext`. Factored out of [`Self::read_resource`] so tests can
    /// exercise URI dispatch without standing up the full MCP runtime.
    ///
    /// Returns `Ok(None)` if the URI isn't recognized at all (the async trait
    /// method surfaces this as an `invalid_params` error to clients).
    ///
    /// The returned [`ResourceBody`] carries its own MIME type so non-JSON
    /// resources (`hyper://readme`, `hyper://tables/{name}/csv-sample`,
    /// etc.) can be served verbatim as markdown / CSV.
    ///
    /// # Errors
    ///
    /// Propagates any [`McpError`] from the underlying engine call
    /// (status probe, table description, CSV sample, saved-query listing,
    /// etc.) and bubbles up [`ErrorCode::TableNotFound`] for
    /// `hyper://tables/{name}/...` URIs whose table is absent from the
    /// workspace.
    pub fn resource_body_for_uri(&self, uri: &str) -> Result<Option<ResourceBody>, McpError> {
        if uri == "hyper://workspace" {
            return self
                .with_engine(super::engine::Engine::status)
                .map(|v| Some(ResourceBody::Json(v)));
        }
        if uri == "hyper://tables" {
            return self
                .with_engine(|engine| {
                    engine
                        .describe_tables()
                        .map(|tables| json!({ "tables": tables }))
                })
                .map(|v| Some(ResourceBody::Json(v)));
        }
        if uri == "hyper://readme" {
            return self.build_readme_body().map(Some);
        }
        if let Some(name) = uri
            .strip_prefix("hyper://tables/")
            .and_then(|rest| rest.strip_suffix("/schema"))
        {
            let name = name.to_string();
            return self
                .with_engine(|engine| {
                    let tables = engine.describe_tables()?;
                    tables
                        .into_iter()
                        .find(|t| t.get("name").and_then(|v| v.as_str()) == Some(name.as_str()))
                        .ok_or_else(|| {
                            McpError::new(
                                ErrorCode::TableNotFound,
                                format!("Table '{name}' does not exist"),
                            )
                        })
                })
                .map(|v| Some(ResourceBody::Json(v)));
        }
        if let Some(name) = uri
            .strip_prefix("hyper://tables/")
            .and_then(|rest| rest.strip_suffix("/sample"))
        {
            let name = name.to_string();
            return self
                .with_engine(|engine| engine.sample_table(&name, TABLE_SAMPLE_ROWS))
                .map(|v| Some(ResourceBody::Json(v)));
        }
        if let Some(name) = uri
            .strip_prefix("hyper://tables/")
            .and_then(|rest| rest.strip_suffix("/csv-sample"))
        {
            let name = name.to_string();
            return self.build_csv_sample_body(&name).map(Some);
        }
        if let Some(name) = uri
            .strip_prefix("hyper://queries/")
            .and_then(|rest| rest.strip_suffix("/definition"))
        {
            return self.build_saved_query_definition(name).map(Some);
        }
        if let Some(name) = uri
            .strip_prefix("hyper://queries/")
            .and_then(|rest| rest.strip_suffix("/result"))
        {
            return self.build_saved_query_result(name).map(Some);
        }
        Ok(None)
    }

    /// Build `hyper://queries/{name}/definition`: the stored SQL plus
    /// metadata, as JSON. Returns a `TableNotFound` error when no saved
    /// query has that name.
    fn build_saved_query_definition(&self, name: &str) -> Result<ResourceBody, McpError> {
        let store = Arc::clone(&self.saved_queries);
        let name = name.to_string();
        let query = self.with_saved_query_store(|engine| store.get(engine, &name))?;
        match query {
            Some(q) => Ok(ResourceBody::Json(q.to_json())),
            None => Err(McpError::new(
                ErrorCode::TableNotFound,
                format!("No saved query named '{name}'"),
            )),
        }
    }

    /// Build `hyper://queries/{name}/result`: re-run the stored SQL on
    /// every read and return `{ result: [...], stats: {...} }`. Fresh by
    /// default — there is no cache, and the underlying engine is fast
    /// enough that caching isn't worth the staleness risk.
    fn build_saved_query_result(&self, name: &str) -> Result<ResourceBody, McpError> {
        let store = Arc::clone(&self.saved_queries);
        let name_owned = name.to_string();
        let query = self
            .with_saved_query_store(|engine| store.get(engine, &name_owned))?
            .ok_or_else(|| {
                McpError::new(
                    ErrorCode::TableNotFound,
                    format!("No saved query named '{name_owned}'"),
                )
            })?;
        let sql = query.sql.clone();
        let body = self.with_engine(|engine| {
            let timer = crate::stats::StatsTimer::start();
            let rows = engine.execute_query_to_json(&sql)?;
            let elapsed = timer.elapsed_ms();
            let result_size = serde_json::to_string(&rows).map_or(0, |s| s.len() as u64);
            let stats = crate::stats::QueryStats {
                operation: "saved_query".into(),
                rows_returned: rows.len() as u64,
                rows_scanned: 0,
                elapsed_ms: elapsed,
                result_size_bytes: result_size,
                tables_touched: vec![],
            };
            Ok(json!({
                "name": query.name,
                "sql": Self::fmt_sql(&query.sql),
                "result": rows,
                "stats": stats.to_json(),
            }))
        })?;
        Ok(ResourceBody::Json(body))
    }

    /// Produce the list of MCP resources without constructing an MCP
    /// `RequestContext`. Factored out of [`Self::list_resources`] for tests.
    ///
    /// Returns one URI for the workspace, one for the full tables list, one
    /// for the workspace readme, three per existing table (schema, sample,
    /// csv-sample), and two per saved query (definition, result).
    #[must_use]
    pub fn list_resource_uris(&self) -> Vec<String> {
        let mut uris = vec![
            "hyper://workspace".to_string(),
            "hyper://tables".to_string(),
            "hyper://readme".to_string(),
        ];
        if let Ok(tables) = self.with_engine(super::engine::Engine::describe_tables) {
            // `describe_tables` already filters out `_hyperdb_*` meta-
            // tables via `is_internal_table`, so any table we see here
            // is user-visible.
            for table in tables {
                if let Some(name) = table.get("name").and_then(|v| v.as_str()) {
                    uris.push(format!("hyper://tables/{name}/schema"));
                    uris.push(format!("hyper://tables/{name}/sample"));
                    uris.push(format!("hyper://tables/{name}/csv-sample"));
                }
            }
        }
        let store = Arc::clone(&self.saved_queries);
        if let Ok(saved) = self.with_saved_query_store(|engine| store.list(engine)) {
            for q in saved {
                uris.push(format!("hyper://queries/{}/definition", q.name));
                uris.push(format!("hyper://queries/{}/result", q.name));
            }
        }
        uris
    }

    /// Build the `hyper://readme` markdown body: a human-friendly overview
    /// of the current workspace, its tables, and pointers to the other
    /// resources and tools an LLM might reach for.
    ///
    /// Designed to be dropped into an LLM context block so the model can
    /// orient itself in a single resource read without first calling
    /// `status` and `describe` tools.
    fn build_readme_body(&self) -> Result<ResourceBody, McpError> {
        let status = self.with_engine(super::engine::Engine::status)?;
        let tables = self
            .with_engine(super::engine::Engine::describe_tables)
            .unwrap_or_default();

        let workspace_mode = status
            .get("workspace_mode")
            .and_then(|v| v.as_str())
            .unwrap_or("unknown");
        let workspace_path = status
            .get("workspace_path")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let read_only = status
            .get("read_only")
            .and_then(serde_json::Value::as_bool)
            .unwrap_or(false);
        let table_count = tables.len();

        let mut md = String::new();
        md.push_str("# HyperDB workspace\n\n");
        let _ = writeln!(
            md,
            "- Mode: **{workspace_mode}**{}\n",
            if read_only { " (read-only)" } else { "" }
        );
        if !workspace_path.is_empty() {
            let _ = writeln!(md, "- Path: `{workspace_path}`\n");
        }
        let _ = write!(md, "- Tables: **{table_count}**\n\n");

        if tables.is_empty() {
            md.push_str(
                "_No tables loaded yet._ Use the `load_file` or `load_data` tools to \
                 ingest CSV / JSON / Parquet / Arrow IPC data; call `inspect_file` \
                 first if you're unsure of the schema.\n",
            );
        } else {
            md.push_str("## Tables\n\n");
            md.push_str("| Table | Rows | Columns |\n");
            md.push_str("|---|---:|---|\n");
            for t in &tables {
                let name = t.get("name").and_then(|v| v.as_str()).unwrap_or("?");
                let rows = t
                    .get("row_count")
                    .and_then(serde_json::Value::as_i64)
                    .unwrap_or(0);
                let cols: Vec<String> = t
                    .get("columns")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|c| {
                                let n = c.get("name")?.as_str()?;
                                let ty = c.get("type")?.as_str()?;
                                Some(format!("`{n}` {ty}"))
                            })
                            .collect()
                    })
                    .unwrap_or_default();
                let _ = writeln!(md, "| `{name}` | {rows} | {} |\n", cols.join(", "));
            }
            md.push('\n');
            md.push_str("## Related resources\n\n");
            for t in &tables {
                if let Some(name) = t.get("name").and_then(|v| v.as_str()) {
                    let _ = write!(md, "- `hyper://tables/{name}/schema` — JSON schema and row count\n\
                         - `hyper://tables/{name}/sample` — first {TABLE_SAMPLE_ROWS} rows as JSON\n\
                         - `hyper://tables/{name}/csv-sample` — first {TABLE_CSV_SAMPLE_ROWS} rows as CSV\n");
                }
            }
            md.push('\n');
        }

        md.push_str(
            "## Tool hints\n\n\
             - `query(sql)` — read-only SQL (SELECT / WITH / EXPLAIN / SHOW / VALUES).\n\
             - `execute(sql)` — DDL/DML (disabled in read-only mode).\n\
             - `sample(table, n)` — configurable row sample; the fixed-size\n  \
               `hyper://tables/{name}/sample` resource uses n=5.\n\
             - `inspect_file(path)` — dry-run schema inference before loading.\n\
             - `chart(sql, chart_type, ...)` — render a PNG/SVG from a query.\n\
             - `export(sql|table, path, format)` — write to CSV / Parquet / Arrow IPC / .hyper.\n",
        );

        Ok(ResourceBody::Text {
            mime_type: "text/markdown".into(),
            content: md,
        })
    }

    /// Build the `hyper://tables/{name}/csv-sample` body: first
    /// [`TABLE_CSV_SAMPLE_ROWS`] rows of a table as `text/csv`, with a
    /// header row derived from the sample schema.
    fn build_csv_sample_body(&self, table: &str) -> Result<ResourceBody, McpError> {
        let sample =
            self.with_engine(|engine| engine.sample_table(table, TABLE_CSV_SAMPLE_ROWS))?;

        // Columns come from the sample's `schema` field in the order Hyper
        // reports them; fall back to keys of the first row if that's empty
        // (can happen transiently during catalog desync).
        let header: Vec<String> = sample
            .get("schema")
            .and_then(|v| v.as_array())
            .map(|cols| {
                cols.iter()
                    .filter_map(|c| c.get("name").and_then(|n| n.as_str()).map(String::from))
                    .collect()
            })
            .filter(|v: &Vec<String>| !v.is_empty())
            .or_else(|| {
                sample
                    .get("rows")
                    .and_then(|v| v.as_array())
                    .and_then(|rows| rows.first())
                    .and_then(|r| r.as_object())
                    .map(|o| o.keys().cloned().collect())
            })
            .unwrap_or_default();

        let mut wtr = csv::Writer::from_writer(Vec::<u8>::new());
        if !header.is_empty() {
            wtr.write_record(&header).map_err(|e| {
                McpError::new(
                    ErrorCode::InternalError,
                    format!("Failed to write CSV header: {e}"),
                )
            })?;
        }
        if let Some(rows) = sample.get("rows").and_then(|v| v.as_array()) {
            for row in rows {
                let record: Vec<String> = header
                    .iter()
                    .map(|col| row.get(col).map(value_to_csv_cell).unwrap_or_default())
                    .collect();
                wtr.write_record(&record).map_err(|e| {
                    McpError::new(
                        ErrorCode::InternalError,
                        format!("Failed to write CSV row: {e}"),
                    )
                })?;
            }
        }
        let bytes = wtr.into_inner().map_err(|e| {
            McpError::new(
                ErrorCode::InternalError,
                format!("Failed to finalize CSV: {e}"),
            )
        })?;
        let content = String::from_utf8(bytes).map_err(|e| {
            McpError::new(
                ErrorCode::InternalError,
                format!("CSV produced invalid UTF-8: {e}"),
            )
        })?;

        Ok(ResourceBody::Text {
            mime_type: "text/csv".into(),
            content,
        })
    }

    /// Build a full analysis context block: schema, row count, and a 10-row sample.
    /// Returns a markdown-formatted string ready to embed in a prompt message.
    fn build_analyze_context(&self, table: &str) -> String {
        match self.with_engine(|engine| engine.sample_table(table, 10)) {
            Ok(sample) => format!(
                "Schema and sample:\n```json\n{}\n```",
                serde_json::to_string_pretty(&sample).unwrap_or_else(|_| sample.to_string())
            ),
            Err(e) => format!("(Could not load table context: {e})"),
        }
    }

    /// Build a brief context block: schema and row count only, no rows.
    fn build_brief_context(&self, table: &str) -> String {
        match self.with_engine(|engine| engine.sample_table(table, 5)) {
            Ok(sample) => format!(
                "```json\n{}\n```",
                serde_json::to_string_pretty(&sample).unwrap_or_else(|_| sample.to_string())
            ),
            Err(e) => format!("(Could not load table context: {e})"),
        }
    }
}

// --- ServerHandler: tools, prompts, and resources ---

#[tool_handler]
#[prompt_handler]
impl ServerHandler for HyperMcpServer {
    fn get_info(&self) -> ServerInfo {
        let sql_dialect = "\n\
\n\
SQL DIALECT — Salesforce Data Cloud SQL (PostgreSQL-compatible with extensions).\n\
Key differences from standard PostgreSQL an LLM should know:\n\
\n\
TYPES\n\
- Supported: SMALLINT, INTEGER/INT, BIGINT, REAL/FLOAT4, DOUBLE PRECISION/FLOAT8,\n\
  NUMERIC(p,s)/DECIMAL(p,s), BOOLEAN, TEXT, CHAR(n), VARCHAR(n), BYTES,\n\
  DATE, TIME, TIMESTAMP, TIMESTAMPTZ, INTERVAL, and arrays of any atomic type\n\
- NUMERIC precision > 18 requires .hyper file format version 3 (default in this MCP)\n\
- No SERIAL / BIGSERIAL / UUID / JSON / JSONB / geometry types\n\
\n\
SELECT / QUERY\n\
- LIMIT / OFFSET work as in PostgreSQL; TOP N is also accepted\n\
- LATERAL is optional: subqueries in FROM always see preceding FROM items implicitly\n\
- DISTINCT ON (expr, ...) is supported\n\
- FROM clause is optional (can evaluate expressions without a table)\n\
- Function calls may appear directly in the FROM list\n\
- information_schema and pg_catalog do NOT exist; use the describe/sample tools\n\
\n\
GROUP BY / AGGREGATION\n\
- GROUPING SETS, ROLLUP, CUBE all supported\n\
- GROUP BY DISTINCT removes duplicate grouping sets before processing\n\
- FILTER (WHERE ...) clause supported on aggregate calls\n\
- Ordered-set aggregates: MODE(), PERCENTILE_CONT(), PERCENTILE_DISC() with WITHIN GROUP (ORDER BY ...)\n\
- APPROX_COUNT_DISTINCT() for fast approximate cardinality\n\
- GROUPING() function identifies which columns are aggregated in GROUPING SETS\n\
\n\
WINDOW FUNCTIONS\n\
- Standard: row_number, rank, dense_rank, percent_rank, cume_dist, ntile, lag, lead,\n\
  first_value, last_value, nth_value\n\
- Hyper extension: modified_rank() — like rank() but assigns the LOWEST rank on ties\n\
- IGNORE NULLS / RESPECT NULLS supported on last_value only\n\
- nth_value supports FROM FIRST / FROM LAST\n\
- Frame modes: ROWS, RANGE, GROUPS; EXCLUDE CURRENT ROW / GROUP / TIES / NO OTHERS\n\
- Window-specific functions do NOT support DISTINCT or ORDER BY in their argument list\n\
\n\
SET-RETURNING FUNCTIONS (usable in FROM)\n\
- unnest(array) — expands an array to rows; supports WITH ORDINALITY\n\
- generate_series(start, stop [, step]) — numeric and datetime variants\n\
- external(path, format => '...') — reads Parquet, CSV, Iceberg etc. directly from files\n\
\n\
SET OPERATORS\n\
- UNION, INTERSECT, EXCEPT all supported; INTERSECT binds tighter than UNION/EXCEPT\n\
- ORDER BY and LIMIT/OFFSET can appear on parenthesized sub-expressions or the final result\n\
\n\
CTEs\n\
- WITH and WITH RECURSIVE both supported\n\
- CTEs evaluate once per query execution even if referenced multiple times\n\
\n\
IDENTIFIERS\n\
- Unquoted identifiers are folded to lowercase; double-quote to preserve case or use special chars\n\
- Quote names containing uppercase letters, digits at the start, or special characters\n\
\n\
NOT AVAILABLE IN HYPER (Data 360 / Data Cloud-only features)\n\
- AI functions: AI_CLASSIFY, AI_SENTIMENT, and other Data Cloud AI scalar functions\n\
- Data Cloud federation / streaming-specific functions\n\
\n\
Full SQL reference: https://developer.salesforce.com/docs/data/data-cloud-query-guide/references/dc-sql-reference";

        let header = if self.read_only {
            "HyperDB MCP (read-only): SQL analytics for LLM workflows. Query existing tables, \
             sample data, export results. Mutating operations are disabled. \
             Call get_readme for a concise tool index, parameter rules, and usage examples."
        } else {
            "HyperDB MCP: instant SQL analytics for LLM workflows. Load data (CSV, JSON, Parquet, \
             Arrow IPC, Apache Iceberg), query with SQL, export results (Parquet, Iceberg, Arrow IPC, \
             CSV, Hyper). Use query for SELECT and execute for DDL/DML. \
             Call get_readme for a concise tool index, parameter rules, and usage examples."
        };
        let instructions = format!("{header}{sql_dialect}");
        let mut server_info = Implementation::default();
        server_info.name = "HyperDB".into();
        server_info.title = Some("HyperDB — Hyper SQL Analytics".into());
        server_info.version = env!("CARGO_PKG_VERSION").into();
        server_info.description = Some(
            "MCP server for Tableau Hyper: instant SQL analytics over \
             CSV, JSON, Parquet, Arrow IPC, and Apache Iceberg with schema inference, \
             partial schema overrides, full-file numeric widening, and \
             dry-run file inspection. SQL dialect is PostgreSQL-compatible with \
             extensions (Salesforce Data Cloud SQL). Full SQL reference: \
             https://developer.salesforce.com/docs/data/data-cloud-query-guide/references/dc-sql-reference/data-cloud-sql-context.html"
                .into(),
        );

        let mut info = ServerInfo::default();
        info.instructions = Some(instructions);
        info.server_info = server_info;
        info.capabilities = ServerCapabilities::builder()
            .enable_tools()
            .enable_prompts()
            .enable_resources()
            // Resource subscriptions + list-changed notifications: lets
            // clients subscribe to any `hyper://...` URI and receive a
            // notification whenever the underlying data has moved,
            // without polling.
            .enable_resources_subscribe()
            .enable_resources_list_changed()
            .build();
        info
    }

    async fn initialize(
        &self,
        request: InitializeRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<InitializeResult, rmcp::ErrorData> {
        let name = &request.client_info.name;
        let version = &request.client_info.version;
        let label = if version.is_empty() {
            name.clone()
        } else {
            format!("{name} {version}")
        };
        if let Ok(mut guard) = self.client_name.lock() {
            *guard = Some(label);
        }
        context.peer.set_peer_info(request);
        Ok(self.get_info())
    }

    /// Handle a `resources/subscribe` request by recording the calling
    /// peer in the registry under the requested URI.
    ///
    /// MCP does not mandate that the server validate the URI exists
    /// beforehand — subscriptions to URIs that don't resolve today (e.g.
    /// a saved-query result before `save_query` is called) are allowed
    /// and will start delivering notifications as soon as the URI
    /// becomes reachable.
    async fn subscribe(
        &self,
        request: SubscribeRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<(), rmcp::ErrorData> {
        self.subscriptions.subscribe(&request.uri, context.peer);
        Ok(())
    }

    /// Handle a `resources/unsubscribe` request. Clears every subscription
    /// recorded against the URI in this process (see the module-level
    /// docs on [`crate::subscriptions`] for why we don't attempt to match
    /// peers individually).
    async fn unsubscribe(
        &self,
        request: UnsubscribeRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<(), rmcp::ErrorData> {
        self.subscriptions.unsubscribe(&request.uri, &context.peer);
        Ok(())
    }

    /// List MCP resources: the workspace, the tables list, a markdown
    /// readme, and three entries per existing table (schema, JSON sample,
    /// CSV sample). Calling this lazily starts the engine, so it doubles
    /// as a "wake up" signal for MCP clients that pre-fetch resources at
    /// connection time.
    async fn list_resources(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListResourcesResult, rmcp::ErrorData> {
        let mut resources = vec![
            RawResource {
                uri: "hyper://workspace".into(),
                name: "Workspace Info".into(),
                title: Some("Hyper Workspace".into()),
                description: Some("Workspace mode, table count, total rows, disk usage".into()),
                mime_type: Some("application/json".into()),
                size: None,
                icons: None,
                meta: None,
            }
            .no_annotation(),
            RawResource {
                uri: "hyper://tables".into(),
                name: "All Tables".into(),
                title: Some("All Tables".into()),
                description: Some("List of all tables with column schemas and row counts".into()),
                mime_type: Some("application/json".into()),
                size: None,
                icons: None,
                meta: None,
            }
            .no_annotation(),
            RawResource {
                uri: "hyper://readme".into(),
                name: "Workspace Readme".into(),
                title: Some("HyperDB workspace readme".into()),
                description: Some(
                    "Markdown overview of the workspace: tables, row counts, related \
                     resources, and tool hints for LLMs orienting themselves."
                        .into(),
                ),
                mime_type: Some("text/markdown".into()),
                size: None,
                icons: None,
                meta: None,
            }
            .no_annotation(),
        ];

        if let Ok(tables) = self.with_engine(super::engine::Engine::describe_tables) {
            // `describe_tables` already excludes `_hyperdb_*` meta-
            // tables (see `is_internal_table`), so the resource
            // catalog only surfaces user-visible tables.
            for table in tables {
                if let Some(name) = table.get("name").and_then(|v| v.as_str()) {
                    let row_count = table
                        .get("row_count")
                        .and_then(serde_json::Value::as_i64)
                        .unwrap_or(0);
                    resources.push(
                        RawResource {
                            uri: format!("hyper://tables/{name}/schema"),
                            name: format!("Schema of {name}"),
                            title: Some(format!("{name} schema")),
                            description: Some(format!(
                                "Column schema and row count ({row_count} rows) for table '{name}'"
                            )),
                            mime_type: Some("application/json".into()),
                            size: None,
                            icons: None,
                            meta: None,
                        }
                        .no_annotation(),
                    );
                    resources.push(
                        RawResource {
                            uri: format!("hyper://tables/{name}/sample"),
                            name: format!("Sample of {name}"),
                            title: Some(format!("{name} sample (JSON)")),
                            description: Some(format!(
                                "First {TABLE_SAMPLE_ROWS} rows of '{name}' as JSON, with schema"
                            )),
                            mime_type: Some("application/json".into()),
                            size: None,
                            icons: None,
                            meta: None,
                        }
                        .no_annotation(),
                    );
                    resources.push(
                        RawResource {
                            uri: format!("hyper://tables/{name}/csv-sample"),
                            name: format!("CSV sample of {name}"),
                            title: Some(format!("{name} sample (CSV)")),
                            description: Some(format!(
                                "First {TABLE_CSV_SAMPLE_ROWS} rows of '{name}' as CSV"
                            )),
                            mime_type: Some("text/csv".into()),
                            size: None,
                            icons: None,
                            meta: None,
                        }
                        .no_annotation(),
                    );
                }
            }
        }

        let store = Arc::clone(&self.saved_queries);
        if let Ok(saved) = self.with_saved_query_store(|engine| store.list(engine)) {
            for q in saved {
                let desc = q
                    .description
                    .clone()
                    .unwrap_or_else(|| format!("Saved read-only SQL query '{}'", q.name));
                resources.push(
                    RawResource {
                        uri: format!("hyper://queries/{}/definition", q.name),
                        name: format!("Query: {}", q.name),
                        title: Some(format!("{} (definition)", q.name)),
                        description: Some(format!("SQL + metadata for saved query '{}'", q.name)),
                        mime_type: Some("application/json".into()),
                        size: None,
                        icons: None,
                        meta: None,
                    }
                    .no_annotation(),
                );
                resources.push(
                    RawResource {
                        uri: format!("hyper://queries/{}/result", q.name),
                        name: format!("Result: {}", q.name),
                        title: Some(format!("{} (result)", q.name)),
                        description: Some(format!("{desc} — re-runs on every read")),
                        mime_type: Some("application/json".into()),
                        size: None,
                        icons: None,
                        meta: None,
                    }
                    .no_annotation(),
                );
            }
        }

        Ok(ListResourcesResult {
            resources,
            next_cursor: None,
            meta: None,
        })
    }

    /// Advertise URI templates so clients can construct resource URIs for
    /// tables they know about without round-tripping `list_resources`.
    async fn list_resource_templates(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListResourceTemplatesResult, rmcp::ErrorData> {
        let templates = vec![
            RawResourceTemplate {
                uri_template: "hyper://tables/{name}/schema".into(),
                name: "Table Schema".into(),
                title: Some("Table Schema".into()),
                description: Some(
                    "Column schema, types, nullability, and row count for a named table".into(),
                ),
                mime_type: Some("application/json".into()),
                icons: None,
            }
            .no_annotation(),
            RawResourceTemplate {
                uri_template: "hyper://tables/{name}/sample".into(),
                name: "Table Sample (JSON)".into(),
                title: Some("Table Sample".into()),
                description: Some(
                    "First few rows of a named table as JSON, with schema. For a \
                     configurable row count use the `sample` tool instead."
                        .into(),
                ),
                mime_type: Some("application/json".into()),
                icons: None,
            }
            .no_annotation(),
            RawResourceTemplate {
                uri_template: "hyper://tables/{name}/csv-sample".into(),
                name: "Table Sample (CSV)".into(),
                title: Some("Table Sample (CSV)".into()),
                description: Some(
                    "First few rows of a named table as CSV, header-first, for \
                     spreadsheet and Pandas consumers."
                        .into(),
                ),
                mime_type: Some("text/csv".into()),
                icons: None,
            }
            .no_annotation(),
            RawResourceTemplate {
                uri_template: "hyper://queries/{name}/definition".into(),
                name: "Saved Query Definition".into(),
                title: Some("Saved Query Definition".into()),
                description: Some(
                    "Stored SQL plus metadata (description, created_at) for a saved \
                     query registered via the `save_query` tool."
                        .into(),
                ),
                mime_type: Some("application/json".into()),
                icons: None,
            }
            .no_annotation(),
            RawResourceTemplate {
                uri_template: "hyper://queries/{name}/result".into(),
                name: "Saved Query Result".into(),
                title: Some("Saved Query Result".into()),
                description: Some(
                    "Live result of a saved query. The stored SQL re-runs on every \
                     resource read — no caching, always fresh."
                        .into(),
                ),
                mime_type: Some("application/json".into()),
                icons: None,
            }
            .no_annotation(),
        ];
        Ok(ListResourceTemplatesResult {
            resource_templates: templates,
            next_cursor: None,
            meta: None,
        })
    }

    /// Read a resource by URI. Dispatches via
    /// [`HyperMcpServer::resource_body_for_uri`] which returns both the
    /// content and its MIME type (JSON for metadata URIs, markdown for the
    /// workspace readme, CSV for per-table samples).
    async fn read_resource(
        &self,
        request: ReadResourceRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<ReadResourceResult, rmcp::ErrorData> {
        let uri = &request.uri;
        let (mime_type, text) = match self.resource_body_for_uri(uri) {
            Ok(Some(body)) => (body.mime_type().to_string(), body.to_text()),
            Ok(None) => {
                return Err(rmcp::ErrorData::invalid_params(
                    format!("Unknown resource URI: {uri}"),
                    None,
                ));
            }
            Err(e) => {
                // Surface errors as JSON so LLMs can parse `code` / `message` /
                // `suggestion` without needing a separate error channel.
                let err_val = serde_json::to_value(&e).unwrap_or(Value::String(e.to_string()));
                let text =
                    serde_json::to_string_pretty(&json!({ "error": err_val })).unwrap_or_default();
                ("application/json".into(), text)
            }
        };

        Ok(ReadResourceResult::new(vec![
            ResourceContents::TextResourceContents {
                uri: uri.clone(),
                mime_type: Some(mime_type),
                text,
                meta: None,
            },
        ]))
    }
}

/// Validates an `execute` batch up front, before any SQL hits the server.
///
/// Rules:
/// 1. Non-empty array.
/// 2. Each element non-empty and not comment-only after stripping comments.
/// 3. No element is read-only (steer LLMs to the `query` tool).
/// 4. No element is an explicit transaction-control statement
///    (BEGIN / COMMIT / ROLLBACK / SAVEPOINT) — the wrapper manages
///    the transaction.
/// 5. No batch mixes DDL with DML — Hyper aborts mixed transactions with
///    SQLSTATE `0A000`.
/// 6. Multi-element all-DDL batches are rejected because Hyper auto-commits
///    `CREATE` / `DROP` / `ALTER` even inside a transaction, so the
///    "atomic" promise would be a lie.
///
/// `Other`-classified statements (everything not in the explicit
/// DDL / DML / read-only / transaction-control sets) are passed
/// through untouched — Hyper itself is the final authority on syntax,
/// and that includes the "Multi-part queries" / SQLSTATE `0A000`
/// error if a caller smuggles a `;`-separated multi-statement string
/// into a single array element. The `error.rs` mapping rewrites that
/// into an actionable "split into separate array elements" suggestion
/// for the LLM.
fn validate_execute_batch(stmts: &[String]) -> Result<(), McpError> {
    use crate::engine::strip_leading_sql_comments;

    if stmts.is_empty() {
        return Err(McpError::new(
            ErrorCode::InvalidArgument,
            "`sql` must be a non-empty array of SQL statements.",
        )
        .with_suggestion("Pass at least one statement: `sql: [\"INSERT INTO t VALUES (1)\"]`."));
    }

    let mut has_schema_change = false;
    let mut has_data_mutation = false;

    for (idx, stmt) in stmts.iter().enumerate() {
        if strip_leading_sql_comments(stmt).trim().is_empty() {
            return Err(McpError::new(
                ErrorCode::InvalidArgument,
                format!("`sql[{idx}]` is empty or contains only whitespace/comments."),
            )
            .with_suggestion("Remove the empty element or replace it with a real statement."));
        }
        // Classification is comment-aware and only inspects the leading
        // keyword, so it returns a meaningful answer even for input
        // that happens to be multi-statement. We don't try to detect
        // multi-statement input client-side — Hyper's own
        // "Multi-part queries" / SQLSTATE 0A000 error is mapped at
        // [error.rs:130-134] to a clear "split into separate array
        // elements" suggestion, so the LLM gets the same actionable
        // hint after one round-trip.
        match classify_statement(stmt) {
            StatementKind::ReadOnly => {
                return Err(McpError::new(
                    ErrorCode::SqlError,
                    format!(
                        "`sql[{idx}]` is a read-only statement; the `execute` tool is for DDL/DML."
                    ),
                )
                .with_suggestion(
                    "Use the `query` tool for SELECT/WITH/EXPLAIN/SHOW/VALUES. To read-then-write atomically, fold the read into the write (e.g. `UPDATE … FROM (SELECT …)` or `INSERT … SELECT …`).",
                ));
            }
            StatementKind::TransactionControl => {
                // Explicit BEGIN / COMMIT / ROLLBACK / SAVEPOINT inside a
                // batch element would defeat atomicity: the `execute`
                // tool already opens its own transaction around multi-
                // element batches, and a user-issued COMMIT mid-batch
                // would commit early. Reject up front with an
                // actionable message rather than silently breaking the
                // contract.
                return Err(McpError::new(
                    ErrorCode::InvalidArgument,
                    format!(
                        "`sql[{idx}]` is a transaction-control statement (BEGIN / COMMIT / ROLLBACK / SAVEPOINT); these are not allowed in `execute` batches."
                    ),
                )
                .with_suggestion(
                    "The `execute` tool manages the transaction for you — multi-element arrays already run inside BEGIN/COMMIT. Just pass the DML statements you want to run atomically.",
                ));
            }
            StatementKind::Ddl => has_schema_change = true,
            StatementKind::Dml => has_data_mutation = true,
            StatementKind::Other => {}
        }
    }

    if has_schema_change && has_data_mutation {
        return Err(McpError::new(
            ErrorCode::InvalidArgument,
            "Cannot mix DDL (CREATE/DROP/ALTER/TRUNCATE/RENAME) with DML (INSERT/UPDATE/DELETE/COPY/MERGE) in one `execute` batch.",
        )
        .with_suggestion(
            "Hyper aborts such transactions with SQLSTATE 0A000. Issue DDL in a separate `execute` call from DML — DDL singletons run as their own auto-commit unit.",
        ));
    }

    if has_schema_change && stmts.len() > 1 {
        return Err(McpError::new(
            ErrorCode::InvalidArgument,
            "Multi-statement DDL batches are not supported.",
        )
        .with_suggestion(
            "Hyper auto-commits CREATE/DROP/ALTER even inside a transaction, so wrapping multiple DDL statements in one `execute` call cannot guarantee atomicity. Issue each DDL as its own single-element `execute` call.",
        ));
    }

    Ok(())
}

/// Render a JSON cell value into a CSV string. Scalars are emitted in their
/// natural form (numbers as `to_string`, booleans as `true` / `false`,
/// strings verbatim); objects and arrays are re-encoded as compact JSON so
/// the CSV round-trips through re-parsing if needed. `null` becomes the
/// empty string, matching typical spreadsheet conventions.
fn value_to_csv_cell(v: &Value) -> String {
    match v {
        Value::Null => String::new(),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => n.to_string(),
        Value::String(s) => s.clone(),
        _ => v.to_string(),
    }
}

/// Heuristic format detection for inline data: if it starts with `[` or `{`
/// it's JSON, otherwise CSV. Used when the caller omits the `format` parameter.
fn detect_format(data: &str) -> String {
    let trimmed = data.trim_start();
    if trimmed.starts_with('[') || trimmed.starts_with('{') {
        "json".into()
    } else {
        "csv".into()
    }
}

/// Generate a nanosecond-based suffix to make temp table names unique within
/// a session. Not cryptographically random — collisions are astronomically
/// unlikely for sequential tool calls.
fn rand_suffix() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let t = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();
    format!("{}", t.as_nanos() % 1_000_000_000)
}

/// Build a fully-qualified `"db"."schema"."table"` name. `db` is the
/// target alias; `None` means "the primary workspace", which resolves
/// via [`Engine::primary_db_name`]. The `public` schema is assumed
/// because every tool in this crate materializes into `public`.
///
/// Note: while `AttachRegistry` now pins `schema_search_path` to the
/// primary on every attach (so unqualified local writes succeed too),
/// the `copy_query` path still fully-qualifies the target so that
/// switching the target to an attached alias requires no SQL
/// rewriting — one code path covers local and remote targets.
fn qualified_name(engine: &Engine, db: Option<&str>, table: &str) -> String {
    let alias = db.map_or_else(|| engine.primary_db_name(), str::to_string);
    let escaped_alias = alias.replace('"', "\"\"");
    let escaped_table = table.replace('"', "\"\"");
    format!("\"{escaped_alias}\".\"public\".\"{escaped_table}\"")
}

/// `true` if the target resolves to an existing relation, `false` if
/// Hyper reports it as missing, `Err` on any other failure. Uses a
/// `LIMIT 0` probe rather than a catalog lookup because attached
/// databases aren't surfaced by [`Engine::describe_tables`].
fn target_exists(engine: &Engine, db: Option<&str>, table: &str) -> Result<bool, McpError> {
    let sql = format!(
        "SELECT 1 FROM {} LIMIT 0",
        qualified_name(engine, db, table)
    );
    match engine.execute_query_to_json(&sql) {
        Ok(_) => Ok(true),
        Err(e) => {
            let m = e.message.to_lowercase();
            let missing = m.contains("does not exist")
                || m.contains("undefined table")
                || e.message.contains("42P01");
            if missing {
                Ok(false)
            } else {
                Err(e)
            }
        }
    }
}

/// Fetch `COUNT(*)` against the fully-qualified target. Returns 0 if
/// the query fails (e.g. after a catalog-invalidation quirk) so the
/// tool still returns a result — the caller cares that the copy
/// succeeded, not about bookkeeping fidelity.
fn count_rows(engine: &Engine, db: Option<&str>, table: &str) -> i64 {
    let sql = format!(
        "SELECT COUNT(*) AS cnt FROM {}",
        qualified_name(engine, db, table)
    );
    engine
        .execute_query_to_json(&sql)
        .ok()
        .and_then(|rows| {
            rows.first()
                .and_then(|r| r.get("cnt").and_then(serde_json::Value::as_i64))
        })
        .unwrap_or(0)
}

/// Best-effort probe for public-schema tables visible under an alias.
/// Returns `Value::Null` on any error so the LLM sees "not available"
/// rather than a fabricated zero.
fn probe_table_count(engine: &Engine, alias: &str) -> Value {
    let escaped_alias = alias.replace('"', "\"\"");
    let sql = format!(
        "SELECT COUNT(*) AS cnt FROM \"{escaped_alias}\".pg_catalog.pg_tables WHERE schemaname = 'public'"
    );
    match engine.execute_query_to_json(&sql) {
        Ok(rows) => rows
            .first()
            .and_then(|r| r.get("cnt").and_then(serde_json::Value::as_i64))
            .map_or(Value::Null, |n| json!(n)),
        Err(_) => Value::Null,
    }
}

/// Validate and convert `copy_query`'s `temp_attach` specs into
/// [`AttachRequest`]s. Runs entirely up front (no engine touching)
/// so a bad alias or path aborts cleanly before any ATTACH is issued.
fn prepare_temp_attachments(
    specs: &[AttachSpec],
    read_only: bool,
) -> Result<Vec<AttachRequest>, McpError> {
    let mut out = Vec::with_capacity(specs.len());
    for spec in specs {
        let writable = spec.writable.unwrap_or(false);
        if writable && read_only {
            return Err(McpError::new(
                ErrorCode::ReadOnlyViolation,
                format!(
                    "temp_attach for alias '{}' requested writable:true but the server is --read-only",
                    spec.alias
                ),
            ));
        }
        let on_missing = attach::OnMissing::parse(spec.on_missing.as_deref())?;
        if on_missing == attach::OnMissing::Create && !writable {
            return Err(McpError::new(
                ErrorCode::InvalidArgument,
                format!(
                    "temp_attach alias '{}' has on_missing='create' but writable is not true — \
                     an empty .hyper file that cannot be written to cannot be populated.",
                    spec.alias
                ),
            ));
        }
        let source = match spec.kind.as_str() {
            "local_file" => {
                let Some(raw) = spec.path.as_deref() else {
                    return Err(McpError::new(
                        ErrorCode::InvalidArgument,
                        format!("temp_attach alias '{}' requires a 'path'", spec.alias),
                    ));
                };
                let resolved = match on_missing {
                    attach::OnMissing::Error => attach::validate_local_path(raw)?,
                    attach::OnMissing::Create => attach::validate_local_path_for_create(raw)?,
                };
                AttachSource::LocalFile { path: resolved }
            }
            other => {
                return Err(McpError::new(
                    ErrorCode::InvalidArgument,
                    format!(
                        "Unsupported temp_attach kind '{other}' for alias '{}'. Only 'local_file' is supported today.",
                        spec.alias
                    ),
                ));
            }
        };
        attach::validate_alias(&spec.alias)?;
        out.push(AttachRequest {
            alias: spec.alias.clone(),
            source,
            writable,
            on_missing,
        });
    }
    Ok(out)
}

/// Execute the chosen copy mode against the fully-qualified target
/// and return a JSON summary. Extracted from the `copy_query` handler
/// so the caller can run it inside the temp-attach cleanup wrapper
/// without re-duplicating the match arms.
fn perform_copy(
    engine: &Engine,
    mode: &str,
    target_db: Option<&str>,
    target_table: &str,
    sql_body: &str,
) -> Result<Value, McpError> {
    let qualified = qualified_name(engine, target_db, target_table);
    let exists = target_exists(engine, target_db, target_table)?;
    let timer = crate::stats::StatsTimer::start();

    match mode {
        "create" => {
            if exists {
                return Err(McpError::new(
                    ErrorCode::InvalidArgument,
                    format!(
                        "Target '{target_table}' already exists. Use mode='append' to add rows or mode='replace' to drop and recreate."
                    ),
                ));
            }
            engine.execute_command(&format!("CREATE TABLE {qualified} AS {sql_body}"))?;
        }
        "append" => {
            if !exists {
                return Err(McpError::new(
                    ErrorCode::InvalidArgument,
                    format!(
                        "Target '{target_table}' does not exist. Use mode='create' to create it from the query or mode='replace' to drop and recreate."
                    ),
                ));
            }
            engine.execute_command(&format!("INSERT INTO {qualified} {sql_body}"))?;
        }
        "replace" => {
            // Hyper auto-commits DDL even inside transactions, so
            // DROP+CREATE isn't atomic across the statement boundary
            // (same caveat documented on `execute_in_transaction`).
            // We still issue them in order — the `IF EXISTS` guard
            // prevents an error when the target is absent, and the
            // follow-up `CREATE TABLE AS` either succeeds or leaves
            // the workspace with a dropped target, which is the
            // expected replace semantics.
            engine.execute_command(&format!("DROP TABLE IF EXISTS {qualified}"))?;
            engine.execute_command(&format!("CREATE TABLE {qualified} AS {sql_body}"))?;
        }
        other => {
            return Err(McpError::new(
                ErrorCode::InvalidArgument,
                format!("copy_query mode '{other}' is not supported"),
            ));
        }
    }

    let elapsed_ms = timer.elapsed_ms();
    let row_count = count_rows(engine, target_db, target_table);
    Ok(json!({
        "target_table": target_table,
        "target_database": target_db.unwrap_or(LOCAL_ALIAS),
        "mode": mode,
        "row_count": row_count,
        "stats": { "operation": "copy_query", "elapsed_ms": elapsed_ms },
    }))
}

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

    fn s(v: &[&str]) -> Vec<String> {
        v.iter().map(|x| (*x).to_string()).collect()
    }

    #[test]
    fn rejects_empty_array() {
        let err = validate_execute_batch(&[]).unwrap_err();
        assert_eq!(err.code, ErrorCode::InvalidArgument);
    }

    #[test]
    fn rejects_whitespace_only_element() {
        let err = validate_execute_batch(&s(&["   "])).unwrap_err();
        assert_eq!(err.code, ErrorCode::InvalidArgument);
        assert!(err.message.contains("sql[0]"));
        let err = validate_execute_batch(&s(&["INSERT INTO t VALUES (1)", "/* */"])).unwrap_err();
        assert!(err.message.contains("sql[1]"));
    }

    #[test]
    fn rejects_read_only_element() {
        let err =
            validate_execute_batch(&s(&["INSERT INTO t VALUES (1)", "SELECT 1"])).unwrap_err();
        assert_eq!(err.code, ErrorCode::SqlError);
        assert!(err.message.contains("sql[1]"));
    }

    #[test]
    fn rejects_transaction_control_in_batch() {
        // The wrapper manages the transaction; a user-issued COMMIT
        // mid-batch would commit early and break atomicity.
        for sql in [
            "BEGIN",
            "COMMIT",
            "ROLLBACK",
            "SAVEPOINT sp1",
            "START TRANSACTION",
            "END",
            "RELEASE SAVEPOINT sp1",
        ] {
            let err = validate_execute_batch(&s(&["INSERT INTO t VALUES (1)", sql])).unwrap_err();
            assert_eq!(err.code, ErrorCode::InvalidArgument, "for `{sql}`");
            assert!(
                err.message.contains("transaction-control"),
                "for `{sql}`: {}",
                err.message
            );
        }
    }

    #[test]
    fn rejects_transaction_control_singleton() {
        // Even a one-element BEGIN-only call is rejected — there's no
        // statement following it that could benefit, and the BEGIN
        // would leave the connection in an open-transaction state for
        // the next caller to inherit.
        let err = validate_execute_batch(&s(&["BEGIN"])).unwrap_err();
        assert_eq!(err.code, ErrorCode::InvalidArgument);
    }

    #[test]
    fn rejects_ddl_dml_mix() {
        let err =
            validate_execute_batch(&s(&["CREATE TABLE x (i INT)", "INSERT INTO x VALUES (1)"]))
                .unwrap_err();
        assert_eq!(err.code, ErrorCode::InvalidArgument);
        assert!(err.message.contains("DDL"));
    }

    #[test]
    fn rejects_multi_ddl() {
        let err = validate_execute_batch(&s(&["CREATE TABLE a (i INT)", "CREATE TABLE b (j INT)"]))
            .unwrap_err();
        assert_eq!(err.code, ErrorCode::InvalidArgument);
        assert!(err.message.contains("Multi-statement DDL"));
    }

    #[test]
    fn allows_single_ddl() {
        validate_execute_batch(&s(&["CREATE TABLE a (i INT)"])).unwrap();
    }

    #[test]
    fn allows_multi_dml() {
        validate_execute_batch(&s(&[
            "UPDATE settings SET value = 'x' WHERE key = 'k'",
            "INSERT INTO settings (key, value) SELECT 'k', 'x' WHERE NOT EXISTS (SELECT 1 FROM settings WHERE key = 'k')",
        ]))
        .unwrap();
    }

    #[test]
    fn allows_other_kinds() {
        // Non-classified statements (e.g. SET, ATTACH) pass through.
        // Transaction-control keywords are NOT in this group — see
        // `rejects_transaction_control_*` tests.
        validate_execute_batch(&s(&["SET schema_search_path = 'mydb'"])).unwrap();
    }

    #[test]
    fn allows_trailing_semicolon() {
        validate_execute_batch(&s(&["INSERT INTO t VALUES (1);"])).unwrap();
    }
}