securegit 0.8.5

Zero-trust git replacement with 12 built-in security scanners, LLM redteam bridge, universal undo, durable backups, and a 50-tool MCP server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
use crate::auth;
use crate::cli::UI;
use crate::core::{Config, ScanEngine};
use crate::mcp::sanitizer;
use crate::mcp::types::*;
use crate::ops;
use crate::platform;
use crate::platform::server_registry::{ServerPlatform, ServerRegistry};
use rmcp::handler::server::tool::ToolRouter;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::*;
use rmcp::{tool, tool_handler, tool_router, ErrorData as McpError, ServerHandler};
use std::borrow::Cow;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, RwLock};
use std::time::Instant;

/// Simple sliding-window rate limiter (no external deps).
struct RateLimiter {
    timestamps: Vec<Instant>,
    max_requests: usize,
    window_secs: u64,
}

impl RateLimiter {
    fn new(max_requests: usize, window_secs: u64) -> Self {
        Self {
            timestamps: Vec::new(),
            max_requests,
            window_secs,
        }
    }

    fn check(&mut self) -> bool {
        let now = Instant::now();
        let cutoff = now - std::time::Duration::from_secs(self.window_secs);
        self.timestamps.retain(|t| *t > cutoff);
        if self.timestamps.len() >= self.max_requests {
            return false;
        }
        self.timestamps.push(now);
        true
    }
}

pub struct SecuregitMcpServer {
    work_dir: PathBuf,
    config: Config,
    last_scan: Arc<RwLock<Option<ScanResult>>>,
    rate_limiter: Arc<Mutex<RateLimiter>>,
    redteam_bridge: Arc<crate::redteam::RedteamBridge>,
    tool_router: ToolRouter<Self>,
}

fn mcp_err(msg: impl Into<String>) -> McpError {
    McpError {
        code: ErrorCode::INTERNAL_ERROR,
        message: Cow::from(msg.into()),
        data: None,
    }
}

#[tool_router]
impl SecuregitMcpServer {
    pub fn new(work_dir: PathBuf) -> Self {
        let config = Config::default();
        let bridge = Arc::new(crate::redteam::RedteamBridge::new(
            config.llm_security.binary.clone(),
        ));
        Self {
            work_dir,
            config,
            last_scan: Arc::new(RwLock::new(None)),
            rate_limiter: Arc::new(Mutex::new(RateLimiter::new(60, 60))),
            redteam_bridge: bridge,
            tool_router: Self::tool_router(),
        }
    }

    fn check_rate_limit(&self) -> Result<(), McpError> {
        let mut limiter = self
            .rate_limiter
            .lock()
            .map_err(|e| mcp_err(e.to_string()))?;
        if !limiter.check() {
            return Err(McpError {
                code: ErrorCode::INTERNAL_ERROR,
                message: Cow::from("Rate limit exceeded (60 requests/minute). Please wait."),
                data: None,
            });
        }
        Ok(())
    }

    /// Resolve a platform client, either from a named server or auto-detected remote.
    fn resolve_platform_client(
        &self,
        server_name: Option<&str>,
    ) -> Result<Box<dyn platform::Platform>, McpError> {
        if let Some(name) = server_name {
            let registry = ServerRegistry::load()
                .map_err(|e| mcp_err(format!("Failed to load server registry: {}", e)))?;
            let server = registry
                .get(name)
                .ok_or_else(|| mcp_err(format!("Server '{}' not found", name)))?
                .clone();
            let token = auth::token_for_server(&server)
                .ok_or_else(|| mcp_err(format!("No credentials for server '{}'", name)))?;
            let remote = platform::detect_remote(&self.work_dir)
                .map_err(|e| mcp_err(format!("Failed to detect remote: {}", e)))?;
            Ok(platform::create_client_for_server(
                &server,
                token,
                &remote.owner,
                &remote.repo,
            ))
        } else {
            let remote = platform::detect_remote(&self.work_dir)
                .map_err(|e| mcp_err(format!("Failed to detect remote: {}", e)))?;
            let token = platform::resolve_token(&remote.host)
                .ok_or_else(|| mcp_err("Not authenticated. Run: securegit auth login"))?;
            Ok(platform::create_client(&remote, token))
        }
    }

    /// Sanitize a text result to strip any leaked credentials.
    fn sanitize_text_result(&self, text: String) -> CallToolResult {
        CallToolResult::success(vec![Content::text(sanitizer::sanitize_output(&text))])
    }

    // ================================================================
    // Security tools (5) — unique to securegit
    // ================================================================

    #[tool(
        description = "Scan a directory for security findings (secrets, vulnerabilities, supply-chain risks). Returns structured results with severity levels."
    )]
    async fn securegit_scan(
        &self,
        Parameters(params): Parameters<ScanParams>,
    ) -> Result<CallToolResult, McpError> {
        self.check_rate_limit()?;
        let scan_path = params
            .path
            .map(PathBuf::from)
            .unwrap_or_else(|| self.work_dir.clone());

        let engine = ScanEngine::new(self.config.clone());
        let mut report = engine
            .scan_directory(&scan_path)
            .await
            .map_err(|e| mcp_err(format!("Scan failed: {}", e)))?;

        // LLM security scan
        if self.config.llm_security.enabled
            && self.redteam_bridge.is_available()
            && self.config.llm_security.scan_mcp_configs
        {
            for pattern in &self.config.llm_security.mcp_config_patterns {
                let config_path = scan_path.join(pattern);
                if config_path.exists() {
                    match self.scan_mcp_config_file(&config_path).await {
                        Ok(findings) => report.findings.extend(findings),
                        Err(e) => report
                            .warnings
                            .push(format!("LLM security scan skipped for {}: {}", pattern, e)),
                    }
                }
            }
        }

        // Also run mcp-scan bridge if available
        if self.config.llm_security.enabled && self.config.llm_security.run_mcp_scan {
            let mcp_bridge = crate::toolbridges::mcp_scan::McpScanBridge::new();
            if mcp_bridge.is_available() {
                for pattern in &self.config.llm_security.mcp_config_patterns {
                    let config_path = scan_path.join(pattern);
                    if config_path.exists() {
                        match mcp_bridge.scan(&config_path).await {
                            Ok(findings) => report.findings.extend(findings),
                            Err(crate::toolbridges::CliError::NotInstalled(_)) => {}
                            Err(e) => report
                                .warnings
                                .push(format!("mcp-scan failed for {}: {}", pattern, e)),
                        }
                    }
                }
            }
        }

        let min_sev = parse_severity(params.min_severity.as_deref());

        let findings: Vec<FindingResult> = report
            .findings
            .iter()
            .filter(|f| severity_rank(&format!("{:?}", f.severity)) >= min_sev)
            .map(|f| FindingResult {
                id: f.id.clone(),
                title: f.title.clone(),
                severity: format!("{:?}", f.severity),
                file: f.file_path.as_ref().map(|p| p.display().to_string()),
                line: f.line_start.map(|l| l as usize),
                description: f.description.clone(),
            })
            .collect();

        let result = ScanResult {
            scanned_files: report.scanned_files,
            findings_count: findings.len(),
            findings,
        };

        // Cache scan results
        if let Ok(mut cache) = self.last_scan.write() {
            *cache = Some(ScanResult {
                scanned_files: result.scanned_files,
                findings_count: result.findings_count,
                findings: result
                    .findings
                    .iter()
                    .map(|f| FindingResult {
                        id: f.id.clone(),
                        title: f.title.clone(),
                        severity: f.severity.clone(),
                        file: f.file.clone(),
                        line: f.line,
                        description: f.description.clone(),
                    })
                    .collect(),
            });
        }

        let json = serde_json::to_string_pretty(&result).map_err(|e| mcp_err(e.to_string()))?;
        Ok(CallToolResult::success(vec![Content::text(json)]))
    }

    #[tool(
        description = "Scan only staged (indexed) changes for security issues before committing."
    )]
    async fn securegit_scan_staged(
        &self,
        Parameters(params): Parameters<ScanStagedParams>,
    ) -> Result<CallToolResult, McpError> {
        self.check_rate_limit()?;
        let min_sev = parse_severity(params.min_severity.as_deref());

        // Get staged file paths in a block so git2 types are dropped before .await
        let staged_paths: Vec<String> = {
            let repo = git2::Repository::open(&self.work_dir)
                .map_err(|e| mcp_err(format!("Failed to open repo: {}", e)))?;
            let mut opts = git2::StatusOptions::new();
            opts.include_untracked(false);
            let statuses = repo
                .statuses(Some(&mut opts))
                .map_err(|e| mcp_err(e.to_string()))?;

            statuses
                .iter()
                .filter(|e| {
                    e.status().intersects(
                        git2::Status::INDEX_NEW
                            | git2::Status::INDEX_MODIFIED
                            | git2::Status::INDEX_RENAMED,
                    )
                })
                .filter_map(|e| e.path().map(|s| s.to_string()))
                .collect()
        };

        if staged_paths.is_empty() {
            return Ok(CallToolResult::success(vec![Content::text(
                "No staged changes to scan.",
            )]));
        }

        // Scan the working directory but only report on staged files
        let engine = ScanEngine::new(self.config.clone());
        let report = engine
            .scan_directory(&self.work_dir)
            .await
            .map_err(|e| mcp_err(format!("Scan failed: {}", e)))?;

        let findings: Vec<FindingResult> = report
            .findings
            .iter()
            .filter(|f| {
                if let Some(ref fp) = f.file_path {
                    let fp_str = fp.display().to_string();
                    staged_paths.iter().any(|sp| fp_str.ends_with(sp))
                } else {
                    false
                }
            })
            .filter(|f| severity_rank(&format!("{:?}", f.severity)) >= min_sev)
            .map(|f| FindingResult {
                id: f.id.clone(),
                title: f.title.clone(),
                severity: format!("{:?}", f.severity),
                file: f.file_path.as_ref().map(|p| p.display().to_string()),
                line: f.line_start.map(|l| l as usize),
                description: f.description.clone(),
            })
            .collect();

        let result = ScanResult {
            scanned_files: staged_paths.len(),
            findings_count: findings.len(),
            findings,
        };

        let json = serde_json::to_string_pretty(&result).map_err(|e| mcp_err(e.to_string()))?;
        Ok(CallToolResult::success(vec![Content::text(json)]))
    }

    #[tool(
        description = "Scan staged changes for security issues, then commit if clean. Blocks commit if findings meet or exceed the max severity threshold."
    )]
    async fn securegit_safe_commit(
        &self,
        Parameters(params): Parameters<SafeCommitParams>,
    ) -> Result<CallToolResult, McpError> {
        self.check_rate_limit()?;
        let max_sev = parse_severity(params.max_severity.as_deref().or(Some("high")));

        // First scan staged changes
        let engine = ScanEngine::new(self.config.clone());
        let mut report = engine
            .scan_directory(&self.work_dir)
            .await
            .map_err(|e| mcp_err(format!("Scan failed: {}", e)))?;

        // LLM security scan (if enabled and bridge available)
        if self.config.llm_security.enabled && self.redteam_bridge.is_available() {
            // Detect MCP config files in the scanned directory
            if self.config.llm_security.scan_mcp_configs {
                for pattern in &self.config.llm_security.mcp_config_patterns {
                    let config_path = self.work_dir.join(pattern);
                    if config_path.exists() {
                        match self.scan_mcp_config_file(&config_path).await {
                            Ok(findings) => report.findings.extend(findings),
                            Err(e) => report
                                .warnings
                                .push(format!("LLM security scan skipped for {}: {}", pattern, e)),
                        }
                    }
                }
            }
        }

        let blocking_findings: Vec<_> = report
            .findings
            .iter()
            .filter(|f| severity_rank(&format!("{:?}", f.severity)) >= max_sev)
            .collect();

        if !blocking_findings.is_empty() {
            let mut msg = format!(
                "BLOCKED: {} security finding(s) at or above threshold:\n\n",
                blocking_findings.len()
            );
            for f in &blocking_findings {
                msg.push_str(&format!("  [{:?}] {}: {}\n", f.severity, f.id, f.title));
                if let Some(ref fp) = f.file_path {
                    msg.push_str(&format!("    File: {}\n", fp.display()));
                }
            }
            msg.push_str("\nResolve these findings before committing.");
            return Ok(CallToolResult::error(vec![Content::text(msg)]));
        }

        // Commit
        let ui = UI::new(false, true, false, false);
        ops::commit::execute(&self.work_dir, &params.message, false, false, &ui)
            .map_err(|e| mcp_err(format!("Commit failed: {}", e)))?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Security scan passed. Committed: {}",
            params.message
        ))]))
    }

    /// Scan an MCP config file by parsing its server entries and calling redteam_scan_mcp for each.
    async fn scan_mcp_config_file(
        &self,
        config_path: &std::path::Path,
    ) -> Result<Vec<crate::core::Finding>, crate::redteam::bridge::BridgeError> {
        let content = std::fs::read_to_string(config_path)
            .map_err(|e| crate::redteam::bridge::BridgeError::CallFailed(e.to_string()))?;

        let parsed: serde_json::Value = serde_json::from_str(&content)
            .map_err(|e| crate::redteam::bridge::BridgeError::CallFailed(e.to_string()))?;

        let mut all_findings = Vec::new();

        // Parse mcpServers entries
        if let Some(servers) = parsed.get("mcpServers").and_then(|v| v.as_object()) {
            for (name, server_config) in servers {
                let command = server_config
                    .get("command")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default();

                if command.is_empty() {
                    continue;
                }

                let args: Vec<String> = server_config
                    .get("args")
                    .and_then(|v| v.as_array())
                    .map(|a| {
                        a.iter()
                            .filter_map(|v| v.as_str().map(String::from))
                            .collect()
                    })
                    .unwrap_or_default();

                match self.redteam_bridge.scan_mcp_server(command, &args).await {
                    Ok(json_text) => {
                        let findings = crate::redteam::findings::parse_mcp_scan_findings(
                            &json_text,
                            Some(&config_path.display().to_string()),
                        );
                        all_findings.extend(findings);
                    }
                    Err(crate::redteam::bridge::BridgeError::NotInstalled(_)) => break,
                    Err(e) => {
                        tracing::warn!("Failed to scan MCP server '{}': {}", name, e);
                    }
                }
            }
        }

        Ok(all_findings)
    }

    #[tool(
        description = "Review a specific file for security issues. Returns detailed analysis of any findings in the file."
    )]
    async fn securegit_review(
        &self,
        Parameters(params): Parameters<ReviewParams>,
    ) -> Result<CallToolResult, McpError> {
        let file_path = self.work_dir.join(&params.file);
        if !file_path.exists() {
            return Ok(CallToolResult::error(vec![Content::text(format!(
                "File not found: {}",
                params.file
            ))]));
        }

        let engine = ScanEngine::new(self.config.clone());
        let mut report = engine
            .scan_file(&file_path)
            .await
            .map_err(|e| mcp_err(format!("Scan failed: {}", e)))?;

        // If the file is an MCP config, also run redteam scan
        if self.config.llm_security.enabled && self.redteam_bridge.is_available() {
            let filename = file_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
            let is_mcp_config = self
                .config
                .llm_security
                .mcp_config_patterns
                .iter()
                .any(|pattern| pattern.ends_with(filename) || pattern == &params.file);

            if is_mcp_config {
                match self.scan_mcp_config_file(&file_path).await {
                    Ok(findings) => report.findings.extend(findings),
                    Err(e) => report
                        .warnings
                        .push(format!("LLM security scan skipped: {}", e)),
                }
            }
        }

        // Also run mcp-scan bridge on MCP config files
        if self.config.llm_security.enabled && self.config.llm_security.run_mcp_scan {
            let filename = file_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
            let is_mcp_config = self
                .config
                .llm_security
                .mcp_config_patterns
                .iter()
                .any(|pattern| pattern.ends_with(filename) || pattern == &params.file);

            if is_mcp_config {
                let mcp_bridge = crate::toolbridges::mcp_scan::McpScanBridge::new();
                if mcp_bridge.is_available() {
                    match mcp_bridge.scan(&file_path).await {
                        Ok(findings) => report.findings.extend(findings),
                        Err(crate::toolbridges::CliError::NotInstalled(_)) => {}
                        Err(e) => report.warnings.push(format!("mcp-scan failed: {}", e)),
                    }
                }
            }
        }

        let findings: Vec<FindingResult> = report
            .findings
            .iter()
            .map(|f| FindingResult {
                id: f.id.clone(),
                title: f.title.clone(),
                severity: format!("{:?}", f.severity),
                file: f.file_path.as_ref().map(|p| p.display().to_string()),
                line: f.line_start.map(|l| l as usize),
                description: f.description.clone(),
            })
            .collect();

        if findings.is_empty() {
            return Ok(CallToolResult::success(vec![Content::text(format!(
                "No security findings in '{}'.",
                params.file
            ))]));
        }

        let json = serde_json::to_string_pretty(&findings).map_err(|e| mcp_err(e.to_string()))?;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "Found {} security issue(s) in '{}':\n\n{}",
            findings.len(),
            params.file,
            json
        ))]))
    }

    #[tool(
        description = "Query cached security findings from the last scan. Filter by severity or file pattern."
    )]
    async fn securegit_findings(
        &self,
        Parameters(params): Parameters<FindingsParams>,
    ) -> Result<CallToolResult, McpError> {
        let cache = self.last_scan.read().map_err(|e| mcp_err(e.to_string()))?;

        let Some(ref cached) = *cache else {
            return Ok(CallToolResult::success(vec![Content::text(
                "No cached scan results. Run securegit_scan first.",
            )]));
        };

        let min_sev = parse_severity(params.min_severity.as_deref());
        let pattern = params.file_pattern.as_deref().unwrap_or("");

        let filtered: Vec<&FindingResult> = cached
            .findings
            .iter()
            .filter(|f| severity_rank(&f.severity) >= min_sev)
            .filter(|f| {
                if pattern.is_empty() {
                    true
                } else {
                    f.file
                        .as_ref()
                        .map(|fp| fp.contains(pattern))
                        .unwrap_or(false)
                }
            })
            .collect();

        let json = serde_json::to_string_pretty(&filtered).map_err(|e| mcp_err(e.to_string()))?;
        Ok(CallToolResult::success(vec![Content::text(format!(
            "{} finding(s) matching filters:\n\n{}",
            filtered.len(),
            json
        ))]))
    }

    // ================================================================
    // Git read tools (9)
    // ================================================================

    #[tool(
        description = "Show structured repository status including staged, unstaged, and untracked files."
    )]
    async fn securegit_status(&self) -> Result<CallToolResult, McpError> {
        let repo = git2::Repository::open(&self.work_dir)
            .map_err(|e| mcp_err(format!("Failed to open repo: {}", e)))?;

        let head = repo.head().ok();
        let branch_name = head
            .as_ref()
            .and_then(|h| h.shorthand().map(|s| s.to_string()))
            .unwrap_or_else(|| "(detached)".to_string());

        let mut opts = git2::StatusOptions::new();
        opts.include_untracked(true).recurse_untracked_dirs(true);
        let statuses = repo
            .statuses(Some(&mut opts))
            .map_err(|e| mcp_err(e.to_string()))?;

        let mut staged = Vec::new();
        let mut unstaged = Vec::new();
        let mut untracked = Vec::new();

        for entry in statuses.iter() {
            let status = entry.status();
            let path_str = entry.path().unwrap_or("").to_string();

            if status.intersects(
                git2::Status::INDEX_NEW
                    | git2::Status::INDEX_MODIFIED
                    | git2::Status::INDEX_DELETED
                    | git2::Status::INDEX_RENAMED,
            ) {
                let kind = if status.contains(git2::Status::INDEX_NEW) {
                    "new"
                } else if status.contains(git2::Status::INDEX_MODIFIED) {
                    "modified"
                } else if status.contains(git2::Status::INDEX_DELETED) {
                    "deleted"
                } else {
                    "renamed"
                };
                staged.push(serde_json::json!({"status": kind, "path": path_str}));
            }

            if status.intersects(
                git2::Status::WT_MODIFIED | git2::Status::WT_DELETED | git2::Status::WT_RENAMED,
            ) {
                let kind = if status.contains(git2::Status::WT_MODIFIED) {
                    "modified"
                } else if status.contains(git2::Status::WT_DELETED) {
                    "deleted"
                } else {
                    "renamed"
                };
                unstaged.push(serde_json::json!({"status": kind, "path": path_str}));
            }

            if status.contains(git2::Status::WT_NEW) {
                untracked.push(path_str);
            }
        }

        let result = serde_json::json!({
            "branch": branch_name,
            "staged": staged,
            "unstaged": unstaged,
            "untracked": untracked,
            "clean": staged.is_empty() && unstaged.is_empty() && untracked.is_empty(),
        });

        let json = serde_json::to_string_pretty(&result).map_err(|e| mcp_err(e.to_string()))?;
        Ok(CallToolResult::success(vec![Content::text(json)]))
    }

    #[tool(description = "Show commit history with optional filters for author and date range.")]
    async fn securegit_log(
        &self,
        Parameters(params): Parameters<LogParams>,
    ) -> Result<CallToolResult, McpError> {
        let repo = git2::Repository::open(&self.work_dir)
            .map_err(|e| mcp_err(format!("Failed to open repo: {}", e)))?;

        let mut revwalk = repo.revwalk().map_err(|e| mcp_err(e.to_string()))?;
        revwalk.push_head().map_err(|e| mcp_err(e.to_string()))?;
        revwalk
            .set_sorting(git2::Sort::TIME)
            .map_err(|e| mcp_err(e.to_string()))?;

        let max_count = params.max_count.unwrap_or(10);
        let mut commits = Vec::new();

        for (i, oid_result) in revwalk.enumerate() {
            if i >= max_count {
                break;
            }
            let oid = oid_result.map_err(|e| mcp_err(e.to_string()))?;
            let commit = repo.find_commit(oid).map_err(|e| mcp_err(e.to_string()))?;

            let author_name = commit.author().name().unwrap_or("").to_string();
            let author_email = commit.author().email().unwrap_or("").to_string();

            // Filter by author if specified
            if let Some(ref filter) = params.author {
                let filter_lower = filter.to_lowercase();
                if !author_name.to_lowercase().contains(&filter_lower)
                    && !author_email.to_lowercase().contains(&filter_lower)
                {
                    continue;
                }
            }

            let oid_str = oid.to_string();
            let short_oid = &oid_str[..7.min(oid_str.len())];
            commits.push(serde_json::json!({
                "oid": short_oid,
                "message": commit.summary().unwrap_or(""),
                "author": format!("{} <{}>", author_name, author_email),
                "time": commit.time().seconds(),
            }));
        }

        let json = serde_json::to_string_pretty(&commits).map_err(|e| mcp_err(e.to_string()))?;
        Ok(CallToolResult::success(vec![Content::text(json)]))
    }

    #[tool(
        description = "Show changes between commits, index, and working tree. Supports staged (cached) diffs and commit ranges."
    )]
    async fn securegit_diff(
        &self,
        Parameters(params): Parameters<DiffParams>,
    ) -> Result<CallToolResult, McpError> {
        let repo = git2::Repository::open(&self.work_dir)
            .map_err(|e| mcp_err(format!("Failed to open repo: {}", e)))?;

        let cached = params.cached.unwrap_or(false);
        let name_only = params.name_only.unwrap_or(false);

        let diff = if cached {
            let head_tree = repo.head().ok().and_then(|h| h.peel_to_tree().ok());
            repo.diff_tree_to_index(head_tree.as_ref(), None, None)
        } else if let Some(ref commit_spec) = params.commit {
            let obj = repo
                .revparse_single(commit_spec)
                .map_err(|e| mcp_err(e.to_string()))?;
            let commit = obj.peel_to_commit().map_err(|e| mcp_err(e.to_string()))?;
            let tree = commit.tree().map_err(|e| mcp_err(e.to_string()))?;
            repo.diff_tree_to_workdir_with_index(Some(&tree), None)
        } else {
            repo.diff_index_to_workdir(None, None)
        }
        .map_err(|e| mcp_err(e.to_string()))?;

        if name_only {
            let mut files = Vec::new();
            diff.foreach(
                &mut |delta, _| {
                    if let Some(path) = delta.new_file().path() {
                        files.push(path.display().to_string());
                    }
                    true
                },
                None,
                None,
                None,
            )
            .map_err(|e| mcp_err(e.to_string()))?;

            let json = serde_json::to_string_pretty(&files).map_err(|e| mcp_err(e.to_string()))?;
            return Ok(CallToolResult::success(vec![Content::text(json)]));
        }

        // Full diff output (control chars stripped for safety)
        let mut output = String::new();
        diff.print(git2::DiffFormat::Patch, |_delta, _hunk, line| {
            let prefix = match line.origin() {
                '+' => "+",
                '-' => "-",
                ' ' => " ",
                _ => "",
            };
            output.push_str(prefix);
            if let Ok(content) = std::str::from_utf8(line.content()) {
                for c in content.chars() {
                    if c == '\x1b' || (c.is_control() && c != '\n' && c != '\t' && c != '\r') {
                        // skip control/escape chars
                    } else {
                        output.push(c);
                    }
                }
            }
            true
        })
        .map_err(|e| mcp_err(e.to_string()))?;

        if output.is_empty() {
            output = "No changes.".to_string();
        }

        // Truncate very large diffs
        if output.len() > 50_000 {
            output.truncate(50_000);
            output.push_str("\n\n... (truncated, diff too large)");
        }

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

    #[tool(description = "Show what revision and author last modified each line of a file.")]
    async fn securegit_blame(
        &self,
        Parameters(params): Parameters<BlameParams>,
    ) -> Result<CallToolResult, McpError> {
        let repo = git2::Repository::open(&self.work_dir)
            .map_err(|e| mcp_err(format!("Failed to open repo: {}", e)))?;

        let blame = repo
            .blame_file(std::path::Path::new(&params.file), None)
            .map_err(|e| mcp_err(format!("Blame failed: {}", e)))?;

        let file_path = self.work_dir.join(&params.file);
        let content = std::fs::read_to_string(&file_path).map_err(|e| mcp_err(e.to_string()))?;

        let mut output = String::new();
        for (i, line) in content.lines().enumerate() {
            if let Some(hunk) = blame.get_line(i + 1) {
                let oid = hunk.final_commit_id();
                let s = oid.to_string();
                let short = &s[..7.min(s.len())];
                let sig = hunk.final_signature();
                let author = sig.name().unwrap_or("?");
                output.push_str(&format!(
                    "{} ({:>12}) {:>4} | {}\n",
                    short,
                    author,
                    i + 1,
                    line
                ));
            } else {
                output.push_str(&format!("{:>7} {:>14} {:>4} | {}\n", "?", "?", i + 1, line));
            }
        }

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

    #[tool(description = "Show details of a commit, tag, or other git object.")]
    async fn securegit_show(
        &self,
        Parameters(params): Parameters<ShowParams>,
    ) -> Result<CallToolResult, McpError> {
        let repo = git2::Repository::open(&self.work_dir)
            .map_err(|e| mcp_err(format!("Failed to open repo: {}", e)))?;

        let object_spec = params.object.as_deref().unwrap_or("HEAD");
        let obj = repo
            .revparse_single(object_spec)
            .map_err(|e| mcp_err(format!("Object not found: {}", e)))?;

        let commit = obj
            .peel_to_commit()
            .map_err(|e| mcp_err(format!("Not a commit: {}", e)))?;

        let result = serde_json::json!({
            "oid": commit.id().to_string(),
            "message": commit.message().unwrap_or(""),
            "author": format!("{} <{}>",
                commit.author().name().unwrap_or(""),
                commit.author().email().unwrap_or("")),
            "committer": format!("{} <{}>",
                commit.committer().name().unwrap_or(""),
                commit.committer().email().unwrap_or("")),
            "time": commit.time().seconds(),
            "parent_count": commit.parent_count(),
        });

        let json = serde_json::to_string_pretty(&result).map_err(|e| mcp_err(e.to_string()))?;
        Ok(CallToolResult::success(vec![Content::text(json)]))
    }

    #[tool(description = "List all local and optionally remote branches.")]
    async fn securegit_branch_list(&self) -> Result<CallToolResult, McpError> {
        let repo = git2::Repository::open(&self.work_dir)
            .map_err(|e| mcp_err(format!("Failed to open repo: {}", e)))?;

        let head_name = repo
            .head()
            .ok()
            .and_then(|h| h.shorthand().map(|s| s.to_string()));

        let mut branches = Vec::new();
        for branch_result in repo.branches(None).map_err(|e| mcp_err(e.to_string()))? {
            let (branch, branch_type) = branch_result.map_err(|e| mcp_err(e.to_string()))?;
            if let Ok(Some(name)) = branch.name() {
                let is_current = head_name.as_deref() == Some(name);
                let kind = match branch_type {
                    git2::BranchType::Local => "local",
                    git2::BranchType::Remote => "remote",
                };
                branches.push(serde_json::json!({
                    "name": name,
                    "type": kind,
                    "current": is_current,
                }));
            }
        }

        let json = serde_json::to_string_pretty(&branches).map_err(|e| mcp_err(e.to_string()))?;
        Ok(CallToolResult::success(vec![Content::text(json)]))
    }

    #[tool(description = "List all tags in the repository.")]
    async fn securegit_tag_list(&self) -> Result<CallToolResult, McpError> {
        let repo = git2::Repository::open(&self.work_dir)
            .map_err(|e| mcp_err(format!("Failed to open repo: {}", e)))?;

        let tag_names = repo.tag_names(None).map_err(|e| mcp_err(e.to_string()))?;

        let mut tags = Vec::new();
        for tag_name in tag_names.iter().flatten() {
            let ref_name = format!("refs/tags/{}", tag_name);
            let oid = repo
                .find_reference(&ref_name)
                .ok()
                .and_then(|r| r.target())
                .map(|o| {
                    let s = o.to_string();
                    s[..7.min(s.len())].to_string()
                })
                .unwrap_or_default();
            tags.push(serde_json::json!({"name": tag_name, "oid": oid}));
        }

        let json = serde_json::to_string_pretty(&tags).map_err(|e| mcp_err(e.to_string()))?;
        Ok(CallToolResult::success(vec![Content::text(json)]))
    }

    #[tool(description = "List all configured remotes with their URLs.")]
    async fn securegit_remote_list(&self) -> Result<CallToolResult, McpError> {
        let repo = git2::Repository::open(&self.work_dir)
            .map_err(|e| mcp_err(format!("Failed to open repo: {}", e)))?;

        let remotes = repo.remotes().map_err(|e| mcp_err(e.to_string()))?;

        let mut result = Vec::new();
        for name in remotes.iter().flatten() {
            let url = repo
                .find_remote(name)
                .ok()
                .and_then(|r| r.url().map(|u| u.to_string()))
                .unwrap_or_default();
            result.push(serde_json::json!({"name": name, "url": url}));
        }

        let json = serde_json::to_string_pretty(&result).map_err(|e| mcp_err(e.to_string()))?;
        Ok(CallToolResult::success(vec![Content::text(json)]))
    }

    #[tool(description = "List all stash entries.")]
    async fn securegit_stash_list(&self) -> Result<CallToolResult, McpError> {
        let repo = git2::Repository::open(&self.work_dir)
            .map_err(|e| mcp_err(format!("Failed to open repo: {}", e)))?;

        let mut stashes = Vec::new();
        // git2's stash_foreach uses a callback
        let mut repo = repo;
        repo.stash_foreach(|index, message, oid| {
            let oid_str = oid.to_string();
            let short_oid = &oid_str[..7.min(oid_str.len())];
            stashes.push(serde_json::json!({
                "index": index,
                "message": message,
                "oid": short_oid,
            }));
            true
        })
        .map_err(|e| mcp_err(e.to_string()))?;

        if stashes.is_empty() {
            return Ok(CallToolResult::success(vec![Content::text(
                "No stash entries.",
            )]));
        }

        let json = serde_json::to_string_pretty(&stashes).map_err(|e| mcp_err(e.to_string()))?;
        Ok(CallToolResult::success(vec![Content::text(json)]))
    }

    // ================================================================
    // Git write tools (10) — security-gated
    // ================================================================

    #[tool(
        description = "Stage files for commit. Specify file paths or use all=true to stage everything."
    )]
    async fn securegit_add(
        &self,
        Parameters(params): Parameters<AddParams>,
    ) -> Result<CallToolResult, McpError> {
        let all = params.all.unwrap_or(false);
        ops::staging::add(&self.work_dir, &params.files, all, false)
            .map_err(|e| mcp_err(format!("Add failed: {}", e)))?;

        let msg = if all {
            "Staged all changes.".to_string()
        } else {
            format!("Staged {} file(s).", params.files.len())
        };
        Ok(CallToolResult::success(vec![Content::text(msg)]))
    }

    #[tool(
        description = "Create a commit with the given message. Does NOT run security scan (use securegit_safe_commit for that)."
    )]
    async fn securegit_commit(
        &self,
        Parameters(params): Parameters<CommitParams>,
    ) -> Result<CallToolResult, McpError> {
        let allow_empty = params.allow_empty.unwrap_or(false);
        let ui = UI::new(false, true, false, false);
        ops::commit::execute(&self.work_dir, &params.message, allow_empty, false, &ui)
            .map_err(|e| mcp_err(format!("Commit failed: {}", e)))?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Committed: {}",
            params.message
        ))]))
    }

    #[tool(
        description = "Switch branches or checkout a specific commit. Optionally create a new branch."
    )]
    async fn securegit_checkout(
        &self,
        Parameters(params): Parameters<CheckoutParams>,
    ) -> Result<CallToolResult, McpError> {
        let create = params.create.unwrap_or(false);
        let ui = UI::new(false, true, false, false);
        ops::checkout::execute(&self.work_dir, &params.target, create, false, &ui)
            .map_err(|e| mcp_err(format!("Checkout failed: {}", e)))?;

        let msg = if create {
            format!("Created and switched to new branch '{}'.", params.target)
        } else {
            format!("Switched to '{}'.", params.target)
        };
        Ok(CallToolResult::success(vec![Content::text(msg)]))
    }

    #[tool(description = "Create a new branch at the current HEAD or a specified start point.")]
    async fn securegit_branch_create(
        &self,
        Parameters(params): Parameters<BranchCreateParams>,
    ) -> Result<CallToolResult, McpError> {
        let ui = UI::new(false, true, false, false);
        ops::branch::create(
            &self.work_dir,
            &params.name,
            params.start_point.as_deref(),
            &ui,
        )
        .map_err(|e| mcp_err(format!("Branch create failed: {}", e)))?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Created branch '{}'.",
            params.name
        ))]))
    }

    #[tool(description = "Delete a branch. Use force=true to delete unmerged branches.")]
    async fn securegit_branch_delete(
        &self,
        Parameters(params): Parameters<BranchDeleteParams>,
    ) -> Result<CallToolResult, McpError> {
        let force = params.force.unwrap_or(false);
        let ui = UI::new(false, true, false, false);
        ops::branch::delete(&self.work_dir, &params.name, force, &ui)
            .map_err(|e| mcp_err(format!("Branch delete failed: {}", e)))?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Deleted branch '{}'.",
            params.name
        ))]))
    }

    #[tool(description = "Merge another branch into the current branch.")]
    async fn securegit_merge(
        &self,
        Parameters(params): Parameters<MergeParams>,
    ) -> Result<CallToolResult, McpError> {
        let ui = UI::new(false, true, false, false);
        ops::merge::execute(
            &self.work_dir,
            &params.branch,
            false,
            false,
            false,
            false,
            &ui,
        )
        .map_err(|e| mcp_err(format!("Merge failed: {}", e)))?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Merged branch '{}'.",
            params.branch
        ))]))
    }

    #[tool(description = "Save current changes to the stash.")]
    async fn securegit_stash_save(
        &self,
        Parameters(params): Parameters<StashSaveParams>,
    ) -> Result<CallToolResult, McpError> {
        let ui = UI::new(false, true, false, false);
        ops::stash::save(&self.work_dir, params.message.as_deref(), &ui)
            .map_err(|e| mcp_err(format!("Stash save failed: {}", e)))?;

        Ok(CallToolResult::success(vec![Content::text(
            "Changes stashed.",
        )]))
    }

    #[tool(description = "Pop (apply and remove) a stash entry.")]
    async fn securegit_stash_pop(
        &self,
        Parameters(params): Parameters<StashPopParams>,
    ) -> Result<CallToolResult, McpError> {
        let index = params.index.unwrap_or(0);
        let ui = UI::new(false, true, false, false);
        ops::stash::pop(&self.work_dir, index, &ui)
            .map_err(|e| mcp_err(format!("Stash pop failed: {}", e)))?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Popped stash@{{{}}}.",
            index
        ))]))
    }

    #[tool(description = "Create a new tag. Optionally create an annotated tag with a message.")]
    async fn securegit_tag_create(
        &self,
        Parameters(params): Parameters<TagCreateParams>,
    ) -> Result<CallToolResult, McpError> {
        let ui = UI::new(false, true, false, false);
        ops::tag::create(
            &self.work_dir,
            &params.name,
            params.message.as_deref(),
            params.target.as_deref(),
            &ui,
        )
        .map_err(|e| mcp_err(format!("Tag create failed: {}", e)))?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Created tag '{}'.",
            params.name
        ))]))
    }

    #[tool(
        description = "Undo the last securegit operation, restoring the repository to its previous state."
    )]
    async fn securegit_undo(
        &self,
        Parameters(params): Parameters<UndoParams>,
    ) -> Result<CallToolResult, McpError> {
        let ui = UI::new(false, true, false, false);
        if let Some(op_id) = params.op_id {
            ops::undo::execute(&self.work_dir, false, Some(&op_id), 1, &ui)
                .map_err(|e| mcp_err(format!("Undo failed: {}", e)))?;
            Ok(CallToolResult::success(vec![Content::text(format!(
                "Undid operation '{}'.",
                op_id
            ))]))
        } else {
            ops::undo::execute(&self.work_dir, false, None, 1, &ui)
                .map_err(|e| mcp_err(format!("Undo failed: {}", e)))?;
            Ok(CallToolResult::success(vec![Content::text(
                "Undid last operation.",
            )]))
        }
    }

    #[tool(
        description = "Push the current branch to a git remote. Credentials are resolved automatically from stored credentials, environment variables, or SSH keys."
    )]
    async fn securegit_push(
        &self,
        Parameters(params): Parameters<PushParams>,
    ) -> Result<CallToolResult, McpError> {
        self.check_rate_limit()?;
        let remote_name = params.remote.as_deref().unwrap_or("origin");
        let ui = UI::new(false, true, false, false);
        let push_opts = ops::push::PushOptions {
            set_upstream: params.set_upstream.unwrap_or(false),
            force: params.force.unwrap_or(false),
            tags: false,
            all: false,
            token: None,
            ssh_key: None,
        };

        // Verify pinned MCP tools before push (rug-pull detection)
        if self.config.llm_security.enabled
            && self.config.llm_security.verify_pins
            && self.redteam_bridge.is_available()
        {
            let pins_path = self.work_dir.join(".redteam-pins.json");
            if pins_path.exists() {
                // Read the pins file to get the list of servers to verify
                if let Ok(pins_content) = std::fs::read_to_string(&pins_path) {
                    if let Ok(pins) = serde_json::from_str::<serde_json::Value>(&pins_content) {
                        if let Some(servers) = pins.get("servers").and_then(|v| v.as_array()) {
                            for server in servers {
                                let command = server
                                    .get("command")
                                    .and_then(|v| v.as_str())
                                    .unwrap_or_default();
                                let args: Vec<String> = server
                                    .get("args")
                                    .and_then(|v| v.as_array())
                                    .map(|a| {
                                        a.iter()
                                            .filter_map(|v| v.as_str().map(String::from))
                                            .collect()
                                    })
                                    .unwrap_or_default();

                                if command.is_empty() {
                                    continue;
                                }

                                match self
                                    .redteam_bridge
                                    .verify_pins(command, &args, &pins_path.display().to_string())
                                    .await
                                {
                                    Ok(result) => {
                                        if let Ok(parsed) =
                                            serde_json::from_str::<serde_json::Value>(&result)
                                        {
                                            let changes = parsed
                                                .get("changes_found")
                                                .and_then(|v| v.as_u64())
                                                .unwrap_or(0);
                                            if changes > 0 {
                                                return Ok(CallToolResult::error(vec![Content::text(
                                                    format!(
                                                        "BLOCKED: MCP tool definitions changed ({} change(s) detected). \
                                                         Possible rug pull. Review changes and re-pin with \
                                                         `armyknife-llm-redteam pin` before pushing.\n\n{}",
                                                        changes, result
                                                    )
                                                )]));
                                            }
                                        }
                                    }
                                    Err(crate::redteam::bridge::BridgeError::NotInstalled(_)) => {
                                        break
                                    }
                                    Err(e) => {
                                        tracing::warn!("Pin verification failed: {}", e);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        ops::push::execute(
            &self.work_dir,
            remote_name,
            params.branch.as_deref(),
            push_opts,
            &ui,
        )
        .map_err(|e| mcp_err(format!("Push failed: {}", e)))?;

        let branch_desc = params.branch.as_deref().unwrap_or("current branch");
        Ok(CallToolResult::success(vec![Content::text(format!(
            "Pushed {} to '{}'.",
            branch_desc, remote_name
        ))]))
    }

    // ================================================================
    // Worktree tools (5) — parallel development
    // ================================================================

    #[tool(
        description = "List all git worktrees in the repository, including main and secondary worktrees with branch and lock status."
    )]
    async fn securegit_worktree_list(&self) -> Result<CallToolResult, McpError> {
        let json = ops::worktree::list_json(&self.work_dir)
            .map_err(|e| mcp_err(format!("Failed to list worktrees: {}", e)))?;
        Ok(CallToolResult::success(vec![Content::text(json)]))
    }

    #[tool(
        description = "Create a new git worktree for parallel development. Optionally specify a branch to checkout."
    )]
    async fn securegit_worktree_add(
        &self,
        Parameters(params): Parameters<WorktreeAddParams>,
    ) -> Result<CallToolResult, McpError> {
        self.check_rate_limit()?;
        let target = params
            .path
            .map(PathBuf::from)
            .unwrap_or_else(|| PathBuf::from(".worktrees").join(&params.name));
        let ui = UI::new(false, true, false, false);
        ops::worktree::add(
            &self.work_dir,
            &params.name,
            &target,
            params.branch.as_deref(),
            &ui,
        )
        .map_err(|e| mcp_err(format!("Worktree add failed: {}", e)))?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Created worktree '{}' at '{}'.",
            params.name,
            target.display()
        ))]))
    }

    #[tool(
        description = "Remove a git worktree. Use force=true to remove even with uncommitted changes or locked state."
    )]
    async fn securegit_worktree_remove(
        &self,
        Parameters(params): Parameters<WorktreeRemoveParams>,
    ) -> Result<CallToolResult, McpError> {
        self.check_rate_limit()?;
        let force = params.force.unwrap_or(false);
        let ui = UI::new(false, true, false, false);
        ops::worktree::remove(&self.work_dir, &params.name, force, &ui)
            .map_err(|e| mcp_err(format!("Worktree remove failed: {}", e)))?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Removed worktree '{}'.",
            params.name
        ))]))
    }

    #[tool(
        description = "Lock a git worktree to prevent it from being pruned. Optionally provide a reason."
    )]
    async fn securegit_worktree_lock(
        &self,
        Parameters(params): Parameters<WorktreeLockParams>,
    ) -> Result<CallToolResult, McpError> {
        ops::worktree::lock(
            &self.work_dir,
            &params.name,
            params.reason.as_deref(),
            &UI::new(false, true, false, false),
        )
        .map_err(|e| mcp_err(format!("Worktree lock failed: {}", e)))?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Locked worktree '{}'.",
            params.name
        ))]))
    }

    #[tool(description = "Unlock a previously locked git worktree.")]
    async fn securegit_worktree_unlock(
        &self,
        Parameters(params): Parameters<WorktreeUnlockParams>,
    ) -> Result<CallToolResult, McpError> {
        ops::worktree::unlock(
            &self.work_dir,
            &params.name,
            &UI::new(false, true, false, false),
        )
        .map_err(|e| mcp_err(format!("Worktree unlock failed: {}", e)))?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Unlocked worktree '{}'.",
            params.name
        ))]))
    }

    // ================================================================
    // Backup tools (4) — durable backup management
    // ================================================================

    #[tool(
        description = "Add a backup destination for durable code backups. Supports local paths, rsync (user@host:/path), and rclone (remote:bucket/) backends."
    )]
    async fn securegit_backup_add(
        &self,
        Parameters(params): Parameters<BackupAddParams>,
    ) -> Result<CallToolResult, McpError> {
        let auto = params.auto.unwrap_or(false);
        ops::backup::add_destination(
            &self.work_dir,
            &params.name,
            &params.destination,
            params.backend_type.as_deref(),
            auto,
        )
        .map_err(|e| mcp_err(format!("Failed to add backup destination: {}", e)))?;

        let backend = params
            .backend_type
            .unwrap_or_else(|| ops::backup::detect_backend(&params.destination).to_string());

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Added backup destination '{}' ({}) -> {}\nAuto-backup: {}",
            params.name,
            backend,
            params.destination,
            if auto { "enabled" } else { "disabled" }
        ))]))
    }

    #[tool(description = "Remove a backup destination by name.")]
    async fn securegit_backup_remove(
        &self,
        Parameters(params): Parameters<BackupRemoveParams>,
    ) -> Result<CallToolResult, McpError> {
        ops::backup::remove_destination(&self.work_dir, &params.name)
            .map_err(|e| mcp_err(format!("Failed to remove destination: {}", e)))?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Removed backup destination '{}'.",
            params.name
        ))]))
    }

    #[tool(
        description = "List all configured backup destinations with their type, path, and auto-backup status."
    )]
    async fn securegit_backup_list(&self) -> Result<CallToolResult, McpError> {
        let config = ops::backup::load_config(&self.work_dir)
            .map_err(|e| mcp_err(format!("Failed to load backup config: {}", e)))?;

        if config.destinations.is_empty() {
            return Ok(CallToolResult::success(vec![Content::text(
                "No backup destinations configured. Use securegit_backup_add to add one.",
            )]));
        }

        let json = serde_json::to_string_pretty(&config.destinations)
            .map_err(|e| mcp_err(e.to_string()))?;
        Ok(CallToolResult::success(vec![Content::text(json)]))
    }

    #[tool(
        description = "Push a git bundle backup to one or all configured destinations. Creates a portable bundle containing full repository history."
    )]
    async fn securegit_backup_push(
        &self,
        Parameters(params): Parameters<BackupPushParams>,
    ) -> Result<CallToolResult, McpError> {
        self.check_rate_limit()?;
        let all_branches = params.all_branches.unwrap_or(false);
        let mut config = ops::backup::load_config(&self.work_dir)
            .map_err(|e| mcp_err(format!("Failed to load backup config: {}", e)))?;

        if config.destinations.is_empty() {
            return Ok(CallToolResult::error(vec![Content::text(
                "No backup destinations configured. Use securegit_backup_add first.",
            )]));
        }

        let targets: Vec<usize> = if let Some(ref n) = params.name {
            let idx = config
                .destinations
                .iter()
                .position(|d| d.name == *n)
                .ok_or_else(|| mcp_err(format!("No backup destination named '{}'", n)))?;
            vec![idx]
        } else {
            (0..config.destinations.len()).collect()
        };

        let bundle = ops::backup::create_bundle(&self.work_dir, all_branches)
            .map_err(|e| mcp_err(format!("Failed to create bundle: {}", e)))?;

        let mut results = Vec::new();
        let now = chrono::Utc::now().to_rfc3339();

        for &idx in &targets {
            let dest = &config.destinations[idx];
            match ops::backup::push_to_destination(dest, &bundle.path) {
                Ok(()) => {
                    results.push(format!("{}: uploaded ({})", dest.name, dest.backend));
                    config.destinations[idx].last_backup = Some(now.clone());
                }
                Err(e) => {
                    results.push(format!("{}: failed ({})", dest.name, e));
                }
            }
        }

        let _ = ops::backup::save_config(&self.work_dir, &config);
        let _ = std::fs::remove_file(&bundle.path);
        if let Some(parent) = bundle.path.parent() {
            let _ = std::fs::remove_dir(parent);
        }

        let bundle_name = bundle
            .path
            .file_name()
            .unwrap_or_default()
            .to_string_lossy();
        let msg = format!(
            "Bundle: {} ({})\n\n{}",
            bundle_name,
            ops::backup::format_size(bundle.size_bytes),
            results.join("\n")
        );
        Ok(CallToolResult::success(vec![Content::text(msg)]))
    }

    // ================================================================
    // Platform tools (4) — GitHub/GitLab integration
    // ================================================================

    #[tool(
        description = "Show authentication status for Git hosting providers (GitHub/GitLab). Shows which providers have stored or environment-based tokens, plus any registered servers."
    )]
    async fn securegit_auth_status(&self) -> Result<CallToolResult, McpError> {
        let stored = crate::auth::store::list_stored_hosts();
        let hosts: &[(&str, &[&str])] = &[
            ("github.com", &["GITHUB_TOKEN", "GH_TOKEN"]),
            ("gitlab.com", &["GITLAB_TOKEN", "GL_TOKEN"]),
        ];

        let mut lines = Vec::new();

        for (host, env_vars) in hosts {
            let has_stored = stored.iter().any(|h| h == host);
            let env_var = env_vars.iter().find(|v| std::env::var(v).is_ok());

            if has_stored {
                lines.push(format!("{}: authenticated (stored credentials)", host));
            } else if let Some(var) = env_var {
                lines.push(format!("{}: authenticated (via {})", host, var));
            } else {
                lines.push(format!("{}: not authenticated", host));
            }
        }

        // Show registered servers
        if let Ok(registry) = ServerRegistry::load() {
            if !registry.servers.is_empty() {
                lines.push(String::new());
                lines.push("Registered servers:".to_string());
                for server in &registry.servers {
                    let auth_status = if auth::token_for_server(server).is_some() {
                        "authenticated"
                    } else {
                        "no credentials"
                    };
                    lines.push(format!(
                        "  {} ({}): {} [push: {}]",
                        server.name,
                        server.platform,
                        auth_status,
                        if server.push_enabled { "on" } else { "off" }
                    ));
                }
            }
        }

        // Check if current repo has a detected remote
        match platform::detect_remote(&self.work_dir) {
            Ok(remote) => {
                lines.push(format!(
                    "\nCurrent repo: {}/{} ({})",
                    remote.owner, remote.repo, remote.host
                ));
            }
            Err(_) => {
                lines.push("\nCurrent repo: no GitHub/GitLab remote detected".to_string());
            }
        }

        Ok(CallToolResult::success(vec![Content::text(
            lines.join("\n"),
        )]))
    }

    #[tool(
        description = "List pull requests (or merge requests on GitLab) for the current repository. Requires authentication."
    )]
    async fn securegit_pr_list(
        &self,
        Parameters(params): Parameters<PrListParams>,
    ) -> Result<CallToolResult, McpError> {
        let state = params.state.as_deref().unwrap_or("open");

        let client = self.resolve_platform_client(params.server.as_deref())?;

        let prs = client
            .list_pull_requests(state)
            .await
            .map_err(|e| mcp_err(format!("Failed to list PRs: {}", e)))?;

        if prs.is_empty() {
            return Ok(CallToolResult::success(vec![Content::text(format!(
                "No {} pull requests found.",
                state
            ))]));
        }

        let json = serde_json::to_string_pretty(&prs).map_err(|e| mcp_err(e.to_string()))?;
        Ok(self.sanitize_text_result(json))
    }

    #[tool(
        description = "Show CI/CD pipeline status (GitHub Actions checks or GitLab pipelines) for the current branch or a specified branch."
    )]
    async fn securegit_ci_status(
        &self,
        Parameters(params): Parameters<CiStatusParams>,
    ) -> Result<CallToolResult, McpError> {
        let client = self.resolve_platform_client(params.server.as_deref())?;

        let ref_name = if let Some(ref branch) = params.branch {
            branch.clone()
        } else {
            let repo = git2::Repository::open(&self.work_dir)
                .map_err(|e| mcp_err(format!("Failed to open repo: {}", e)))?;
            let head = repo.head().map_err(|e| mcp_err(e.to_string()))?;
            head.shorthand().unwrap_or("HEAD").to_string()
        };

        let status = client
            .get_check_runs(&ref_name)
            .await
            .map_err(|e| mcp_err(format!("Failed to get CI status: {}", e)))?;

        let json = serde_json::to_string_pretty(&status).map_err(|e| mcp_err(e.to_string()))?;
        Ok(self.sanitize_text_result(json))
    }

    #[tool(description = "List releases for the current repository from GitHub or GitLab.")]
    async fn securegit_release_list(
        &self,
        Parameters(params): Parameters<ReleaseListParams>,
    ) -> Result<CallToolResult, McpError> {
        let count = params.count.unwrap_or(10);

        let client = self.resolve_platform_client(params.server.as_deref())?;

        let releases = client
            .list_releases(count)
            .await
            .map_err(|e| mcp_err(format!("Failed to list releases: {}", e)))?;

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

        let json = serde_json::to_string_pretty(&releases).map_err(|e| mcp_err(e.to_string()))?;
        Ok(self.sanitize_text_result(json))
    }

    // ================================================================
    // Server management tools (4) — multi-server credential vault
    // ================================================================

    #[tool(
        description = "Register a new git hosting server (GitHub/GitLab, including self-hosted). Token is stored encrypted and never returned in any response."
    )]
    async fn securegit_server_add(
        &self,
        Parameters(params): Parameters<ServerAddParams>,
    ) -> Result<CallToolResult, McpError> {
        self.check_rate_limit()?;

        let platform = match params.platform.to_lowercase().as_str() {
            "github" | "gh" => ServerPlatform::GitHub,
            "gitlab" | "gl" => ServerPlatform::GitLab,
            other => {
                return Err(mcp_err(format!(
                    "Unknown platform '{}'. Use 'github' or 'gitlab'.",
                    other
                )))
            }
        };

        // Validate URL format
        url::Url::parse(&params.api_url)
            .map_err(|e| mcp_err(format!("Invalid API URL '{}': {}", params.api_url, e)))?;

        let secure_token = auth::SecureString::from_string(params.token);
        let store_key = format!("server:{}", params.name);

        // Store token first so validation client can use it
        auth::store::store_token(&store_key, &secure_token)
            .map_err(|e| mcp_err(format!("Failed to store token: {}", e)))?;

        // Validate by getting authenticated user
        let temp_client = platform::create_client_for_server(
            &crate::platform::server_registry::ServerConfig {
                name: params.name.clone(),
                platform: platform.clone(),
                api_url: params.api_url.clone(),
                web_url: None,
                push_enabled: params.push_enabled.unwrap_or(true),
            },
            secure_token,
            "validation",
            "check",
        );

        let username = match temp_client.get_authenticated_user().await {
            Ok(user) => user,
            Err(e) => {
                // Clean up stored token on validation failure
                let _ = auth::store::delete_token(&store_key);
                return Err(mcp_err(format!(
                    "Token validation failed for '{}': {}",
                    params.name, e
                )));
            }
        };

        // Add to registry
        let mut registry = ServerRegistry::load()
            .map_err(|e| mcp_err(format!("Failed to load registry: {}", e)))?;

        let server_config = crate::platform::server_registry::ServerConfig {
            name: params.name.clone(),
            platform,
            api_url: params.api_url.clone(),
            web_url: None,
            push_enabled: params.push_enabled.unwrap_or(true),
        };

        registry
            .add(server_config)
            .map_err(|e| mcp_err(e.to_string()))?;
        registry
            .save()
            .map_err(|e| mcp_err(format!("Failed to save registry: {}", e)))?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Server '{}' registered. Authenticated as '{}'.",
            params.name, username
        ))]))
    }

    #[tool(description = "Remove a registered git hosting server and its stored credentials.")]
    async fn securegit_server_remove(
        &self,
        Parameters(params): Parameters<ServerRemoveParams>,
    ) -> Result<CallToolResult, McpError> {
        let mut registry = ServerRegistry::load()
            .map_err(|e| mcp_err(format!("Failed to load registry: {}", e)))?;

        registry
            .remove(&params.name)
            .map_err(|e| mcp_err(e.to_string()))?;
        registry
            .save()
            .map_err(|e| mcp_err(format!("Failed to save registry: {}", e)))?;

        // Delete stored token
        let store_key = format!("server:{}", params.name);
        let _ = auth::store::delete_token(&store_key);

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Server '{}' removed.",
            params.name
        ))]))
    }

    #[tool(
        description = "List all registered git hosting servers with their platform, URL, and authentication status. Never reveals token values."
    )]
    async fn securegit_server_list(&self) -> Result<CallToolResult, McpError> {
        let registry = ServerRegistry::load()
            .map_err(|e| mcp_err(format!("Failed to load registry: {}", e)))?;

        if registry.servers.is_empty() {
            return Ok(CallToolResult::success(vec![Content::text(
                "No servers registered. Use securegit_server_add to register one.",
            )]));
        }

        let mut servers_info = Vec::new();
        for server in &registry.servers {
            let auth_status = if auth::token_for_server(server).is_some() {
                "authenticated"
            } else {
                "no credentials"
            };

            servers_info.push(serde_json::json!({
                "name": server.name,
                "platform": server.platform.to_string(),
                "api_url": server.api_url,
                "push_enabled": server.push_enabled,
                "auth_status": auth_status,
            }));
        }

        let json =
            serde_json::to_string_pretty(&servers_info).map_err(|e| mcp_err(e.to_string()))?;
        Ok(CallToolResult::success(vec![Content::text(json)]))
    }

    #[tool(
        description = "Push the current branch to one or more registered git hosting servers. Credentials are resolved internally and never exposed."
    )]
    async fn securegit_server_push(
        &self,
        Parameters(params): Parameters<ServerPushParams>,
    ) -> Result<CallToolResult, McpError> {
        self.check_rate_limit()?;

        let registry = ServerRegistry::load()
            .map_err(|e| mcp_err(format!("Failed to load registry: {}", e)))?;

        let targets: Vec<_> = if let Some(ref names) = params.servers {
            let mut found = Vec::new();
            for name in names {
                let server = registry
                    .get(name)
                    .ok_or_else(|| mcp_err(format!("Server '{}' not found", name)))?;
                found.push(server);
            }
            found
        } else {
            let targets = registry.push_targets();
            if targets.is_empty() {
                return Ok(CallToolResult::error(vec![Content::text(
                    "No push-enabled servers found. Register servers with securegit_server_add.",
                )]));
            }
            targets
        };

        // Determine branch to push
        let branch = if let Some(ref b) = params.branch {
            b.clone()
        } else {
            let repo = git2::Repository::open(&self.work_dir)
                .map_err(|e| mcp_err(format!("Failed to open repo: {}", e)))?;
            let head = repo.head().map_err(|e| mcp_err(e.to_string()))?;
            head.shorthand().unwrap_or("main").to_string()
        };

        let force = params.force.unwrap_or(false);
        let ui = UI::new(false, true, false, false);
        let mut results = Vec::new();

        for server in &targets {
            let token = match auth::token_for_server(server) {
                Some(t) => t,
                None => {
                    results.push(format!("  x {}: no credentials found", server.name));
                    continue;
                }
            };

            // Construct a temporary remote name for pushing
            let remote_url =
                build_authenticated_url(&server.api_url, &server.platform, token.as_str());

            // Use a temporary remote to push
            match push_to_url(&self.work_dir, &remote_url, &branch, force, &ui) {
                Ok(()) => {
                    results.push(format!("  ok {}: pushed {}", server.name, branch));
                }
                Err(e) => {
                    let sanitized = sanitizer::sanitize_output(&e.to_string());
                    results.push(format!("  x {}: {}", server.name, sanitized));
                }
            }
        }

        let msg = format!("Push results:\n\n{}", results.join("\n"));
        Ok(CallToolResult::success(vec![Content::text(
            sanitizer::sanitize_output(&msg),
        )]))
    }

    // ================================================================
    // HuggingFace Hub tools (7) — model management + pipeline
    // ================================================================

    #[tool(
        description = "Download a model from HuggingFace Hub to the local cache (~/.cache/huggingface/hub/). Supports revision selection and glob-based file filtering. Returns the local snapshot path."
    )]
    async fn securegit_hf_pull(
        &self,
        Parameters(params): Parameters<HfPullParams>,
    ) -> Result<CallToolResult, McpError> {
        self.check_rate_limit()?;

        let client = crate::huggingface::client::HfClient::from_env();
        let cache = crate::huggingface::cache::HfCache::new();
        let opts = crate::huggingface::download::DownloadOptions {
            revision: params.revision.unwrap_or_else(|| "main".to_string()),
            include: params.include.unwrap_or_default(),
            exclude: params.exclude.unwrap_or_default(),
        };

        let result =
            crate::huggingface::download::download_model(&client, &cache, &params.model_id, &opts)
                .await
                .map_err(|e| mcp_err(format!("Model pull failed: {}", e)))?;

        let json = serde_json::json!({
            "model_id": result.model_id,
            "revision": result.revision,
            "commit_sha": result.commit_sha,
            "snapshot_path": result.snapshot_path.display().to_string(),
            "files_downloaded": result.files_downloaded,
            "total_bytes": result.total_bytes,
            "from_cache": result.from_cache,
        });

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&json).map_err(|e| mcp_err(e.to_string()))?,
        )]))
    }

    #[tool(
        description = "Upload model files to a HuggingFace Hub repository. Creates the repo if it doesn't exist."
    )]
    async fn securegit_hf_push(
        &self,
        Parameters(params): Parameters<HfPushParams>,
    ) -> Result<CallToolResult, McpError> {
        self.check_rate_limit()?;

        let client = crate::huggingface::client::HfClient::from_env();
        let full_repo = if let Some(ref org) = params.hf_org {
            format!("{}/{}", org, params.repo_id)
        } else {
            params.repo_id.clone()
        };

        client
            .create_repo(&full_repo, false)
            .await
            .map_err(|e| mcp_err(format!("Failed to create HF repo '{}': {}", full_repo, e)))?;

        let path = PathBuf::from(&params.path);
        let opts = crate::huggingface::upload::UploadOptions {
            repo_id: full_repo,
            revision: "main".to_string(),
            commit_message: "Upload model via securegit MCP".to_string(),
        };

        let result = crate::huggingface::upload::upload_model(&client, &path, &opts)
            .await
            .map_err(|e| mcp_err(format!("Model push failed: {}", e)))?;

        let json = serde_json::json!({
            "repo_id": result.repo_id,
            "files_uploaded": result.files_uploaded,
            "url": result.commit_url,
        });

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&json).map_err(|e| mcp_err(e.to_string()))?,
        )]))
    }

    #[tool(
        description = "Search for models on HuggingFace Hub by keyword, task, or library. Returns model IDs, download counts, and metadata."
    )]
    async fn securegit_hf_search(
        &self,
        Parameters(params): Parameters<HfSearchParams>,
    ) -> Result<CallToolResult, McpError> {
        self.check_rate_limit()?;

        let client = crate::huggingface::client::HfClient::from_env();
        let limit = params.limit.unwrap_or(10);

        let models = client
            .search_models(
                &params.query,
                params.task.as_deref(),
                params.library.as_deref(),
                limit,
            )
            .await
            .map_err(|e| mcp_err(format!("Search failed: {}", e)))?;

        let results: Vec<serde_json::Value> = models
            .iter()
            .map(|m| {
                serde_json::json!({
                    "model_id": m.model_id.as_deref().unwrap_or(&m.id),
                    "pipeline_tag": m.pipeline_tag,
                    "library_name": m.library_name,
                    "downloads": m.downloads,
                    "likes": m.likes,
                    "private": m.private,
                })
            })
            .collect();

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&results).map_err(|e| mcp_err(e.to_string()))?,
        )]))
    }

    #[tool(
        description = "Get detailed model info from HuggingFace Hub including metadata, tags, and file listing."
    )]
    async fn securegit_hf_info(
        &self,
        Parameters(params): Parameters<HfInfoParams>,
    ) -> Result<CallToolResult, McpError> {
        self.check_rate_limit()?;

        let client = crate::huggingface::client::HfClient::from_env();
        let info = client
            .model_info(&params.model_id)
            .await
            .map_err(|e| mcp_err(format!("Model info failed: {}", e)))?;

        let files: Vec<serde_json::Value> = info
            .siblings
            .as_ref()
            .map(|s| {
                s.iter()
                    .map(|f| {
                        serde_json::json!({
                            "filename": f.filename,
                            "size": f.size.or(f.lfs.as_ref().map(|l| l.size)),
                        })
                    })
                    .collect()
            })
            .unwrap_or_default();

        let json = serde_json::json!({
            "model_id": info.model_id.as_deref().unwrap_or(&info.id),
            "sha": info.sha,
            "pipeline_tag": info.pipeline_tag,
            "library_name": info.library_name,
            "tags": info.tags,
            "downloads": info.downloads,
            "likes": info.likes,
            "private": info.private,
            "files": files,
        });

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&json).map_err(|e| mcp_err(e.to_string()))?,
        )]))
    }

    #[tool(
        description = "Scan a HuggingFace model for security vulnerabilities using the LLM redteam bridge. Returns findings with severity levels."
    )]
    async fn securegit_hf_scan(
        &self,
        Parameters(params): Parameters<HfScanParams>,
    ) -> Result<CallToolResult, McpError> {
        self.check_rate_limit()?;

        let result = self
            .redteam_bridge
            .pipeline_scan(&params.model_id, None)
            .await
            .map_err(|e| mcp_err(format!("HF scan failed: {}", e)))?;

        Ok(self.sanitize_text_result(result))
    }

    #[tool(
        description = "Trigger a model hardening CI/CD pipeline on a GPU-enabled GitLab server. Uses the server registry for authentication."
    )]
    async fn securegit_hf_pipeline_trigger(
        &self,
        Parameters(params): Parameters<HfPipelineTriggerParams>,
    ) -> Result<CallToolResult, McpError> {
        self.check_rate_limit()?;

        let server_name = params.server.as_deref().unwrap_or("gpubox");
        let registry = ServerRegistry::load()
            .map_err(|e| mcp_err(format!("Failed to load server registry: {}", e)))?;
        let server = registry
            .get(server_name)
            .ok_or_else(|| mcp_err(format!("Server '{}' not found", server_name)))?;

        let project_id = params
            .project_id
            .or_else(|| {
                std::env::var("SECUREGIT_PIPELINE_PROJECT_ID")
                    .ok()?
                    .parse()
                    .ok()
            })
            .ok_or_else(|| {
                mcp_err("project_id required (param or SECUREGIT_PIPELINE_PROJECT_ID)")
            })?;

        let token = params
            .token
            .or_else(|| std::env::var("SECUREGIT_PIPELINE_TOKEN").ok())
            .ok_or_else(|| {
                mcp_err("Pipeline trigger token required (param or SECUREGIT_PIPELINE_TOKEN)")
            })?;

        let url = format!(
            "{}/projects/{}/trigger/pipeline",
            server.api_url, project_id
        );

        let client = reqwest::Client::new();
        let resp = client
            .post(&url)
            .form(&[
                ("token", token.as_str()),
                ("ref", "main"),
                ("variables[MODEL_ID]", params.model_id.as_str()),
            ])
            .send()
            .await
            .map_err(|e| mcp_err(format!("Pipeline trigger failed: {}", e)))?;

        if !resp.status().is_success() {
            let text = resp.text().await.unwrap_or_default();
            return Err(mcp_err(format!("Pipeline trigger failed: {}", text)));
        }

        let result: serde_json::Value = resp.json().await.map_err(|e| mcp_err(e.to_string()))?;

        let json = serde_json::json!({
            "pipeline_id": result["id"],
            "status": result["status"],
            "web_url": result["web_url"],
            "ref": result["ref"],
        });

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&json).map_err(|e| mcp_err(e.to_string()))?,
        )]))
    }

    #[tool(
        description = "Check the status of a CI/CD pipeline run on a GitLab server. Omit pipeline_id to see recent pipelines."
    )]
    async fn securegit_hf_pipeline_status(
        &self,
        Parameters(params): Parameters<HfPipelineStatusParams>,
    ) -> Result<CallToolResult, McpError> {
        self.check_rate_limit()?;

        let server_name = params.server.as_deref().unwrap_or("gpubox");
        let registry = ServerRegistry::load()
            .map_err(|e| mcp_err(format!("Failed to load server registry: {}", e)))?;
        let server = registry
            .get(server_name)
            .ok_or_else(|| mcp_err(format!("Server '{}' not found", server_name)))?;

        let project_id: u64 = std::env::var("SECUREGIT_PIPELINE_PROJECT_ID")
            .ok()
            .and_then(|v| v.parse().ok())
            .ok_or_else(|| mcp_err("SECUREGIT_PIPELINE_PROJECT_ID required"))?;

        let token = auth::token_for_server(server)
            .ok_or_else(|| mcp_err(format!("No credentials for server '{}'", server_name)))?;

        let url = if let Some(pid) = params.pipeline_id {
            format!(
                "{}/projects/{}/pipelines/{}",
                server.api_url, project_id, pid
            )
        } else {
            format!(
                "{}/projects/{}/pipelines?per_page=5&order_by=id&sort=desc",
                server.api_url, project_id
            )
        };

        let client = reqwest::Client::new();
        let resp = client
            .get(&url)
            .header("PRIVATE-TOKEN", token.as_str())
            .send()
            .await
            .map_err(|e| mcp_err(format!("Pipeline status check failed: {}", e)))?;

        if !resp.status().is_success() {
            let text = resp.text().await.unwrap_or_default();
            return Err(mcp_err(format!("Pipeline status failed: {}", text)));
        }

        let result: serde_json::Value = resp.json().await.map_err(|e| mcp_err(e.to_string()))?;

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&result).map_err(|e| mcp_err(e.to_string()))?,
        )]))
    }

    // ================================================================
    // HF Full Pipeline tool
    // ================================================================

    #[tool(
        description = "Run the full cloud automation pipeline: scan model on HF Inference, generate DPO training data, train on AutoTrain, verify fixes via targeted re-scan, and publish hardened model. Zero local GPU required. Estimated cost: $3.50-5.50 per model."
    )]
    async fn securegit_hf_fullpipeline(
        &self,
        Parameters(params): Parameters<HfFullPipelineParams>,
    ) -> Result<CallToolResult, McpError> {
        self.check_rate_limit()?;

        let hf_org = params.hf_org.as_deref().unwrap_or("ArmyknifeLabs");
        let hf_hardware = params.hf_hardware.as_deref().unwrap_or("a10g-large");
        let min_fix_rate = params.min_fix_rate.unwrap_or(0.30);
        let epochs = params.epochs.unwrap_or(3);
        let fail_on_regression = params.fail_on_regression.unwrap_or(true);

        let mut steps_log = Vec::new();

        // Step 1: Scan model on HF Inference
        let scan_model_spec = format!("huggingface://{}", params.model_id);
        let scan_result = self
            .redteam_bridge
            .pipeline_scan(&scan_model_spec, Some("scan-results"))
            .await
            .map_err(|e| mcp_err(format!("Cloud scan failed: {}", e)))?;

        // Parse findings count
        let scan_json: serde_json::Value =
            serde_json::from_str(&scan_result).unwrap_or(serde_json::json!({}));
        let total_findings = scan_json["total_findings"]
            .as_u64()
            .or_else(|| {
                scan_json["content"]
                    .as_array()
                    .and_then(|arr| arr.first())
                    .and_then(|c| c["text"].as_str())
                    .and_then(|text| serde_json::from_str::<serde_json::Value>(text).ok())
                    .and_then(|v| v["total_findings"].as_u64())
            })
            .unwrap_or(0);

        steps_log.push(format!("scan: {} findings", total_findings));

        if total_findings == 0 {
            let result = HfFullPipelineResult {
                original_model: params.model_id.clone(),
                hardened_model: params.model_id.clone(),
                model_url: format!("https://huggingface.co/{}", params.model_id),
                total_findings: 0,
                fix_rate: 1.0,
                verdict: "CLEAN".to_string(),
                regression_count: 0,
                status: "Model already clean — no hardening needed".to_string(),
            };
            let json =
                serde_json::to_string_pretty(&result).map_err(|e| mcp_err(e.to_string()))?;
            return Ok(CallToolResult::success(vec![Content::text(json)]));
        }

        // Step 2: Harden (generate + train on HF)
        let _harden_result = self
            .redteam_bridge
            .pipeline_harden(
                &params.model_id,
                "scan-results",
                Some("hardened-model"),
                Some("dpo"),
                Some("firm"),
                Some(epochs),
                Some("hf"),
                Some(hf_org),
                Some(hf_hardware),
            )
            .await
            .map_err(|e| mcp_err(format!("Hardening failed: {}", e)))?;

        steps_log.push("harden: DPO pairs generated + cloud training started".to_string());

        // Step 3: Derive hardened model name
        let hardened_name = params
            .model_id
            .split('/')
            .last()
            .unwrap_or(&params.model_id)
            .replace('.', "-");
        let hardened_repo = format!("{}/{}-Hardened", hf_org, hardened_name);
        let hardened_spec = format!("huggingface://{}", hardened_repo);

        // Step 4: Verify
        let verify_result = self
            .redteam_bridge
            .pipeline_verify(
                "scan-results/findings.json",
                &hardened_spec,
                Some(&params.model_id),
                Some("verification-report"),
                Some(min_fix_rate),
                Some(fail_on_regression),
            )
            .await
            .map_err(|e| mcp_err(format!("Verification failed: {}", e)))?;

        let verify_json: serde_json::Value =
            serde_json::from_str(&verify_result).unwrap_or(serde_json::json!({}));
        let verify_data = verify_json["content"]
            .as_array()
            .and_then(|arr| arr.first())
            .and_then(|c| c["text"].as_str())
            .and_then(|text| serde_json::from_str::<serde_json::Value>(text).ok())
            .unwrap_or(verify_json);

        let fix_rate = verify_data["fix_rate"].as_f64().unwrap_or(0.0);
        let verdict = verify_data["verdict"]
            .as_str()
            .unwrap_or("UNKNOWN")
            .to_string();
        let regression_count = verify_data["regression_count"].as_u64().unwrap_or(0);
        let passed = verify_data["passed"].as_bool().unwrap_or(false);

        steps_log.push(format!(
            "verify: {:.1}% fix rate, {} regressions, verdict={}",
            fix_rate * 100.0,
            regression_count,
            verdict
        ));

        // Step 5: Publish (if verification passed)
        let status = if passed {
            let _publish_result = self
                .redteam_bridge
                .pipeline_publish("hardened-model", "verification-report", &hardened_name, Some(hf_org))
                .await
                .map_err(|e| mcp_err(format!("Publish failed: {}", e)))?;
            steps_log.push("publish: model published to HuggingFace".to_string());
            "completed".to_string()
        } else {
            steps_log.push("publish: skipped (verification failed)".to_string());
            format!(
                "verification failed: {:.1}% fix rate (threshold: {:.1}%)",
                fix_rate * 100.0,
                min_fix_rate * 100.0
            )
        };

        let result = HfFullPipelineResult {
            original_model: params.model_id,
            hardened_model: hardened_repo.clone(),
            model_url: format!("https://huggingface.co/{}", hardened_repo),
            total_findings,
            fix_rate,
            verdict,
            regression_count,
            status,
        };

        let json = serde_json::to_string_pretty(&result).map_err(|e| mcp_err(e.to_string()))?;
        Ok(CallToolResult::success(vec![Content::text(json)]))
    }

    // ================================================================
    // Repository creation tool
    // ================================================================

    #[tool(
        description = "Create a new repository on a registered GitHub or GitLab server. Returns the repo URL and clone URLs."
    )]
    async fn securegit_repo_create(
        &self,
        Parameters(params): Parameters<CreateRepoParams>,
    ) -> Result<CallToolResult, McpError> {
        self.check_rate_limit()?;

        let registry = ServerRegistry::load()
            .map_err(|e| mcp_err(format!("Failed to load registry: {}", e)))?;

        let server = if let Some(ref name) = params.server {
            registry
                .get(name)
                .ok_or_else(|| mcp_err(format!("Server '{}' not found", name)))?
                .clone()
        } else {
            // Try to auto-detect from remote
            let remote = platform::detect_remote(&self.work_dir)
                .map_err(|_| mcp_err("No server specified and could not auto-detect from remote. Use the 'server' parameter."))?;
            let platform_str = match remote.host {
                platform::PlatformHost::GitHub => "github",
                platform::PlatformHost::GitLab => "gitlab",
            };
            // Find a matching server in registry
            registry
                .servers
                .iter()
                .find(|s| s.platform.to_string().to_lowercase() == platform_str)
                .ok_or_else(|| mcp_err(format!("No registered {} server found", platform_str)))?
                .clone()
        };

        let token = auth::token_for_server(&server)
            .ok_or_else(|| mcp_err(format!("No credentials found for server '{}'", server.name)))?;

        let client = platform::create_client_for_server(&server, token, "", "");

        let create_req = platform::types::CreateRepo {
            name: params.name.clone(),
            description: params.description.clone(),
            private: params.private.unwrap_or(false),
            namespace: params.namespace.clone(),
        };

        let repo = client
            .create_repo(&create_req)
            .await
            .map_err(|e| mcp_err(format!("Failed to create repository: {}", e)))?;

        let json = serde_json::json!({
            "name": repo.name,
            "full_name": repo.full_name,
            "web_url": repo.web_url,
            "clone_url_http": repo.clone_url_http,
            "clone_url_ssh": repo.clone_url_ssh,
            "private": repo.private,
            "server": server.name,
        });

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&json).map_err(|e| mcp_err(e.to_string()))?,
        )]))
    }
}

#[tool_handler]
impl ServerHandler for SecuregitMcpServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo {
            protocol_version: ProtocolVersion::V_2024_11_05,
            capabilities: ServerCapabilities::builder().enable_tools().build(),
            server_info: Implementation {
                name: "securegit-mcp".into(),
                title: Some("SecureGit MCP Server".into()),
                version: env!("CARGO_PKG_VERSION").into(),
                description: Some("Security-aware git operations via MCP".into()),
                icons: None,
                website_url: None,
            },
            instructions: Some(
                "SecureGit MCP Server — a security-aware git tool server. \
                 Provides 50 tools for repository operations with integrated \
                 security scanning. Use securegit_safe_commit for security-gated \
                 commits, securegit_scan for vulnerability detection, \
                 standard git operations (status, log, diff, push, etc.), \
                 backup management (backup_add, backup_push, backup_list), \
                 platform integration (auth_status, pr_list, ci_status, release_list), \
                 and multi-server management (server_add, server_remove, server_list, server_push)."
                    .into(),
            ),
        }
    }
}

// ---- Helpers ----

fn parse_severity(s: Option<&str>) -> u8 {
    severity_rank(s.unwrap_or("low"))
}

fn severity_rank(s: &str) -> u8 {
    match s.to_lowercase().as_str() {
        "critical" => 4,
        "high" => 3,
        "medium" => 2,
        "low" => 1,
        _ => 0,
    }
}

/// Build an authenticated git remote URL from an API base URL.
/// Converts API URLs to git-push-compatible HTTP URLs with embedded token.
fn build_authenticated_url(api_url: &str, platform: &ServerPlatform, token: &str) -> String {
    // Parse the API URL to extract the scheme and host
    if let Ok(parsed) = url::Url::parse(api_url) {
        let scheme = parsed.scheme();
        let host = parsed.host_str().unwrap_or("localhost");
        let port = parsed.port().map(|p| format!(":{}", p)).unwrap_or_default();

        match platform {
            ServerPlatform::GitHub => {
                // GitHub API: https://api.github.com -> https://TOKEN@github.com
                // For GitHub Enterprise: https://ghe.example.com/api/v3 -> https://TOKEN@ghe.example.com
                let git_host = host.strip_prefix("api.").unwrap_or(host);
                format!("{}://x-access-token:{}@{}{}", scheme, token, git_host, port)
            }
            ServerPlatform::GitLab => {
                // GitLab: https://gitlab.example.com/api/v4 -> https://oauth2:TOKEN@gitlab.example.com
                format!("{}://oauth2:{}@{}{}", scheme, token, host, port)
            }
        }
    } else {
        // Fallback: return the URL as-is
        api_url.to_string()
    }
}

/// Push a branch to a URL using git2.
fn push_to_url(
    work_dir: &std::path::Path,
    remote_url: &str,
    branch: &str,
    force: bool,
    _ui: &UI,
) -> anyhow::Result<()> {
    let repo = git2::Repository::open(work_dir)?;

    // Create a temporary anonymous remote
    let mut remote = repo.remote_anonymous(remote_url)?;

    let refspec = if force {
        format!("+refs/heads/{}:refs/heads/{}", branch, branch)
    } else {
        format!("refs/heads/{}:refs/heads/{}", branch, branch)
    };

    // Set up push options with credentials from the URL
    let mut push_opts = git2::PushOptions::new();
    let mut callbacks = git2::RemoteCallbacks::new();
    callbacks.credentials(|_url, _username_from_url, _allowed_types| {
        // The credentials are embedded in the URL, so git2 should handle it
        Err(git2::Error::from_str("credentials embedded in URL"))
    });
    push_opts.remote_callbacks(callbacks);

    remote.push(&[&refspec], Some(&mut push_opts))?;
    Ok(())
}