meerkat-core 0.8.1

Core agent logic for Meerkat (no I/O deps)
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
//! MCP server configuration loading and management
//!
//! Provides file-based MCP server configuration with two scopes:
//! - `project`: `<context-root>/.rkat/mcp.toml` (or cwd when ambient) - local, shared in repo
//! - `user`: `~/.rkat/mcp.toml` - global, personal
//!
//! Precedence: project > user (project wins on name collision)

#[cfg(not(target_arch = "wasm32"))]
use fs4::fs_std::FileExt;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[cfg(not(target_arch = "wasm32"))]
use std::collections::HashSet;
#[cfg(not(target_arch = "wasm32"))]
use std::fs::{File, OpenOptions};
#[cfg(not(target_arch = "wasm32"))]
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
#[cfg(not(target_arch = "wasm32"))]
use toml_edit::{Array, DocumentMut, Item, Table};

/// MCP configuration containing server definitions
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct McpConfig {
    #[serde(default)]
    pub servers: Vec<McpServerConfig>,
}

/// Transport kind for MCP servers
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum McpTransportKind {
    Stdio,
    StreamableHttp,
    Sse,
}

impl McpTransportKind {
    pub fn default_for_http() -> Self {
        McpTransportKind::StreamableHttp
    }
}

/// Stdio transport configuration
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct McpStdioConfig {
    /// Command to spawn the server
    pub command: String,
    /// Arguments to pass to the command
    #[serde(default)]
    pub args: Vec<String>,
    /// Environment variables
    #[serde(default)]
    pub env: HashMap<String, String>,
}

/// HTTP transport configuration (streamable HTTP or legacy SSE)
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct McpHttpConfig {
    /// Server URL
    pub url: String,
    /// Extra headers to include on requests
    #[serde(default)]
    pub headers: HashMap<String, String>,
    /// HTTP transport selection (default: streamable-http)
    #[serde(default)]
    pub transport: Option<McpHttpTransport>,
}

/// HTTP transport selection for URL-based servers
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
#[derive(Default)]
pub enum McpHttpTransport {
    #[default]
    StreamableHttp,
    Sse,
}

/// MCP server transport configuration
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(untagged)]
pub enum McpTransportConfig {
    Stdio(McpStdioConfig),
    Http(McpHttpConfig),
}

/// Configuration for a single MCP server
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct McpServerConfig {
    /// Server name (must be unique within scope)
    pub name: String,
    /// Transport configuration (stdio or HTTP)
    #[serde(flatten)]
    pub transport: McpTransportConfig,
    /// Connection timeout in seconds (connect + handshake + list_tools).
    /// Defaults to 10 seconds when not specified.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub connect_timeout_secs: Option<u32>,
}

impl McpServerConfig {
    pub fn stdio(
        name: impl Into<String>,
        command: impl Into<String>,
        args: Vec<String>,
        env: HashMap<String, String>,
    ) -> Self {
        Self {
            name: name.into(),
            transport: McpTransportConfig::Stdio(McpStdioConfig {
                command: command.into(),
                args,
                env,
            }),
            connect_timeout_secs: None,
        }
    }

    pub fn streamable_http(
        name: impl Into<String>,
        url: impl Into<String>,
        headers: HashMap<String, String>,
    ) -> Self {
        Self {
            name: name.into(),
            transport: McpTransportConfig::Http(McpHttpConfig {
                url: url.into(),
                headers,
                transport: None,
            }),
            connect_timeout_secs: None,
        }
    }

    pub fn sse(
        name: impl Into<String>,
        url: impl Into<String>,
        headers: HashMap<String, String>,
    ) -> Self {
        Self {
            name: name.into(),
            transport: McpTransportConfig::Http(McpHttpConfig {
                url: url.into(),
                headers,
                transport: Some(McpHttpTransport::Sse),
            }),
            connect_timeout_secs: None,
        }
    }

    pub fn transport_kind(&self) -> McpTransportKind {
        match &self.transport {
            McpTransportConfig::Stdio(_) => McpTransportKind::Stdio,
            McpTransportConfig::Http(http) => match http.transport.unwrap_or_default() {
                McpHttpTransport::StreamableHttp => McpTransportKind::StreamableHttp,
                McpHttpTransport::Sse => McpTransportKind::Sse,
            },
        }
    }
}

/// Scope for MCP server configuration
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum McpScope {
    /// User-level config: ~/.rkat/mcp.toml
    User,
    /// Project-level config: `<context-root>/.rkat/mcp.toml` (or cwd when ambient)
    Project,
}

/// MCP server with its source scope
#[derive(Debug, Clone)]
pub struct McpServerWithScope {
    pub server: McpServerConfig,
    pub scope: McpScope,
}

/// Authority for mutating persisted MCP server configuration.
///
/// Public surfaces do not choose ad hoc files. They present the caller's
/// persisted intent to this authority, which resolves the canonical config path
/// from the same convention roots used by config loading.
#[derive(Debug, Clone)]
pub struct McpConfigMutationAuthority {
    pub scope: McpScope,
    pub context_root: Option<PathBuf>,
    pub user_config_root: Option<PathBuf>,
}

impl McpConfigMutationAuthority {
    /// Bind a mutation to a canonical scope and explicit convention roots.
    pub fn for_scope(
        scope: McpScope,
        context_root: Option<PathBuf>,
        user_config_root: Option<PathBuf>,
    ) -> Self {
        Self {
            scope,
            context_root,
            user_config_root,
        }
    }

    pub fn project(context_root: Option<PathBuf>, user_config_root: Option<PathBuf>) -> Self {
        Self::for_scope(McpScope::Project, context_root, user_config_root)
    }

    /// Resolve the canonical persisted path selected by this authority.
    ///
    /// Explicit convention roots win. Ambient CWD/HOME lookup remains only
    /// for callers that deliberately construct an authority without roots.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn resolved_path(&self) -> Result<PathBuf, McpConfigError> {
        match self.scope {
            McpScope::Project => Ok(self
                .context_root
                .as_deref()
                .map(project_mcp_path_in)
                .or_else(project_mcp_path)
                .ok_or(McpConfigError::PathUnavailable { scope: self.scope })?),
            McpScope::User => Ok(self
                .user_config_root
                .as_deref()
                .map(user_mcp_path_in)
                .or_else(user_mcp_path)
                .ok_or(McpConfigError::PathUnavailable { scope: self.scope })?),
        }
    }
}

/// Rollback token returned by persisted mutations.
///
/// Surfaces keep this token until the live adapter stages the same mutation. If
/// staging fails, rolling back restores the exact previous bytes (or removes a
/// newly-created file).
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone)]
pub struct McpConfigRollback {
    path: PathBuf,
    previous_bytes: Option<Vec<u8>>,
    committed_bytes: Vec<u8>,
    committed_revision: uuid::Uuid,
}

#[cfg(not(target_arch = "wasm32"))]
impl McpConfigRollback {
    pub async fn rollback(self) -> Result<(), McpConfigError> {
        let lock = acquire_mcp_config_lock(&self.path).await?;
        let current = read_existing_bytes(&self.path).await?;
        if lock.revision != Some(self.committed_revision)
            || current.as_deref() != Some(self.committed_bytes.as_slice())
        {
            return Err(McpConfigError::RollbackConflict {
                path: self.path.display().to_string(),
            });
        }

        // Fence the rollback before touching the config bytes. A process crash
        // after this durable revision reservation can leave the committed file
        // in place, but the stale rollback token can never be replayed.
        let (lock, _) = reserve_mcp_config_revision(lock).await?;
        let result = restore_mcp_file(&self.path, self.previous_bytes.as_deref()).await;
        drop(lock);
        result
    }
}

/// Errors that can occur during MCP config operations
#[derive(Debug, thiserror::Error)]
pub enum McpConfigError {
    #[error("IO error: {0}")]
    Io(String),
    #[error("Parse error in {path}: {message}")]
    Parse { path: String, message: String },
    #[error("Server '{0}' already exists. Remove it first with: rkat mcp remove {0}")]
    ServerExists(String),
    #[error("Server '{0}' not found")]
    ServerNotFound(String),
    #[error("Server '{name}' exists in multiple scopes. Specify --scope: {scopes:?}")]
    AmbiguousServer { name: String, scopes: Vec<McpScope> },
    #[error("MCP config rollback conflict at {path}: config changed after this mutation")]
    RollbackConflict { path: String },
    #[error("MCP config revision sidecar is corrupt at {path}: {message}")]
    RevisionCorrupt { path: String, message: String },
    #[error("Could not determine MCP config path for {scope} scope")]
    PathUnavailable { scope: McpScope },
    #[error("Missing environment variable '{var}' referenced in {field}")]
    MissingEnvVar { field: String, var: String },
    #[error("Invalid environment variable reference in {field}: '{value}'")]
    InvalidEnvVarSyntax { field: String, value: String },
}

#[cfg(not(target_arch = "wasm32"))]
impl McpConfig {
    /// Load from user + project config, project wins on name collision.
    /// Returns servers in precedence order (project first, then user).
    pub async fn load() -> Result<Self, McpConfigError> {
        let user = user_mcp_path();
        let project = project_mcp_path();

        let user_cfg = read_mcp_file(user.as_deref()).await?;
        let project_cfg = read_mcp_file(project.as_deref()).await?;

        Ok(merge_project_over_user(user_cfg, project_cfg))
    }

    /// Load with explicit convention roots.
    ///
    /// `context_root` maps to project scope (`<context_root>/.rkat/mcp.toml`),
    /// `user_config_root` maps to user scope (`<user_config_root>/.rkat/mcp.toml`).
    pub async fn load_from_roots(
        context_root: Option<&Path>,
        user_config_root: Option<&Path>,
    ) -> Result<Self, McpConfigError> {
        let project_path = context_root.map(project_mcp_path_in);
        let user_path = user_config_root.map(user_mcp_path_in);
        Self::load_from_paths(user_path.as_deref(), project_path.as_deref()).await
    }

    /// Load from explicit paths (useful for testing)
    pub async fn load_from_paths(
        user_path: Option<&Path>,
        project_path: Option<&Path>,
    ) -> Result<Self, McpConfigError> {
        let user_cfg = read_mcp_file(user_path).await?;
        let project_cfg = read_mcp_file(project_path).await?;
        Ok(merge_project_over_user(user_cfg, project_cfg))
    }

    /// Load servers with their scope information
    pub async fn load_with_scopes() -> Result<Vec<McpServerWithScope>, McpConfigError> {
        let user_path = user_mcp_path();
        let project_path = project_mcp_path();

        let user_cfg = read_mcp_file(user_path.as_deref()).await?;
        let project_cfg = read_mcp_file(project_path.as_deref()).await?;

        let mut seen: HashSet<String> = HashSet::new();
        let mut result: Vec<McpServerWithScope> = Vec::new();

        // Project first (highest precedence)
        for server in project_cfg.servers {
            if seen.insert(server.name.clone()) {
                result.push(McpServerWithScope {
                    server,
                    scope: McpScope::Project,
                });
            }
        }

        // Then user servers not shadowed by project
        for server in user_cfg.servers {
            if seen.insert(server.name.clone()) {
                result.push(McpServerWithScope {
                    server,
                    scope: McpScope::User,
                });
            }
        }

        Ok(result)
    }

    /// Load scoped server list from explicit convention roots.
    pub async fn load_with_scopes_from_roots(
        context_root: Option<&Path>,
        user_config_root: Option<&Path>,
    ) -> Result<Vec<McpServerWithScope>, McpConfigError> {
        let user_path = user_config_root.map(user_mcp_path_in);
        let project_path = context_root.map(project_mcp_path_in);
        let user_cfg = read_mcp_file(user_path.as_deref()).await?;
        let project_cfg = read_mcp_file(project_path.as_deref()).await?;

        let mut seen: HashSet<String> = HashSet::new();
        let mut result: Vec<McpServerWithScope> = Vec::new();

        for server in project_cfg.servers {
            if seen.insert(server.name.clone()) {
                result.push(McpServerWithScope {
                    server,
                    scope: McpScope::Project,
                });
            }
        }

        for server in user_cfg.servers {
            if seen.insert(server.name.clone()) {
                result.push(McpServerWithScope {
                    server,
                    scope: McpScope::User,
                });
            }
        }
        Ok(result)
    }

    /// Load from a specific scope only
    pub async fn load_scope(scope: McpScope) -> Result<Self, McpConfigError> {
        let path = match scope {
            McpScope::User => user_mcp_path(),
            McpScope::Project => project_mcp_path(),
        };
        read_mcp_file(path.as_deref()).await
    }

    /// Load from a specific scope using explicit convention roots.
    pub async fn load_scope_from_roots(
        scope: McpScope,
        context_root: Option<&Path>,
        user_config_root: Option<&Path>,
    ) -> Result<Self, McpConfigError> {
        let path = match scope {
            McpScope::User => user_config_root.map(user_mcp_path_in),
            McpScope::Project => context_root.map(project_mcp_path_in),
        };
        read_mcp_file(path.as_deref()).await
    }

    /// Check if a server exists in a specific scope
    pub async fn server_exists(name: &str, scope: McpScope) -> Result<bool, McpConfigError> {
        let config = Self::load_scope(scope).await?;
        Ok(config.servers.iter().any(|s| s.name == name))
    }

    /// Check a scope using the caller's explicit convention roots.
    pub async fn server_exists_from_roots(
        name: &str,
        scope: McpScope,
        context_root: Option<&Path>,
        user_config_root: Option<&Path>,
    ) -> Result<bool, McpConfigError> {
        let authority = McpConfigMutationAuthority::for_scope(
            scope,
            context_root.map(Path::to_path_buf),
            user_config_root.map(Path::to_path_buf),
        );
        document_contains_server(&authority.resolved_path()?, name).await
    }

    /// Find which scopes contain a server with the given name
    pub async fn find_server_scopes(name: &str) -> Result<Vec<McpScope>, McpConfigError> {
        let mut scopes = Vec::new();

        if Self::server_exists(name, McpScope::Project).await? {
            scopes.push(McpScope::Project);
        }
        if Self::server_exists(name, McpScope::User).await? {
            scopes.push(McpScope::User);
        }

        Ok(scopes)
    }

    /// Find every scope containing a server using explicit convention roots.
    pub async fn find_server_scopes_from_roots(
        name: &str,
        context_root: Option<&Path>,
        user_config_root: Option<&Path>,
    ) -> Result<Vec<McpScope>, McpConfigError> {
        let mut scopes = Vec::new();

        if Self::server_exists_from_roots(name, McpScope::Project, context_root, user_config_root)
            .await?
        {
            scopes.push(McpScope::Project);
        }
        if Self::server_exists_from_roots(name, McpScope::User, context_root, user_config_root)
            .await?
        {
            scopes.push(McpScope::User);
        }

        Ok(scopes)
    }

    /// Persist a server addition under an explicit mutation authority.
    ///
    /// The write is atomic at the file level and returns a rollback token for
    /// the caller to use if the coupled live operation fails.
    pub async fn persist_add_with_rollback(
        authority: &McpConfigMutationAuthority,
        server: McpServerConfig,
    ) -> Result<McpConfigRollback, McpConfigError> {
        let path = authority.resolved_path()?;
        let lock = acquire_mcp_config_lock(&path).await?;
        let previous = read_existing_bytes(&path).await?;
        let mut document = read_mcp_document(&path).await?;
        let servers = servers_array_mut(&mut document, &path)?;
        for existing in servers.iter() {
            if document_server_name(existing, &path)? == server.name.as_str() {
                return Err(McpConfigError::ServerExists(server.name));
            }
        }
        servers.push(server_table(&server));
        // Reserve and fsync a fresh cross-process revision before mutating the
        // config file. If the process crashes after this point, older rollback
        // tokens fail closed instead of overwriting the uncertain result.
        let (lock, committed_revision) = reserve_mcp_config_revision(lock).await?;
        let committed_bytes = write_mcp_document_atomic(&path, &document).await?;
        drop(lock);
        Ok(McpConfigRollback {
            path,
            previous_bytes: previous,
            committed_bytes,
            committed_revision,
        })
    }

    /// Persist a server removal under an explicit mutation authority.
    ///
    /// The write is atomic at the file level and returns a rollback token for
    /// the caller to use if the coupled live operation fails.
    pub async fn persist_remove_with_rollback(
        authority: &McpConfigMutationAuthority,
        server_name: &str,
    ) -> Result<McpConfigRollback, McpConfigError> {
        let path = authority.resolved_path()?;
        let lock = acquire_mcp_config_lock(&path).await?;
        let previous = read_existing_bytes(&path).await?;
        let mut document = read_mcp_document(&path).await?;
        let servers = servers_array_mut(&mut document, &path)?;
        for server in servers.iter() {
            document_server_name(server, &path)?;
        }
        let initial_len = servers.len();
        servers.retain(|server| {
            server.get("name").and_then(|value| value.as_str()) != Some(server_name)
        });
        if servers.len() == initial_len {
            return Err(McpConfigError::ServerNotFound(server_name.to_string()));
        }
        let (lock, committed_revision) = reserve_mcp_config_revision(lock).await?;
        let committed_bytes = write_mcp_document_atomic(&path, &document).await?;
        drop(lock);
        Ok(McpConfigRollback {
            path,
            previous_bytes: previous,
            committed_bytes,
            committed_revision,
        })
    }
}

#[cfg(not(target_arch = "wasm32"))]
struct McpConfigFileLock {
    file: File,
    revision: Option<uuid::Uuid>,
    valid_revision_bytes: u64,
}

#[cfg(not(target_arch = "wasm32"))]
impl Drop for McpConfigFileLock {
    fn drop(&mut self) {
        let _ = FileExt::unlock(&self.file);
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn mcp_config_lock_path(path: &Path) -> PathBuf {
    path.with_extension(format!(
        "{}.lock",
        path.extension()
            .and_then(|extension| extension.to_str())
            .unwrap_or("toml")
    ))
}

#[cfg(not(target_arch = "wasm32"))]
async fn acquire_mcp_config_lock(path: &Path) -> Result<McpConfigFileLock, McpConfigError> {
    let lock_path = mcp_config_lock_path(path);
    tokio::task::spawn_blocking(move || -> Result<McpConfigFileLock, McpConfigError> {
        if let Some(parent) = lock_path.parent() {
            std::fs::create_dir_all(parent).map_err(|error| {
                McpConfigError::Io(format!("create MCP config lock directory failed: {error}"))
            })?;
        }
        let mut file = OpenOptions::new()
            .create(true)
            .truncate(false)
            .read(true)
            .write(true)
            .open(&lock_path)
            .map_err(|error| McpConfigError::Io(format!("open MCP config lock failed: {error}")))?;
        FileExt::lock_exclusive(&file)
            .map_err(|error| McpConfigError::Io(format!("MCP config lock failed: {error}")))?;
        let (revision, valid_revision_bytes) = read_mcp_config_revision(&mut file, &lock_path)?;
        Ok(McpConfigFileLock {
            file,
            revision,
            valid_revision_bytes,
        })
    })
    .await
    .map_err(|error| McpConfigError::Io(format!("MCP config lock task failed: {error}")))?
}

#[cfg(not(target_arch = "wasm32"))]
const MCP_CONFIG_REVISION_PREFIX: &str = "rkat-mcp-config-revision-v1 ";

/// Read the append-only revision log stored in the already-locked sidecar.
///
/// A trailing partial record can only come from a crash before a reservation
/// was durably acknowledged. The next reservation truncates that tail while
/// still holding the same cross-process lock. Complete malformed records fail
/// closed so mutation cannot proceed on ambiguous revision state.
#[cfg(not(target_arch = "wasm32"))]
fn read_mcp_config_revision(
    file: &mut File,
    lock_path: &Path,
) -> Result<(Option<uuid::Uuid>, u64), McpConfigError> {
    file.seek(SeekFrom::Start(0))
        .and_then(|_| {
            let mut bytes = Vec::new();
            file.read_to_end(&mut bytes).map(|_| bytes)
        })
        .map_err(|error| McpConfigError::Io(format!("read MCP config revision failed: {error}")))
        .and_then(|bytes| {
            let valid_len = bytes
                .iter()
                .rposition(|byte| *byte == b'\n')
                .map_or(0, |index| index.saturating_add(1));
            let mut revision = None;
            for raw_line in bytes[..valid_len].split(|byte| *byte == b'\n') {
                if raw_line.is_empty() {
                    continue;
                }
                let line = std::str::from_utf8(raw_line).map_err(|error| {
                    McpConfigError::RevisionCorrupt {
                        path: lock_path.display().to_string(),
                        message: format!("record is not UTF-8: {error}"),
                    }
                })?;
                let value = line
                    .strip_prefix(MCP_CONFIG_REVISION_PREFIX)
                    .ok_or_else(|| McpConfigError::RevisionCorrupt {
                        path: lock_path.display().to_string(),
                        message: "record has an unknown format".to_string(),
                    })?;
                revision = Some(uuid::Uuid::parse_str(value).map_err(|error| {
                    McpConfigError::RevisionCorrupt {
                        path: lock_path.display().to_string(),
                        message: format!("record has an invalid UUID: {error}"),
                    }
                })?);
            }
            let valid_revision_bytes =
                u64::try_from(valid_len).map_err(|_| McpConfigError::RevisionCorrupt {
                    path: lock_path.display().to_string(),
                    message: "revision log length exceeds the supported range".to_string(),
                })?;
            Ok((revision, valid_revision_bytes))
        })
}

/// Append and fsync a fresh revision while retaining the exclusive sidecar
/// lock. Callers must complete their config write/restore before dropping the
/// returned guard.
#[cfg(not(target_arch = "wasm32"))]
async fn reserve_mcp_config_revision(
    lock: McpConfigFileLock,
) -> Result<(McpConfigFileLock, uuid::Uuid), McpConfigError> {
    tokio::task::spawn_blocking(move || {
        let mut lock = lock;
        let revision = fresh_mcp_config_revision(lock.revision)?;
        lock.file
            .set_len(lock.valid_revision_bytes)
            .and_then(|()| lock.file.seek(SeekFrom::End(0)).map(|_| ()))
            .and_then(|()| writeln!(lock.file, "{MCP_CONFIG_REVISION_PREFIX}{revision}"))
            .and_then(|()| lock.file.sync_all())
            .map_err(|error| {
                McpConfigError::Io(format!("reserve MCP config revision failed: {error}"))
            })?;
        lock.valid_revision_bytes = lock.file.stream_position().map_err(|error| {
            McpConfigError::Io(format!("read MCP config revision position failed: {error}"))
        })?;
        lock.revision = Some(revision);
        Ok((lock, revision))
    })
    .await
    .map_err(|error| McpConfigError::Io(format!("MCP config revision task failed: {error}")))?
}

#[cfg(not(target_arch = "wasm32"))]
fn fresh_mcp_config_revision(current: Option<uuid::Uuid>) -> Result<uuid::Uuid, McpConfigError> {
    let mut bytes = [0_u8; 16];
    getrandom::fill(&mut bytes).map_err(|error| {
        McpConfigError::Io(format!(
            "generate MCP config revision entropy failed: {error}"
        ))
    })?;
    let mut revision = uuid::Builder::from_random_bytes(bytes).into_uuid();
    if Some(revision) == current {
        // Preserve the fallible, panic-free RNG path while making freshness
        // deterministic even in the astronomically unlikely repeated draw.
        bytes[15] ^= 1;
        revision = uuid::Builder::from_random_bytes(bytes).into_uuid();
    }
    Ok(revision)
}

#[cfg(not(target_arch = "wasm32"))]
async fn read_mcp_file(path: Option<&Path>) -> Result<McpConfig, McpConfigError> {
    let parsed = read_mcp_file_raw(path).await?;
    expand_env_in_config(parsed)
}

#[cfg(not(target_arch = "wasm32"))]
async fn read_mcp_file_raw(path: Option<&Path>) -> Result<McpConfig, McpConfigError> {
    let Some(path) = path else {
        return Ok(McpConfig::default());
    };
    if !tokio::fs::try_exists(path)
        .await
        .map_err(|e| McpConfigError::Io(e.to_string()))?
    {
        return Ok(McpConfig::default());
    }
    let contents = tokio::fs::read_to_string(path)
        .await
        .map_err(|e| McpConfigError::Io(e.to_string()))?;
    let parsed: McpConfig = toml::from_str(&contents).map_err(|e| McpConfigError::Parse {
        path: path.display().to_string(),
        message: e.to_string(),
    })?;
    Ok(parsed)
}

#[cfg(not(target_arch = "wasm32"))]
async fn read_existing_bytes(path: &Path) -> Result<Option<Vec<u8>>, McpConfigError> {
    if !tokio::fs::try_exists(path)
        .await
        .map_err(|err| McpConfigError::Io(err.to_string()))?
    {
        return Ok(None);
    }
    tokio::fs::read(path)
        .await
        .map(Some)
        .map_err(|err| McpConfigError::Io(err.to_string()))
}

#[cfg(not(target_arch = "wasm32"))]
async fn read_mcp_document(path: &Path) -> Result<DocumentMut, McpConfigError> {
    if !tokio::fs::try_exists(path)
        .await
        .map_err(|err| McpConfigError::Io(err.to_string()))?
    {
        return Ok(DocumentMut::new());
    }
    let contents = tokio::fs::read_to_string(path)
        .await
        .map_err(|err| McpConfigError::Io(err.to_string()))?;
    contents
        .parse::<DocumentMut>()
        .map_err(|err| McpConfigError::Parse {
            path: path.display().to_string(),
            message: err.to_string(),
        })
}

#[cfg(not(target_arch = "wasm32"))]
async fn document_contains_server(path: &Path, name: &str) -> Result<bool, McpConfigError> {
    let document = read_mcp_document(path).await?;
    let Some(servers) = document.get("servers") else {
        return Ok(false);
    };
    let servers = servers
        .as_array_of_tables()
        .ok_or_else(|| McpConfigError::Parse {
            path: path.display().to_string(),
            message: "'servers' must be an array of tables".to_string(),
        })?;
    for server in servers {
        if document_server_name(server, path)? == name {
            return Ok(true);
        }
    }
    Ok(false)
}

#[cfg(not(target_arch = "wasm32"))]
fn document_server_name<'a>(server: &'a Table, path: &Path) -> Result<&'a str, McpConfigError> {
    server
        .get("name")
        .and_then(|value| value.as_str())
        .ok_or_else(|| McpConfigError::Parse {
            path: path.display().to_string(),
            message: "each [[servers]] table must contain a string 'name'".to_string(),
        })
}

#[cfg(not(target_arch = "wasm32"))]
fn servers_array_mut<'a>(
    document: &'a mut DocumentMut,
    path: &Path,
) -> Result<&'a mut toml_edit::ArrayOfTables, McpConfigError> {
    if !document.contains_key("servers") {
        document["servers"] = Item::ArrayOfTables(toml_edit::ArrayOfTables::new());
    }
    document["servers"]
        .as_array_of_tables_mut()
        .ok_or_else(|| McpConfigError::Parse {
            path: path.display().to_string(),
            message: "'servers' must be an array of tables".to_string(),
        })
}

#[cfg(not(target_arch = "wasm32"))]
fn string_array(values: &[String]) -> Array {
    let mut array = Array::new();
    for value in values {
        array.push(value.as_str());
    }
    array
}

#[cfg(not(target_arch = "wasm32"))]
fn string_map(values: &HashMap<String, String>) -> toml_edit::InlineTable {
    let mut table = toml_edit::InlineTable::new();
    let mut entries = values.iter().collect::<Vec<_>>();
    entries.sort_unstable_by(|(left, _), (right, _)| left.cmp(right));
    for (key, value) in entries {
        table.insert(key, value.as_str().into());
    }
    table
}

#[cfg(not(target_arch = "wasm32"))]
fn server_table(server: &McpServerConfig) -> Table {
    let mut table = Table::new();
    table["name"] = toml_edit::value(&server.name);
    match &server.transport {
        McpTransportConfig::Stdio(stdio) => {
            table["command"] = toml_edit::value(&stdio.command);
            if !stdio.args.is_empty() {
                table["args"] = toml_edit::value(string_array(&stdio.args));
            }
            if !stdio.env.is_empty() {
                table["env"] = toml_edit::value(string_map(&stdio.env));
            }
        }
        McpTransportConfig::Http(http) => {
            table["url"] = toml_edit::value(&http.url);
            if !http.headers.is_empty() {
                table["headers"] = toml_edit::value(string_map(&http.headers));
            }
            if let Some(transport) = http.transport {
                table["transport"] = toml_edit::value(match transport {
                    McpHttpTransport::StreamableHttp => "streamable-http",
                    McpHttpTransport::Sse => "sse",
                });
            }
        }
    }
    if let Some(timeout) = server.connect_timeout_secs {
        table["connect_timeout_secs"] = toml_edit::value(i64::from(timeout));
    }
    table
}

#[cfg(not(target_arch = "wasm32"))]
async fn write_mcp_document_atomic(
    path: &Path,
    document: &DocumentMut,
) -> Result<Vec<u8>, McpConfigError> {
    if let Some(parent) = path.parent() {
        tokio::fs::create_dir_all(parent)
            .await
            .map_err(|err| McpConfigError::Io(err.to_string()))?;
    }

    let contents = document.to_string().into_bytes();
    let tmp_path = path.with_extension(format!(
        "{}.tmp",
        path.extension()
            .and_then(|ext| ext.to_str())
            .unwrap_or("toml")
    ));
    tokio::fs::write(&tmp_path, &contents)
        .await
        .map_err(|err| McpConfigError::Io(err.to_string()))?;
    tokio::fs::rename(&tmp_path, path)
        .await
        .map_err(|err| McpConfigError::Io(err.to_string()))?;
    Ok(contents)
}

#[cfg(not(target_arch = "wasm32"))]
async fn restore_mcp_file(path: &Path, previous: Option<&[u8]>) -> Result<(), McpConfigError> {
    match previous {
        Some(bytes) => {
            if let Some(parent) = path.parent() {
                tokio::fs::create_dir_all(parent)
                    .await
                    .map_err(|err| McpConfigError::Io(err.to_string()))?;
            }
            let tmp_path = path.with_extension(format!(
                "{}.rollback.tmp",
                path.extension()
                    .and_then(|ext| ext.to_str())
                    .unwrap_or("toml")
            ));
            tokio::fs::write(&tmp_path, bytes)
                .await
                .map_err(|err| McpConfigError::Io(err.to_string()))?;
            tokio::fs::rename(&tmp_path, path)
                .await
                .map_err(|err| McpConfigError::Io(err.to_string()))?;
        }
        None => {
            if tokio::fs::try_exists(path)
                .await
                .map_err(|err| McpConfigError::Io(err.to_string()))?
            {
                tokio::fs::remove_file(path)
                    .await
                    .map_err(|err| McpConfigError::Io(err.to_string()))?;
            }
        }
    }
    Ok(())
}

#[cfg(not(target_arch = "wasm32"))]
fn merge_project_over_user(user: McpConfig, project: McpConfig) -> McpConfig {
    let mut seen: HashSet<String> = HashSet::new();
    let mut merged: Vec<McpServerConfig> = Vec::new();

    // Project first (highest precedence, local-first)
    for server in project.servers {
        if seen.insert(server.name.clone()) {
            merged.push(server);
        }
    }

    // Then user servers not shadowed by project
    for server in user.servers {
        if seen.insert(server.name.clone()) {
            merged.push(server);
        }
    }

    McpConfig { servers: merged }
}

#[cfg(not(target_arch = "wasm32"))]
fn expand_env_in_config(config: McpConfig) -> Result<McpConfig, McpConfigError> {
    expand_env_in_config_with(config, &|key| std::env::var(key).ok())
}

#[cfg(not(target_arch = "wasm32"))]
fn expand_env_in_config_with<F>(config: McpConfig, env: &F) -> Result<McpConfig, McpConfigError>
where
    F: Fn(&str) -> Option<String>,
{
    let mut servers = Vec::with_capacity(config.servers.len());
    for server in config.servers {
        servers.push(expand_env_in_server_with(server, env)?);
    }
    Ok(McpConfig { servers })
}

#[cfg(not(target_arch = "wasm32"))]
fn expand_env_in_server_with<F>(
    server: McpServerConfig,
    env: &F,
) -> Result<McpServerConfig, McpConfigError>
where
    F: Fn(&str) -> Option<String>,
{
    let transport = match server.transport {
        McpTransportConfig::Stdio(stdio) => {
            let command = expand_env_in_string_with(&stdio.command, "servers[].command", env)?;
            let args = stdio
                .args
                .into_iter()
                .map(|arg| expand_env_in_string_with(&arg, "servers[].args", env))
                .collect::<Result<Vec<_>, _>>()?;
            let env = expand_env_in_map_with(stdio.env, "servers[].env", env)?;
            McpTransportConfig::Stdio(McpStdioConfig { command, args, env })
        }
        McpTransportConfig::Http(http) => {
            let url = expand_env_in_string_with(&http.url, "servers[].url", env)?;
            let headers = expand_env_in_map_with(http.headers, "servers[].headers", env)?;
            McpTransportConfig::Http(McpHttpConfig {
                url,
                headers,
                transport: http.transport,
            })
        }
    };
    Ok(McpServerConfig {
        name: server.name,
        transport,
        connect_timeout_secs: server.connect_timeout_secs,
    })
}

#[cfg(not(target_arch = "wasm32"))]
fn expand_env_in_map_with<F>(
    map: HashMap<String, String>,
    field: &str,
    env: &F,
) -> Result<HashMap<String, String>, McpConfigError>
where
    F: Fn(&str) -> Option<String>,
{
    let mut expanded = HashMap::with_capacity(map.len());
    for (key, value) in map {
        let value = expand_env_in_string_with(&value, field, env)?;
        expanded.insert(key, value);
    }
    Ok(expanded)
}

#[cfg(not(target_arch = "wasm32"))]
fn expand_env_in_string_with<F>(value: &str, field: &str, env: &F) -> Result<String, McpConfigError>
where
    F: Fn(&str) -> Option<String>,
{
    let mut output = String::with_capacity(value.len());
    let mut remaining = value;
    while let Some(start) = remaining.find("${") {
        output.push_str(&remaining[..start]);
        let after = &remaining[start + 2..];
        let Some(end) = after.find('}') else {
            return Err(McpConfigError::InvalidEnvVarSyntax {
                field: field.to_string(),
                value: value.to_string(),
            });
        };
        let var_name = &after[..end];
        if var_name.is_empty() {
            return Err(McpConfigError::InvalidEnvVarSyntax {
                field: field.to_string(),
                value: value.to_string(),
            });
        }
        let var_value = env(var_name).ok_or_else(|| McpConfigError::MissingEnvVar {
            field: field.to_string(),
            var: var_name.to_string(),
        })?;
        output.push_str(&var_value);
        remaining = &after[end + 1..];
    }
    output.push_str(remaining);
    Ok(output)
}

// === Path helpers ===

/// Get the user-level MCP config path: ~/.rkat/mcp.toml
pub fn user_mcp_path() -> Option<PathBuf> {
    home_dir().map(|h| h.join(".rkat/mcp.toml"))
}

pub fn user_mcp_path_in(root: &Path) -> PathBuf {
    root.join(".rkat/mcp.toml")
}

/// Get the user-level MCP config directory: ~/.rkat/
pub fn user_mcp_dir() -> Option<PathBuf> {
    home_dir().map(|h| h.join(".rkat"))
}

/// Find project-level MCP config in cwd only: ./.rkat/mcp.toml
/// Does NOT walk up the directory tree for security reasons.
pub fn find_project_mcp() -> Option<PathBuf> {
    let cwd = std::env::current_dir().ok()?;
    find_project_mcp_in(&cwd)
}

/// Find project-level MCP config in a specific directory only.
/// Does NOT walk up the directory tree for security reasons.
pub fn find_project_mcp_in(dir: &Path) -> Option<PathBuf> {
    let candidate = dir.join(".rkat/mcp.toml");
    if candidate.exists() {
        Some(candidate)
    } else {
        None
    }
}

/// Get the project MCP config path for the current directory (creates path even if doesn't exist)
pub fn project_mcp_path() -> Option<PathBuf> {
    std::env::current_dir()
        .ok()
        .map(|cwd| cwd.join(".rkat/mcp.toml"))
}

pub fn project_mcp_path_in(root: &Path) -> PathBuf {
    root.join(".rkat/mcp.toml")
}

/// Get the project MCP config directory for the current directory
pub fn project_mcp_dir() -> Option<PathBuf> {
    std::env::current_dir().ok().map(|cwd| cwd.join(".rkat"))
}

fn home_dir() -> Option<PathBuf> {
    std::env::var_os("HOME").map(PathBuf::from)
}

impl std::fmt::Display for McpScope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            McpScope::User => write!(f, "user"),
            McpScope::Project => write!(f, "project"),
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[tokio::test]
    async fn test_empty_config_loads() {
        let config = McpConfig::load_from_paths(None, None).await.unwrap();
        assert!(config.servers.is_empty());
    }

    #[test]
    fn test_parse_mcp_toml() {
        let toml = r#"
[[servers]]
name = "test-server"
command = "npx"
args = ["-y", "@test/mcp-server"]
env = { API_KEY = "secret" }

[[servers]]
name = "remote-server"
url = "https://example.com/mcp"
headers = { Authorization = "Bearer token" }
"#;
        let config: McpConfig = toml::from_str(toml).unwrap();
        assert_eq!(config.servers.len(), 2);
        assert_eq!(config.servers[0].name, "test-server");
        match &config.servers[0].transport {
            McpTransportConfig::Stdio(stdio) => {
                assert_eq!(stdio.command, "npx");
                assert_eq!(stdio.args, vec!["-y", "@test/mcp-server"]);
                assert_eq!(stdio.env.get("API_KEY"), Some(&"secret".to_string()));
            }
            McpTransportConfig::Http(_) => unreachable!("Expected stdio transport"),
        }
        assert_eq!(config.servers[1].name, "remote-server");
        match &config.servers[1].transport {
            McpTransportConfig::Http(http) => {
                assert_eq!(http.url, "https://example.com/mcp");
                assert_eq!(
                    http.headers.get("Authorization"),
                    Some(&"Bearer token".to_string())
                );
            }
            McpTransportConfig::Stdio(_) => unreachable!("Expected http transport"),
        }
    }

    #[test]
    fn test_merge_project_over_user() {
        let user = McpConfig {
            servers: vec![
                McpServerConfig::stdio("shared", "user-cmd", vec![], HashMap::new()),
                McpServerConfig::stdio("user-only", "user-only-cmd", vec![], HashMap::new()),
            ],
        };

        let project = McpConfig {
            servers: vec![
                McpServerConfig::stdio("shared", "project-cmd", vec![], HashMap::new()),
                McpServerConfig::stdio("project-only", "project-only-cmd", vec![], HashMap::new()),
            ],
        };

        let merged = merge_project_over_user(user, project);

        // Project servers first, then user-only
        assert_eq!(merged.servers.len(), 3);
        assert_eq!(merged.servers[0].name, "shared");
        match &merged.servers[0].transport {
            McpTransportConfig::Stdio(stdio) => {
                assert_eq!(stdio.command, "project-cmd"); // Project wins
            }
            McpTransportConfig::Http(_) => unreachable!("Expected stdio transport"),
        }
        assert_eq!(merged.servers[1].name, "project-only");
        assert_eq!(merged.servers[2].name, "user-only");
    }

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

        let user_dir = temp.path().join("user");
        tokio::fs::create_dir_all(&user_dir).await.unwrap();
        let user_file = user_dir.join("mcp.toml");
        tokio::fs::write(
            &user_file,
            r#"
[[servers]]
name = "user-server"
command = "user-cmd"
"#,
        )
        .await
        .unwrap();

        let project_dir = temp.path().join("project");
        tokio::fs::create_dir_all(&project_dir).await.unwrap();
        let project_file = project_dir.join("mcp.toml");
        tokio::fs::write(
            &project_file,
            r#"
[[servers]]
name = "project-server"
command = "project-cmd"
"#,
        )
        .await
        .unwrap();

        let config = McpConfig::load_from_paths(Some(&user_file), Some(&project_file))
            .await
            .unwrap();

        assert_eq!(config.servers.len(), 2);
        // Project first
        assert_eq!(config.servers[0].name, "project-server");
        assert_eq!(config.servers[1].name, "user-server");
    }

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

        // Create parent/.rkat/mcp.toml (should NOT be found)
        let parent_config = temp.path().join(".rkat");
        tokio::fs::create_dir_all(&parent_config).await.unwrap();
        tokio::fs::write(
            parent_config.join("mcp.toml"),
            r#"
[[servers]]
name = "parent-server"
command = "should-not-load"
"#,
        )
        .await
        .unwrap();

        // Create parent/child/ directory (no .rkat here)
        let child_dir = temp.path().join("child");
        tokio::fs::create_dir_all(&child_dir).await.unwrap();

        // Looking from child/ should NOT find parent/.rkat/mcp.toml
        let result = find_project_mcp_in(&child_dir);
        assert!(
            result.is_none(),
            "Should not find config in parent directory"
        );

        // But looking from parent/ should find it
        let result = find_project_mcp_in(temp.path());
        assert!(result.is_some(), "Should find config in current directory");
    }

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

        // Create .rkat/mcp.toml in the directory
        let meerkat_dir = temp.path().join(".rkat");
        tokio::fs::create_dir_all(&meerkat_dir).await.unwrap();
        let config_path = meerkat_dir.join("mcp.toml");
        tokio::fs::write(
            &config_path,
            r#"
[[servers]]
name = "local-server"
command = "echo"
"#,
        )
        .await
        .unwrap();

        let result = find_project_mcp_in(temp.path());
        assert_eq!(result, Some(config_path));
    }

    #[test]
    fn test_http_transport_defaults_to_streamable() {
        let toml = r#"
[[servers]]
name = "remote"
url = "https://mcp.example.com/mcp"
"#;
        let config: McpConfig = toml::from_str(toml).unwrap();
        assert_eq!(config.servers.len(), 1);
        assert_eq!(
            config.servers[0].transport_kind(),
            McpTransportKind::StreamableHttp
        );
    }

    #[test]
    fn test_http_transport_sse() {
        let toml = r#"
[[servers]]
name = "legacy"
url = "https://old.example.com/sse"
transport = "sse"
"#;
        let config: McpConfig = toml::from_str(toml).unwrap();
        assert_eq!(config.servers.len(), 1);
        assert_eq!(config.servers[0].transport_kind(), McpTransportKind::Sse);
    }

    #[test]
    fn test_rejects_conflicting_transport_fields() {
        let toml = r#"
[[servers]]
name = "invalid"
command = "cmd"
url = "https://example.com/mcp"
"#;
        let parsed: Result<McpConfig, _> = toml::from_str(toml);
        assert!(parsed.is_err(), "Config with command + url should fail");
    }

    #[tokio::test]
    async fn test_env_expansion_in_config() {
        let parsed: McpConfig = toml::from_str(
            r#"
[[servers]]
name = "remote"
url = "https://mcp.example.com/mcp"
headers = { Authorization = "Bearer ${RKAT_TEST_API_KEY}" }
"#,
        )
        .unwrap();

        let env = HashMap::from([("RKAT_TEST_API_KEY".to_string(), "secret".to_string())]);
        let config = expand_env_in_config_with(parsed, &|key| env.get(key).cloned()).unwrap();

        let server = &config.servers[0];
        match &server.transport {
            McpTransportConfig::Http(http) => {
                assert_eq!(
                    http.headers.get("Authorization"),
                    Some(&"Bearer secret".to_string())
                );
            }
            McpTransportConfig::Stdio(_) => unreachable!("Expected http transport"),
        }
    }

    #[tokio::test]
    async fn test_load_with_scopes_from_roots_precedence_and_dedup() {
        let temp = TempDir::new().unwrap();
        let context_root = temp.path().join("context");
        let user_root = temp.path().join("user");
        tokio::fs::create_dir_all(context_root.join(".rkat"))
            .await
            .unwrap();
        tokio::fs::create_dir_all(user_root.join(".rkat"))
            .await
            .unwrap();

        tokio::fs::write(
            context_root.join(".rkat/mcp.toml"),
            r#"
[[servers]]
name = "shared"
command = "context-cmd"

[[servers]]
name = "context-only"
command = "context-only-cmd"
"#,
        )
        .await
        .unwrap();

        tokio::fs::write(
            user_root.join(".rkat/mcp.toml"),
            r#"
[[servers]]
name = "shared"
command = "user-cmd"

[[servers]]
name = "user-only"
command = "user-only-cmd"
"#,
        )
        .await
        .unwrap();

        let merged = McpConfig::load_with_scopes_from_roots(Some(&context_root), Some(&user_root))
            .await
            .unwrap();
        let names: Vec<String> = merged.iter().map(|s| s.server.name.clone()).collect();
        assert_eq!(names, vec!["shared", "context-only", "user-only"]);
        assert_eq!(merged[0].scope, McpScope::Project);
    }

    #[tokio::test]
    async fn test_load_with_scopes_from_roots_none_is_empty() {
        let merged = McpConfig::load_with_scopes_from_roots(None, None)
            .await
            .unwrap();
        assert!(merged.is_empty());
    }

    #[tokio::test]
    async fn test_load_scope_from_roots_reads_unmerged_scope() {
        let temp = TempDir::new().unwrap();
        let context_root = temp.path().join("context");
        let user_root = temp.path().join("user");
        tokio::fs::create_dir_all(context_root.join(".rkat"))
            .await
            .unwrap();
        tokio::fs::create_dir_all(user_root.join(".rkat"))
            .await
            .unwrap();

        tokio::fs::write(
            context_root.join(".rkat/mcp.toml"),
            r#"
[[servers]]
name = "shared"
command = "context-cmd"
"#,
        )
        .await
        .unwrap();
        tokio::fs::write(
            user_root.join(".rkat/mcp.toml"),
            r#"
[[servers]]
name = "shared"
command = "user-cmd"
"#,
        )
        .await
        .unwrap();

        let user =
            McpConfig::load_scope_from_roots(McpScope::User, Some(&context_root), Some(&user_root))
                .await
                .unwrap();
        assert_eq!(user.servers[0].name, "shared");
        let command = match &user.servers[0].transport {
            McpTransportConfig::Stdio(stdio) => Some(stdio.command.as_str()),
            McpTransportConfig::Http(_) => None,
        };
        assert_eq!(command, Some("user-cmd"));
    }

    #[tokio::test]
    async fn test_find_server_scopes_from_roots_never_reads_ambient_paths() {
        let temp = TempDir::new().unwrap();
        let context_root = temp.path().join("context");
        let user_root = temp.path().join("user");
        tokio::fs::create_dir_all(context_root.join(".rkat"))
            .await
            .unwrap();
        tokio::fs::create_dir_all(user_root.join(".rkat"))
            .await
            .unwrap();
        let shared = r#"
[[servers]]
name = "shared"
command = "echo"
"#;
        tokio::fs::write(context_root.join(".rkat/mcp.toml"), shared)
            .await
            .unwrap();
        tokio::fs::write(user_root.join(".rkat/mcp.toml"), shared)
            .await
            .unwrap();

        let scopes = McpConfig::find_server_scopes_from_roots(
            "shared",
            Some(&context_root),
            Some(&user_root),
        )
        .await
        .unwrap();
        assert_eq!(scopes, vec![McpScope::Project, McpScope::User]);
    }

    #[test]
    fn test_mutation_authority_resolves_each_explicit_convention_root() {
        let context_root = PathBuf::from("/explicit/context");
        let user_root = PathBuf::from("/explicit/user");
        let project = McpConfigMutationAuthority::for_scope(
            McpScope::Project,
            Some(context_root.clone()),
            Some(user_root.clone()),
        );
        let user = McpConfigMutationAuthority::for_scope(
            McpScope::User,
            Some(context_root.clone()),
            Some(user_root.clone()),
        );

        assert_eq!(
            project.resolved_path().unwrap(),
            context_root.join(".rkat/mcp.toml")
        );
        assert_eq!(
            user.resolved_path().unwrap(),
            user_root.join(".rkat/mcp.toml")
        );
    }

    #[tokio::test]
    async fn test_persist_add_uses_project_authority_and_rolls_back_new_file() {
        let temp = TempDir::new().unwrap();
        let authority = McpConfigMutationAuthority::project(Some(temp.path().to_path_buf()), None);
        let server = McpServerConfig::stdio("persisted", "echo", vec!["ok".into()], HashMap::new());

        let rollback = McpConfig::persist_add_with_rollback(&authority, server)
            .await
            .unwrap();
        let path = temp.path().join(".rkat/mcp.toml");
        let config = McpConfig::load_from_paths(None, Some(&path)).await.unwrap();
        assert_eq!(config.servers.len(), 1);
        assert_eq!(config.servers[0].name, "persisted");

        rollback.rollback().await.unwrap();
        assert!(
            !path.exists(),
            "rollback should remove a newly-created config"
        );
    }

    #[tokio::test]
    async fn test_persist_add_preserves_comments_and_forward_compatible_keys() {
        let temp = TempDir::new().unwrap();
        tokio::fs::create_dir_all(temp.path().join(".rkat"))
            .await
            .unwrap();
        let path = temp.path().join(".rkat/mcp.toml");
        let original = r#"# operator-owned heading
future_config = "leave-me"

[[servers]]
# server note
name = "existing"
command = "existing-cmd"
future_server_key = "leave-this-too"
"#;
        tokio::fs::write(&path, original).await.unwrap();

        let authority = McpConfigMutationAuthority::project(Some(temp.path().to_path_buf()), None);
        assert!(
            McpConfig::server_exists_from_roots(
                "existing",
                McpScope::Project,
                Some(temp.path()),
                None,
            )
            .await
            .unwrap(),
            "scope discovery must tolerate forward-compatible document fields"
        );
        let server = McpServerConfig::stdio("added", "echo", vec!["ok".into()], HashMap::new());
        McpConfig::persist_add_with_rollback(&authority, server)
            .await
            .unwrap();

        let persisted = tokio::fs::read_to_string(&path).await.unwrap();
        assert!(persisted.contains("# operator-owned heading"));
        assert!(persisted.contains("future_config = \"leave-me\""));
        assert!(persisted.contains("# server note"));
        assert!(persisted.contains("future_server_key = \"leave-this-too\""));
        assert!(persisted.contains("name = \"added\""));
    }

    #[tokio::test]
    async fn test_persist_add_serializes_sse_headers_and_timeout() {
        let temp = TempDir::new().unwrap();
        let authority = McpConfigMutationAuthority::project(Some(temp.path().to_path_buf()), None);
        let mut headers = HashMap::new();
        headers.insert("Authorization".to_string(), "Bearer token".to_string());
        let mut server = McpServerConfig::sse("remote", "https://example.test/sse", headers);
        server.connect_timeout_secs = Some(42);

        McpConfig::persist_add_with_rollback(&authority, server.clone())
            .await
            .unwrap();

        let path = temp.path().join(".rkat/mcp.toml");
        let config = McpConfig::load_from_paths(None, Some(&path)).await.unwrap();
        assert_eq!(config.servers, vec![server]);
        let persisted = tokio::fs::read_to_string(path).await.unwrap();
        assert!(persisted.contains("transport = \"sse\""));
        assert!(persisted.contains("connect_timeout_secs = 42"));
    }

    #[tokio::test]
    async fn test_concurrent_distinct_adds_both_survive() {
        let temp = TempDir::new().unwrap();
        let authority = McpConfigMutationAuthority::project(Some(temp.path().to_path_buf()), None);
        let first_authority = authority.clone();
        let second_authority = authority.clone();

        let (first, second) = tokio::join!(
            McpConfig::persist_add_with_rollback(
                &first_authority,
                McpServerConfig::stdio("first", "echo", Vec::new(), HashMap::new()),
            ),
            McpConfig::persist_add_with_rollback(
                &second_authority,
                McpServerConfig::stdio("second", "echo", Vec::new(), HashMap::new()),
            ),
        );
        first.unwrap();
        second.unwrap();

        let path = temp.path().join(".rkat/mcp.toml");
        let mut names = McpConfig::load_from_paths(None, Some(&path))
            .await
            .unwrap()
            .servers
            .into_iter()
            .map(|server| server.name)
            .collect::<Vec<_>>();
        names.sort_unstable();
        assert_eq!(names, vec!["first", "second"]);
    }

    #[tokio::test]
    async fn test_stale_rollback_preserves_intervening_add() {
        let temp = TempDir::new().unwrap();
        let authority = McpConfigMutationAuthority::project(Some(temp.path().to_path_buf()), None);
        let stale_rollback = McpConfig::persist_add_with_rollback(
            &authority,
            McpServerConfig::stdio("first", "echo", Vec::new(), HashMap::new()),
        )
        .await
        .unwrap();
        McpConfig::persist_add_with_rollback(
            &authority,
            McpServerConfig::stdio("later", "echo", Vec::new(), HashMap::new()),
        )
        .await
        .unwrap();

        let error = stale_rollback.rollback().await.unwrap_err();
        assert!(matches!(error, McpConfigError::RollbackConflict { .. }));

        let path = temp.path().join(".rkat/mcp.toml");
        let mut names = McpConfig::load_from_paths(None, Some(&path))
            .await
            .unwrap()
            .servers
            .into_iter()
            .map(|server| server.name)
            .collect::<Vec<_>>();
        names.sort_unstable();
        assert_eq!(names, vec!["first", "later"]);
    }

    #[tokio::test]
    async fn test_revision_fence_rejects_byte_identical_aba_rollback() {
        let temp = TempDir::new().unwrap();
        let authority = McpConfigMutationAuthority::project(Some(temp.path().to_path_buf()), None);
        let server = McpServerConfig::stdio("same", "echo", Vec::new(), HashMap::new());

        let stale_rollback = McpConfig::persist_add_with_rollback(&authority, server.clone())
            .await
            .unwrap();
        let originally_committed = stale_rollback.committed_bytes.clone();

        McpConfig::persist_remove_with_rollback(&authority, "same")
            .await
            .unwrap();
        McpConfig::persist_add_with_rollback(&authority, server)
            .await
            .unwrap();

        let path = temp.path().join(".rkat/mcp.toml");
        assert_eq!(
            tokio::fs::read(&path).await.unwrap(),
            originally_committed,
            "exercise an exact byte-level ABA, not merely a semantic rewrite"
        );

        let error = stale_rollback.rollback().await.unwrap_err();
        assert!(matches!(error, McpConfigError::RollbackConflict { .. }));
        let config = McpConfig::load_from_paths(None, Some(&path)).await.unwrap();
        assert_eq!(config.servers.len(), 1);
        assert_eq!(config.servers[0].name, "same");
    }

    #[tokio::test]
    async fn test_persist_remove_rolls_back_previous_bytes() {
        let temp = TempDir::new().unwrap();
        tokio::fs::create_dir_all(temp.path().join(".rkat"))
            .await
            .unwrap();
        let path = temp.path().join(".rkat/mcp.toml");
        let original = r#"
# preserve this file-level comment
future_config = "leave-me"

[[servers]]
name = "keep"
command = "keep-cmd"
future_server_key = "leave-this-too"

[[servers]]
name = "remove"
command = "remove-cmd"
"#;
        tokio::fs::write(&path, original).await.unwrap();

        let authority = McpConfigMutationAuthority::project(Some(temp.path().to_path_buf()), None);
        let rollback = McpConfig::persist_remove_with_rollback(&authority, "remove")
            .await
            .unwrap();
        let persisted = tokio::fs::read_to_string(&path).await.unwrap();
        assert!(persisted.contains("# preserve this file-level comment"));
        assert!(persisted.contains("future_config = \"leave-me\""));
        assert!(persisted.contains("future_server_key = \"leave-this-too\""));
        assert!(!persisted.contains("name = \"remove\""));

        rollback.rollback().await.unwrap();
        let restored = tokio::fs::read_to_string(&path).await.unwrap();
        assert_eq!(restored, original);
    }
}