zebflow 0.11.14

Reactive web automation platform — pipelines, templates, and real-time collaboration in a single binary.
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
//! Zebflow MCP handler exposing project-scoped tools.
//!
//! Thin adapter over `PlatformOps`. Each `#[tool]` method:
//! 1. Extracts + validates the MCP session
//! 2. Checks tool capability authorization
//! 3. Delegates to `PlatformOps`
//! 4. Wraps the text result in `CallToolResult` (navigate field is ignored for MCP)

use std::sync::Arc;

use axum::body::{Body, Bytes, to_bytes};
use axum::extract::OriginalUri;
use axum::http::{self, HeaderMap, StatusCode, header};
use axum::response::{IntoResponse, Response};
use base64::Engine as _;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::handler::server::{ServerHandler, tool::Extension};
use rmcp::model::{
    CallToolRequestParams, CallToolResult, Content, GetPromptRequestParams, GetPromptResult,
    ListPromptsResult, ListToolsResult, PaginatedRequestParams, Prompt, PromptMessage,
    PromptMessageContent, PromptMessageRole, ServerCapabilities, ServerInfo, Tool,
};
use rmcp::schemars::JsonSchema;
use rmcp::service::RequestContext;
use rmcp::{ErrorData as McpError, RoleServer, schemars, tool, tool_router};

use crate::infra::execution::placement::ProjectRuntimePlacementTarget;
use crate::platform::model::{McpSession, mcp_tool_capability};
use crate::platform::services::{PlatformOps, PlatformService};

const INTERNAL_CLUSTER_TOKEN_HEADER: &str = "x-zebflow-cluster-token";
const INTERNAL_MCP_SESSION_HEADER: &str = "x-zebflow-mcp-session";
const MCP_PROXY_BODY_LIMIT: usize = 16 * 1024 * 1024;

// ── Parameter structs (MCP schema only) ──────────────────────────────────────

#[derive(serde::Deserialize, JsonSchema)]
struct PipelineGetParams {
    /// Source-relative path of the pipeline (e.g. "my-pipeline.zf.json").
    file_rel_path: String,
}

#[derive(serde::Deserialize, JsonSchema)]
struct PipelineListParams {
    /// Optional semantic filter across path, title, description, trigger kind, and trigger summary.
    #[schemars(with = "String")]
    query: Option<String>,
    /// Optional glob to filter pipeline files (e.g. "api/*.zf.json").
    #[schemars(with = "String")]
    glob: Option<String>,
    /// Optional status filter: "active", "stale" (active, but changed since activation), "draft", or "all".
    #[schemars(with = "String")]
    status: Option<String>,
    /// Optional trigger kind filter: "webhook", "schedule", "function", or full "trigger.webhook".
    #[schemars(with = "String")]
    trigger_kind: Option<String>,
    /// Optional cap on returned rows. Compact defaults to a small cap.
    #[schemars(with = "u32")]
    limit: Option<u32>,
    /// Output format: "compact" (default), "json" for full legacy metadata, or "tree".
    #[schemars(with = "String")]
    format: Option<String>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct FileReadParams {
    /// Relative path to the template file (e.g. "pages/home.tsx").
    rel_path: String,
    /// 1-based starting line number. Omit to read the full file.
    #[schemars(with = "u32")]
    offset: Option<u32>,
    /// Number of lines to return. Omit to read to the end.
    #[schemars(with = "u32")]
    limit: Option<u32>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct FileListParams {
    /// Optional glob to filter files (e.g. "pages/*.tsx", "**/*.tsx"). Omit to list all files.
    #[schemars(with = "String")]
    glob: Option<String>,
    /// Optional semantic filter across path, kind, title, description, and keywords.
    #[schemars(with = "String")]
    query: Option<String>,
    /// Optional template kind filter: "page", "component", "script", "style", "other", or "all".
    #[schemars(with = "String")]
    kind: Option<String>,
    /// Optional cap on returned rows. Compact defaults to a small cap.
    #[schemars(with = "u32")]
    limit: Option<u32>,
    /// Output format: "compact" (default), "json" for full legacy workspace data, or "tree".
    #[schemars(with = "String")]
    format: Option<String>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct HelpParams {
    /// Help path to load (e.g. "pipeline", "web/hooks", "pipeline/nodes", "tool").
    /// Pass empty string or omit for the full index.
    #[schemars(with = "String")]
    topic: Option<String>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct FileWriteParams {
    /// Path relative to the project source root (e.g. "pages/blog-home.tsx", "components/card.tsx", "docs/schema.md").
    rel_path: String,
    /// Full file content to write.
    content: String,
}

#[derive(serde::Deserialize, JsonSchema)]
struct FileSearchParams {
    /// Pattern to search for (case-insensitive substring).
    pattern: String,
    /// Optional glob to filter files (e.g. "pages/*.tsx", "**/*.tsx"). Omit to search all files.
    #[schemars(with = "String")]
    glob: Option<String>,
    /// Number of context lines to include before and after each match. Default 0 (match line only).
    #[schemars(with = "u32")]
    context: Option<u32>,
    /// Optional cap on returned matches.
    #[schemars(with = "u32")]
    head_limit: Option<u32>,
    /// Output mode: "content" (default) or "files_with_matches".
    #[schemars(with = "String")]
    output_mode: Option<String>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct PipelineSearchParams {
    /// Pattern to search for (case-insensitive substring).
    pattern: String,
    /// Optional glob to filter pipeline files (e.g. "api/*.zf.json"). Omit to search all .zf.json files.
    #[schemars(with = "String")]
    glob: Option<String>,
    /// Number of context lines to include before and after each match. Default 0 (match line only).
    #[schemars(with = "u32")]
    context: Option<u32>,
    /// Optional cap on returned matches.
    #[schemars(with = "u32")]
    head_limit: Option<u32>,
    /// Output mode: "content" (default) or "files_with_matches".
    #[schemars(with = "String")]
    output_mode: Option<String>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct FileEditParams {
    /// Relative path to the template file (e.g. "pages/home.tsx").
    rel_path: String,
    /// Exact string to find. Must match exactly once — provide enough context to be unique.
    old_string: String,
    /// Replacement string.
    new_string: String,
}

#[derive(serde::Deserialize, JsonSchema)]
struct FileOutlineParams {
    /// Relative path to the template file (e.g. "pages/home.tsx").
    rel_path: String,
}

#[derive(serde::Deserialize, JsonSchema)]
struct FileDepsParams {
    /// Relative path to the template file (e.g. "pages/home.tsx").
    rel_path: String,
}

#[derive(serde::Deserialize, JsonSchema)]
struct TemplateBatchEditItem {
    /// Relative path to the template file (e.g. "pages/home.tsx").
    rel_path: String,
    /// Exact string to find. Must match exactly once in the file.
    old_string: String,
    /// Replacement string.
    new_string: String,
}

#[derive(serde::Deserialize, JsonSchema)]
struct FileBatchEditParams {
    /// Edits to apply. Fails fast on the first edit error.
    edits: Vec<TemplateBatchEditItem>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct FileCreateParams {
    /// Kind of entry to create: "page", "component", "script", or "folder".
    kind: String,
    /// Base name for the file or folder (e.g. "blog-home", "user-card").
    name: String,
    /// Optional parent folder path under templates/ (e.g. "components/ui").
    #[schemars(with = "String")]
    parent_rel_path: Option<String>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct DocsAgentReadParams {
    /// Agent doc name: "AGENTS.md", "SOUL.md", or "MEMORY.md".
    name: String,
}

#[derive(serde::Deserialize, JsonSchema)]
struct DocsAgentWriteParams {
    /// Agent doc name: "AGENTS.md" (project instructions), "SOUL.md" (agent personality),
    /// or "MEMORY.md" (persistent memory across sessions).
    name: String,
    /// Full file content to write.
    content: String,
}

#[derive(serde::Deserialize, JsonSchema)]
struct PipelineRegisterParams {
    /// Source-relative path of the pipeline (e.g. "api/blog-home").
    /// The .zf.json extension is added automatically if omitted.
    /// Preferred over name+path. If omitted, derived from name and path fields.
    #[serde(default)]
    #[schemars(with = "String")]
    file_rel_path: Option<String>,
    /// Pipeline name slug (e.g. "blog-home", "process-order"). Used when file_rel_path is not set.
    #[serde(default)]
    #[schemars(with = "String")]
    name: Option<String>,
    /// Virtual path for grouping (e.g. "/pages", "/api", "/jobs"). Defaults to "/". Used when file_rel_path is not set.
    #[serde(default)]
    #[schemars(with = "String")]
    path: Option<String>,
    /// Optional human-readable display title.
    #[schemars(with = "String")]
    title: Option<String>,
    /// Optional human-readable description of what this pipeline does.
    /// Stored in the pipeline graph (.zf.json) and indexed in the catalog for search.
    #[serde(default)]
    #[schemars(with = "String")]
    description: Option<String>,
    /// Pipeline body: nodes written as their kinds (`family.noun.verb`), pipe mode or graph mode.
    /// Example: "| trigger.webhook --route /blog --method GET | postgres.query.run --credential pg_main -- \"SELECT * FROM posts\" | web.response.send --template pages/blog.tsx"
    /// Each node adds one key, its noun (the rows are `input.query.rows`). help("pipeline/dsl") is the grammar; help("pipeline/nodes/<kind>") one node.
    body: String,
}

#[derive(serde::Deserialize, JsonSchema)]
struct PipelineCheckParams {
    /// The pipeline body you would give pipeline_register: pipe mode starting with `|` or graph mode starting with `[label]`.
    #[serde(default)]
    #[schemars(with = "String")]
    body: Option<String>,
    /// A saved pipeline to check instead of a body (e.g. "api/blog-home.zf.json").
    #[serde(default)]
    #[schemars(with = "String")]
    file_rel_path: Option<String>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct PipelineDescribeParams {
    /// Source-relative path of the pipeline (e.g. "api/blog-home.zf.json").
    file_rel_path: String,
    /// When true, shows one compact line per node (id | kind | key flags) without body content.
    /// Use for orientation when pipelines have long SQL or script bodies.
    #[serde(default)]
    compact: bool,
}

#[derive(serde::Deserialize, JsonSchema)]
struct PipelinePatchParams {
    /// Source-relative path of the pipeline (e.g. "api/blog-home.zf.json").
    file_rel_path: String,
    /// Node ID to patch — get IDs from pipeline_describe output (e.g. "n0", "b", "trigger").
    /// With target "note" this is the note id (created when it does not exist yet).
    node_id: String,
    /// What to patch: "node" (default) or "note" — a canvas note. Note flags:
    /// --text, --at x,y, --size WxH, --color amber|blue|green|rose|violet|teal|orange|slate, --remove.
    #[schemars(with = "String")]
    target: Option<String>,
    /// Space-separated --flag value pairs to update in the node config — flags the node declares
    /// (help("pipeline/nodes/<kind>")). Example: "--limit 100 --timeout 30s"
    #[schemars(with = "String")]
    flags: Option<String>,
    /// The node's body: the SQL of a query node, the code of a script node.
    #[schemars(with = "String")]
    body: Option<String>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct PipelineActivateParams {
    /// Source-relative path of the pipeline to activate (e.g. "api/blog-home.zf.json").
    /// Ignored when glob is set.
    #[serde(default)]
    file_rel_path: String,
    /// Glob pattern to bulk-activate matching pipelines (e.g. "modules/manage/**").
    /// When set, activates all pipelines whose file_rel_path matches. file_rel_path is ignored.
    #[serde(default)]
    #[schemars(with = "String")]
    glob: Option<String>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct MigrationPlanParams {
    /// "markdown" for the readable report alone; omit for the whole plan as JSON.
    #[serde(default)]
    #[schemars(with = "String")]
    format: Option<String>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct MigrationApplyParams {
    /// The fingerprint of the plan being applied, as migration_plan answered it.
    fingerprint: String,
}

#[derive(serde::Deserialize, JsonSchema)]
struct PipelineDeactivateParams {
    /// Source-relative path of the pipeline to deactivate (e.g. "api/blog-home.zf.json").
    file_rel_path: String,
}

#[derive(serde::Deserialize, JsonSchema)]
struct PipelineExecuteParams {
    /// Source-relative path of the registered active pipeline to execute (e.g. "api/blog-home.zf.json").
    file_rel_path: String,
    /// Optional JSON input payload (object or string). For a pipeline with `input.*` nodes:
    /// `{"body": {"<field>": …}, "files": {"<field>": "<store path>"}}` — a store path becomes the FileRef.
    #[serde(default)]
    input: Option<serde_json::Value>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct PipelineRunParams {
    /// Pipe-chained node body to execute inline — NOT saved, NOT logged.
    /// Starts with | followed by nodes: "| postgres.query.run --credential pg_main -- \"SELECT count(*) FROM users\""
    /// Auto-prepends trigger.manual if no trigger node is specified.
    /// Use this for testing queries, one-off scripts, or data exploration.
    body: String,
    /// Optional JSON input payload (object or JSON string).
    /// Passed as the initial pipeline payload to trigger nodes.
    /// Example: {"message": "hello"} or "{\"message\": \"hello\"}"
    #[serde(default)]
    input: Option<serde_json::Value>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct PipelineGetInvocationsParams {
    /// Source-relative path of the pipeline (e.g. "api/blog-home.zf.json").
    file_rel_path: String,
}

#[derive(serde::Deserialize, JsonSchema)]
struct GitCommandParams {
    /// Git subcommand: status, log, diff, add, commit — and the remote verbs state, fetch, sync, push, resolve, continue, abort.
    /// `sync` rebases local commits on the remote and, on a conflict, leaves it in progress and lists the files;
    /// `resolve <path> mine|theirs` settles one (or `content` with the file's text in `message`), then `continue`; `abort` puts everything back.
    subcommand: String,
    /// Additional arguments as a space-separated string (e.g. "path/to/file" for add/diff, "--limit 10" for log, "<path> mine" for resolve).
    #[schemars(with = "String")]
    args: Option<String>,
    /// Commit message — only used when subcommand is "commit".
    #[schemars(with = "String")]
    message: Option<String>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct SkillReadParams {
    /// Skill name as listed by skill_list (e.g. "zebflow-pipeline").
    name: String,
    /// Optional file inside the skill folder (e.g. "references/verify.md"). Omit for SKILL.md.
    #[schemars(with = "String")]
    path: Option<String>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct ConnectionDescribeParams {
    /// Connection slug — get slugs from connection_list (e.g. "main-db", "default").
    slug: String,
    /// Scope to inspect: "tables", "schemas", "functions", or omit for full tree.
    #[schemars(with = "String")]
    scope: Option<String>,
    /// Filter to a specific schema name (e.g. "public"). Only meaningful with scope="tables".
    #[schemars(with = "String")]
    schema: Option<String>,
    /// Filter to a specific table for column-level detail.
    /// Format: "schema.table" (e.g. "academic.staff") or just "table" for public schema.
    /// Use scope="tables" first to discover table names, then table=<name> for columns.
    #[schemars(with = "String")]
    table: Option<String>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct HelpSearchParams {
    /// Search query — node name, DSL flag, concept, or keyword.
    query: String,
}

#[derive(serde::Deserialize, JsonSchema)]
struct ThemeGenerateParams {
    /// The brand's main colour as #RRGGBB. Omit to use the mood's default seed.
    #[serde(default)]
    seed: Option<String>,
    /// calm | warm | serious | energetic | playful | luxurious | technical (default calm).
    #[serde(default)]
    mood: Option<String>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct RouteFetchParams {
    /// The route under this project, e.g. "/book" or "/api/slots?date=2026-09-14". Not a full URL.
    path: String,
    /// GET (default), POST, PUT, PATCH, DELETE.
    #[serde(default)]
    method: Option<String>,
    /// JSON body (an object) or raw text (a string). Ignored when `form` is given.
    #[serde(default)]
    body: Option<serde_json::Value>,
    /// Fields to post as application/x-www-form-urlencoded, like a browser <form>.
    /// With `files`, they go as text parts of the multipart body instead.
    #[serde(default)]
    form: Option<serde_json::Map<String, serde_json::Value>>,
    /// Files to upload, by form field: a store key in the project's default store
    /// (`{"photo": "uploads/cat.png"}`) or `{"name": "cat.png", "content_type": "image/png", "base64": "iVBOR…"}`.
    /// With `files` the request is multipart/form-data, like a browser <form enctype="multipart/form-data">;
    /// a webhook reads them as `input.webhook.files.<field>`.
    #[serde(default)]
    files: Option<serde_json::Map<String, serde_json::Value>>,
    /// Extra request headers.
    #[serde(default)]
    headers: Option<serde_json::Map<String, serde_json::Value>>,
    /// Cookie header value, e.g. "zebflow_session=eyJ…" — from a login response's set_cookie.
    #[serde(default)]
    cookie: Option<String>,
    /// Follow up to 5 redirects. Default false, so a 302/303 and its location are visible.
    #[serde(default)]
    #[schemars(with = "bool")]
    follow_redirects: Option<bool>,
    /// Cap on returned body characters (200–60000, default 6000).
    #[serde(default)]
    #[schemars(with = "u32")]
    max_body_chars: Option<usize>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct HubSearchParams {
    /// A word to match in the package id, title, description or tags. Empty lists everything.
    #[serde(default)]
    query: Option<String>,
    /// Restrict to one asset kind: skill, rwe_library, pipeline, template_pack, folder_bundle, project_bundle, node_bundle.
    #[serde(default)]
    kind: Option<String>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct HubPackageParams {
    /// The package id from `hub_search`, e.g. `zebflow.skill-procedural-assets`.
    package_id: String,
    /// A release version from `hub_search`; omitted, the latest live release.
    #[serde(default)]
    version: Option<String>,
    /// Where a bundle lands, relative to the source root. Ignored for skills and libraries, which have fixed homes.
    #[serde(default)]
    target_folder: Option<String>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct InstallUiComponentsParams {
    /// Component names to install, e.g. ["button", "card", "dialog"].
    names: Vec<String>,
    /// If true, overwrite existing files. Default: false.
    #[serde(default)]
    #[schemars(with = "bool")]
    overwrite: Option<bool>,
}

#[derive(serde::Deserialize, JsonSchema)]
struct MoveParams {
    /// Source path to move from.
    /// Pipelines: file_rel_path e.g. "api/old-name.zf.json" or just "old-name".
    /// Templates: rel_path e.g. "pages/old-name.tsx" or "components/old-card.tsx".
    from_path: String,
    /// Destination path to move to. Same domain as from_path.
    /// Parent folders are created automatically.
    to_path: String,
}

// ── Handler ───────────────────────────────────────────────────────────────────

/// Zebflow MCP handler with project-scoped tools.
///
/// Sessions are injected via HTTP request extensions by the middleware layer.
/// Tools access the session via `Extension<http::request::Parts>` and extract
/// the `McpSession` from `parts.extensions`.
#[derive(Clone)]
pub struct ZebflowMcpHandler {
    platform: Arc<PlatformService>,
    template_cache: crate::pipeline::engines::basic::TemplateCache,
    tool_router: rmcp::handler::server::tool::ToolRouter<Self>,
}

#[tool_router]
impl ZebflowMcpHandler {
    pub fn new(
        platform: Arc<PlatformService>,
        template_cache: crate::pipeline::engines::basic::TemplateCache,
    ) -> Self {
        Self {
            platform,
            template_cache,
            tool_router: Self::tool_router(),
        }
    }

    // ── Orientation ──────────────────────────────────────────────────────────

    #[tool(
        description = "Call this first. Returns the project (its documents, what exists, databases, \
        AGENTS.md and MEMORY.md), how a pipeline is written (kinds are family.noun.verb; each node \
        adds one key, its noun), how to find a node (help pipeline/nodes, then pipeline/nodes/<kind>, \
        then help_search), and which skill each kind of task opens."
    )]
    async fn start_here(
        &self,
        Extension(parts): Extension<http::request::Parts>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.start_here().await;
        Ok(CallToolResult::success(vec![Content::text(result.text)]))
    }

    // ── Version ──────────────────────────────────────────────────────────────

    #[tool(description = "Returns the running platform version string. \
        Use this to verify the deployed binary matches the expected Docker image tag.")]
    async fn version(&self) -> Result<CallToolResult, McpError> {
        Ok(CallToolResult::success(vec![Content::text(
            crate::version::APP_VERSION.to_string(),
        )]))
    }

    // ── Help / Knowledge ─────────────────────────────────────────────────────

    #[tool(description = "Hierarchical docs browser. No topic = full index. \
        Paths: 'pipeline' (DSL + web patterns), 'pipeline/dsl', 'pipeline/authoring', 'pipeline/web', \
        'pipeline/nodes' (every kind, one line each), 'pipeline/nodes/{kind}' (one node: signature, answer, flags, examples), \
        'pipeline/examples' (index), 'pipeline/examples/{slug}' (full recipe), \
        'web' (TSX pages), 'web/hooks', 'web/tailwind', 'web/design-system', 'web/libraries', \
        'tool' (Tool.time/arr/stat/geo), 'db', \
        'platform', 'platform/agent', 'platform/api', 'platform/operations', 'platform/workflow'. \
        Call help() before writing pipelines or templates.")]
    async fn help(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<HelpParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "help")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.help(params.topic.as_deref().unwrap_or(""));
        if result.text.starts_with("Error:") {
            Err(McpError::invalid_params(result.text, None))
        } else {
            Ok(CallToolResult::success(vec![Content::text(result.text)]))
        }
    }

    #[tool(
        description = "Search Zebflow docs. Returns matching chunks from pipeline docs, \
        web template docs, node catalog, and all help files. Use for any concept, node name, DSL flag, \
        or syntax question. Example: query='jwt', query='sqlite query', query='web.response.send'."
    )]
    async fn help_search(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<HelpSearchParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "help_search")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.help_search(&params.query);
        Ok(CallToolResult::success(vec![Content::text(result.text)]))
    }

    // ── Skills ───────────────────────────────────────────────────────────────

    #[tool(
        description = "List the skills this project's agent can load — name and one-line trigger each. \
                       A skill is the procedure for one kind of task (building a page, a pipeline, auth, verification…). \
                       When a task matches a skill, read it with skill_read before acting. \
                       Blessed skills ship with the platform; a project's own skills/<name>/SKILL.md shadows one by name."
    )]
    async fn skill_list(
        &self,
        Extension(parts): Extension<http::request::Parts>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "skill_list")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.skill_list();
        Ok(CallToolResult::success(vec![Content::text(result.text)]))
    }

    #[tool(
        description = "Read a skill's SKILL.md (the procedure, gates and checks for one kind of task), \
                       or with `path` a reference file beside it. Read a skill when its trigger matches \
                       the task at hand; do not read them all."
    )]
    async fn skill_read(
        &self,
        Parameters(params): Parameters<SkillReadParams>,
        Extension(parts): Extension<http::request::Parts>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "skill_read")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.skill_read(&params.name, params.path.as_deref());
        if result.text.starts_with("Error: ") {
            return Err(McpError::invalid_params(result.text, None));
        }
        Ok(CallToolResult::success(vec![Content::text(result.text)]))
    }

    // ── Pipelines ────────────────────────────────────────────────────────────

    #[tool(
        description = "List pipelines as a lean semantic index. Default compact rows are: \
                       file_rel_path | trigger summary | status | description. \
                       Use format='json' for full legacy metadata."
    )]
    async fn pipeline_list(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<PipelineListParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "pipeline_list")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.pipeline_list(crate::platform::services::ops::PipelineListOptions {
            query: params.query.as_deref(),
            glob: params.glob.as_deref(),
            status: params.status.as_deref(),
            trigger_kind: params.trigger_kind.as_deref(),
            limit: params.limit,
            format: params.format.as_deref(),
        });
        ok_or_err(result)
    }

    #[tool(
        description = "Search pipeline .zf.json files for a pattern. Returns file:line matches. \
                       Use glob to narrow scope (e.g. \"api/*.zf.json\"). \
                       Equivalent to Grep across pipelines — find which pipelines use a credential, path, or node kind."
    )]
    async fn pipeline_search(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<PipelineSearchParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "pipeline_search")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        ok_or_err(ops.pipeline_search(
            &params.pattern,
            params.glob.as_deref(),
            params.context.unwrap_or(0) as usize,
            params.head_limit,
            params.output_mode.as_deref(),
        ))
    }

    #[tool(description = "Get a specific pipeline by file-relative path")]
    async fn pipeline_get(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<PipelineGetParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "pipeline_get")?;
        if self.pipeline_locked(&session.owner, &session.project, &params.file_rel_path) {
            return Err(McpError::invalid_params(
                "This pipeline is locked by the project owner and cannot be accessed by agents. Ask the owner to unlock it.",
                None,
            ));
        }
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.pipeline_get(&params.file_rel_path, None);
        ok_or_err(result)
    }

    #[tool(
        description = "Register (create or update) a pipeline at file_rel_path from a DSL body. \
                       The body is the nodes only — pipe mode '| trigger.webhook --route /x | sekejap.query.run -- \"SQL\" | web.response.send --template pages/x.tsx' \
                       or graph mode '[a] trigger.webhook … [b] … [a] -> [b]' — with no leading 'register …' line (that is the console form). \
                       It is saved as a draft; call pipeline_activate to make it live. Re-registering a live pipeline makes it stale until activated. \
                       Each node is written as its kind (family.noun.verb) and adds one key, its noun. \
                       help(\"pipeline/dsl\") for the grammar, help(\"pipeline/nodes/<kind>\") for a node's flags and answer."
    )]
    async fn pipeline_register(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<PipelineRegisterParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "pipeline_register")?;
        // Check lock on existing pipeline (by resolved file_rel_path if provided)
        if let Some(ref frp) = params.file_rel_path {
            let frp = self
                .platform
                .projects
                .pipeline_identity(&session.owner, &session.project, frp)
                .map_err(|error| McpError::internal_error(error.to_string(), None))?;
            if self.pipeline_locked(&session.owner, &session.project, &frp) {
                return Err(McpError::invalid_params(
                    "This pipeline is locked by the project owner and cannot be accessed by agents. Ask the owner to unlock it.",
                    None,
                ));
            }
        }
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops
            .pipeline_register(
                &params.body,
                params.file_rel_path.as_deref(),
                params.name.as_deref(),
                params.path.as_deref(),
                params.title.as_deref(),
                params.description.as_deref(),
            )
            .await;
        // navigate is ignored for MCP
        Ok(CallToolResult::success(vec![Content::text(result.text)]))
    }

    #[tool(
        description = "Check a pipeline before you save it — the first step of check → register → run → fetch. \
                       Lists every problem pipeline_register would refuse (an unknown kind or flag, a missing required flag, \
                       a word outside a closed choice such as `--format jpeg`, a duration or size that does not parse, a cycle) \
                       and, as warnings, every `input.<key>` or `$nodes.<id>.<key>` no upstream node answers, with the key it \
                       likely meant (`input.result` after a script → `input.script`). Saves nothing. Give `body` (the DSL you \
                       would register) or `file_rel_path` (a saved pipeline)."
    )]
    async fn pipeline_check(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<PipelineCheckParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "pipeline_check")?;
        if let Some(frp) = params.file_rel_path.as_deref().filter(|p| !p.trim().is_empty())
            && self.pipeline_locked(&session.owner, &session.project, frp)
        {
            return Err(McpError::invalid_params(
                "This pipeline is locked by the project owner and cannot be accessed by agents. Ask the owner to unlock it.",
                None,
            ));
        }
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.pipeline_check(params.body.as_deref(), params.file_rel_path.as_deref()).await;
        Ok(CallToolResult::success(vec![Content::text(result.text)]))
    }

    #[tool(
        description = "Inspect a pipeline — returns its nodes, edges, status, and hit stats. \
                       Node IDs from this output are required for pipeline_patch. \
                       Set compact=true to show one line per node (id | kind | key flags) \
                       without body content — useful for pipelines with long SQL or scripts."
    )]
    async fn pipeline_describe(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<PipelineDescribeParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "pipeline_describe")?;
        if self.pipeline_locked(&session.owner, &session.project, &params.file_rel_path) {
            return Err(McpError::invalid_params(
                "This pipeline is locked by the project owner and cannot be accessed by agents. Ask the owner to unlock it.",
                None,
            ));
        }
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops
            .pipeline_describe(&params.file_rel_path, params.compact)
            .await;
        Ok(CallToolResult::success(vec![Content::text(result.text)]))
    }

    #[tool(
        description = "Patch one node in a saved pipeline without rewriting the full graph. \
                       node_id accepts: opaque ID (e.g. 'n0'), node kind (e.g. 'trigger.webhook', 'postgres.query.run'), \
                       or kind+index (e.g. 'postgres.query.run[1]') when multiple nodes share the same kind. \
                       Pipeline status becomes stale after patching — call pipeline_activate to make it live again."
    )]
    async fn pipeline_patch(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<PipelinePatchParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "pipeline_patch")?;
        if self.pipeline_locked(&session.owner, &session.project, &params.file_rel_path) {
            return Err(McpError::invalid_params(
                "This pipeline is locked by the project owner and cannot be accessed by agents. Ask the owner to unlock it.",
                None,
            ));
        }
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops
            .pipeline_patch(
                &params.file_rel_path,
                params.target.as_deref().unwrap_or("node"),
                &params.node_id,
                params.flags.as_deref(),
                params.body.as_deref(),
            )
            .await;
        Ok(CallToolResult::success(vec![Content::text(result.text)]))
    }

    #[tool(
        description = "Activate a pipeline — makes it live so it can serve traffic and be executed. \
                       Must be called after pipeline_register or after patching. \
                       A pipeline must be active before pipeline_execute will run it. \
                       Set glob (e.g. \"modules/manage/**\") to bulk-activate all matching pipelines \
                       instead of activating one at a time."
    )]
    async fn pipeline_activate(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<PipelineActivateParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "pipeline_activate")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);

        // Bulk mode: glob provided → activate all matching pipelines (no lock check per pipeline).
        if let Some(ref glob) = params.glob {
            let result = ops.pipeline_activate_glob(glob).await;
            return Ok(CallToolResult::success(vec![Content::text(result.text)]));
        }

        // Single mode: check lock and activate exact path.
        if self.pipeline_locked(&session.owner, &session.project, &params.file_rel_path) {
            return Err(McpError::invalid_params(
                "This pipeline is locked by the project owner and cannot be accessed by agents. Ask the owner to unlock it.",
                None,
            ));
        }
        let result = ops.pipeline_activate(&params.file_rel_path).await;
        // navigate is ignored for MCP
        Ok(CallToolResult::success(vec![Content::text(result.text)]))
    }

    #[tool(
        description = "Plan moving this project from 0.10 to 0.11 — reads only. Every 0.10 pipeline rewritten for the 0.11 \
                       kinds, flags and answers and put through the save-time check, and every page a 0.10 pipeline renders \
                       rewritten for the payload it now receives: per file the changes, a diff, the check, behaviour notes \
                       and what could not be mapped. Answers a fingerprint for migration_apply. A plan that is ready and holds \
                       no review item was already applied when the server started; this is for the rest. Only for a \
                       session the project's owner created."
    )]
    async fn migration_plan(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<MigrationPlanParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "migration_plan")?;
        self.check_owner_grant(&session)?;
        let service = crate::platform::services::MigrationService::new(self.platform.clone());
        let plan = service
            .plan_project(&session.owner, &session.project)
            .map_err(|e| McpError::internal_error(e.message, None))?;
        let text = if params.format.as_deref() == Some("markdown") {
            plan.report
        } else {
            serde_json::to_string_pretty(&plan).unwrap_or_default()
        };
        Ok(CallToolResult::success(vec![Content::text(text)]))
    }

    #[tool(
        description = "Apply the 0.11 migration plan whose fingerprint is given: each rewritten pipeline is deactivated, its \
                       0.10 original copied to archive/0.10/<same path>, the rewrite registered at the same path and activated \
                       again if it was active; each rewritten page is archived and written. Refused when the plan has unresolved \
                       items or refused checks, or the project changed since the plan. Running it again changes nothing. Only for \
                       a session the project's owner created."
    )]
    async fn migration_apply(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<MigrationApplyParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "migration_apply")?;
        self.check_owner_grant(&session)?;
        let service = crate::platform::services::MigrationService::new(self.platform.clone());
        match service.apply_plan(&session.owner, &session.project, &params.fingerprint).await {
            Ok(report) => Ok(CallToolResult::success(vec![Content::text(
                serde_json::to_string_pretty(&report).unwrap_or_default(),
            )])),
            Err(e) => Err(McpError::invalid_params(format!("{}: {}", e.code, e.message), None)),
        }
    }

    #[tool(
        description = "Deactivate a pipeline — takes it offline. Traffic stops being served. \
                       Pipeline source is retained and can be re-activated later."
    )]
    async fn pipeline_deactivate(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<PipelineDeactivateParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "pipeline_deactivate")?;
        if self.pipeline_locked(&session.owner, &session.project, &params.file_rel_path) {
            return Err(McpError::invalid_params(
                "This pipeline is locked by the project owner and cannot be accessed by agents. Ask the owner to unlock it.",
                None,
            ));
        }
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.pipeline_deactivate(&params.file_rel_path).await;
        Ok(CallToolResult::success(vec![Content::text(result.text)]))
    }

    #[tool(
        description = "Execute a registered active pipeline by name. Records execution hits. \
                       Pipeline must be activated first — use pipeline_activate if status is draft or stale. \
                       Use pipeline_list to see pipeline names and activation status. \
                       For function pipelines (trigger.function) always pass `input` to test with real data; \
                       without it the pipeline receives an empty payload {}. \
                       A pipeline with input.* nodes expects the trigger envelope: \
                       input={\"body\": {\"prompt\": \"x\"}, \"files\": {\"photo\": \"uploads/cat.png\"}} — \
                       a `files` value is a store path (project files, private or public) that becomes the FileRef of that object."
    )]
    async fn pipeline_execute(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<PipelineExecuteParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "pipeline_execute")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        // Normalize input: accept JSON object/array or string, serialize to JSON string for DSL.
        let input_str = params.input.as_ref().and_then(|v| match v {
            serde_json::Value::String(s) if !s.is_empty() => Some(s.clone()),
            serde_json::Value::Null => None,
            other => serde_json::to_string(other).ok(),
        });
        let result = ops
            .pipeline_execute(&params.file_rel_path, input_str.as_deref())
            .await;
        Ok(CallToolResult::success(vec![Content::text(result.text)]))
    }

    #[tool(
        description = "Run a pipe-chained node body EPHEMERALLY — not saved, not logged, no hit recording. \
                       Use this to test queries, explore data, or prototype before registering. \
                       Example body: '| postgres.query.run --credential pg_main -- \"SELECT count(*) FROM users\"' — the rows come back at input.query.rows. \
                       Auto-prepends trigger.manual if no trigger node specified."
    )]
    async fn pipeline_run(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<PipelineRunParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "pipeline_run")?;
        let initial_input = params.input.and_then(|v| match v {
            serde_json::Value::Object(_) | serde_json::Value::Array(_) => Some(v),
            serde_json::Value::String(s) if !s.is_empty() => serde_json::from_str(&s).ok(),
            _ => None,
        });
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.pipeline_run(&params.body, initial_input).await;
        Ok(CallToolResult::success(vec![Content::text(result.text)]))
    }

    #[tool(
        description = "Get recent execution history for a pipeline. Returns stored invocations \
                           with timestamp, duration, status (ok/error), trigger source, error message, \
                           and per-node trace. Use this to inspect past runs, debug failures on scheduled \
                           pipelines, or verify that a pipeline is executing correctly."
    )]
    async fn pipeline_get_invocations(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<PipelineGetInvocationsParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "pipeline_get_invocations")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        ok_or_err(ops.pipeline_get_invocations(&params.file_rel_path))
    }

    // ── Templates ────────────────────────────────────────────────────────────

    #[tool(description = "List templates in the project workspace. Optional glob filters files.")]
    async fn file_list(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<FileListParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "file_list")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.file_list(crate::platform::services::ops::FileListOptions {
            query: params.query.as_deref(),
            glob: params.glob.as_deref(),
            kind: params.kind.as_deref(),
            limit: params.limit,
            format: params.format.as_deref(),
        });
        ok_or_err(result)
    }

    #[tool(description = "Get a specific template by relative path. \
                       Use offset and limit to read a line-numbered slice instead of the full file.")]
    async fn file_read(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<FileReadParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "file_read")?;
        if self.template_locked(&session.owner, &session.project, &params.rel_path) {
            return Err(McpError::invalid_params(
                "This template is locked by the project owner and cannot be accessed by agents. Ask the owner to unlock it.",
                None,
            ));
        }
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.file_read(&params.rel_path, params.offset, params.limit);
        ok_or_err(result)
    }

    #[tool(description = "Create a new source file with scaffolding. \
                       Kind must be one of: page (.tsx), component (.tsx), script (.ts), style (.css), doc (.md), folder. \
                       The file lands at parent_rel_path/name.<ext> relative to the source root — pass \
                       parent_rel_path=\"pages\" to get pages/<name>.tsx; without it the file is created at the root. \
                       Returns the scaffolded content — use file_write to customise it after.")]
    async fn file_create(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<FileCreateParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "file_create")?;
        // Check lock on parent folder if provided
        if let Some(ref parent) = params.parent_rel_path {
            if self.template_locked(&session.owner, &session.project, parent) {
                return Err(McpError::invalid_params(
                    "This template folder is locked by the project owner and cannot be accessed by agents. Ask the owner to unlock it.",
                    None,
                ));
            }
        }
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.file_create(
            &params.kind,
            &params.name,
            params.parent_rel_path.as_deref(),
        );
        // navigate is ignored for MCP
        ok_or_err(result)
    }

    #[tool(description = "Write (create or overwrite) a template file. \
                       Use file_create first to scaffold with boilerplate, then file_write to fill in content. \
                       Path is relative to templates/ (e.g. 'pages/blog-home.tsx', 'components/ui/card.tsx', 'scripts/format-address.ts'). \
                       Use help(\"web\") for TSX conventions or help(\"web/custom-scripts\") for TypeScript module rules before writing. \
                       A .tsx / .ts file is checked as it is written: the answer's template_problems lists each parse error, each name used \
                       but never imported and each local `h` with path:line:column — the file is saved anyway; fix them before route_fetch.")]
    async fn file_write(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<FileWriteParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "file_write")?;
        if self.template_locked(&session.owner, &session.project, &params.rel_path) {
            return Err(McpError::invalid_params(
                "This template is locked by the project owner and cannot be accessed by agents. Ask the owner to unlock it.",
                None,
            ));
        }
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.file_write(&params.rel_path, &params.content);
        if !result.text.starts_with("Error:") {
            if let Ok(abs) = self.platform.projects.resolve_template_abs_path(
                &session.owner,
                &session.project,
                &params.rel_path,
            ) {
                crate::pipeline::engines::basic::evict_template_cache_by_path(
                    &self.template_cache,
                    &abs.to_string_lossy(),
                );
            }
        }
        // navigate is ignored for MCP
        ok_or_err(result)
    }

    #[tool(
        description = "Search template files for a pattern. Returns file:line matches. \
                       Use glob to narrow scope (e.g. \"pages/*.tsx\", \"**/*.tsx\"). \
                       Equivalent to Grep across templates — find which files use an import, component, or value."
    )]
    async fn file_search(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<FileSearchParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "file_search")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        ok_or_err(ops.file_search(
            &params.pattern,
            params.glob.as_deref(),
            params.context.unwrap_or(0) as usize,
            params.head_limit,
            params.output_mode.as_deref(),
        ))
    }

    #[tool(description = "Surgical string replacement in a template file. \
                       Equivalent to Edit — no need to read the full file first. \
                       Fails if old_string is not found or matches more than once (provide more context). \
                       Answers { rel_path, line }; a .tsx / .ts file is checked as it stands after the edit and \
                       template_problems lists what will break the page, as file_write does.")]
    async fn file_edit(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<FileEditParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "file_edit")?;
        if self.template_locked(&session.owner, &session.project, &params.rel_path) {
            return Err(McpError::invalid_params(
                "This template is locked by the project owner and cannot be accessed by agents. Ask the owner to unlock it.",
                None,
            ));
        }
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.file_edit(&params.rel_path, &params.old_string, &params.new_string);
        if !result.text.starts_with("Error:") {
            if let Ok(abs) = self.platform.projects.resolve_template_abs_path(
                &session.owner,
                &session.project,
                &params.rel_path,
            ) {
                crate::pipeline::engines::basic::evict_template_cache_by_path(
                    &self.template_cache,
                    &abs.to_string_lossy(),
                );
            }
        }
        ok_or_err(result)
    }

    #[tool(
        description = "Parse a template file and return its code outline: imports, exports, \
                       functions, classes, types, interfaces, and line numbers. \
                       Use this before file_read when orienting on a large TSX/TS file."
    )]
    async fn file_outline(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<FileOutlineParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "file_outline")?;
        if self.template_locked(&session.owner, &session.project, &params.rel_path) {
            return Err(McpError::invalid_params(
                "This template is locked by the project owner and cannot be accessed by agents. Ask the owner to unlock it.",
                None,
            ));
        }
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.file_outline(&params.rel_path);
        ok_or_err(result)
    }

    #[tool(
        description = "Show a template dependency graph: imports used by this file and \
                       other project templates that import it. Use before refactoring shared UI."
    )]
    async fn file_deps(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<FileDepsParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "file_deps")?;
        if self.template_locked(&session.owner, &session.project, &params.rel_path) {
            return Err(McpError::invalid_params(
                "This template is locked by the project owner and cannot be accessed by agents. Ask the owner to unlock it.",
                None,
            ));
        }
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.file_deps(&params.rel_path);
        ok_or_err(result)
    }

    #[tool(
        description = "Apply multiple exact string edits across template files in one call. \
                       Each edit is rel_path + old_string + new_string. \
                       Evicts template cache for edited files when the batch succeeds. \
                       Answers { results }; every .tsx / .ts file it changed is checked once after its edits and \
                       template_problems lists what will break the page, as file_write does."
    )]
    async fn file_batch_edit(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<FileBatchEditParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "file_batch_edit")?;
        for edit in &params.edits {
            if self.template_locked(&session.owner, &session.project, &edit.rel_path) {
                return Err(McpError::invalid_params(
                    format!("Template '{}' is locked", edit.rel_path),
                    None,
                ));
            }
        }
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let edits: Vec<(String, String, String)> = params
            .edits
            .iter()
            .map(|edit| {
                (
                    edit.rel_path.clone(),
                    edit.old_string.clone(),
                    edit.new_string.clone(),
                )
            })
            .collect();
        let result = ops.file_batch_edit(&edits);
        if result.text.contains("ERROR:") {
            return Err(McpError::invalid_params(result.text, None));
        }
        if !result.text.starts_with("Error:") {
            for edit in &params.edits {
                if let Ok(abs) = self.platform.projects.resolve_template_abs_path(
                    &session.owner,
                    &session.project,
                    &edit.rel_path,
                ) {
                    crate::pipeline::engines::basic::evict_template_cache_by_path(
                        &self.template_cache,
                        &abs.to_string_lossy(),
                    );
                }
            }
        }
        ok_or_err(result)
    }

    // ── Agent Docs ───────────────────────────────────────────────────────────

    #[tool(
        description = "List the three agent doc files: AGENTS.md (project instructions for agents), \
                       SOUL.md (agent personality and behavior config), MEMORY.md (persistent memory across sessions). \
                       Always read AGENTS.md first when starting work on a project."
    )]
    async fn docs_agent_list(
        &self,
        Extension(parts): Extension<http::request::Parts>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "docs_agent_list")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.docs_agent_list();
        ok_or_err(result)
    }

    #[tool(description = "Read one agent doc: AGENTS.md (project instructions), \
                       SOUL.md (agent personality), or MEMORY.md (persistent memory). \
                       Read AGENTS.md at the start of every session to understand the project.")]
    async fn docs_agent_read(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<DocsAgentReadParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "docs_agent_read")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.docs_agent_read(&params.name);
        ok_or_err(result)
    }

    #[tool(
        description = "Write an agent doc. AGENTS.md: project-specific instructions for all agents. \
                       SOUL.md: agent personality, tone, and behavioral config. \
                       MEMORY.md: persistent notes the agent writes to remember things across sessions. \
                       Agents should update MEMORY.md after completing significant work."
    )]
    async fn docs_agent_write(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<DocsAgentWriteParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "docs_agent_write")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.docs_agent_write(&params.name, &params.content);
        ok_or_err(result)
    }

    // ── Connections & Credentials ─────────────────────────────────────────────

    #[tool(
        description = "List all DB connections for this project — returns slug, label, and kind (postgresql, sekejap, sqlite, ...). Every project has `default` (sqlite) and `default-multimodel` (sekejap). Use the slug with connection_describe. (`--credential` flags take a credential id from credential_list, not a connection slug.)"
    )]
    async fn connection_list(
        &self,
        Extension(parts): Extension<http::request::Parts>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "connection_list")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.connection_list();
        ok_or_err(result)
    }

    #[tool(
        description = "Describe a DB connection's schema — tables, columns, types, constraints. Use scope='tables' for a quick overview, scope='schemas' to list schemas, or omit scope for the full tree. Always run this before writing SQL queries. Use table='schema.table' (e.g. table='academic.staff') to get column detail for a specific table."
    )]
    async fn connection_describe(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<ConnectionDescribeParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "connection_describe")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops
            .connection_describe(
                &params.slug,
                params.scope.as_deref(),
                params.schema.as_deref(),
                params.table.as_deref(),
            )
            .await;
        ok_or_err(result)
    }

    #[tool(
        description = "List credentials for this project — returns id, title, and kind only. Values are never exposed. Use the id in pipeline nodes that require authentication."
    )]
    async fn credential_list(
        &self,
        Extension(parts): Extension<http::request::Parts>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "credential_list")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.credential_list();
        ok_or_err(result)
    }

    // ── Git ──────────────────────────────────────────────────────────────────

    #[tool(description = "Run a git command on the project repository. \
                       Allowed subcommands: status, log, diff, add, commit. \
                       Destructive operations (reset, rebase, force, checkout) are blocked. \
                       Always commit after registering or patching pipelines.")]
    async fn git_command(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<GitCommandParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "git_command")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops
            .git_command(
                &params.subcommand,
                params.args.as_deref(),
                params.message.as_deref(),
            )
            .await;
        Ok(CallToolResult::success(vec![Content::text(result.text)]))
    }

    // ── UI Catalog ───────────────────────────────────────────────────────────

    #[tool(
        description = "List all available shadcn-compatible Zeb React UI components \
        that can be installed into shared/ui/. Returns name, category, description, \
        filename, and whether each component is already installed in this project."
    )]
    async fn list_ui_catalog(
        &self,
        Extension(parts): Extension<http::request::Parts>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "list_ui_catalog")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.list_ui_catalog();
        ok_or_err(result)
    }

    #[tool(
        description = "Install shadcn-compatible UI components into shared/ui/. \
        Pass names like [\"button\",\"card\",\"dialog\"]. \
        Set overwrite=true to replace existing files. \
        Returns installed and skipped lists."
    )]
    async fn install_ui_components(
        &self,
        Parameters(params): Parameters<InstallUiComponentsParams>,
        Extension(parts): Extension<http::request::Parts>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "install_ui_components")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.install_ui_components(params.names, params.overwrite);
        ok_or_err(result)
    }

    // ── Theme ─────────────────────────────────────────────────────────────────

    #[tool(
        description = "Generate a complete theme from one seed colour and one mood — every colour token for light \
        and dark as hex, contrast-checked (text 4.5:1, marks 3:1 against every surface), the `:root` / `.dark` \
        blocks to paste into globals.css, the mood's fonts (with the Google Fonts link), sizes, radius, spacing \
        and shadow, a contrast table, and notes on anything adjusted. `seed` is #RRGGBB (omit for the mood's \
        default); `mood` is calm | warm | serious | energetic | playful | luxurious | technical. Never pick \
        colours by hand — call this, paste `css`, record the notes in docs/brand.md (skill: brand-system)."
    )]
    async fn theme_generate(
        &self,
        Parameters(params): Parameters<ThemeGenerateParams>,
        Extension(parts): Extension<http::request::Parts>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "theme_generate")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        ok_or_err(ops.theme_generate(params.seed, params.mood))
    }

    // ── Route fetch ───────────────────────────────────────────────────────────

    #[tool(
        description = "Fetch one of this project's own routes the way a browser would — the verification step. \
        `path` is the route under the project (`/`, `/book`, `/api/slots?date=2026-09-14`); the request goes to \
        the project's own host (`<project>.<owner>.localhost`) through the real ingress, so auth, cookies, \
        redirects (`location: /admin` means the project's /admin) and page rendering happen exactly as in a browser. Returns status, content_type, location, set_cookie, length, rwe_component_errors (every \
        `<!-- RWE component error -->` in the body — a 200 with one of these is a broken page), for HTML an \
        `seo` object (title, description_chars, canonical, h1_count, og completeness and whether og:image is \
        absolute, twitter_card, jsonld_types, hreflang, images_without_alt, robots, lang — compare these against \
        the growth-rules skill instead of reading HTML) and the body (capped, `max_body_chars`). `method` GET|POST|PUT|DELETE; `form` posts url-encoded fields like a <form>; \
        `body` sends JSON (an object) or raw text (a string); `files` uploads files as multipart/form-data (field → a store key, \
        or `{name, content_type, base64}`; `form` fields go beside them) — a webhook reads them as `input.webhook.files.<field>`; `cookie` is a Cookie header value — copy it from a \
        login's set_cookie (`name=value`) to reach protected routes; `follow_redirects` is off by default so you \
        see the 302/303 and its location. Fetch every route you built, and every failure path, before saying done."
    )]
    async fn route_fetch(
        &self,
        Parameters(params): Parameters<RouteFetchParams>,
        Extension(parts): Extension<http::request::Parts>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "route_fetch")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        ok_or_err(
            ops.route_fetch(crate::platform::services::ops::RouteFetchRequest {
                path: params.path,
                method: params.method,
                body: params.body,
                form: params.form,
                files: params.files,
                headers: params.headers,
                cookie: params.cookie,
                follow_redirects: params.follow_redirects,
                max_body_chars: params.max_body_chars,
            })
            .await,
        )
    }

    // ── Hub ───────────────────────────────────────────────────────────────────

    #[tool(
        description = "List what this project can add from the Hub shelf — optional skills, zeb/* libraries, \
        pipeline and template bundles, node bundles. Filter with `query` (a word in the id, title, description \
        or tags) and `kind` (skill, rwe_library, pipeline, template_pack, folder_bundle, project_bundle, node_bundle). \
        Each row carries `package_id` and `latest_version`, which `hub_review` and `hub_add` take. \
        The core zebflow-* skills are not here: every project already has them (`skill_list`)."
    )]
    async fn hub_search(
        &self,
        Parameters(params): Parameters<HubSearchParams>,
        Extension(parts): Extension<http::request::Parts>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "hub_search")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        ok_or_err(ops.hub_search(params.query, params.kind))
    }

    #[tool(
        description = "Review a Hub package before adding it: the files it would add or overwrite, pipelines it \
        registers, nodes it uses, credentials it needs, outbound hosts, public endpoints, schedules, and any \
        violation that makes it uninstallable. `version` defaults to the latest live release. Read the review, \
        then `hub_add` — never the other way round."
    )]
    async fn hub_review(
        &self,
        Parameters(params): Parameters<HubPackageParams>,
        Extension(parts): Extension<http::request::Parts>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "hub_review")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        ok_or_err(ops.hub_review(params.package_id, params.version, params.target_folder))
    }

    #[tool(
        description = "Add a Hub package to this project (the Studio's Add button). A skill lands at \
        `skills/<name>/` and appears in `skill_list`; a zeb/* library under `shared/`; a pipeline or template \
        bundle under `target_folder` (default: the package's own folder). Pipelines arrive as drafts — \
        `pipeline_activate` them. `version` defaults to the latest live release. Returns files written and \
        pipelines registered; the dependency is recorded in zeb.lock."
    )]
    async fn hub_add(
        &self,
        Parameters(params): Parameters<HubPackageParams>,
        Extension(parts): Extension<http::request::Parts>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "hub_add")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        ok_or_err(ops.hub_add(params.package_id, params.version, params.target_folder))
    }

    // ── Move Resource ─────────────────────────────────────────────────────────

    #[tool(description = "Rename or reorganize a pipeline or template file. \
            Domain detected automatically from path: .zf.json = pipeline, anything else = template. \
            For pipelines: deactivate → move → re-activate lifecycle handled automatically. \
            Parent folders created automatically. No cross-domain moves (pipeline ↔ template).")]
    async fn move_resource(
        &self,
        Extension(parts): Extension<http::request::Parts>,
        Parameters(params): Parameters<MoveParams>,
    ) -> Result<CallToolResult, McpError> {
        let session = self.get_session_from_http_parts(&parts)?;
        self.check_tool_capability(&session, "move_resource")?;
        let ops = PlatformOps::new(self.platform.clone(), &session.owner, &session.project);
        let result = ops.move_resource(&params.from_path, &params.to_path).await;
        ok_or_err(result)
    }

    // ── Lock helpers ──────────────────────────────────────────────────────────

    /// Returns true if the pipeline at `file_rel_path` is locked.
    fn pipeline_locked(&self, owner: &str, project: &str, file_rel_path: &str) -> bool {
        self.platform
            .projects
            .read_pipeline_source(owner, project, file_rel_path)
            .map(|source| {
                let Ok(value) = serde_json::from_str::<serde_json::Value>(&source) else {
                    return false;
                };
                value
                    .get("metadata")
                    .and_then(|m| m.get("locked"))
                    .and_then(serde_json::Value::as_bool)
                    .or_else(|| value.get("locked").and_then(serde_json::Value::as_bool))
                    .unwrap_or(false)
            })
            .unwrap_or(false)
    }

    /// Returns true if the template at `rel_path` is locked.
    fn template_locked(&self, owner: &str, project: &str, rel_path: &str) -> bool {
        self.platform
            .zebflow_cfg
            .is_template_locked(owner, project, rel_path)
            .unwrap_or(false)
    }

    // ── Auth helpers ──────────────────────────────────────────────────────────

    fn get_session_from_http_parts(
        &self,
        parts: &http::request::Parts,
    ) -> Result<McpSession, McpError> {
        parts
            .extensions
            .get::<McpSession>()
            .cloned()
            .ok_or_else(|| {
                McpError::invalid_params(
                    "No active MCP session; ensure Authorization header is set with valid session token",
                    None,
                )
            })
    }

    /// Extract session from RequestContext extensions (used by manual ServerHandler impl).
    fn session_from_context(&self, context: &RequestContext<RoleServer>) -> Option<McpSession> {
        context
            .extensions
            .get::<http::request::Parts>()
            .and_then(|parts| parts.extensions.get::<McpSession>().cloned())
    }

    /// An owner-only tool: a session's capabilities are whatever its creator
    /// listed, so the creator must hold the capability itself, as the HTTP
    /// route asks of the signed-in user (`ProjectDelete`: the owner, or a
    /// superadmin).
    fn check_owner_grant(&self, session: &McpSession) -> Result<(), McpError> {
        if session.granted_by.trim().is_empty() {
            return Err(McpError::invalid_params(
                "This session does not record who created it; create the MCP session again as the project owner to use this tool.",
                None,
            ));
        }
        let subject = crate::platform::model::ProjectAccessSubject::user(&session.granted_by);
        self.platform
            .authz
            .ensure_project_capability(
                &subject,
                &session.owner,
                &session.project,
                crate::platform::model::ProjectCapability::ProjectDelete,
            )
            .map_err(|_| {
                McpError::invalid_params(
                    "This tool is the project owner's: the user who created this MCP session is not the owner of the project.",
                    None,
                )
            })
    }

    fn check_tool_capability(&self, session: &McpSession, tool_name: &str) -> Result<(), McpError> {
        let required_capability = mcp_tool_capability(tool_name)
            .ok_or_else(|| McpError::invalid_params(format!("Unknown tool '{tool_name}'"), None))?;

        if session.capabilities.contains(&required_capability) {
            return Ok(());
        }
        Err(McpError::invalid_params(
            format!(
                "Tool '{tool_name}' requires capability '{}' which is not allowed in this session",
                required_capability.key()
            ),
            None,
        ))
    }
}

/// Every text this server hands an agent besides `start_here`: the
/// instructions, and each tool's description and every description inside
/// its input schema — what the guide lint (`help::guide_lint`) parses.
#[cfg(test)]
pub(crate) fn agent_texts() -> Vec<(String, String)> {
    fn descriptions(value: &serde_json::Value, out: &mut Vec<String>) {
        match value {
            serde_json::Value::Object(map) => {
                for (key, v) in map {
                    match (key.as_str(), v) {
                        ("description", serde_json::Value::String(text)) => out.push(text.clone()),
                        _ => descriptions(v, out),
                    }
                }
            }
            serde_json::Value::Array(items) => items.iter().for_each(|v| descriptions(v, out)),
            _ => {}
        }
    }
    let mut texts = vec![("MCP_INSTRUCTIONS".to_string(), MCP_INSTRUCTIONS.to_string())];
    for tool in ZebflowMcpHandler::tool_router().list_all() {
        let mut parts: Vec<String> = tool.description.iter().map(|d| d.to_string()).collect();
        descriptions(&serde_json::Value::Object((*tool.input_schema).clone()), &mut parts);
        texts.push((format!("mcp tool {}", tool.name), parts.join("\n")));
    }
    texts
}

/// The MCP `initialize` instructions. Kept under 1 KB on purpose.
pub const MCP_INSTRUCTIONS: &str = "\
Zebflow is a unified full-stack runtime: one running instance, many projects. \
This MCP server is scoped to ONE project — its repository, store, databases, credentials and hosts. \
Project knowledge lives in the project's files (docs/, AGENTS.md, MEMORY.md); Zebflow knowledge lives in `help` and the skills. Do not confuse the two.\n\n\
Call `start_here` first: the project, how a pipeline is written, how to find a node, and the one topic or skill each task opens — one at a time, per need.\n\n\
A node is written as its kind, `family.noun.verb`, and adds one key, its noun (`input.webhook.body`, `input.query.rows`); `help topic=\"pipeline/dsl\"` is the grammar.\n\n\
Work only through the tools: `pipeline_check`, then `pipeline_register`, then `pipeline_activate`, `file_write` for pages, `route_fetch` to prove a route (a 200 with a component error is not done), `docs_agent_write name=\"MEMORY.md\"` to record what you learned. \
Never write to the filesystem behind the tools, never commit or push unless the user asks (`git_command`).";

impl ServerHandler for ZebflowMcpHandler {
    fn get_info(&self) -> ServerInfo {
        // Read by every client before its first tool call, so it is the
        // frame and one instruction — not the 10 KB agent guide, which stays
        // one `help topic="platform/agent"` away. The frame is the shape the
        // start_here ablation (2026-09-18) showed the weakest models need:
        // platform vs project, then where each kind of knowledge lives.
        let instructions = MCP_INSTRUCTIONS.to_string();
        ServerInfo {
            instructions: Some(instructions.into()),
            capabilities: ServerCapabilities::builder()
                .enable_tools()
                .enable_prompts()
                .build(),
            ..Default::default()
        }
    }

    async fn list_tools(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListToolsResult, McpError> {
        // The dev tools and nothing else. A published `trigger.mcp` tool is
        // the app's, served on its own route; this server never lists one
        // (`published-mcp.md`).
        Ok(ListToolsResult {
            tools: self.tool_router.list_all(),
            meta: None,
            next_cursor: None,
        })
    }

    /// Every skill is also an MCP prompt, so a client with slash commands
    /// (Claude Code, Cursor, …) gets `/zebflow-page` for free. The body a
    /// prompt returns is exactly what `skill_read` returns; the listing is
    /// the same tier-1 name + description.
    async fn list_prompts(
        &self,
        _request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> Result<ListPromptsResult, McpError> {
        let Some(session) = self.session_from_context(&context) else {
            return Ok(ListPromptsResult::default());
        };
        let Ok(layout) = self.platform.projects.project_layout(&session.owner, &session.project) else {
            return Ok(ListPromptsResult::default());
        };
        let prompts = crate::platform::skills::list(&layout.repo_source_dir())
            .into_iter()
            .map(|skill| Prompt::new(skill.name, Some(skill.description), None))
            .collect();
        Ok(ListPromptsResult::with_all_items(prompts))
    }

    async fn get_prompt(
        &self,
        request: GetPromptRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<GetPromptResult, McpError> {
        let session = self
            .session_from_context(&context)
            .ok_or_else(|| McpError::invalid_request("no MCP session", None))?;
        let layout = self
            .platform
            .projects
            .project_layout(&session.owner, &session.project)
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;
        let Some((_, text)) = crate::platform::skills::read(&layout.repo_source_dir(), &request.name, "") else {
            return Err(McpError::invalid_params(format!("no skill '{}'", request.name), None));
        };
        let description = crate::platform::skills::parse_frontmatter(&text).description;
        Ok(GetPromptResult {
            description,
            messages: vec![PromptMessage {
                role: PromptMessageRole::User,
                content: PromptMessageContent::Text { text },
            }],
        })
    }

    async fn call_tool(
        &self,
        request: CallToolRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        // The dev tools only: a published tool's name is unknown here.
        if !self.tool_router.has_route(&request.name) {
            return Err(McpError::invalid_params(format!("Unknown tool '{}'", request.name), None));
        }
        let tcc = rmcp::handler::server::tool::ToolCallContext::new(self, request, context);
        self.tool_router.call(tcc).await
    }

    fn get_tool(&self, name: &str) -> Option<Tool> {
        self.tool_router.get(name).cloned()
    }
}

// ── Helpers ───────────────────────────────────────────────────────────────────

/// Convert an `OpsResult` to `CallToolResult`, treating "Error: ..." text as an MCP error.
fn ok_or_err(
    result: crate::platform::services::ops::OpsResult,
) -> Result<CallToolResult, McpError> {
    if result.text.starts_with("Error:") {
        Err(McpError::internal_error(result.text, None))
    } else {
        Ok(CallToolResult::success(vec![Content::text(result.text)]))
    }
}

/// Build the MCP service with token validation using rmcp's StreamableHttpService.
pub fn build_mcp_service<S: Clone + Send + Sync + 'static>(
    platform: Arc<PlatformService>,
    template_cache: crate::pipeline::engines::basic::TemplateCache,
) -> axum::Router<S> {
    use axum::middleware;
    use rmcp::transport::streamable_http_server::{
        StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
    };
    use tokio_util::sync::CancellationToken;

    let session_manager = Arc::new(LocalSessionManager::default());
    let cancellation_token = CancellationToken::new();

    let config = StreamableHttpServerConfig {
        sse_keep_alive: Some(std::time::Duration::from_secs(30)),
        sse_retry: Some(std::time::Duration::from_secs(5)),
        stateful_mode: false,
        json_response: true,
        cancellation_token: cancellation_token.clone(),
    };

    let platform_for_factory = platform.clone();
    let cache_for_factory = template_cache.clone();
    let service = StreamableHttpService::new(
        move || {
            let platform = platform_for_factory.clone();
            let cache = cache_for_factory.clone();
            let handler = ZebflowMcpHandler::new(platform, cache);
            Ok(handler)
        },
        session_manager,
        config,
    );

    let platform_for_middleware = platform.clone();
    axum::Router::new()
        .route_service("/", service)
        .layer(middleware::from_fn(
            move |mut req: axum::extract::Request, next: middleware::Next| {
                let platform = platform_for_middleware.clone();
                async move {
                    let Some((owner, project)) = mcp_project_scope_from_request(&req) else {
                        return StatusCode::BAD_REQUEST.into_response();
                    };

                    let session = match mcp_session_from_request(&platform, req.headers()) {
                        Some(session) => session,
                        None => return StatusCode::UNAUTHORIZED.into_response(),
                    };

                    if crate::platform::model::slug_segment(&session.owner)
                        != crate::platform::model::slug_segment(&owner)
                        || crate::platform::model::slug_segment(&session.project)
                            != crate::platform::model::slug_segment(&project)
                    {
                        return StatusCode::FORBIDDEN.into_response();
                    }

                    match mcp_remote_project_worker_id(&platform, &owner, &project) {
                        Ok(Some(worker_id)) => {
                            return match forward_mcp_request_to_worker(
                                &platform, req, &worker_id, &session,
                            )
                            .await
                            {
                                Ok(response) => response,
                                Err(response) => response,
                            };
                        }
                        Ok(None) => {}
                        Err(response) => return response,
                    }

                    req.extensions_mut().insert(session);

                    next.run(req).await
                }
            },
        ))
}

fn mcp_session_from_request(platform: &PlatformService, headers: &HeaderMap) -> Option<McpSession> {
    if let Some(token) = headers
        .get(header::AUTHORIZATION)
        .and_then(|h| h.to_str().ok())
        .and_then(parse_bearer_token)
        && let Some(session) = platform.mcp_sessions.lookup(token)
    {
        return Some(session);
    }

    if !is_controller_call(platform, headers) {
        return None;
    }
    let encoded = headers
        .get(INTERNAL_MCP_SESSION_HEADER)
        .and_then(|h| h.to_str().ok())?;
    let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(encoded)
        .ok()?;
    let session: McpSession = serde_json::from_slice(&bytes).ok()?;
    if session.enabled { Some(session) } else { None }
}

/// Whether this request is **this office's controller** proxying an MCP call.
///
/// The header below carries a whole session, so what authenticates it decides
/// who that session may be. It used to accept any active office's join token on
/// a controller, which let one office hand a controller any session it liked.
/// One direction only now: an office accepting its controller's proxied call.
fn is_controller_call(platform: &PlatformService, headers: &HeaderMap) -> bool {
    let Some(presented) = headers
        .get(INTERNAL_CLUSTER_TOKEN_HEADER)
        .and_then(|value| value.to_str().ok())
    else {
        return false;
    };
    platform
        .cluster_join_tokens
        .controller_call_authenticates(presented)
}

fn mcp_remote_project_worker_id(
    platform: &PlatformService,
    owner: &str,
    project: &str,
) -> Result<Option<String>, Response> {
    let placement = platform
        .cluster_placement
        .get(owner, project)
        .map_err(|err| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("failed reading project placement: {}", err.message),
            )
                .into_response()
        })?;
    let worker_id = match placement {
        Some(record) if record.target == ProjectRuntimePlacementTarget::Worker => record.worker_id,
        _ => None,
    };
    let local_id = platform.cluster_bootstrap.node_id();
    if worker_id.as_deref() == Some(local_id.as_str()) {
        return Ok(None);
    }
    Ok(worker_id)
}

async fn forward_mcp_request_to_worker(
    platform: &PlatformService,
    req: axum::extract::Request,
    worker_id: &str,
    session: &McpSession,
) -> Result<Response, Response> {
    let worker = platform
        .cluster_registry
        .get_worker(worker_id)
        .map_err(|err| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("failed reading worker registry: {}", err.message),
            )
                .into_response()
        })?
        .ok_or_else(|| {
            (
                StatusCode::BAD_GATEWAY,
                format!("office '{worker_id}' not found"),
            )
                .into_response()
        })?;
    // Derived per office from that office's own token digest, so this
    // controller proves itself to exactly one office (`offices.md` §8).
    let office_id = if worker.office_id.trim().is_empty() {
        worker.node_id.as_str()
    } else {
        worker.office_id.as_str()
    };
    let token = platform
        .cluster_join_tokens
        .controller_call_header_for(office_id)
        .map_err(|err| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("{}: {}", err.code, err.message),
            )
                .into_response()
        })?;

    let (parts, body) = req.into_parts();
    let body = to_bytes(body, MCP_PROXY_BODY_LIMIT).await.map_err(|err| {
        (
            StatusCode::BAD_REQUEST,
            format!("failed reading MCP request body: {err}"),
        )
            .into_response()
    })?;

    let original_uri = parts.extensions.get::<OriginalUri>();
    let path_and_query = original_uri
        .and_then(|uri| uri.path_and_query().map(|pq| pq.as_str().to_string()))
        .or_else(|| parts.uri.path_and_query().map(|pq| pq.as_str().to_string()))
        .unwrap_or_else(|| parts.uri.path().to_string());
    let url = format!(
        "{}{}",
        worker.base_url.trim_end_matches('/'),
        path_and_query
    );
    let method = reqwest::Method::from_bytes(parts.method.as_str().as_bytes()).map_err(|err| {
        (
            StatusCode::BAD_REQUEST,
            format!("unsupported MCP method '{}': {err}", parts.method),
        )
            .into_response()
    })?;

    let mut request = reqwest::Client::new()
        .request(method, url)
        .header(INTERNAL_CLUSTER_TOKEN_HEADER, token);
    for (name, value) in parts.headers.iter() {
        let header_name = name.as_str();
        if header_name.eq_ignore_ascii_case("host")
            || header_name.eq_ignore_ascii_case("content-length")
            || header_name.eq_ignore_ascii_case("cookie")
            || header_name.eq_ignore_ascii_case(INTERNAL_CLUSTER_TOKEN_HEADER)
            || header_name.eq_ignore_ascii_case(INTERNAL_MCP_SESSION_HEADER)
        {
            continue;
        }
        request = request.header(name, value);
    }

    let session_bytes = serde_json::to_vec(session).map_err(|err| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("failed serializing MCP session: {err}"),
        )
            .into_response()
    })?;
    let session_header = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(session_bytes);
    let response = request
        .header(INTERNAL_MCP_SESSION_HEADER, session_header)
        .body(body)
        .send()
        .await
        .map_err(|err| {
            (
                StatusCode::BAD_GATEWAY,
                format!("MCP worker proxy failed: {err}"),
            )
                .into_response()
        })?;
    Ok(reqwest_response_to_axum(response).await)
}

async fn reqwest_response_to_axum(response: reqwest::Response) -> Response {
    let status = response.status();
    let headers = response.headers().clone();
    let body = response.bytes().await.unwrap_or_else(|_| Bytes::new());
    let mut builder = Response::builder().status(status);
    for (name, value) in headers.iter() {
        if name.as_str().eq_ignore_ascii_case("connection")
            || name.as_str().eq_ignore_ascii_case("transfer-encoding")
        {
            continue;
        }
        builder = builder.header(name, value);
    }
    builder
        .body(Body::from(body))
        .unwrap_or_else(|_| StatusCode::BAD_GATEWAY.into_response())
}

fn parse_bearer_token(header_value: &str) -> Option<&str> {
    let token = header_value.trim().strip_prefix("Bearer ")?.trim();
    if token.is_empty() { None } else { Some(token) }
}

fn mcp_project_scope_from_request(req: &axum::extract::Request) -> Option<(String, String)> {
    if let Some(original_uri) = req.extensions().get::<OriginalUri>()
        && let Some(scope) = mcp_project_scope_from_path(original_uri.path())
    {
        return Some(scope);
    }
    mcp_project_scope_from_path(req.uri().path())
}

fn mcp_project_scope_from_path(path: &str) -> Option<(String, String)> {
    let segments = path
        .split('/')
        .filter(|segment| !segment.is_empty())
        .collect::<Vec<_>>();
    if segments.len() < 5 {
        return None;
    }
    for index in 0..=(segments.len() - 5) {
        if segments[index] == "api"
            && segments[index + 1] == "projects"
            && segments[index + 4] == "mcp"
        {
            return Some((
                segments[index + 2].to_string(),
                segments[index + 3].to_string(),
            ));
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::{mcp_project_scope_from_path, parse_bearer_token};

    #[test]
    fn parse_bearer_token_rejects_missing_or_empty_tokens() {
        assert_eq!(parse_bearer_token("Bearer abc123"), Some("abc123"));
        assert_eq!(parse_bearer_token("Bearer   abc123  "), Some("abc123"));
        assert_eq!(parse_bearer_token("Bearer "), None);
        assert_eq!(parse_bearer_token("Basic abc123"), None);
        assert_eq!(parse_bearer_token(""), None);
    }

    #[test]
    fn mcp_project_scope_is_extracted_from_project_url() {
        assert_eq!(
            mcp_project_scope_from_path("/api/projects/alice/my-app/mcp"),
            Some(("alice".to_string(), "my-app".to_string()))
        );
        assert_eq!(
            mcp_project_scope_from_path("/api/projects/alice/my-app/mcp/"),
            Some(("alice".to_string(), "my-app".to_string()))
        );
        assert_eq!(mcp_project_scope_from_path("/api/projects/alice"), None);
        assert_eq!(mcp_project_scope_from_path("/mcp"), None);
    }
}