surql-mcp 0.1.1

MCP server for SurrealQL — interactive query playground with embedded SurrealDB
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
use rmcp::{
	handler::server::wrapper::Parameters,
	model::{CallToolResult, Content, Implementation, ServerCapabilities, ServerInfo},
	schemars, tool, tool_handler, tool_router,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use surrealdb::{Surreal, engine::local::Mem};
use tokio::sync::RwLock;

pub(crate) mod file_ops;
pub(crate) mod validation;

use file_ops::categorize_files;
pub use file_ops::inject_overwrite;
#[cfg(test)]
pub(crate) use file_ops::{FileCategory, classify_file};
pub(crate) use validation::error_result;
use validation::{is_valid_surql_identifier, validate_path_against};

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct ExecArgs {
	#[schemars(description = "SurrealQL query to run")]
	pub query: String,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct LoadProjectArgs {
	#[schemars(description = "Path to directory containing .surql files")]
	pub path: String,
	#[schemars(description = "Reset database before loading (default: true)")]
	pub clean: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct LoadFileArgs {
	#[schemars(description = "Path to a single .surql file to run")]
	pub path: String,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct DescribeArgs {
	#[schemars(description = "Table name to describe")]
	pub table: String,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct ManifestArgs {
	#[schemars(description = "Path to directory containing manifest.toml (overshift project)")]
	pub path: String,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct CompareArgs {
	#[schemars(
		description = "JSON string from INFO FOR DB on the target database (expected state)"
	)]
	pub expected_json: String,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct VerifyArgs {
	#[schemars(
		description = "Path to overshift project directory containing manifest.toml. \
			Loads the manifest, applies schema+migrations to both the playground and a \
			fresh shadow DB, then compares INFO FOR DB from both to detect drift."
	)]
	pub path: String,
	#[schemars(
		description = "Read-only mode: only build shadow DB and compare with playground, \
			do NOT apply anything to the playground. Use to safely verify without writes."
	)]
	pub verify_only: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct RollbackArgs {
	#[schemars(description = "Path to directory containing manifest.toml (overshift project)")]
	pub path: String,
	#[schemars(
		description = "Target version to roll back to (migrations above this version are reversed)"
	)]
	pub target_version: u32,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct CheckArgs {
	#[schemars(description = "Path to a .surql file or directory containing .surql files")]
	pub path: String,
	#[schemars(description = "Recurse into subdirectories (default: true)")]
	pub recursive: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct GraphAffectedArgs {
	#[schemars(description = "Table name to check for reverse dependencies")]
	pub table: String,
	#[schemars(
		description = "Path to directory containing .surql files (required for static analysis)"
	)]
	pub schema_path: String,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct GraphTraverseArgs {
	#[schemars(description = "Starting table name")]
	pub table: String,
	#[schemars(
		description = "Path to directory containing .surql files (required for static analysis)"
	)]
	pub schema_path: String,
	#[schemars(description = "Maximum traversal depth (default: 10)")]
	pub depth: Option<u32>,
	#[schemars(description = "Traversal direction: 'forward' (default) or 'reverse'")]
	pub direction: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct GraphSiblingsArgs {
	#[schemars(description = "Table name to find siblings for")]
	pub table: String,
	#[schemars(
		description = "Path to directory containing .surql files (required for static analysis)"
	)]
	pub schema_path: String,
}

#[derive(Clone)]
pub struct SurqlMcp {
	db: Arc<RwLock<Surreal<surrealdb::engine::local::Db>>>,
	query_count: Arc<AtomicU64>,
	workspace_root: Arc<PathBuf>,
	tool_router: rmcp::handler::server::router::tool::ToolRouter<Self>,
}

const QUERY_WARNING_THRESHOLDS: &[u64] = &[1000, 5000, 10000];

#[tool_router]
impl SurqlMcp {
	pub async fn new() -> anyhow::Result<Self> {
		let cwd = std::env::current_dir()?;
		Self::with_workspace_root(cwd).await
	}

	pub async fn with_workspace_root(root: PathBuf) -> anyhow::Result<Self> {
		let db = Surreal::new::<Mem>(()).await?;
		db.use_ns("default").use_db("default").await?;
		tracing::info!("SurrealDB playground started (root: {})", root.display());
		Ok(Self {
			db: Arc::new(RwLock::new(db)),
			query_count: Arc::new(AtomicU64::new(0)),
			workspace_root: Arc::new(root),
			tool_router: Self::tool_router(),
		})
	}

	fn increment_query_count(&self) {
		let count = self.query_count.fetch_add(1, Ordering::Relaxed) + 1;
		if QUERY_WARNING_THRESHOLDS.contains(&count) {
			tracing::warn!(
				"In-memory DB has processed {count} queries — \
				 consider resetting with the 'reset' tool if performance degrades"
			);
		}
	}

	#[tool(
		name = "exec",
		description = "Run a SurrealQL query and return the result as JSON"
	)]
	pub async fn run_query(
		&self,
		Parameters(args): Parameters<ExecArgs>,
	) -> Result<CallToolResult, rmcp::ErrorData> {
		self.increment_query_count();
		let db = self.db.read().await;
		match db.query(&args.query).await {
			Ok(response) => match response.check() {
				Ok(mut checked) => {
					let result: Result<Vec<serde_json::Value>, _> = checked.take(0);
					match result {
						Ok(rows) => {
							let json = serde_json::to_string_pretty(&rows)
								.unwrap_or_else(|_| "[]".to_string());
							let summary = if rows.is_empty() {
								"(empty result)".to_string()
							} else {
								format!(
									"{} row{}",
									rows.len(),
									if rows.len() == 1 { "" } else { "s" }
								)
							};
							Ok(CallToolResult::success(vec![Content::text(format!(
								"{summary}\n\n```json\n{json}\n```"
							))]))
						}
						Err(e) => Ok(CallToolResult::success(vec![Content::text(format!(
							"Query ran but result extraction failed: {e}"
						))])),
					}
				}
				Err(e) => error_result(format!("Query error: {e}")),
			},
			Err(e) => error_result(format!("Query failed: {e}")),
		}
	}

	#[tool(
		name = "load_project",
		description = "Load .surql files from a directory into the database. Resets DB first \
			by default. Files are categorized by directory: schema/ files get OVERWRITE \
			injected, migrations/ run in version order, examples/ errors are warnings."
	)]
	pub async fn load_project(
		&self,
		Parameters(args): Parameters<LoadProjectArgs>,
	) -> Result<CallToolResult, rmcp::ErrorData> {
		let dir = match validate_path_against(&args.path, &self.workspace_root) {
			Ok(p) => p,
			Err(e) => return error_result(e),
		};
		if !dir.is_dir() {
			return error_result(format!("Not a directory: {}", args.path));
		}

		let clean = args.clean.unwrap_or(true);
		if clean {
			let db = self.db.read().await;
			// Reset to known state: switch to default NS/DB first, then remove the database
			if let Err(e) = db.use_ns("default").use_db("default").await {
				return error_result(format!("Failed to reset namespace: {e}"));
			}
			db.query("REMOVE DATABASE IF EXISTS default").await.ok();
			// Re-create the default database after removal
			if let Err(e) = db.use_ns("default").use_db("default").await {
				return error_result(format!("Failed to re-create default database: {e}"));
			}
		}

		let mut surql_files = Vec::new();
		surql_parser::collect_surql_files(&dir, &mut surql_files);

		if surql_files.is_empty() {
			return Ok(CallToolResult::success(vec![Content::text(
				"No .surql files found",
			)]));
		}

		let categorized = categorize_files(&surql_files);

		let db = self.db.read().await;
		let mut schema_count = 0usize;
		let mut migration_count = 0usize;
		let mut function_count = 0usize;
		let mut example_count = 0usize;
		let mut errors = Vec::new();
		let mut warnings = Vec::new();

		// 1. Schema files (with OVERWRITE injection)
		for path in &categorized.schema {
			let content = match surql_parser::read_surql_file(path) {
				Ok(c) => inject_overwrite(&c),
				Err(e) => {
					errors.push(e);
					continue;
				}
			};
			match db.query(&content).await {
				Ok(response) => match response.check() {
					Ok(_) => schema_count += 1,
					Err(e) => errors.push(format!("{}: {e}", path.display())),
				},
				Err(e) => errors.push(format!("{}: {e}", path.display())),
			}
		}

		// 2. Function files (with OVERWRITE injection)
		for path in &categorized.functions {
			let content = match surql_parser::read_surql_file(path) {
				Ok(c) => inject_overwrite(&c),
				Err(e) => {
					errors.push(e);
					continue;
				}
			};
			match db.query(&content).await {
				Ok(response) => match response.check() {
					Ok(_) => function_count += 1,
					Err(e) => errors.push(format!("{}: {e}", path.display())),
				},
				Err(e) => errors.push(format!("{}: {e}", path.display())),
			}
		}

		// 3. Migration files (in version order, one-shot)
		let mut migrations = categorized.migrations.clone();
		migrations.sort();
		for path in &migrations {
			let content = match surql_parser::read_surql_file(path) {
				Ok(c) => c,
				Err(e) => {
					errors.push(e);
					continue;
				}
			};
			match db.query(&content).await {
				Ok(response) => match response.check() {
					Ok(_) => migration_count += 1,
					Err(e) => errors.push(format!("{}: {e}", path.display())),
				},
				Err(e) => errors.push(format!("{}: {e}", path.display())),
			}
		}

		// 4. General files
		for path in &categorized.general {
			let content = match surql_parser::read_surql_file(path) {
				Ok(c) => c,
				Err(e) => {
					errors.push(e);
					continue;
				}
			};
			match db.query(&content).await {
				Ok(response) => match response.check() {
					Ok(_) => {}
					Err(e) => errors.push(format!("{}: {e}", path.display())),
				},
				Err(e) => errors.push(format!("{}: {e}", path.display())),
			}
		}

		// 5. Example files (errors become warnings)
		for path in &categorized.examples {
			let content = match surql_parser::read_surql_file(path) {
				Ok(c) => c,
				Err(e) => {
					warnings.push(e);
					continue;
				}
			};
			match db.query(&content).await {
				Ok(response) => match response.check() {
					Ok(_) => example_count += 1,
					Err(e) => {
						warnings.push(format!("{}: {e}", path.display()));
					}
				},
				Err(e) => {
					warnings.push(format!("{}: {e}", path.display()));
				}
			}
		}

		let mut output = format!(
			"Loaded {} schema, {} migrations, {} functions, {} examples ({} warnings) from `{}`{}",
			schema_count,
			migration_count,
			function_count,
			example_count,
			warnings.len(),
			args.path,
			if clean { " (clean)" } else { "" }
		);
		if !errors.is_empty() {
			output.push_str(&format!(
				"\n\n**Errors ({}):**\n{}",
				errors.len(),
				errors.join("\n")
			));
		}
		if !warnings.is_empty() {
			output.push_str(&format!(
				"\n\n**Warnings ({}):**\n{}",
				warnings.len(),
				warnings.join("\n")
			));
		}
		Ok(CallToolResult::success(vec![Content::text(output)]))
	}

	#[tool(
		name = "load_file",
		description = "Run a single .surql file against the database"
	)]
	pub async fn load_file(
		&self,
		Parameters(args): Parameters<LoadFileArgs>,
	) -> Result<CallToolResult, rmcp::ErrorData> {
		self.increment_query_count();
		let path = match validate_path_against(&args.path, &self.workspace_root) {
			Ok(p) => p,
			Err(e) => return error_result(e),
		};
		let content = match surql_parser::read_surql_file(&path) {
			Ok(c) => c,
			Err(e) => return error_result(e),
		};
		let db = self.db.read().await;
		match db.query(&content).await {
			Ok(response) => match response.check() {
				Ok(_) => Ok(CallToolResult::success(vec![Content::text(format!(
					"Applied `{}`",
					path.file_name()
						.and_then(|n| n.to_str())
						.unwrap_or(&args.path)
				))])),
				Err(e) => error_result(format!("{e}")),
			},
			Err(e) => error_result(format!("{e}")),
		}
	}

	#[tool(
		name = "schema",
		description = "Show all tables, fields, indexes, and events in the current database"
	)]
	pub async fn schema(&self) -> Result<CallToolResult, rmcp::ErrorData> {
		let db = self.db.read().await;
		let mut response = match db.query("INFO FOR DB").await {
			Ok(r) => r,
			Err(e) => return error_result(format!("Failed: {e}")),
		};
		let info: Result<Option<serde_json::Value>, _> = response.take(0);
		match info {
			Ok(Some(val)) => {
				let json = serde_json::to_string_pretty(&val).unwrap_or_else(|_| "{}".to_string());
				Ok(CallToolResult::success(vec![Content::text(format!(
					"```json\n{json}\n```"
				))]))
			}
			Ok(None) => Ok(CallToolResult::success(vec![Content::text(
				"(empty database)",
			)])),
			Err(e) => error_result(format!("Failed to read schema: {e}")),
		}
	}

	#[tool(
		name = "describe",
		description = "Show detailed info about a specific table (fields, indexes, events)"
	)]
	pub async fn describe(
		&self,
		Parameters(args): Parameters<DescribeArgs>,
	) -> Result<CallToolResult, rmcp::ErrorData> {
		if args.table.contains('`') {
			return error_result("Table name must not contain backticks".into());
		}
		if !is_valid_surql_identifier(&args.table) {
			return error_result(format!("Invalid table name: {}", args.table));
		}
		let db = self.db.read().await;
		let query = format!("INFO FOR TABLE `{}`", args.table);
		let mut response = match db.query(&query).await {
			Ok(r) => r,
			Err(e) => return error_result(format!("Failed: {e}")),
		};
		let info: Result<Option<serde_json::Value>, _> = response.take(0);
		match info {
			Ok(Some(val)) => {
				let json = serde_json::to_string_pretty(&val).unwrap_or_else(|_| "{}".to_string());
				Ok(CallToolResult::success(vec![Content::text(format!(
					"**Table `{}`**\n\n```json\n{json}\n```",
					args.table
				))]))
			}
			Ok(None) => error_result(format!("Table '{}' not found", args.table)),
			Err(e) => error_result(format!("Failed: {e}")),
		}
	}

	#[tool(
		name = "manifest",
		description = "Read an overshift manifest.toml and show project configuration \
			(namespace, database, modules, migrations)"
	)]
	pub async fn manifest(
		&self,
		Parameters(args): Parameters<ManifestArgs>,
	) -> Result<CallToolResult, rmcp::ErrorData> {
		let validated = match validate_path_against(&args.path, &self.workspace_root) {
			Ok(p) => p,
			Err(e) => return error_result(e),
		};
		let manifest = match overshift::Manifest::load(&validated) {
			Ok(m) => m,
			Err(e) => return error_result(format!("Cannot load manifest: {e}")),
		};

		let mut output = format!(
			"**overshift manifest** from `{}`\n\n\
			 - **Namespace:** `{}`\n\
			 - **Database:** `{}`\n\
			 - **System DB:** `{}`\n",
			args.path, manifest.meta.ns, manifest.meta.db, manifest.meta.system_db
		);
		if let Some(ver) = &manifest.meta.surrealdb {
			output.push_str(&format!("- **SurrealDB:** `{ver}`\n"));
		}

		if !manifest.modules.is_empty() {
			output.push_str(&format!("\n**{} module(s):**\n", manifest.modules.len()));
			for m in &manifest.modules {
				let deps = if m.depends_on.is_empty() {
					String::new()
				} else {
					format!(" (depends: {})", m.depends_on.join(", "))
				};
				output.push_str(&format!("- `{}` \u{2192} `{}`{deps}\n", m.name, m.path));
			}
		}

		// Discover migrations via overshift
		let migrations = overshift::migration::discover_migrations(
			manifest.root_path().unwrap_or(std::path::Path::new(".")),
		);
		match migrations {
			Ok(migs) if !migs.is_empty() => {
				output.push_str(&format!("\n**{} migration(s):**\n", migs.len()));
				for m in &migs {
					output.push_str(&format!("- `{}` ({})\n", m.name, &m.checksum[..8]));
				}
			}
			_ => {}
		}

		Ok(CallToolResult::success(vec![Content::text(output)]))
	}

	#[tool(
		name = "load_manifest",
		description = "Load an overshift project into the playground DB: applies schema \
			modules then migrations in order"
	)]
	pub async fn load_manifest(
		&self,
		Parameters(args): Parameters<ManifestArgs>,
	) -> Result<CallToolResult, rmcp::ErrorData> {
		let validated = match validate_path_against(&args.path, &self.workspace_root) {
			Ok(p) => p,
			Err(e) => return error_result(e),
		};
		let manifest = match overshift::Manifest::load(&validated) {
			Ok(m) => m,
			Err(e) => return error_result(format!("Cannot load manifest: {e}")),
		};

		// Reset DB
		let db = self.db.read().await;
		// REMOVE DATABASE may fail if it doesn't exist yet -- safe to ignore
		db.query("REMOVE DATABASE default").await.ok();
		if let Err(e) = db.use_ns(&manifest.meta.ns).use_db(&manifest.meta.db).await {
			return error_result(format!(
				"Failed to switch to NS={}/DB={}: {e}",
				manifest.meta.ns, manifest.meta.db
			));
		}

		let mut applied = 0;
		let mut errors = Vec::new();

		// Apply schema modules first
		let modules = match overshift::schema::load_schema_modules(&manifest) {
			Ok(m) => m,
			Err(e) => return error_result(format!("Failed to load schema modules: {e}")),
		};
		for module in &modules {
			match db.query(&module.content).await {
				Ok(r) => match r.check() {
					Ok(_) => applied += 1,
					Err(e) => errors.push(format!("schema/{}: {e}", module.name)),
				},
				Err(e) => errors.push(format!("schema/{}: {e}", module.name)),
			}
		}

		// Then migrations
		let migrations = match overshift::migration::discover_migrations(
			manifest.root_path().unwrap_or(std::path::Path::new(".")),
		) {
			Ok(m) => m,
			Err(e) => return error_result(format!("Failed to discover migrations: {e}")),
		};
		for mig in &migrations {
			match db.query(mig.content.as_str()).await {
				Ok(r) => match r.check() {
					Ok(_) => applied += 1,
					Err(e) => errors.push(format!("{}: {e}", mig.name)),
				},
				Err(e) => errors.push(format!("{}: {e}", mig.name)),
			}
		}

		let mut output = format!(
			"Loaded overshift project `{}` (NS={}, DB={})\n\
			 {} schema module(s) + {} migration(s) = {applied} applied",
			args.path,
			manifest.meta.ns,
			manifest.meta.db,
			modules.len(),
			migrations.len()
		);
		if !errors.is_empty() {
			output.push_str(&format!(
				"\n\n**Errors ({}):**\n{}",
				errors.len(),
				errors.join("\n")
			));
		}
		Ok(CallToolResult::success(vec![Content::text(output)]))
	}

	#[tool(
		name = "compare",
		description = "Compare the playground DB schema against an expected INFO FOR DB \
			JSON response. Returns a diff of missing/extra tables and functions."
	)]
	pub async fn compare(
		&self,
		Parameters(args): Parameters<CompareArgs>,
	) -> Result<CallToolResult, rmcp::ErrorData> {
		let expected: serde_json::Value = match serde_json::from_str(&args.expected_json) {
			Ok(v) => v,
			Err(e) => return error_result(format!("Invalid expected_json: {e}")),
		};

		let db = self.db.read().await;
		let mut response = match db.query("INFO FOR DB").await {
			Ok(r) => r,
			Err(e) => return error_result(format!("Failed to query playground: {e}")),
		};
		let actual: Option<serde_json::Value> = match response.take(0) {
			Ok(v) => v,
			Err(e) => return error_result(format!("Failed to read playground schema: {e}")),
		};
		let actual = match actual {
			Some(v) => v,
			None => return error_result("INFO FOR DB returned no data".into()),
		};

		let diff = overshift::validate::compare_db_info(&expected, &actual);
		let output = diff.to_string();
		Ok(CallToolResult::success(vec![Content::text(output)]))
	}

	#[tool(
		name = "verify",
		description = "Verify an overshift project by applying it to both the playground \
			DB and a fresh shadow in-memory DB, then comparing their schemas via INFO FOR \
			DB. Detects drift between the two environments."
	)]
	pub async fn verify(
		&self,
		Parameters(args): Parameters<VerifyArgs>,
	) -> Result<CallToolResult, rmcp::ErrorData> {
		let validated = match validate_path_against(&args.path, &self.workspace_root) {
			Ok(p) => p,
			Err(e) => return error_result(e),
		};
		let manifest = match overshift::Manifest::load(&validated) {
			Ok(m) => m,
			Err(e) => return error_result(format!("Cannot load manifest: {e}")),
		};

		let modules = match overshift::schema::load_schema_modules(&manifest) {
			Ok(m) => m,
			Err(e) => return error_result(format!("Failed to load schema modules: {e}")),
		};

		let migrations = match overshift::migration::discover_migrations(
			manifest.root_path().unwrap_or(std::path::Path::new(".")),
		) {
			Ok(m) => m,
			Err(e) => return error_result(format!("Failed to discover migrations: {e}")),
		};

		let verify_only = args.verify_only.unwrap_or(false);

		// Apply to playground DB (skip in verify-only mode)
		if !verify_only {
			if !is_valid_surql_identifier(&manifest.meta.ns)
				|| !is_valid_surql_identifier(&manifest.meta.db)
			{
				return error_result(format!(
					"Invalid NS/DB in manifest: NS={}, DB={}",
					manifest.meta.ns, manifest.meta.db
				));
			}
			let db = self.db.read().await;
			if let Err(e) = db.use_ns(&manifest.meta.ns).use_db("default").await {
				return error_result(format!("Failed to switch to NS={}: {e}", manifest.meta.ns));
			}
			db.query(format!(
				"REMOVE DATABASE IF EXISTS `{}`",
				manifest.meta.db.replace('`', "")
			))
			.await
			.ok();
			if let Err(e) = db.use_ns(&manifest.meta.ns).use_db(&manifest.meta.db).await {
				return error_result(format!(
					"Failed to switch playground to NS={}/DB={}: {e}",
					manifest.meta.ns, manifest.meta.db
				));
			}

			for module in &modules {
				if let Err(e) = db.query(&module.content).await.and_then(|r| r.check()) {
					return error_result(format!(
						"Playground: schema module '{}' failed: {e}",
						module.name
					));
				}
			}
			for mig in &migrations {
				if let Err(e) = db.query(mig.content.as_str()).await.and_then(|r| r.check()) {
					return error_result(format!(
						"Playground: migration '{}' failed: {e}",
						mig.name
					));
				}
			}
		}

		// Create shadow in-memory DB and apply the same project
		let shadow_db = match Surreal::new::<Mem>(()).await {
			Ok(db) => db,
			Err(e) => return error_result(format!("Failed to create shadow DB: {e}")),
		};
		if let Err(e) = shadow_db
			.use_ns(&manifest.meta.ns)
			.use_db(&manifest.meta.db)
			.await
		{
			return error_result(format!(
				"Failed to switch shadow to NS={}/DB={}: {e}",
				manifest.meta.ns, manifest.meta.db
			));
		}

		for module in &modules {
			if let Err(e) = shadow_db
				.query(&module.content)
				.await
				.and_then(|r| r.check())
			{
				return error_result(format!(
					"Shadow: schema module '{}' failed: {e}",
					module.name
				));
			}
		}
		for mig in &migrations {
			if let Err(e) = shadow_db
				.query(mig.content.as_str())
				.await
				.and_then(|r| r.check())
			{
				return error_result(format!("Shadow: migration '{}' failed: {e}", mig.name));
			}
		}

		if verify_only {
			let shadow_info = {
				let mut resp = match shadow_db.query("INFO FOR DB").await {
					Ok(r) => r,
					Err(e) => {
						return error_result(format!("Failed to query shadow INFO FOR DB: {e}"));
					}
				};
				let val: Option<serde_json::Value> = match resp.take(0) {
					Ok(v) => v,
					Err(e) => {
						return error_result(format!("Failed to read shadow schema: {e}"));
					}
				};
				match val {
					Some(v) => v,
					None => return error_result("Shadow INFO FOR DB returned no data".into()),
				}
			};
			let shadow_text =
				serde_json::to_string_pretty(&shadow_info).unwrap_or_else(|_| "{}".to_string());
			return Ok(CallToolResult::success(vec![Content::text(format!(
				"Shadow verification (read-only)\n\
				 {} module(s), {} migration(s)\n\n\
				 ```json\n{shadow_text}\n```",
				modules.len(),
				migrations.len(),
			))]));
		}

		// Get INFO FOR DB from both
		let playground_info = {
			let db = self.db.read().await;
			let mut resp = match db.query("INFO FOR DB").await {
				Ok(r) => r,
				Err(e) => {
					return error_result(format!("Failed to query playground INFO FOR DB: {e}"));
				}
			};
			let val: Option<serde_json::Value> = match resp.take(0) {
				Ok(v) => v,
				Err(e) => return error_result(format!("Failed to read playground schema: {e}")),
			};
			match val {
				Some(v) => v,
				None => return error_result("Playground INFO FOR DB returned no data".into()),
			}
		};

		let shadow_info = {
			let mut resp = match shadow_db.query("INFO FOR DB").await {
				Ok(r) => r,
				Err(e) => return error_result(format!("Failed to query shadow INFO FOR DB: {e}")),
			};
			let val: Option<serde_json::Value> = match resp.take(0) {
				Ok(v) => v,
				Err(e) => return error_result(format!("Failed to read shadow schema: {e}")),
			};
			match val {
				Some(v) => v,
				None => return error_result("Shadow INFO FOR DB returned no data".into()),
			}
		};

		let diff = overshift::validate::compare_db_info(&playground_info, &shadow_info);

		let mut output = format!(
			"**Verify** `{}` (NS={}, DB={})\n\
			 Applied {} module(s) + {} migration(s) to playground\n\
			 Applied {} module(s) + {} migration(s) to shadow\n\n",
			args.path,
			manifest.meta.ns,
			manifest.meta.db,
			modules.len(),
			migrations.len(),
			modules.len(),
			migrations.len(),
		);

		if diff.is_empty() {
			output.push_str("Schema matches -- playground and shadow are identical.");
		} else {
			output.push_str(&format!("**Drift detected:**\n{diff}"));
		}

		Ok(CallToolResult::success(vec![Content::text(output)]))
	}

	#[tool(
		name = "check",
		description = "Parse .surql files and report syntax errors without executing. \
            Path can be a single file or a directory."
	)]
	pub async fn check(
		&self,
		Parameters(args): Parameters<CheckArgs>,
	) -> Result<CallToolResult, rmcp::ErrorData> {
		let path = match validate_path_against(&args.path, &self.workspace_root) {
			Ok(p) => p,
			Err(e) => return error_result(e),
		};
		let recursive = args.recursive.unwrap_or(true);

		let files: Vec<PathBuf> = if path.is_file() {
			vec![path]
		} else if path.is_dir() {
			if recursive {
				let mut collected = Vec::new();
				surql_parser::collect_surql_files(&path, &mut collected);
				collected
			} else {
				match std::fs::read_dir(&path) {
					Ok(entries) => entries
						.filter_map(|e| e.ok())
						.map(|e| e.path())
						.filter(|p| {
							p.extension()
								.and_then(|ext| ext.to_str())
								.is_some_and(|ext| ext == "surql")
						})
						.collect(),
					Err(e) => {
						return error_result(format!("Cannot read directory {}: {e}", args.path));
					}
				}
			}
		} else {
			return error_result(format!("Path does not exist: {}", args.path));
		};

		if files.is_empty() {
			return Ok(CallToolResult::success(vec![Content::text(
				"No .surql files found",
			)]));
		}

		let mut seen = std::collections::HashSet::new();
		let mut total_errors = 0usize;
		let mut error_details = Vec::new();

		for file in &files {
			let canonical = file.canonicalize().unwrap_or_else(|_| file.clone());
			if !seen.insert(canonical.clone()) {
				continue;
			}
			let content = match surql_parser::read_surql_file(&canonical) {
				Ok(c) => c,
				Err(e) => {
					error_details.push(format!("{}:0:0: {e}", file.display()));
					total_errors += 1;
					continue;
				}
			};
			if let Err(diags) = surql_parser::parse_for_diagnostics(&content) {
				for d in &diags {
					error_details.push(format!(
						"{}:{}:{}: {}",
						file.display(),
						d.line,
						d.column,
						d.message
					));
				}
				total_errors += diags.len();
			}
		}

		let file_count = seen.len();
		let mut output = format!(
			"{file_count} file{} checked, {total_errors} error{} found",
			if file_count == 1 { "" } else { "s" },
			if total_errors == 1 { "" } else { "s" },
		);
		if !error_details.is_empty() {
			output.push_str("\n\n");
			output.push_str(&error_details.join("\n"));
		}

		Ok(CallToolResult::success(vec![Content::text(output)]))
	}

	#[tool(
		name = "rollback",
		description = "Roll back applied migrations in an overshift project to a target version. \
			Resets the playground and re-applies schema modules + migrations up to target_version. \
			In-memory playground rebuilds from scratch (no down.surql needed)."
	)]
	pub async fn rollback(
		&self,
		Parameters(args): Parameters<RollbackArgs>,
	) -> Result<CallToolResult, rmcp::ErrorData> {
		let validated = match validate_path_against(&args.path, &self.workspace_root) {
			Ok(p) => p,
			Err(e) => return error_result(e),
		};
		let manifest = match overshift::Manifest::load(&validated) {
			Ok(m) => m,
			Err(e) => return error_result(format!("Cannot load manifest: {e}")),
		};

		let db = self.db.read().await;

		// Reset playground: switch to NS/DB then remove+recreate so we rebuild from scratch.
		// In-memory playground does not need down.surql — we rebuild state up to target_version.
		let remove_sql = format!("REMOVE DATABASE IF EXISTS {}", manifest.meta.db);
		db.query(&remove_sql).await.ok();
		if let Err(e) = db.use_ns(&manifest.meta.ns).use_db(&manifest.meta.db).await {
			return error_result(format!(
				"Failed to switch to NS={}/DB={}: {e}",
				manifest.meta.ns, manifest.meta.db
			));
		}

		// Re-apply schema modules (same as load_manifest)
		let modules = match overshift::schema::load_schema_modules(&manifest) {
			Ok(m) => m,
			Err(e) => return error_result(format!("Failed to load schema modules: {e}")),
		};
		let mut schema_applied = 0u32;
		for module in &modules {
			let injected = inject_overwrite(&module.content);
			if let Err(e) = db.query(&injected).await.and_then(|r| r.check()) {
				return error_result(format!("Schema module {} failed: {e}", module.name));
			}
			schema_applied += 1;
		}

		// Discover and re-apply migrations only up to target_version
		let target = args.target_version;
		let migrations = match overshift::migration::discover_migrations(
			manifest.root_path().unwrap_or(std::path::Path::new(".")),
		) {
			Ok(m) => m,
			Err(e) => return error_result(format!("Failed to discover migrations: {e}")),
		};
		let total_migrations = migrations.len() as u32;
		let mut migrations_applied = 0u32;
		let mut total_rolled_back = 0u32;
		for mig in &migrations {
			if mig.version > target {
				total_rolled_back += 1;
				continue;
			}
			if let Err(e) = db.query(mig.content.as_str()).await.and_then(|r| r.check()) {
				return error_result(format!("Migration {} failed: {e}", mig.name));
			}
			migrations_applied += 1;
		}

		let mut output = format!(
			"**Rollback** `{}` to v{target:03}\n\
			 {schema_applied} schema module(s) re-applied, \
			 {migrations_applied} migration(s) re-applied, \
			 {total_rolled_back} migration(s) rolled back",
			args.path,
		);

		if total_migrations > 0 {
			let max_version = migrations.last().map(|m| m.version).unwrap_or(0);
			output.push_str(&format!("\n\nState: v{target:03} of v{max_version:03}"));
		}

		Ok(CallToolResult::success(vec![Content::text(output)]))
	}

	#[tool(
		name = "graph_affected",
		description = "Show which tables would be affected if a table is dropped or modified. \
			Follows record<> links in reverse to find all dependents."
	)]
	pub async fn graph_affected(
		&self,
		Parameters(args): Parameters<GraphAffectedArgs>,
	) -> Result<CallToolResult, rmcp::ErrorData> {
		let dir = match validate_path_against(&args.schema_path, &self.workspace_root) {
			Ok(p) => p,
			Err(e) => return error_result(e),
		};
		if !dir.is_dir() {
			return error_result(format!("Not a directory: {}", args.schema_path));
		}
		let graph = match surql_parser::SchemaGraph::from_files(&dir) {
			Ok(g) => g,
			Err(e) => return error_result(format!("Failed to build schema graph: {e}")),
		};
		if graph.table(&args.table).is_none() {
			return error_result(format!(
				"Table '{}' not found in schema at {}",
				args.table, args.schema_path
			));
		}

		let refs = graph.tables_referencing(&args.table);
		if refs.is_empty() {
			return Ok(CallToolResult::success(vec![Content::text(format!(
				"No tables reference `{}`",
				args.table
			))]));
		}

		let mut output = format!(
			"**{} table(s) reference `{}`:**\n\n",
			refs.len(),
			args.table
		);
		for (ref_table, ref_field) in &refs {
			output.push_str(&format!(
				"- `{ref_table}.{ref_field}` has `record<{}>`\n",
				args.table
			));
		}

		output.push_str(&format!(
			"\nDropping or renaming `{}` would break {} field(s).",
			args.table,
			refs.len()
		));

		Ok(CallToolResult::success(vec![Content::text(output)]))
	}

	#[tool(
		name = "graph_traverse",
		description = "Traverse the schema graph from a table, following record<> links \
			up to N hops deep. Supports forward (outgoing links) and reverse (incoming links) \
			directions."
	)]
	pub async fn graph_traverse(
		&self,
		Parameters(args): Parameters<GraphTraverseArgs>,
	) -> Result<CallToolResult, rmcp::ErrorData> {
		let dir = match validate_path_against(&args.schema_path, &self.workspace_root) {
			Ok(p) => p,
			Err(e) => return error_result(e),
		};
		if !dir.is_dir() {
			return error_result(format!("Not a directory: {}", args.schema_path));
		}
		let graph = match surql_parser::SchemaGraph::from_files(&dir) {
			Ok(g) => g,
			Err(e) => return error_result(format!("Failed to build schema graph: {e}")),
		};
		if graph.table(&args.table).is_none() {
			return error_result(format!(
				"Table '{}' not found in schema at {}",
				args.table, args.schema_path
			));
		}

		let depth = args.depth.unwrap_or(10) as usize;
		let direction = args.direction.as_deref().unwrap_or("forward");

		match direction {
			"forward" => {
				let reachable = graph.tables_reachable_from(&args.table, depth);
				if reachable.is_empty() {
					return Ok(CallToolResult::success(vec![Content::text(format!(
						"`{}` has no outgoing record<> links",
						args.table
					))]));
				}

				let tree = graph.dependency_tree(&args.table, depth);
				let mut output = format!(
					"**Forward traversal from `{}`** (max depth: {depth})\n\n\
					 {} table(s) reachable:\n\n```\n",
					args.table,
					reachable.len()
				);
				output.push_str(&format!("[{}]\n", tree.table));
				for child in &tree.children {
					format_dependency_node_mcp(&mut output, child, 1);
				}
				output.push_str("```\n\n**Flat list:**\n");
				for (name, d, path) in &reachable {
					let path_str = path.join(" -> ");
					output.push_str(&format!("- `{name}` (depth {d}): {path_str}\n"));
				}
				Ok(CallToolResult::success(vec![Content::text(output)]))
			}
			"reverse" => {
				let refs = graph.tables_referencing(&args.table);
				if refs.is_empty() {
					return Ok(CallToolResult::success(vec![Content::text(format!(
						"No tables reference `{}`",
						args.table
					))]));
				}

				let mut output = format!(
					"**Reverse traversal for `{}`**\n\n\
					 {} table(s) reference it:\n\n",
					args.table,
					refs.len()
				);
				for (ref_table, ref_field) in &refs {
					output.push_str(&format!(
						"- `{ref_table}.{ref_field}` -> `{}`\n",
						args.table
					));
				}
				Ok(CallToolResult::success(vec![Content::text(output)]))
			}
			other => error_result(format!(
				"Invalid direction '{other}': must be 'forward' or 'reverse'"
			)),
		}
	}

	#[tool(
		name = "graph_siblings",
		description = "Find tables that share record<> link targets with a given table. \
			Shows which other tables also point to the same targets."
	)]
	pub async fn graph_siblings(
		&self,
		Parameters(args): Parameters<GraphSiblingsArgs>,
	) -> Result<CallToolResult, rmcp::ErrorData> {
		let dir = match validate_path_against(&args.schema_path, &self.workspace_root) {
			Ok(p) => p,
			Err(e) => return error_result(e),
		};
		if !dir.is_dir() {
			return error_result(format!("Not a directory: {}", args.schema_path));
		}
		let graph = match surql_parser::SchemaGraph::from_files(&dir) {
			Ok(g) => g,
			Err(e) => return error_result(format!("Failed to build schema graph: {e}")),
		};
		if graph.table(&args.table).is_none() {
			return error_result(format!(
				"Table '{}' not found in schema at {}",
				args.table, args.schema_path
			));
		}

		let siblings = graph.siblings_of(&args.table);
		if siblings.is_empty() {
			return Ok(CallToolResult::success(vec![Content::text(format!(
				"`{}` shares no record<> targets with other tables",
				args.table
			))]));
		}

		let mut output = format!("**Siblings of `{}`:**\n\n", args.table);
		for (sib, target, field) in &siblings {
			output.push_str(&format!(
				"- `{sib}` also links to `{target}` (via `.{field}`)\n"
			));
		}
		Ok(CallToolResult::success(vec![Content::text(output)]))
	}

	#[tool(name = "reset", description = "Clear the database and start fresh")]
	pub async fn reset(&self) -> Result<CallToolResult, rmcp::ErrorData> {
		let db = self.db.read().await;
		// REMOVE DATABASE may fail if it doesn't exist yet -- safe to ignore
		db.query("REMOVE DATABASE default").await.ok();
		if let Err(e) = db.use_ns("default").use_db("default").await {
			return error_result(format!("Reset failed: {e}"));
		}
		Ok(CallToolResult::success(vec![Content::text(
			"Database cleared",
		)]))
	}
}

#[tool_handler]
impl rmcp::handler::server::ServerHandler for SurqlMcp {
	fn get_info(&self) -> ServerInfo {
		ServerInfo {
			instructions: Some(
				"SurrealQL playground: run queries, load schema files, explore database".into(),
			),
			capabilities: ServerCapabilities::builder().enable_tools().build(),
			server_info: Implementation {
				name: "surql-mcp".into(),
				version: env!("CARGO_PKG_VERSION").into(),
				title: None,
				description: None,
				icons: None,
				website_url: None,
			},
			..Default::default()
		}
	}
}

fn format_dependency_node_mcp(
	out: &mut String,
	node: &surql_parser::DependencyNode,
	indent: usize,
) {
	let prefix = "  ".repeat(indent);
	let field_label = node
		.field
		.as_deref()
		.map(|f| format!(".{f} -> "))
		.unwrap_or_default();
	let cycle_label = if node.is_cycle { " (cycle)" } else { "" };
	out.push_str(&format!(
		"{prefix}{field_label}[{}]{cycle_label}\n",
		node.table
	));
	if !node.is_cycle {
		for child in &node.children {
			format_dependency_node_mcp(out, child, indent + 1);
		}
	}
}

pub fn result_text(result: &CallToolResult) -> String {
	result
		.content
		.iter()
		.filter_map(|c| match &c.raw {
			rmcp::model::RawContent::Text(t) => Some(t.text.as_str()),
			_ => None,
		})
		.collect::<Vec<_>>()
		.join("\n")
}

#[cfg(test)]
mod tests {
	use super::*;
	use rmcp::handler::server::wrapper::Parameters;
	use std::fs;
	use tempfile::TempDir;

	#[tokio::test]
	async fn should_start_and_run_query_return() {
		let server = SurqlMcp::new().await.unwrap();
		let result = server
			.run_query(Parameters(ExecArgs {
				query: "RETURN 42".into(),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(text.contains("42"), "expected 42 in: {text}");
	}

	#[tokio::test]
	async fn should_run_query_create_and_select() {
		let server = SurqlMcp::new().await.unwrap();
		server
			.run_query(Parameters(ExecArgs {
				query: "CREATE user:alice SET name = 'Alice'".into(),
			}))
			.await
			.unwrap();

		let result = server
			.run_query(Parameters(ExecArgs {
				query: "SELECT * FROM user".into(),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(text.contains("Alice"), "expected Alice in: {text}");
		assert!(text.contains("1 row"), "expected 1 row in: {text}");
	}

	#[tokio::test]
	async fn should_run_query_select_from_nonexistent_returns_empty() {
		let server = SurqlMcp::new().await.unwrap();
		let result = server
			.run_query(Parameters(ExecArgs {
				query: "SELECT * FROM nonexistent".into(),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(
			text.contains("empty") || result.is_error == Some(true),
			"nonexistent table should return empty or error: {text}"
		);
	}

	#[tokio::test]
	async fn should_run_query_report_syntax_error() {
		let server = SurqlMcp::new().await.unwrap();
		let result = server
			.run_query(Parameters(ExecArgs {
				query: "NOT VALID SQL !!!".into(),
			}))
			.await
			.unwrap();
		assert!(result.is_error == Some(true));
	}

	#[tokio::test]
	async fn should_load_project_from_directory() {
		let dir = TempDir::new().unwrap();
		fs::create_dir_all(dir.path().join("schema")).unwrap();
		fs::write(
			dir.path().join("schema/tables.surql"),
			"DEFINE TABLE user SCHEMAFULL; DEFINE FIELD name ON user TYPE string;",
		)
		.unwrap();

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();
		let result = server
			.load_project(Parameters(LoadProjectArgs {
				path: dir.path().to_string_lossy().to_string(),
				clean: Some(true),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(text.contains("1 schema"), "expected '1 schema' in: {text}");

		let select = server
			.run_query(Parameters(ExecArgs {
				query: "SELECT * FROM user".into(),
			}))
			.await
			.unwrap();
		assert!(result_text(&select).contains("empty"));
	}

	#[tokio::test]
	async fn should_load_project_categorize_and_report() {
		let dir = TempDir::new().unwrap();
		fs::create_dir_all(dir.path().join("schema")).unwrap();
		fs::create_dir_all(dir.path().join("migrations")).unwrap();
		fs::create_dir_all(dir.path().join("functions")).unwrap();
		fs::create_dir_all(dir.path().join("examples")).unwrap();
		fs::write(
			dir.path().join("schema/tables.surql"),
			"DEFINE TABLE user SCHEMAFULL;\n\
			 DEFINE FIELD name ON user TYPE string;",
		)
		.unwrap();
		fs::write(
			dir.path().join("migrations/001_init.surql"),
			"CREATE user:alice SET name = 'Alice';",
		)
		.unwrap();
		fs::write(
			dir.path().join("functions/greet.surql"),
			"DEFINE FUNCTION fn::greet() { RETURN 'hi'; };",
		)
		.unwrap();
		fs::write(
			dir.path().join("examples/demo.surql"),
			"SELECT * FROM user;",
		)
		.unwrap();

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();
		let result = server
			.load_project(Parameters(LoadProjectArgs {
				path: dir.path().to_string_lossy().to_string(),
				clean: Some(true),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(text.contains("1 schema"), "expected 1 schema in: {text}");
		assert!(
			text.contains("1 migrations"),
			"expected 1 migrations in: {text}"
		);
		assert!(
			text.contains("1 functions"),
			"expected 1 functions in: {text}"
		);
		assert!(
			text.contains("1 examples"),
			"expected 1 examples in: {text}"
		);
	}

	#[tokio::test]
	async fn should_load_project_example_errors_become_warnings() {
		let dir = TempDir::new().unwrap();
		fs::create_dir_all(dir.path().join("examples")).unwrap();
		fs::write(dir.path().join("examples/bad.surql"), "NOT VALID SQL !!!").unwrap();

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();
		let result = server
			.load_project(Parameters(LoadProjectArgs {
				path: dir.path().to_string_lossy().to_string(),
				clean: Some(true),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(
			text.contains("Warnings"),
			"example errors should be warnings: {text}"
		);
		assert!(
			!text.contains("**Errors"),
			"example errors should NOT appear as errors: {text}"
		);
	}

	#[tokio::test]
	async fn should_load_project_inject_overwrite_for_schema() {
		let dir = TempDir::new().unwrap();
		fs::create_dir_all(dir.path().join("schema")).unwrap();
		fs::write(
			dir.path().join("schema/tables.surql"),
			"DEFINE TABLE user SCHEMAFULL;",
		)
		.unwrap();

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();

		// Load twice -- second load should succeed due to OVERWRITE injection
		server
			.load_project(Parameters(LoadProjectArgs {
				path: dir.path().to_string_lossy().to_string(),
				clean: Some(true),
			}))
			.await
			.unwrap();
		let result = server
			.load_project(Parameters(LoadProjectArgs {
				path: dir.path().to_string_lossy().to_string(),
				clean: Some(false),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(
			text.contains("1 schema"),
			"second load with OVERWRITE should succeed: {text}"
		);
		assert!(
			!text.contains("**Errors"),
			"second load should not have errors: {text}"
		);
	}

	#[tokio::test]
	async fn should_load_project_reject_nonexistent_dir() {
		let server = SurqlMcp::new().await.unwrap();
		let result = server
			.load_project(Parameters(LoadProjectArgs {
				path: "/nonexistent/path".into(),
				clean: None,
			}))
			.await
			.unwrap();
		assert!(result.is_error == Some(true));
	}

	#[tokio::test]
	async fn should_schema_return_db_info() {
		let server = SurqlMcp::new().await.unwrap();
		server
			.run_query(Parameters(ExecArgs {
				query: "DEFINE TABLE user SCHEMAFULL".into(),
			}))
			.await
			.unwrap();

		let result = server.schema().await.unwrap();
		let text = result_text(&result);
		assert!(text.contains("user"), "expected user in schema: {text}");
	}

	#[tokio::test]
	async fn should_describe_return_table_info() {
		let server = SurqlMcp::new().await.unwrap();
		server
			.run_query(Parameters(ExecArgs {
				query: "DEFINE TABLE post SCHEMAFULL; \
				 DEFINE FIELD title ON post TYPE string"
					.into(),
			}))
			.await
			.unwrap();

		let result = server
			.describe(Parameters(DescribeArgs {
				table: "post".into(),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(text.contains("post"), "expected post in: {text}");
		assert!(text.contains("title"), "expected title field in: {text}");
	}

	#[tokio::test]
	async fn should_reset_clear_all_data() {
		let server = SurqlMcp::new().await.unwrap();
		server
			.run_query(Parameters(ExecArgs {
				query: "CREATE user:alice SET name = 'Alice'".into(),
			}))
			.await
			.unwrap();

		server.reset().await.unwrap();

		let result = server
			.run_query(Parameters(ExecArgs {
				query: "SELECT * FROM user".into(),
			}))
			.await
			.unwrap();
		assert!(
			result.is_error == Some(true),
			"expected error after reset (table gone)"
		);
	}

	#[tokio::test]
	async fn should_load_file_single() {
		let dir = TempDir::new().unwrap();
		let file = dir.path().join("schema.surql");
		fs::write(&file, "DEFINE TABLE test SCHEMAFULL;").unwrap();

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();
		let result = server
			.load_file(Parameters(LoadFileArgs {
				path: file.to_string_lossy().to_string(),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(text.contains("Applied"), "expected Applied in: {text}");
	}

	#[tokio::test]
	async fn should_load_file_report_error_for_missing() {
		let server = SurqlMcp::new().await.unwrap();
		let result = server
			.load_file(Parameters(LoadFileArgs {
				path: "/nonexistent.surql".into(),
			}))
			.await
			.unwrap();
		assert!(result.is_error == Some(true));
	}

	#[tokio::test]
	async fn should_reject_describe_with_injection() {
		let server = SurqlMcp::new().await.unwrap();
		let result = server
			.describe(Parameters(DescribeArgs {
				table: "user; REMOVE DATABASE default".into(),
			}))
			.await
			.unwrap();
		assert!(
			result.is_error == Some(true),
			"should reject table name with injection"
		);
	}

	#[test]
	fn should_categorize_files_by_directory() {
		let schema = PathBuf::from("/project/schema.surql");
		let schema_dir = PathBuf::from("/project/schema/tables.surql");
		let migrations = PathBuf::from("/project/migrations/001.surql");
		let example = PathBuf::from("/project/examples/demo.surql");
		let seed = PathBuf::from("/project/seed/data.surql");
		let func = PathBuf::from("/project/functions/auth.surql");
		let func_file = PathBuf::from("/project/functions.surql");
		let other = PathBuf::from("/project/queries.surql");

		assert_eq!(classify_file(&schema), FileCategory::Schema);
		assert_eq!(classify_file(&schema_dir), FileCategory::Schema);
		assert_eq!(classify_file(&migrations), FileCategory::Migration);
		assert_eq!(classify_file(&example), FileCategory::Example);
		assert_eq!(classify_file(&seed), FileCategory::Example);
		assert_eq!(classify_file(&func), FileCategory::Function);
		assert_eq!(classify_file(&func_file), FileCategory::Function);
		assert_eq!(classify_file(&other), FileCategory::General);
	}

	#[test]
	fn should_inject_overwrite_into_define_statements() {
		let input = "\
DEFINE TABLE user SCHEMAFULL;
DEFINE FIELD name ON user TYPE string;
DEFINE INDEX user_name ON user FIELDS name UNIQUE;
DEFINE FUNCTION fn::greet() { RETURN 'hi'; };";

		let result = inject_overwrite(input);
		assert!(
			result.contains("DEFINE TABLE OVERWRITE user"),
			"expected OVERWRITE after DEFINE TABLE: {result}"
		);
		assert!(
			result.contains("DEFINE FIELD OVERWRITE name"),
			"expected OVERWRITE after DEFINE FIELD: {result}"
		);
		assert!(
			result.contains("DEFINE INDEX OVERWRITE user_name"),
			"expected OVERWRITE after DEFINE INDEX: {result}"
		);
		assert!(
			result.contains("DEFINE FUNCTION OVERWRITE fn::greet"),
			"expected OVERWRITE after DEFINE FUNCTION: {result}"
		);
	}

	#[test]
	fn should_not_double_inject_overwrite() {
		let input = "DEFINE TABLE OVERWRITE user SCHEMAFULL;";
		let result = inject_overwrite(input);
		assert_eq!(
			result.matches("OVERWRITE").count(),
			1,
			"should not double-inject OVERWRITE: {result}"
		);
	}

	#[test]
	fn should_not_inject_overwrite_when_if_not_exists() {
		let input = "DEFINE TABLE IF NOT EXISTS user SCHEMAFULL;";
		let result = inject_overwrite(input);
		assert!(
			!result.contains("OVERWRITE"),
			"should not inject OVERWRITE when IF NOT EXISTS is present: {result}"
		);
	}

	#[test]
	fn should_inject_overwrite_preserve_indentation() {
		let input = "  \tDEFINE TABLE user SCHEMAFULL;";
		let result = inject_overwrite(input);
		assert!(
			result.starts_with("  \tDEFINE TABLE OVERWRITE user"),
			"should preserve leading whitespace: {result}"
		);
	}

	#[test]
	fn should_inject_overwrite_all_supported_keywords() {
		let input = "\
DEFINE TABLE t1;
DEFINE FIELD f1 ON t1 TYPE string;
DEFINE INDEX i1 ON t1 FIELDS f1;
DEFINE FUNCTION fn::x() { RETURN 1; };
DEFINE EVENT e1 ON t1 WHEN true THEN {};
DEFINE ANALYZER a1 TOKENIZERS blank;
DEFINE PARAM $p VALUE 1;";

		let result = inject_overwrite(input);
		assert!(result.contains("DEFINE TABLE OVERWRITE"), "{result}");
		assert!(result.contains("DEFINE FIELD OVERWRITE"), "{result}");
		assert!(result.contains("DEFINE INDEX OVERWRITE"), "{result}");
		assert!(result.contains("DEFINE FUNCTION OVERWRITE"), "{result}");
		assert!(result.contains("DEFINE EVENT OVERWRITE"), "{result}");
		assert!(result.contains("DEFINE ANALYZER OVERWRITE"), "{result}");
		assert!(result.contains("DEFINE PARAM OVERWRITE"), "{result}");
	}

	#[test]
	fn should_inject_overwrite_case_insensitive() {
		let input = "define table user SCHEMAFULL;";
		let result = inject_overwrite(input);
		assert!(
			result.contains("define table OVERWRITE user"),
			"should handle case-insensitive DEFINE: {result}"
		);
	}

	#[test]
	fn should_not_inject_overwrite_in_line_comments() {
		let input = "-- DEFINE TABLE user SCHEMAFULL;\nDEFINE TABLE post;";
		let result = inject_overwrite(input);
		assert!(
			result.contains("-- DEFINE TABLE user SCHEMAFULL;"),
			"should not inject OVERWRITE inside line comment: {result}"
		);
		assert!(
			result.contains("DEFINE TABLE OVERWRITE post"),
			"should still inject OVERWRITE outside comment: {result}"
		);
	}

	#[test]
	fn should_not_inject_overwrite_in_block_comments() {
		let input = "/*\nDEFINE TABLE user SCHEMAFULL;\n*/\nDEFINE TABLE post;";
		let result = inject_overwrite(input);
		assert!(
			!result.contains("DEFINE TABLE OVERWRITE user"),
			"should not inject OVERWRITE inside block comment: {result}"
		);
		assert!(
			result.contains("DEFINE TABLE OVERWRITE post"),
			"should still inject OVERWRITE after block comment: {result}"
		);
	}

	#[tokio::test]
	async fn should_read_overshift_manifest() {
		let dir = TempDir::new().unwrap();
		fs::write(
			dir.path().join("manifest.toml"),
			"[meta]\nns = \"myapp\"\ndb = \"main\"\nsystem_db = \"_system\"\n\n\
			 [[modules]]\nname = \"auth\"\npath = \"schema/auth\"\ndepends_on = []\n",
		)
		.unwrap();
		fs::create_dir_all(dir.path().join("migrations")).unwrap();
		fs::write(
			dir.path().join("migrations/v001_init.surql"),
			"DEFINE TABLE user;",
		)
		.unwrap();

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();
		let result = server
			.manifest(Parameters(ManifestArgs {
				path: dir.path().to_string_lossy().to_string(),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(text.contains("myapp"), "expected ns in: {text}");
		assert!(text.contains("main"), "expected db in: {text}");
		assert!(text.contains("auth"), "expected module in: {text}");
		assert!(
			text.contains("1 migration"),
			"expected migrations in: {text}"
		);
	}

	#[tokio::test]
	async fn should_reject_missing_manifest() {
		let server = SurqlMcp::new().await.unwrap();
		let result = server
			.manifest(Parameters(ManifestArgs {
				path: "/nonexistent".into(),
			}))
			.await
			.unwrap();
		assert!(result.is_error == Some(true));
	}

	#[tokio::test]
	async fn should_compare_detect_missing_table() {
		let server = SurqlMcp::new().await.unwrap();
		server
			.run_query(Parameters(ExecArgs {
				query: "DEFINE TABLE user SCHEMAFULL".into(),
			}))
			.await
			.unwrap();

		let expected_json = serde_json::json!({
			"tables": {
				"user": "DEFINE TABLE user TYPE NORMAL SCHEMAFULL",
				"post": "DEFINE TABLE post TYPE NORMAL SCHEMAFULL"
			},
			"functions": {}
		});

		let result = server
			.compare(Parameters(CompareArgs {
				expected_json: expected_json.to_string(),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(
			text.contains("post") && text.contains("missing"),
			"expected missing table 'post' in diff: {text}"
		);
	}

	#[tokio::test]
	async fn should_compare_return_match_when_identical() {
		let server = SurqlMcp::new().await.unwrap();
		server
			.run_query(Parameters(ExecArgs {
				query: "DEFINE TABLE user SCHEMAFULL; \
				 DEFINE TABLE post SCHEMAFULL"
					.into(),
			}))
			.await
			.unwrap();

		let schema_result = server.schema().await.unwrap();
		let schema_text = result_text(&schema_result);
		let json_start = schema_text.find('{').expect("schema should contain JSON");
		let json_end = schema_text.rfind('}').expect("schema should contain JSON") + 1;
		let raw_json = &schema_text[json_start..json_end];

		let result = server
			.compare(Parameters(CompareArgs {
				expected_json: raw_json.to_string(),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(
			text.contains("Schema matches"),
			"expected 'Schema matches' for identical schemas: {text}"
		);
	}

	#[tokio::test]
	async fn should_verify_matching_project() {
		let dir = TempDir::new().unwrap();
		fs::write(
			dir.path().join("manifest.toml"),
			"[meta]\nns = \"test\"\ndb = \"main\"\nsystem_db = \"_system\"\n\n\
			 [[modules]]\nname = \"core\"\npath = \"schema/core\"\n",
		)
		.unwrap();
		fs::create_dir_all(dir.path().join("schema/core")).unwrap();
		fs::write(
			dir.path().join("schema/core/tables.surql"),
			"DEFINE TABLE user SCHEMAFULL;\n\
			 DEFINE FIELD name ON user TYPE string;",
		)
		.unwrap();

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();
		let result = server
			.verify(Parameters(VerifyArgs {
				verify_only: None,
				path: dir.path().to_string_lossy().to_string(),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(
			text.contains("Schema matches"),
			"expected matching schemas in: {text}"
		);
		assert!(text.contains("1 module(s)"), "expected 1 module in: {text}");
	}

	#[tokio::test]
	async fn should_verify_reject_missing_manifest() {
		let server = SurqlMcp::new().await.unwrap();
		let result = server
			.verify(Parameters(VerifyArgs {
				verify_only: None,
				path: "/nonexistent".into(),
			}))
			.await
			.unwrap();
		assert!(result.is_error == Some(true));
	}

	#[tokio::test]
	async fn should_check_valid_file() {
		let dir = TempDir::new().unwrap();
		let file = dir.path().join("schema.surql");
		fs::write(&file, "DEFINE TABLE user SCHEMAFULL;").unwrap();

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();
		let result = server
			.check(Parameters(CheckArgs {
				path: file.to_string_lossy().to_string(),
				recursive: None,
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(
			text.contains("1 file checked") && text.contains("0 errors"),
			"expected no errors for valid file: {text}"
		);
	}

	#[tokio::test]
	async fn should_check_invalid_file_report_errors() {
		let dir = TempDir::new().unwrap();
		let file = dir.path().join("broken.surql");
		fs::write(&file, "SELEC * FORM user;").unwrap();

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();
		let result = server
			.check(Parameters(CheckArgs {
				path: file.to_string_lossy().to_string(),
				recursive: None,
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(
			!text.contains("0 errors"),
			"expected errors for invalid file: {text}"
		);
	}

	#[tokio::test]
	async fn should_check_directory_recursively() {
		let dir = TempDir::new().unwrap();
		let sub = dir.path().join("schemas");
		fs::create_dir_all(&sub).unwrap();
		fs::write(sub.join("a.surql"), "DEFINE TABLE a;").unwrap();
		fs::write(dir.path().join("b.surql"), "DEFINE TABLE b;").unwrap();

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();
		let result = server
			.check(Parameters(CheckArgs {
				path: dir.path().to_string_lossy().to_string(),
				recursive: Some(true),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(
			text.contains("2 files checked"),
			"expected 2 files checked: {text}"
		);
	}

	#[tokio::test]
	async fn should_check_nonrecursive_skip_subdirs() {
		let dir = TempDir::new().unwrap();
		let sub = dir.path().join("schemas");
		fs::create_dir_all(&sub).unwrap();
		fs::write(sub.join("a.surql"), "DEFINE TABLE a;").unwrap();
		fs::write(dir.path().join("b.surql"), "DEFINE TABLE b;").unwrap();

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();
		let result = server
			.check(Parameters(CheckArgs {
				path: dir.path().to_string_lossy().to_string(),
				recursive: Some(false),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(
			text.contains("1 file checked"),
			"expected 1 file checked (non-recursive): {text}"
		);
	}

	#[tokio::test]
	async fn should_check_reject_nonexistent_path() {
		let server = SurqlMcp::new().await.unwrap();
		let result = server
			.check(Parameters(CheckArgs {
				path: "/nonexistent/path.surql".into(),
				recursive: None,
			}))
			.await
			.unwrap();
		assert!(
			result.is_error == Some(true),
			"expected error for nonexistent path"
		);
	}

	#[tokio::test]
	async fn should_check_empty_directory() {
		let dir = TempDir::new().unwrap();

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();
		let result = server
			.check(Parameters(CheckArgs {
				path: dir.path().to_string_lossy().to_string(),
				recursive: None,
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(
			text.contains("No .surql files found"),
			"expected no files found: {text}"
		);
	}

	fn write_graph_schema(dir: &std::path::Path) {
		fs::create_dir_all(dir.join("schema")).unwrap();
		fs::write(
			dir.join("schema/tables.surql"),
			"DEFINE TABLE user SCHEMAFULL;\n\
			 DEFINE TABLE post SCHEMAFULL;\n\
			 DEFINE TABLE comment SCHEMAFULL;\n\
			 DEFINE FIELD author ON post TYPE record<user>;\n\
			 DEFINE FIELD post ON comment TYPE record<post>;\n\
			 DEFINE FIELD author ON comment TYPE record<user>;\n",
		)
		.unwrap();
	}

	#[tokio::test]
	async fn should_graph_affected_find_dependents() {
		let dir = TempDir::new().unwrap();
		write_graph_schema(dir.path());

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();
		let result = server
			.graph_affected(Parameters(GraphAffectedArgs {
				table: "user".into(),
				schema_path: dir.path().to_string_lossy().to_string(),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(
			text.contains("comment.author"),
			"expected comment.author in: {text}"
		);
		assert!(
			text.contains("post.author"),
			"expected post.author in: {text}"
		);
	}

	#[tokio::test]
	async fn should_graph_affected_report_no_dependents() {
		let dir = TempDir::new().unwrap();
		write_graph_schema(dir.path());

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();
		let result = server
			.graph_affected(Parameters(GraphAffectedArgs {
				table: "comment".into(),
				schema_path: dir.path().to_string_lossy().to_string(),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(
			text.contains("No tables reference"),
			"expected no references for leaf table: {text}"
		);
	}

	#[tokio::test]
	async fn should_graph_affected_reject_missing_table() {
		let dir = TempDir::new().unwrap();
		write_graph_schema(dir.path());

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();
		let result = server
			.graph_affected(Parameters(GraphAffectedArgs {
				table: "nonexistent".into(),
				schema_path: dir.path().to_string_lossy().to_string(),
			}))
			.await
			.unwrap();
		assert!(
			result.is_error == Some(true),
			"expected error for nonexistent table"
		);
	}

	#[tokio::test]
	async fn should_graph_traverse_forward() {
		let dir = TempDir::new().unwrap();
		write_graph_schema(dir.path());

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();
		let result = server
			.graph_traverse(Parameters(GraphTraverseArgs {
				table: "comment".into(),
				schema_path: dir.path().to_string_lossy().to_string(),
				depth: None,
				direction: Some("forward".into()),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(text.contains("post"), "expected post in traversal: {text}");
		assert!(text.contains("user"), "expected user in traversal: {text}");
	}

	#[tokio::test]
	async fn should_graph_traverse_reverse() {
		let dir = TempDir::new().unwrap();
		write_graph_schema(dir.path());

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();
		let result = server
			.graph_traverse(Parameters(GraphTraverseArgs {
				table: "user".into(),
				schema_path: dir.path().to_string_lossy().to_string(),
				depth: None,
				direction: Some("reverse".into()),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(
			text.contains("post.author"),
			"expected post.author in reverse: {text}"
		);
		assert!(
			text.contains("comment.author"),
			"expected comment.author in reverse: {text}"
		);
	}

	#[tokio::test]
	async fn should_graph_traverse_reject_invalid_direction() {
		let dir = TempDir::new().unwrap();
		write_graph_schema(dir.path());

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();
		let result = server
			.graph_traverse(Parameters(GraphTraverseArgs {
				table: "user".into(),
				schema_path: dir.path().to_string_lossy().to_string(),
				depth: None,
				direction: Some("sideways".into()),
			}))
			.await
			.unwrap();
		assert!(
			result.is_error == Some(true),
			"expected error for invalid direction"
		);
	}

	#[tokio::test]
	async fn should_graph_siblings_find_shared_targets() {
		let dir = TempDir::new().unwrap();
		write_graph_schema(dir.path());

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();
		let result = server
			.graph_siblings(Parameters(GraphSiblingsArgs {
				table: "post".into(),
				schema_path: dir.path().to_string_lossy().to_string(),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(
			text.contains("comment"),
			"expected comment as sibling of post (both link to user): {text}"
		);
	}

	#[tokio::test]
	async fn should_graph_siblings_report_no_siblings() {
		let dir = TempDir::new().unwrap();
		fs::create_dir_all(dir.path().join("schema")).unwrap();
		fs::write(
			dir.path().join("schema/tables.surql"),
			"DEFINE TABLE solo SCHEMAFULL;\n\
			 DEFINE FIELD name ON solo TYPE string;\n",
		)
		.unwrap();

		let server = SurqlMcp::with_workspace_root(dir.path().to_path_buf())
			.await
			.unwrap();
		let result = server
			.graph_siblings(Parameters(GraphSiblingsArgs {
				table: "solo".into(),
				schema_path: dir.path().to_string_lossy().to_string(),
			}))
			.await
			.unwrap();
		let text = result_text(&result);
		assert!(
			text.contains("shares no record<> targets"),
			"expected no siblings for isolated table: {text}"
		);
	}
}