agent-loadout 1.0.0

Loadout CLI: manage MCP servers, skills and secret references for AI coding clients
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
//! `loadout server ls|show|add|edit|enable|disable|rm|update|checkout`
//! (SPEC 14). Every change is one store commit; `rm` with several ids is
//! one commit too. In instant mode (the default, SPEC 8.7) the change is
//! applied in that same commit. `enable` and `disable` with `--project`
//! edit the project's manifest instead (one commit that mirrors, trusts
//! and applies it, as the app's project pills do).
//!
//! `add --from` drafts servers from a git repository or a local folder
//! (#5): nothing runs while drafting; saving goes through the source trust
//! prompt (or `--trust-source`) and the built-in scan (`--allow-dangerous`).

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use agent_loadout_core::apply::import::unrelease_clients;
use agent_loadout_core::apply::render::{DesiredState, Detected};
use agent_loadout_core::apply::{ApplyReport, Touched};
use agent_loadout_core::catalog;
use agent_loadout_core::layering::project_servers::{ServerEdit, edit_server};
use agent_loadout_core::layering::projects::load_project;
use agent_loadout_core::layering::{
    EntryBody, EntryLayer, LOCAL_FILE, ManifestFile, Project, SHARED_FILE, TrustStore,
    project_entries, trust_required,
};
use agent_loadout_core::mcp_source::{self, Draft, Pick, ResolveRequest, Resolved};
use agent_loadout_core::model::clients::{ClientSelection, KNOWN_CLIENTS, toggle_clients};
use agent_loadout_core::model::ids::{self, IdKind};
use agent_loadout_core::model::project::ProjectServer;
use agent_loadout_core::model::server::{Enable, Meta, Server, ServerSource, Transport};
use agent_loadout_core::remote::git::{IDLE_TIMEOUT, SystemRunner};
use agent_loadout_core::scan::ScanReport;
use agent_loadout_core::skills::install::{Decisions, FileChange, Source, UpdateStatus};
use agent_loadout_core::skills::{LinkKind, SkillsEnv};
use agent_loadout_core::sources::SourceRef;
use agent_loadout_core::store::{
    CommitId, Machine, Operation, ServerEntry, Store, StoreRead, server_path,
};
use agent_loadout_core::{CoreError, ErrorCode};
use clap::builder::PossibleValuesParser;
use clap::{ArgGroup, Args, Subcommand, ValueEnum};
use serde_json::{Value, json};

use super::skills::{print_scan, scan_json};
use super::source::{Answer, Answers, TrustSourceArg, cancelled};
use super::{
    Context, EXIT_SCAN_BLOCKED, JSON_SCHEMA, apply_exit_code, error_json, instant_apply, path_json,
    print_json, print_report, report_json, report_warnings,
};

static RUNNER: SystemRunner = SystemRunner {
    idle_timeout: IDLE_TIMEOUT,
};

#[derive(Debug, Args)]
pub struct ServerArgs {
    #[command(subcommand)]
    command: ServerCommand,
}

#[derive(Debug, Subcommand)]
enum ServerCommand {
    /// List servers.
    Ls,
    /// Print a server definition.
    Show {
        /// Server id.
        id: String,
    },
    /// Add a server, or (--from) draft servers from a git repository or
    /// a local folder.
    Add(Box<AddArgs>),
    /// Change fields of a server: what is given replaces what the file
    /// has; everything else (comments and other keys too) stays.
    Edit(Box<EditArgs>),
    /// Enable a server for clients: at user scope, or with --project in
    /// the project's private manifest (--shared: its shared one).
    Enable(SwitchArgs),
    /// Disable a server for clients: at user scope, or with --project in
    /// the project's private manifest (--shared: its shared one).
    Disable(SwitchArgs),
    /// Remove servers; several ids make one commit.
    Rm {
        /// Server ids.
        #[arg(required = true)]
        ids: Vec<String>,
    },
    /// Update servers added with --from (all, or ID) to what their source
    /// gives now; --check only reports.
    Update {
        id: Option<String>,
        /// Report available updates; change nothing.
        #[arg(long)]
        check: bool,
        /// Answer the source trust prompt up front (see `server add`).
        #[arg(
            long,
            value_enum,
            value_name = "ONCE|REPO|OWNER|HOST",
            num_args = 0..=1,
            default_missing_value = "once",
            conflicts_with = "check"
        )]
        trust_source: Option<TrustSourceArg>,
        /// Update even when the built-in scan finds dangerous content.
        #[arg(long, conflicts_with = "check")]
        allow_dangerous: bool,
    },
    /// Re-create or bring up to date this machine's checkout of a server
    /// added with --from that runs from its repository
    /// (`LOADOUT_HOME/servers/<ID>`), at the commit its file names. The
    /// same gates as `add --from`: source trust, then the scan.
    Checkout {
        id: String,
        /// Answer the source trust prompt up front (see `server add`).
        #[arg(
            long,
            value_enum,
            value_name = "ONCE|REPO|OWNER|HOST",
            num_args = 0..=1,
            default_missing_value = "once"
        )]
        trust_source: Option<TrustSourceArg>,
        /// Check out even when the built-in scan finds dangerous content.
        #[arg(long)]
        allow_dangerous: bool,
    },
}

#[derive(Debug, Args)]
struct AddArgs {
    /// Server id: 1 to 64 characters from a-z, 0-9, '.', '_', '-'. With
    /// --from: the id of the one draft saved [default: from its name].
    #[arg(required_unless_present = "from")]
    id: Option<String>,
    /// Endpoint of an http or sse server.
    #[arg(long)]
    url: Option<String>,
    /// Transport [default: stdio, or http with --url].
    #[arg(long, value_enum)]
    transport: Option<TransportArg>,
    /// Environment variable of a stdio server; the value may be a reference
    /// such as ${secret:ALIAS} and is never a secret itself.
    #[arg(long = "env", value_name = "KEY=VALUE", value_parser = parse_pair)]
    env: Vec<(String, String)>,
    /// HTTP header of an http or sse server; the value may hold references.
    #[arg(long = "header", value_name = "NAME=VALUE", value_parser = parse_pair)]
    headers: Vec<(String, String)>,
    /// Working directory of a stdio server.
    #[arg(long)]
    cwd: Option<String>,
    #[arg(long)]
    display_name: Option<String>,
    #[arg(long)]
    description: Option<String>,
    /// Tag (repeatable).
    #[arg(long = "tag", value_name = "TAG")]
    tags: Vec<String>,
    /// Enable at system scope for this client (repeatable).
    #[arg(
        long = "client",
        value_name = "CLIENT",
        conflicts_with = "all_detected"
    )]
    clients: Vec<String>,
    /// Enable at system scope for every detected client.
    #[arg(long)]
    all_detected: bool,
    /// Command and arguments of a stdio server, after `--`.
    #[arg(last = true, value_name = "COMMAND")]
    command: Vec<String>,
    /// Draft servers from a git repository (https, ssh, file://, a bare
    /// repository) or a local folder: server.json, an MCPB manifest.json,
    /// committed client configs, or the repository as a package. Or from
    /// a catalog entry: catalog:<SOURCE>/<ID> (`loadout catalog search`).
    #[arg(
        long,
        value_name = "GIT-URL|PATH|catalog:SOURCE/ID",
        conflicts_with_all = ["url", "transport", "env", "headers", "cwd", "command"]
    )]
    from: Option<String>,
    /// Folder inside the git repository.
    #[arg(long, requires = "from")]
    path: Option<String>,
    /// Branch, tag or commit of the git repository; for a registry
    /// catalog entry, the version (pins it: updates do not follow).
    #[arg(long = "ref", value_name = "REF", requires = "from")]
    git_ref: Option<String>,
    /// The draft to save, by key or id (repeatable) [default: the only
    /// draft].
    #[arg(long = "pick", value_name = "KEY|ID", requires = "from")]
    picks: Vec<String>,
    /// Save every draft.
    #[arg(long, requires = "from", conflicts_with = "picks")]
    all: bool,
    /// List the drafts, their inputs and scan findings; save nothing (the
    /// clone is removed).
    #[arg(long, requires = "from")]
    dry_run: bool,
    /// Answer the source trust prompt up front: once (this save only), or
    /// always for the repo, its owner or its host. Only for a source you
    /// trust: a server drafted from it runs its commands. --yes never
    /// answers the trust prompt.
    #[arg(
        long,
        value_enum,
        value_name = "ONCE|REPO|OWNER|HOST",
        num_args = 0..=1,
        default_missing_value = "once",
        requires = "from"
    )]
    trust_source: Option<TrustSourceArg>,
    /// Save even when the built-in scan finds dangerous content (review
    /// the findings first, with --dry-run).
    #[arg(long, requires = "from")]
    allow_dangerous: bool,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum TransportArg {
    Stdio,
    Http,
    Sse,
}

impl From<TransportArg> for Transport {
    fn from(arg: TransportArg) -> Self {
        match arg {
            TransportArg::Stdio => Transport::Stdio,
            TransportArg::Http => Transport::Http,
            TransportArg::Sse => Transport::Sse,
        }
    }
}

#[derive(Debug, Args)]
#[command(
    group(ArgGroup::new("change").required(true).multiple(true)),
    override_usage = "loadout server edit [OPTIONS] <ID> [-- <COMMAND>...]"
)]
struct EditArgs {
    /// Server id.
    id: String,
    /// Endpoint of an http or sse server.
    #[arg(long, group = "change")]
    url: Option<String>,
    /// Transport [default: as it is; http when --url is given to a stdio
    /// server, stdio when a command is given to an http or sse server].
    /// Switching drops the other transport's fields.
    #[arg(long, value_enum, group = "change")]
    transport: Option<TransportArg>,
    /// Set an environment variable of a stdio server (repeatable); the
    /// value may be a reference such as ${secret:ALIAS} and is never a
    /// secret itself.
    #[arg(long = "env", value_name = "KEY=VALUE", value_parser = parse_pair, group = "change")]
    env: Vec<(String, String)>,
    /// Set an HTTP header of an http or sse server (repeatable); the value
    /// may hold references.
    #[arg(
        long = "header",
        value_name = "NAME=VALUE",
        value_parser = parse_pair,
        group = "change"
    )]
    headers: Vec<(String, String)>,
    /// Working directory of a stdio server.
    #[arg(long, group = "change", conflicts_with = "clear_cwd")]
    cwd: Option<String>,
    /// Name shown instead of the id; empty removes it.
    #[arg(long, group = "change")]
    display_name: Option<String>,
    /// One-line description; empty removes it.
    #[arg(long, group = "change")]
    description: Option<String>,
    /// Tag (repeatable); replaces the server's tags.
    #[arg(long = "tag", value_name = "TAG", group = "change")]
    tags: Vec<String>,
    /// Remove an environment variable (repeatable).
    #[arg(long = "unset-env", value_name = "KEY", group = "change")]
    unset_env: Vec<String>,
    /// Remove an HTTP header (repeatable).
    #[arg(long = "unset-header", value_name = "NAME", group = "change")]
    unset_headers: Vec<String>,
    /// Remove the working directory.
    #[arg(long, group = "change")]
    clear_cwd: bool,
    /// New command and arguments of a stdio server, after `--`.
    #[arg(last = true, value_name = "COMMAND", group = "change")]
    command: Vec<String>,
}

#[derive(Debug, Args)]
struct SwitchArgs {
    /// Server id (with --project: the server's name in the manifests).
    id: String,
    /// Client id (repeatable).
    #[arg(
        long = "client",
        value_name = "CLIENT",
        required = true,
        value_parser = client_ids()
    )]
    clients: Vec<String>,
    /// A folder in a project: edit the project's manifest instead of the
    /// store server (the project must be trusted as it is).
    #[arg(long, value_name = "PATH")]
    project: Option<PathBuf>,
    /// With --project: write the shared `.loadout/project.toml` instead of
    /// the private `.loadout/project.local.toml`.
    #[arg(long, requires = "project")]
    shared: bool,
}

/// `--client` values: the known client ids.
fn client_ids() -> PossibleValuesParser {
    PossibleValuesParser::new(KNOWN_CLIENTS.iter().map(|client| client.id))
}

fn parse_pair(text: &str) -> Result<(String, String), String> {
    match text.split_once('=') {
        Some((key, value)) if !key.is_empty() => Ok((key.to_owned(), value.to_owned())),
        _ => Err(format!("expected KEY=VALUE, got {text:?}")),
    }
}

/// `add`, `edit`, `enable`, `disable` and `rm` exit like `loadout apply`
/// when their instant apply left entries blocked (5), unresolved (4) or a
/// file failed (1); the store edit itself is committed either way.
pub fn run(ctx: &Context, args: &ServerArgs) -> Result<u8, CoreError> {
    // Temporary clones a crash or an interrupted prompt left behind.
    mcp_source::sweep_temp_clones(&sx(ctx), std::time::Duration::from_secs(60 * 60));
    match &args.command {
        ServerCommand::Ls => list(ctx).map(|()| 0),
        ServerCommand::Show { id } => show(ctx, id).map(|()| 0),
        ServerCommand::Add(args) if args.from.is_some() => add_from(ctx, args),
        ServerCommand::Add(args) => add(ctx, args),
        ServerCommand::Edit(args) => edit(ctx, args),
        ServerCommand::Enable(args) => switch(ctx, args, true),
        ServerCommand::Disable(args) => switch(ctx, args, false),
        ServerCommand::Rm { ids } => remove(ctx, ids),
        ServerCommand::Update {
            id,
            check,
            trust_source,
            allow_dangerous,
        } => update(ctx, id.as_deref(), *check, *trust_source, *allow_dangerous),
        ServerCommand::Checkout {
            id,
            trust_source,
            allow_dangerous,
        } => checkout(ctx, id, *trust_source, *allow_dangerous),
    }
}

fn sx(ctx: &Context) -> SkillsEnv<'_> {
    SkillsEnv {
        env: &ctx.env,
        fs: ctx.fs(),
        home: &ctx.home,
        registry: ctx.apply_env().registry,
        runner: &RUNNER,
        link_kind: LinkKind::Junction,
    }
}

fn list(ctx: &Context) -> Result<(), CoreError> {
    let store = ctx.open_store()?;
    let entries = match &store {
        Some(store) => store.servers()?,
        None => Vec::new(),
    };
    if ctx.json {
        print_json(&json!({
            "schema": JSON_SCHEMA,
            "servers": entries.iter().map(entry_json).collect::<Vec<_>>(),
        }));
        return Ok(());
    }
    if entries.is_empty() {
        println!("No servers.");
        if store.is_none() {
            println!("{}", super::NO_STORE_HINT);
        }
        return Ok(());
    }
    let rows: Vec<[String; 4]> = entries.iter().map(entry_row).collect();
    let header = [
        "ID".to_owned(),
        "TRANSPORT".to_owned(),
        "TARGET".to_owned(),
        "CLIENTS".to_owned(),
    ];
    let widths: Vec<usize> = (0..3)
        .map(|column| {
            rows.iter()
                .chain([&header])
                .map(|row| row[column].chars().count())
                .max()
                .unwrap_or(0)
        })
        .collect();
    for row in [&header].into_iter().chain(&rows) {
        println!(
            "{:<w0$}  {:<w1$}  {:<w2$}  {}",
            row[0],
            row[1],
            row[2],
            row[3],
            w0 = widths[0],
            w1 = widths[1],
            w2 = widths[2],
        );
    }
    Ok(())
}

fn entry_row(entry: &ServerEntry) -> [String; 4] {
    match &entry.document {
        Ok(doc) => {
            let server = doc.value();
            let body = &server.body;
            let target = match (&body.url, &body.command) {
                (Some(url), _) => url.clone(),
                (None, Some(command)) => std::iter::once(command)
                    .chain(body.args.iter().flatten())
                    .cloned()
                    .collect::<Vec<_>>()
                    .join(" "),
                (None, None) => String::new(),
            };
            let clients = match server.enable.as_ref().and_then(|e| e.clients.as_ref()) {
                Some(ClientSelection::AllDetected) => "all-detected".to_owned(),
                Some(ClientSelection::List(ids)) => ids.join(", "),
                None => String::new(),
            };
            [
                entry.id.clone(),
                body.transport.map_or("", Transport::as_str).to_owned(),
                target,
                clients,
            ]
        }
        Err(err) => [
            entry.id.clone(),
            "invalid".to_owned(),
            format!("error[{}]: {}", err.code(), err.message()),
            String::new(),
        ],
    }
}

fn entry_json(entry: &ServerEntry) -> Value {
    match &entry.document {
        Ok(doc) => {
            let server = doc.value();
            let body = &server.body;
            let clients = match server.enable.as_ref().and_then(|e| e.clients.as_ref()) {
                Some(selection) => serde_json::to_value(selection).unwrap_or(Value::Null),
                None => Value::Null,
            };
            json!({
                "id": entry.id,
                "valid": true,
                "display_name": body.display_name,
                "transport": body.transport.map(Transport::as_str),
                "command": body.command,
                "args": body.args,
                "url": body.url,
                "clients": clients,
            })
        }
        Err(err) => json!({
            "id": entry.id,
            "valid": false,
            "error": error_json(err),
        }),
    }
}

fn show(ctx: &Context, id: &str) -> Result<(), CoreError> {
    ids::check(IdKind::Server, id)?;
    let store = ctx.open_store()?.ok_or_else(|| not_found(id))?;
    if ctx.json {
        let doc = store.server(id)?.ok_or_else(|| not_found(id))?;
        let server = serde_json::to_value(doc.value()).map_err(|err| {
            CoreError::new(
                ErrorCode::InvalidValue,
                format!("cannot render JSON: {err}"),
            )
        })?;
        print_json(&json!({ "schema": JSON_SCHEMA, "server": server }));
    } else {
        let relative = agent_loadout_core::store::server_path(id)?;
        let text = store
            .read_to_string(&relative)?
            .ok_or_else(|| not_found(id))?;
        print!("{text}");
    }
    Ok(())
}

fn add(ctx: &Context, args: &AddArgs) -> Result<u8, CoreError> {
    let id = args.id.clone().unwrap_or_default();
    let server = build_server(&id, args);
    // Checked before the store is opened, so a bad definition creates nothing.
    let diagnostics = server.validate(Some(&id));
    if let Some(err) = diagnostics.first_error(None) {
        return Err(err);
    }
    report_warnings(diagnostics.warnings());

    let store = ctx.open_store_for_change()?;
    let operation =
        Operation::new("server.add", format!("server: add {id}")).entity(format!("server/{id}"));
    let ax = ctx.apply_env();
    let committed = store.transaction(operation, |tx| {
        tx.add_server(server)?;
        instant_apply(tx, &ax, &Touched::Servers(vec![id.clone()]))
    })?;
    let report = committed.value;
    let commit = committed.commit.as_ref().map(|commit| commit.to_string());
    if ctx.json {
        print_json(&json!({
            "schema": JSON_SCHEMA,
            "server": id,
            "commit": commit,
            "apply": report.as_ref().map(|r| report_json(r, committed.commit.as_ref())),
        }));
    } else {
        println!(
            "Added server {id} (commit {}).",
            committed.commit.as_ref().map_or("none", |c| c.short())
        );
        if let Some(report) = &report {
            print_report(report, committed.commit.as_ref());
        }
    }
    Ok(report.as_ref().map_or(0, apply_exit_code))
}

fn build_server(id: &str, args: &AddArgs) -> Server {
    let transport = match (args.transport, &args.url) {
        (Some(TransportArg::Stdio), _) | (None, None) => Transport::Stdio,
        (Some(TransportArg::Http), _) | (None, Some(_)) => Transport::Http,
        (Some(TransportArg::Sse), _) => Transport::Sse,
    };
    let map = |pairs: &[(String, String)]| {
        (!pairs.is_empty()).then(|| pairs.iter().cloned().collect::<BTreeMap<_, _>>())
    };
    let mut server = Server::new(id.to_owned());
    let body = &mut server.body;
    body.transport = Some(transport);
    body.command = args.command.first().cloned();
    body.args = (args.command.len() > 1).then(|| args.command[1..].to_vec());
    body.url = args.url.clone();
    body.cwd = args.cwd.clone();
    body.env = map(&args.env);
    body.headers = map(&args.headers);
    body.display_name = args.display_name.clone();
    body.description = args.description.clone();
    body.tags = (!args.tags.is_empty()).then(|| args.tags.clone());
    body.meta = Some(Meta {
        origin: Some("manual".to_owned()),
        ..Meta::default()
    });
    server.enable = clients(args).map(|clients| Enable {
        clients: Some(clients),
        ..Enable::default()
    });
    server
}

/// The `--client`/`--all-detected` choice.
fn clients(args: &AddArgs) -> Option<ClientSelection> {
    if args.all_detected {
        Some(ClientSelection::AllDetected)
    } else {
        (!args.clients.is_empty()).then(|| ClientSelection::List(args.clients.clone()))
    }
}

fn remove(ctx: &Context, ids: &[String]) -> Result<u8, CoreError> {
    let mut unique: Vec<String> = Vec::new();
    for id in ids {
        ids::check(IdKind::Server, id)?;
        if !unique.contains(id) {
            unique.push(id.clone());
        }
    }
    let store = ctx.open_store()?.ok_or_else(|| not_found(&unique[0]))?;
    let summary = match unique.as_slice() {
        [one] => format!("server: remove {one}"),
        many => format!(
            "server: remove {} servers ({})",
            many.len(),
            many.join(", ")
        ),
    };
    let operation = unique
        .iter()
        .fold(Operation::new("server.remove", summary), |operation, id| {
            operation.entity(format!("server/{id}"))
        });
    let ax = ctx.apply_env();
    let sx = sx(ctx);
    // Machine-local checkouts of servers added with --from go with them:
    // moved aside under the store lock, deleted once the removal commits.
    let mut removal = None;
    let result = store.transaction(operation, |tx| {
        unique.iter().try_for_each(|id| tx.remove_server(id))?;
        removal = Some(mcp_source::CheckoutRemoval::begin(&sx, &unique)?);
        instant_apply(tx, &ax, &Touched::Servers(unique.clone()))
    });
    if let Some(removal) = removal {
        removal.finish(sx.fs, result.is_ok());
    }
    let committed = result?;
    let report = committed.value;
    if ctx.json {
        print_json(&json!({
            "schema": JSON_SCHEMA,
            "servers": unique,
            "commit": committed.commit.as_ref().map(|commit| commit.to_string()),
            "apply": report.as_ref().map(|r| report_json(r, committed.commit.as_ref())),
        }));
    } else {
        println!(
            "Removed server {} (commit {}).",
            unique.join(", "),
            committed.commit.as_ref().map_or("none", |c| c.short())
        );
        if let Some(report) = &report {
            print_report(report, committed.commit.as_ref());
        }
    }
    Ok(report.as_ref().map_or(0, apply_exit_code))
}

/// `loadout server edit`: the fields given replace the file's, everything
/// else stays (the file is edited in place, as the app's Form save does).
fn edit(ctx: &Context, args: &EditArgs) -> Result<u8, CoreError> {
    let id = args.id.as_str();
    ids::check(IdKind::Server, id)?;
    let store = ctx.open_store()?.ok_or_else(|| not_found(id))?;
    let mut doc = store.server(id)?.ok_or_else(|| not_found(id))?;
    apply_edit(doc.value_mut(), args)?;
    let diagnostics = doc.value().validate(Some(id));
    if let Some(err) = diagnostics.first_error(None) {
        return Err(err);
    }
    report_warnings(diagnostics.warnings());
    let text = doc.to_text()?;
    drop(store);

    let store = ctx.open_store_for_change()?;
    let operation = Operation::new("server.update", format!("server: update {id}"))
        .entity(format!("server/{id}"));
    let ax = ctx.apply_env();
    let committed = store.transaction(operation, |tx| {
        tx.write(&server_path(id)?, text)?;
        instant_apply(tx, &ax, &Touched::Servers(vec![id.to_owned()]))
    })?;
    Ok(print_change(
        ctx,
        &format!("Updated server {id}"),
        json!({"schema": JSON_SCHEMA, "server": id}),
        committed.commit.as_ref(),
        committed.value.as_ref(),
    ))
}

/// Writes `args` into `server`. A transport switch first drops the other
/// transport's fields (`command`, `args`, `cwd`, `env` for http and sse;
/// `url`, `headers` for stdio), as the app's Form does.
fn apply_edit(server: &mut Server, args: &EditArgs) -> Result<(), CoreError> {
    let both = |set: &[(String, String)], unset: &[String], what: &str| match unset
        .iter()
        .find(|key| set.iter().any(|(name, _)| name == *key))
    {
        Some(key) => Err(CoreError::new(
            ErrorCode::InvalidValue,
            format!("{what} {key:?} is both set and unset"),
        )),
        None => Ok(()),
    };
    both(&args.env, &args.unset_env, "environment variable")?;
    both(&args.headers, &args.unset_headers, "header")?;

    let id = server.id.clone();
    let body = &mut server.body;
    let remote =
        |transport: Option<Transport>| matches!(transport, Some(Transport::Http | Transport::Sse));
    let before = body.transport;
    let transport = match args.transport {
        Some(arg) => Some(arg.into()),
        None if args.url.is_some() && !remote(before) => Some(Transport::Http),
        None if !args.command.is_empty() && remote(before) => Some(Transport::Stdio),
        None => before,
    };
    if transport != before {
        if remote(transport) {
            body.command = None;
            body.args = None;
            body.cwd = None;
            body.env = None;
        } else {
            body.url = None;
            body.headers = None;
        }
    }
    body.transport = transport;
    if let Some((command, rest)) = args.command.split_first() {
        body.command = Some(command.clone());
        body.args = (!rest.is_empty()).then(|| rest.to_vec());
    }
    if let Some(url) = &args.url {
        body.url = Some(url.clone());
    }
    if let Some(cwd) = &args.cwd {
        body.cwd = Some(cwd.clone());
    } else if args.clear_cwd {
        body.cwd = None;
    }
    edit_map(&mut body.env, &args.env, &args.unset_env, |key| {
        format!("server {id:?} has no environment variable {key:?}")
    })?;
    edit_map(
        &mut body.headers,
        &args.headers,
        &args.unset_headers,
        |key| format!("server {id:?} has no header {key:?}"),
    )?;
    // Trimmed, and empty text removes the key, as the app's Form does.
    let text = |value: &str| Some(value.trim().to_owned()).filter(|value| !value.is_empty());
    if let Some(name) = &args.display_name {
        body.display_name = text(name);
    }
    if let Some(description) = &args.description {
        body.description = text(description);
    }
    if !args.tags.is_empty() {
        body.tags = Some(args.tags.clone());
    }
    Ok(())
}

/// Sets the keys of `set` and removes those of `unset` (each must be
/// there: `missing` says why not); an empty map is removed.
fn edit_map(
    map: &mut Option<BTreeMap<String, String>>,
    set: &[(String, String)],
    unset: &[String],
    missing: impl Fn(&str) -> String,
) -> Result<(), CoreError> {
    if set.is_empty() && unset.is_empty() {
        return Ok(());
    }
    let mut values = map.take().unwrap_or_default();
    values.extend(set.iter().cloned());
    for key in unset {
        if values.remove(key).is_none() {
            return Err(CoreError::new(ErrorCode::NotFound, missing(key)));
        }
    }
    *map = (!values.is_empty()).then_some(values);
    Ok(())
}

/// `loadout server enable|disable`: a client turned on or off as the app's
/// pills do it, at user scope or in a project's manifest.
fn switch(ctx: &Context, args: &SwitchArgs, enabled: bool) -> Result<u8, CoreError> {
    ids::check(IdKind::Server, &args.id)?;
    match &args.project {
        Some(path) => switch_in_project(ctx, args, path, enabled),
        None => switch_user(ctx, args, enabled),
    }
}

/// `("enable", "enabled")` or `("disable", "disabled")`.
fn verbs(enabled: bool) -> (&'static str, &'static str) {
    if enabled {
        ("enable", "enabled")
    } else {
        ("disable", "disabled")
    }
}

fn selection_json(selection: Option<&ClientSelection>) -> Value {
    selection.map_or(Value::Null, |selection| {
        serde_json::to_value(selection).unwrap_or(Value::Null)
    })
}

/// The store's desired state on this machine (its overlay applied).
fn desired_state(ctx: &Context, store: &Store<'_>) -> Result<DesiredState, CoreError> {
    let machine = Machine::load(ctx.fs(), &ctx.home.state_dir())?;
    DesiredState::load(store, machine.as_ref().map(|machine| machine.id.as_str()))
}

/// The store server's `[enable] clients`. `all-detected` becomes the
/// clients it selects here (the app's selected pills); enabling a client
/// this machine released takes the release back.
fn switch_user(ctx: &Context, args: &SwitchArgs, enabled: bool) -> Result<u8, CoreError> {
    let id = args.id.as_str();
    let store = ctx.open_store()?.ok_or_else(|| not_found(id))?;
    let mut doc = store.server(id)?.ok_or_else(|| not_found(id))?;
    let desired = desired_state(ctx, &store)?;
    let current = doc
        .value()
        .enable
        .as_ref()
        .and_then(|enable| enable.clients.clone());
    let here = match &current {
        Some(ClientSelection::AllDetected) => {
            let ax = ctx.apply_env();
            let cx = ax.render_cx(store.secret_memory().clone());
            let server = desired.servers.get(id).unwrap_or(doc.value());
            Detected::default().system_clients(&cx, &desired, server)
        }
        _ => Vec::new(),
    };
    let next = toggle_clients(current.as_ref(), || here, &args.clients, enabled);
    let released: Vec<String> = args
        .clients
        .iter()
        .filter(|client| enabled && desired.released(id, client))
        .cloned()
        .collect();
    let (verb, done) = verbs(enabled);
    let targets = args.clients.join(", ");
    let mut out = json!({"schema": JSON_SCHEMA, "server": id, "project": null});
    if next.is_none() && released.is_empty() {
        out["clients"] = selection_json(current.as_ref());
        return Ok(unchanged(
            ctx,
            &format!("Server {id} is already {done} for {targets}; nothing changed."),
            out,
        ));
    }
    let selection = match next {
        Some(list) => (!list.is_empty()).then_some(ClientSelection::List(list)),
        None => current,
    };
    out["clients"] = selection_json(selection.as_ref());
    doc.value_mut().set_clients(selection);
    if let Some(err) = doc.value().validate(Some(id)).first_error(None) {
        return Err(err);
    }
    let text = doc.to_text()?;
    drop(store);

    let store = ctx.open_store_for_change()?;
    let operation = Operation::new(
        format!("server.{verb}"),
        format!("server: {verb} {id} for {targets}"),
    )
    .entity(format!("server/{id}"));
    let ax = ctx.apply_env();
    let committed = store.transaction(operation, |tx| {
        tx.write(&server_path(id)?, text)?;
        if !released.is_empty() {
            unrelease_clients(tx, id, &released)?;
        }
        instant_apply(tx, &ax, &Touched::Servers(vec![id.to_owned()]))
    })?;
    let message = format!("{} server {id} for {targets}", capitalized(done));
    Ok(print_change(
        ctx,
        &message,
        out,
        committed.commit.as_ref(),
        committed.value.as_ref(),
    ))
}

/// `[servers.<ID>] clients` in the project's private manifest (`--shared`:
/// its shared one), through the same core edit as the app's project pills.
/// The project must be trusted as it is (checked first, so an untrusted or
/// changed project always exits 7).
///
/// The start: in `project.local.toml`, that file's `clients` for the name,
/// else the merged entry's (the shared file's, else the project's
/// defaults). In `project.toml`, only what that file alone gives (its
/// table's `clients`, else its own `[defaults] clients`, else
/// `all-detected`): private choices never reach the team's file.
/// `all-detected` starts from the clients it selects here. A file without
/// the table gets one: only `clients` over the other file's entry, else an
/// override of the store server (`from`). Hide entries (`enabled = false`)
/// are refused: their `clients` say where the server is hidden.
fn switch_in_project(
    ctx: &Context,
    args: &SwitchArgs,
    path: &Path,
    enabled: bool,
) -> Result<u8, CoreError> {
    let id = args.id.as_str();
    let root = super::project::project_root(ctx, path)?;
    let fs = ctx.fs();
    let project = load_project(fs, &root)?;
    let trust = TrustStore::load(fs, &ctx.home.state_dir())?;
    if let Some(err) = trust_required(&project, &root, trust.state(&project)) {
        return Err(err);
    }
    super::require_store(ctx, "no project is known")?;
    let store = ctx.open_store_for_change()?;
    let desired = desired_state(ctx, &store)?;
    let (layer, file, file_name, layer_name) = if args.shared {
        (
            EntryLayer::Shared,
            project.shared.as_ref(),
            SHARED_FILE,
            "shared",
        )
    } else {
        (
            EntryLayer::Local,
            project.local.as_ref(),
            LOCAL_FILE,
            "local",
        )
    };
    let table = table_in(file, id);
    // The entry as the edited file sees it: `project.toml` alone (as
    // `ProjectEntry::shared` is built), or both files merged.
    let shared_only;
    let view = if args.shared {
        shared_only = Project {
            local: None,
            ..project.clone()
        };
        &shared_only
    } else {
        &project
    };
    let entries = project_entries(view, &desired.servers, &ctx.env, desired.overlay.as_ref());
    let entry = entries.iter().find(|entry| entry.name == id);
    let hidden = table.is_some_and(ProjectServer::is_suppression)
        || entry.is_some_and(|entry| matches!(entry.body, EntryBody::Suppression));
    if hidden {
        return Err(CoreError::new(
            ErrorCode::InvalidValue,
            format!(
                "server {id:?} is hidden in project {:?} (`enabled = false`); `server enable` and \
                 `server disable` do not edit hide entries: remove its `[servers.{id}]` table \
                 (or change which clients it is hidden for) in the manifest, or on the MCP page \
                 at project scope",
                project.id
            ),
        ));
    }
    let in_store = desired.servers.contains_key(id);
    if entry.is_none() {
        if args.shared && table_in(project.local.as_ref(), id).is_some() && !in_store {
            return Err(CoreError::new(
                ErrorCode::InvalidValue,
                format!(
                    "{SHARED_FILE} has no server {id:?}: only {LOCAL_FILE} defines it (move it \
                     with `loadout project share {} --server {id}`)",
                    project.id
                ),
            ));
        }
        if !in_store {
            return Err(CoreError::new(
                ErrorCode::NotFound,
                format!(
                    "project {:?} has no server {id:?}, and the store has none either",
                    project.id
                ),
            ));
        }
        if !enabled {
            let place = if args.shared {
                SHARED_FILE
            } else {
                "its manifests"
            };
            return Err(CoreError::new(
                ErrorCode::NotFound,
                format!(
                    "project {:?} has no server {id:?} in {place}: there is nothing to disable",
                    project.id
                ),
            ));
        }
    }
    let current = match (layer, table) {
        (EntryLayer::Local, Some(table)) => table
            .clients
            .clone()
            .or_else(|| entry.map(|entry| entry.clients.clone())),
        _ => entry.map(|entry| entry.clients.clone()),
    };
    let here = match (&current, entry) {
        (Some(ClientSelection::AllDetected), Some(entry)) => {
            let ax = ctx.apply_env();
            let cx = ax.render_cx(store.secret_memory().clone());
            let mut probe = entry.clone();
            probe.clients = ClientSelection::AllDetected;
            Detected::default().project_clients(&cx, &desired, &probe)
        }
        _ => Vec::new(),
    };
    let next = toggle_clients(current.as_ref(), || here, &args.clients, enabled);
    let (_, done) = verbs(enabled);
    let targets = args.clients.join(", ");
    let place = format!("in project {} ({file_name})", project.id);
    let mut out = json!({
        "schema": JSON_SCHEMA,
        "server": id,
        "project": {"id": project.id, "path": path_json(&root), "layer": layer_name},
    });
    let Some(next) = next else {
        out["clients"] = selection_json(current.as_ref());
        return Ok(unchanged(
            ctx,
            &format!("Server {id} is already {done} for {targets} {place}; nothing changed."),
            out,
        ));
    };
    let selection = ClientSelection::List(next);
    out["clients"] = selection_json(Some(&selection));
    let change = if table.is_some() {
        ServerEdit::Clients(Some(selection))
    } else {
        let server = if layer == EntryLayer::Local && entry.is_some() {
            // A private table over the shared entry: only its clients.
            ProjectServer {
                clients: Some(selection),
                ..ProjectServer::default()
            }
        } else {
            ProjectServer {
                from: Some(id.to_owned()),
                clients: Some(selection),
                ..ProjectServer::default()
            }
        };
        ServerEdit::Set {
            server: Box::new(server),
            create: true,
        }
    };
    let (report, commit) = edit_server(
        &store,
        &ctx.apply_env(),
        &root,
        &project.hash(),
        layer,
        id,
        change,
    )?;
    let message = format!("{} server {id} for {targets} {place}", capitalized(done));
    Ok(print_change(
        ctx,
        &message,
        out,
        commit.as_ref(),
        report.as_ref(),
    ))
}

/// `[servers.<id>]` of a manifest file.
fn table_in<'a>(file: Option<&'a ManifestFile>, id: &str) -> Option<&'a ProjectServer> {
    file.and_then(|file| file.manifest.servers.as_ref())
        .and_then(|servers| servers.get(id))
}

fn capitalized(word: &str) -> String {
    let mut chars = word.chars();
    chars
        .next()
        .map(|first| first.to_uppercase().chain(chars).collect())
        .unwrap_or_default()
}

/// Prints a committed change (`--json`: `out` with the commit and its
/// apply; text: `<message> (commit <short>).` and the apply report) and
/// returns its exit code, like `loadout apply` for that apply.
fn print_change(
    ctx: &Context,
    message: &str,
    mut out: Value,
    commit: Option<&CommitId>,
    report: Option<&ApplyReport>,
) -> u8 {
    if ctx.json {
        out["commit"] = json!(commit.map(CommitId::to_string));
        out["apply"] = json!(report.map(|report| report_json(report, commit)));
        print_json(&out);
    } else {
        println!(
            "{message} (commit {}).",
            commit.map_or("none", CommitId::short)
        );
        if let Some(report) = report {
            print_report(report, commit);
        }
    }
    report.map_or(0, apply_exit_code)
}

/// A change that would change nothing: no commit, exit 0.
fn unchanged(ctx: &Context, message: &str, mut out: Value) -> u8 {
    if ctx.json {
        out["commit"] = Value::Null;
        out["apply"] = Value::Null;
        print_json(&out);
    } else {
        println!("{message}");
    }
    0
}

fn not_found(id: &str) -> CoreError {
    CoreError::new(ErrorCode::NotFound, format!("server {id:?} does not exist"))
}

/// The trust answer for `source`, or the error a cancelled prompt ends
/// with.
fn trust_answer(
    ctx: &Context,
    answers: &mut Answers,
    store: &Store<'_>,
    source: &SourceRef,
    flag: Option<TrustSourceArg>,
) -> Result<Answer, CoreError> {
    let answer = answers.decide(ctx, Some(store), source, flag)?;
    if answer == Answer::Cancelled {
        return Err(cancelled(source));
    }
    Ok(answer)
}

fn decisions(answer: Answer, moved: Option<Answer>, allow_dangerous: bool) -> Decisions {
    let (trust, via) = answer.grant();
    Decisions {
        allow_dangerous,
        trust,
        moved_trust: moved.and_then(|moved| moved.grant().0),
        via,
        external: None,
    }
}

fn source_json(source: &ServerSource) -> Value {
    json!({
        "kind": source.kind.as_str(),
        "url": source.url,
        "folder": source.folder,
        "path": source.path,
        "ref": source.git_ref,
        "commit": source.commit,
        "catalog": source.catalog,
        "version": source.version,
    })
}

fn launch(server: &Server) -> String {
    let body = &server.body;
    match (&body.url, &body.command) {
        (Some(url), _) => url.clone(),
        (None, Some(command)) => std::iter::once(command)
            .chain(body.args.iter().flatten())
            .cloned()
            .collect::<Vec<_>>()
            .join(" "),
        (None, None) => String::new(),
    }
}

fn lines_json(server: &Server) -> Value {
    json!(
        mcp_source::launch_lines(server)
            .iter()
            .map(|line| json!({"os": line.os, "line": line.line}))
            .collect::<Vec<_>>()
    )
}

fn draft_json(draft: &Draft) -> Value {
    let source = draft.provenance();
    json!({
        "key": draft.key,
        "kind": draft.kind.as_str(),
        "id": draft.server.id,
        "file": source.file,
        "converter": source.converter,
        "entry": source.entry,
        "launch": launch(&draft.server),
        "launch_lines": lines_json(&draft.server),
        "runs_repo_code": draft.runs_repo_code,
        "checkout": draft.checkout,
        "pinned": draft.pinned,
        "setup": draft.setup,
        "also_in": draft.also_in,
        "inputs": draft.inputs.iter().map(|input| json!({
            "field": input.field,
            "description": input.description,
            "secret": input.secret,
            "required": input.required,
            "alias": input.alias,
            "value_dropped": input.value_dropped,
        })).collect::<Vec<_>>(),
        "scan": scan_json(&draft.scan),
    })
}

/// A setup step as a person types it: the store's `${home}` and
/// `${loadout_home}` written out (they are not shell variables).
fn setup_line(ctx: &Context, step: &str) -> String {
    mcp_source::setup_text(
        step,
        &ctx.env.home().to_string_lossy(),
        &ctx.home.path.to_string_lossy(),
    )
}

fn print_drafts(ctx: &Context, resolved: &Resolved) {
    let source = resolved.source();
    let place = source
        .url
        .as_deref()
        .or(source.folder.as_deref())
        .unwrap_or_default();
    match (&source.commit, &source.version) {
        (Some(commit), _) => println!("Source: {place} at {}", &commit[..commit.len().min(12)]),
        (None, Some(version)) => println!("Source: {place}, version {version}"),
        (None, None) => println!("Source: {place}"),
    }
    if let Some(entry) = &source.catalog {
        println!(
            "Catalog entry: {}{}",
            catalog::REF_PREFIX,
            super::catalog::plain(entry, 200)
        );
    }
    if !resolved.skipped_folders().is_empty() {
        println!(
            "Not read or scanned (dependencies and builds): {}",
            resolved.skipped_folders().join(", ")
        );
    }
    for draft in resolved.drafts() {
        println!();
        println!(
            "{}  ({}, {})",
            draft.key,
            draft.server.id,
            draft.kind.as_str()
        );
        if let Some(own) = &draft.trust_source {
            println!(
                "  Runs from {} (asked about before it is saved).",
                own.key()
            );
        }
        for line in mcp_source::launch_lines(&draft.server) {
            match &line.os {
                None => println!("  {}", line.line),
                Some(os) => println!("  on {os}: {}", line.line),
            }
        }
        if !draft.pinned {
            println!(
                "  Not pinned: the package has no version, so each start can run different code."
            );
        }
        if draft.runs_repo_code {
            println!("  Runs code from this source every time a client starts it.");
        }
        if draft.checkout {
            println!(
                "  Runs from a clone kept in {}/{}.",
                mcp_source::CHECKOUTS_DIR,
                draft.server.id
            );
        }
        for step in &draft.setup {
            println!("  Before it works, run: {}", setup_line(ctx, step));
        }
        for other in &draft.also_in {
            println!("  Also in {other}.");
        }
        for input in &draft.inputs {
            match (&input.alias, input.secret) {
                (Some(alias), true) if input.value_dropped => println!(
                    "  {}: the file held a value; it was not kept. Set secret {alias}.",
                    input.field
                ),
                (Some(alias), true) => println!("  {}: set secret {alias}.", input.field),
                (None, true) => println!(
                    "  {}: the file held a value that looks secret; it was left out.",
                    input.field
                ),
                _ => println!(
                    "  {}: read from the environment{}.",
                    input.field,
                    input
                        .description
                        .as_deref()
                        .map(|d| format!(" ({d})"))
                        .unwrap_or_default()
                ),
            }
        }
        print_scan(&draft.scan, "  ");
    }
    for skipped in resolved.skipped() {
        let entry = skipped
            .entry
            .as_deref()
            .map(|entry| format!(" {entry}"))
            .unwrap_or_default();
        eprintln!(
            "skipped {}{entry}: [{}] {}",
            skipped.file,
            skipped.error.code(),
            skipped.error.message()
        );
    }
}

fn resolved_json(resolved: &Resolved) -> Value {
    json!({
        "source": source_json(resolved.source()),
        "skipped_folders": resolved.skipped_folders(),
        "drafts": resolved.drafts().iter().map(draft_json).collect::<Vec<_>>(),
        "skipped": resolved.skipped().iter().map(|skipped| json!({
            "file": skipped.file,
            "entry": skipped.entry,
            "error": error_json(&skipped.error),
        })).collect::<Vec<_>>(),
    })
}

/// The drafts `args` picks: `--pick` by key or id, `--all`, or the only
/// draft.
fn chosen<'a>(resolved: &'a Resolved, args: &AddArgs) -> Result<Vec<&'a Draft>, CoreError> {
    let drafts = resolved.drafts();
    if drafts.is_empty() {
        return Err(CoreError::new(
            ErrorCode::NotFound,
            "the source holds no MCP server Loadout can draft",
        ));
    }
    if args.all {
        return Ok(drafts.iter().collect());
    }
    if args.picks.is_empty() {
        return match drafts {
            [one] => Ok(vec![one]),
            many => Err(CoreError::new(
                ErrorCode::InvalidValue,
                format!(
                    "the source holds {} drafts; choose with --pick <KEY|ID> or --all: {}",
                    many.len(),
                    many.iter()
                        .map(|draft| draft.key.as_str())
                        .collect::<Vec<_>>()
                        .join(", ")
                ),
            )),
        };
    }
    args.picks
        .iter()
        .map(|wanted| {
            drafts
                .iter()
                .find(|draft| draft.key == *wanted || draft.server.id == *wanted)
                .ok_or_else(|| CoreError::new(ErrorCode::NotFound, format!("no draft {wanted:?}")))
        })
        .collect()
}

/// What `--from` drafts from: a git repository or folder, or a catalog
/// entry (`catalog:<source>/<id>`, #26).
enum Drafting {
    Plain(ResolveRequest),
    Catalog(Box<catalog::McpHandoff>),
}

impl Drafting {
    /// The source asked about before anything is fetched; `None` for a
    /// registry entry (each draft is asked about what it runs).
    fn asked(&self) -> Result<Option<SourceRef>, CoreError> {
        match self {
            Drafting::Plain(request) => match &request.source {
                Source::Git { url, .. } => SourceRef::from_git_url(url).map(Some),
                Source::Local(folder) => SourceRef::from_local_path(folder).map(Some),
            },
            Drafting::Catalog(handoff) => handoff.trust_source(),
        }
    }

    fn resolve(
        &self,
        store: Option<&Store<'_>>,
        sx: &SkillsEnv<'_>,
    ) -> Result<Resolved, CoreError> {
        match self {
            Drafting::Plain(request) => mcp_source::resolve(store, sx, request),
            Drafting::Catalog(handoff) => handoff.resolve(store, sx),
        }
    }
}

/// The catalog entry `text` names, read for the review (needs online
/// catalogs); its notes (deprecated, a look-alike name) go to stderr.
fn catalog_drafting(
    ctx: &Context,
    sx: &SkillsEnv<'_>,
    text: &str,
    args: &AddArgs,
) -> Result<Drafting, CoreError> {
    if args.path.is_some() {
        return Err(super::catalog::not_here("--path"));
    }
    let store = ctx.open_store()?;
    let http = super::catalog::http(ctx);
    let cx = catalog::CatalogEnv { sx, http: &http };
    let read = store.as_ref().map(|s| s as &dyn StoreRead);
    let handoff = catalog::mcp_handoff(&cx, read, text, args.git_ref.as_deref())?;
    let entry = &handoff.entry;
    if !ctx.json {
        let plain = |text: &str| super::catalog::plain(text, 300);
        eprintln!(
            "note: {} from the catalog {}; its text is the publisher's, not Loadout's.",
            plain(&entry.reference()),
            plain(&entry.catalog)
        );
        if entry.deprecated {
            eprintln!(
                "warning: this entry is deprecated{}",
                entry
                    .status_message
                    .as_deref()
                    .map(|m| format!(": {}", plain(m)))
                    .unwrap_or_default()
            );
        }
        if let Some(warning) = &entry.warning {
            eprintln!("warning: {}", plain(warning));
        }
    }
    Ok(Drafting::Catalog(Box::new(handoff)))
}

/// `loadout server add --from`: drafts, the trust prompt, the save.
fn add_from(ctx: &Context, args: &AddArgs) -> Result<u8, CoreError> {
    let text = args.from.as_deref().unwrap_or_default();
    let sx = sx(ctx);
    let drafting = if text.trim_start().starts_with(catalog::REF_PREFIX) {
        catalog_drafting(ctx, &sx, text.trim(), args)?
    } else {
        let mut source = Source::parse(text, sx.fs);
        if let Source::Local(local) = &source {
            let absolute = std::path::absolute(local).map_err(|err| {
                CoreError::new(
                    ErrorCode::InvalidPath,
                    format!("cannot resolve path: {err}"),
                )
                .with_path(local)
            })?;
            source = Source::parse(&absolute.to_string_lossy(), sx.fs);
        }
        let mut request = ResolveRequest::new(source);
        request.path.clone_from(&args.path);
        request.git_ref.clone_from(&args.git_ref);
        Drafting::Plain(request)
    };
    let asked = drafting.asked()?;

    if args.dry_run {
        let store = ctx.open_store()?;
        let resolved = drafting.resolve(store.as_ref(), &sx)?;
        if ctx.json {
            let mut doc = resolved_json(&resolved);
            doc["schema"] = json!(JSON_SCHEMA);
            doc["saved"] = Value::Null;
            print_json(&doc);
        } else {
            print_drafts(ctx, &resolved);
        }
        return Ok(0);
    }

    let store = ctx.open_store_for_change()?;
    // Asked before anything is fetched, like `skills add`.
    let mut answers = Answers::default();
    let answer = match &asked {
        Some(asked) => Some(trust_answer(
            ctx,
            &mut answers,
            &store,
            asked,
            args.trust_source,
        )?),
        None => None,
    };
    let mut resolved = drafting.resolve(Some(&store), &sx)?;
    // The host redirected a moved repository: where the content really
    // comes from is asked about too.
    let moved = match resolved.moved_source() {
        Some(real) => {
            if !ctx.json {
                let from = asked.as_ref().map_or("", SourceRef::key);
                eprintln!("note: {from} moved to {}", real.key());
            }
            Some(trust_answer(
                ctx,
                &mut answers,
                &store,
                real,
                args.trust_source,
            )?)
        }
        None => None,
    };
    let drafts = match chosen(&resolved, args) {
        Ok(drafts) => drafts,
        Err(err) => {
            if !ctx.json {
                print_drafts(ctx, &resolved);
            }
            return Err(err);
        }
    };
    if args.id.is_some() && drafts.len() > 1 {
        return Err(CoreError::new(
            ErrorCode::InvalidValue,
            "an id names one draft; pick one with --pick",
        ));
    }
    let selection = clients(args);
    // A registry entry's drafts run from their own sources (a package, a
    // remote host): each picked one is asked about.
    let mut own_answer = None;
    let mut grants = Vec::with_capacity(drafts.len());
    for draft in &drafts {
        grants.push(match &draft.trust_source {
            Some(own) => {
                let answer = trust_answer(ctx, &mut answers, &store, own, args.trust_source)?;
                own_answer = own_answer.or(Some(answer));
                answer.grant().0
            }
            None => None,
        });
    }
    let picks: Vec<Pick> = drafts
        .iter()
        .zip(grants)
        .map(|(draft, trust)| {
            let mut server = draft.server.clone();
            if let Some(id) = &args.id {
                server.id.clone_from(id);
            }
            let body = &mut server.body;
            if args.display_name.is_some() {
                body.display_name.clone_from(&args.display_name);
            }
            if args.description.is_some() {
                body.description.clone_from(&args.description);
            }
            if !args.tags.is_empty() {
                body.tags = Some(args.tags.clone());
            }
            server.enable = selection.clone().map(|clients| Enable {
                clients: Some(clients),
                ..Enable::default()
            });
            Pick {
                key: draft.key.clone(),
                server,
                trust,
            }
        })
        .collect();
    let answer = answer.or(own_answer).unwrap_or(Answer::NotNeeded);
    let decisions = decisions(answer, moved, args.allow_dangerous);
    let saved = match mcp_source::save(
        &store,
        &sx,
        &ctx.apply_env(),
        &mut resolved,
        &picks,
        &decisions,
    ) {
        Ok(saved) => saved,
        Err(err) if err.code() == ErrorCode::ScanBlocked => {
            blocked(ctx, &err, &resolved, &picks);
            return Ok(EXIT_SCAN_BLOCKED);
        }
        Err(err) => return Err(err),
    };
    if ctx.json {
        let mut doc = resolved_json(&resolved);
        doc["schema"] = json!(JSON_SCHEMA);
        doc["saved"] = json!(saved.ids);
        doc["commit"] = json!(saved.commit.as_ref().map(ToString::to_string));
        doc["apply"] = json!(
            saved
                .apply
                .as_ref()
                .map(|report| report_json(report, saved.commit.as_ref()))
        );
        print_json(&doc);
    } else {
        print_drafts(ctx, &resolved);
        println!();
        println!(
            "Added server {} (commit {}).",
            saved.ids.join(", "),
            saved.commit.as_ref().map_or("none", |c| c.short())
        );
        if let Some(report) = &saved.apply {
            print_report(report, saved.commit.as_ref());
        }
    }
    Ok(saved.apply.as_ref().map_or(0, apply_exit_code))
}

/// A save the scan blocked: the findings, then the error.
fn blocked(ctx: &Context, err: &CoreError, resolved: &Resolved, picks: &[Pick]) {
    let scans: Vec<&ScanReport> = resolved
        .drafts()
        .iter()
        .filter(|draft| picks.iter().any(|pick| pick.key == draft.key))
        .map(|draft| &draft.scan)
        .collect();
    if ctx.json {
        print_json(&json!({
            "schema": JSON_SCHEMA,
            "error": error_json(err),
            "scans": scans.iter().map(|scan| scan_json(scan)).collect::<Vec<_>>(),
        }));
    } else {
        for scan in scans {
            print_scan(scan, "");
        }
        eprintln!("error[{}]: {err}", err.code());
        eprintln!(
            "Nothing was saved. Review the findings; to save anyway, run again with --allow-dangerous."
        );
    }
}

fn file_json(change: &FileChange) -> Value {
    json!({"path": change.path, "kind": change.kind.as_str(), "script": change.script})
}

/// Ids of the servers added with --from.
fn source_servers(store: &Store<'_>) -> Result<Vec<String>, CoreError> {
    Ok(store
        .servers()?
        .into_iter()
        .filter_map(|ServerEntry { id, document }| {
            let has_source = document.ok()?.value().body.meta.as_ref()?.source.is_some();
            has_source.then_some(id)
        })
        .collect())
}

/// `loadout server update [ID] [--check]`.
fn update(
    ctx: &Context,
    id: Option<&str>,
    check_only: bool,
    trust_source: Option<TrustSourceArg>,
    allow_dangerous: bool,
) -> Result<u8, CoreError> {
    let store = super::require_store(ctx, "server")?;
    let ids = match id {
        Some(id) => {
            ids::check(IdKind::Server, id)?;
            vec![id.to_owned()]
        }
        None => source_servers(&store)?,
    };
    let sx = sx(ctx);
    let ax = ctx.apply_env();
    let mut answers = Answers::default();
    let mut code = 0u8;
    let mut rows = Vec::new();
    for id in &ids {
        // One server's failure is its row; the others are still checked.
        let check = match mcp_source::check_update(&store, &sx, id) {
            Ok(check) => check,
            Err(err) => {
                if !ctx.json {
                    println!("{id}: failed\n  [{}] {}", err.code(), err.message());
                }
                rows.push(json!({ "id": id, "status": "failed", "error": error_json(&err) }));
                code = 1;
                continue;
            }
        };
        let mut row = json!({
            "id": id,
            "status": check.status.as_str(),
            "current": check.current,
            "latest": check.latest,
            "version": check.version,
            "changes": check.changes.iter().map(|c| json!({"field": c.field, "old": c.old, "new": c.new})).collect::<Vec<_>>(),
            "files": check.files.iter().map(file_json).collect::<Vec<_>>(),
            "launch_lines": check.server.as_ref().map(lines_json),
            "runs_repo_code": check.runs_repo_code,
            "setup": check.setup,
            "setup_again": check.setup_again,
            "checkout_out_of_date": check.checkout_out_of_date,
            "scan": check.scan.as_ref().map(scan_json),
            "error": check.error.as_ref().map(error_json),
            "commit": Value::Null,
        });
        if !ctx.json {
            print_check(ctx, &check);
        }
        if matches!(
            check.status,
            UpdateStatus::Unreachable | UpdateStatus::Blocked
        ) {
            code = 1;
        }
        if check_only || check.status != UpdateStatus::Available {
            rows.push(row);
            continue;
        }
        let answer = match &check.trust {
            Some(trust) => trust_answer(ctx, &mut answers, &store, &trust.source, trust_source)?,
            None => Answer::NotNeeded,
        };
        let moved = match &check.moved_trust {
            Some(trust) => Some(trust_answer(
                ctx,
                &mut answers,
                &store,
                &trust.source,
                trust_source,
            )?),
            None => None,
        };
        match mcp_source::update(
            &store,
            &sx,
            &ax,
            id,
            check.latest.as_deref(),
            &decisions(answer, moved, allow_dangerous),
        ) {
            Ok(updated) => {
                row["status"] = json!("updated");
                row["commit"] = json!(updated.commit.as_ref().map(ToString::to_string));
                if let Some(report) = &updated.apply {
                    code = code.max(apply_exit_code(report));
                    if !ctx.json {
                        print_report(report, updated.commit.as_ref());
                    }
                }
                if !ctx.json {
                    println!("Updated server {id}.");
                }
            }
            Err(err) if err.code() == ErrorCode::ScanBlocked => {
                row["status"] = json!("blocked");
                row["error"] = error_json(&err);
                if !ctx.json {
                    eprintln!("error[{}]: {err}", err.code());
                }
                if code == 0 {
                    code = EXIT_SCAN_BLOCKED;
                }
            }
            Err(err) => {
                row["status"] = json!("failed");
                row["error"] = error_json(&err);
                if !ctx.json {
                    eprintln!("error[{}]: {err}", err.code());
                }
                code = 1;
            }
        }
        rows.push(row);
    }
    if ctx.json {
        print_json(&json!({ "schema": JSON_SCHEMA, "servers": rows }));
    } else if ids.is_empty() {
        println!("No server was added from a git repository or folder.");
    }
    Ok(code)
}

fn print_check(ctx: &Context, check: &mcp_source::UpdateCheck) {
    let status = check.status.as_str();
    println!("{}: {status}", check.id);
    for change in &check.changes {
        println!(
            "  {}: {} -> {}",
            change.field,
            change.old.as_deref().unwrap_or("(none)"),
            change.new.as_deref().unwrap_or("(none)")
        );
    }
    for file in &check.files {
        let script = if file.script { "  (runs code)" } else { "" };
        println!("  {} {}{script}", file.kind.as_str(), file.path);
    }
    if check.setup_again {
        println!("  The update replaces the checkout: run the setup steps again afterwards:");
        for step in &check.setup {
            println!("    {}", setup_line(ctx, step));
        }
    }
    if check.checkout_out_of_date {
        println!(
            "  This machine's checkout is missing or out of date; run `loadout server checkout {}`.",
            check.id
        );
    }
    if let Some(scan) = &check.scan {
        print_scan(scan, "  ");
    }
    if let Some(err) = &check.error {
        println!("  [{}] {}", err.code(), err.message());
    }
}

/// `loadout server checkout <ID>`: fetches the repository at the commit
/// the server file names, then the trust prompt (the requested source and
/// a redirect target) and the scan gate, like `add --from`.
fn checkout(
    ctx: &Context,
    id: &str,
    trust_source: Option<TrustSourceArg>,
    allow_dangerous: bool,
) -> Result<u8, CoreError> {
    let store = super::require_store(ctx, "server")?;
    ids::check(IdKind::Server, id)?;
    let sx = sx(ctx);
    let dir: PathBuf = mcp_source::checkout_dir(&sx, id);
    let Some(prepared) = mcp_source::prepare_checkout(&store, &sx, id)? else {
        if ctx.json {
            print_json(
                &json!({ "schema": JSON_SCHEMA, "server": id, "checkout": super::path_json(&dir), "changed": false }),
            );
        } else {
            println!("The checkout of {id} is up to date.");
        }
        return Ok(0);
    };
    if !ctx.json {
        print_scan(prepared.scan(), "");
    }
    let mut answers = Answers::default();
    let answer = match prepared.trust_source() {
        Some(source) => trust_answer(ctx, &mut answers, &store, source, trust_source)?,
        None => Answer::NotNeeded,
    };
    let moved = match prepared.moved_source() {
        Some(source) => Some(trust_answer(
            ctx,
            &mut answers,
            &store,
            source,
            trust_source,
        )?),
        None => None,
    };
    let scan = prepared.scan().clone();
    let report = match mcp_source::restore_checkout(
        &store,
        &sx,
        &ctx.apply_env(),
        prepared,
        &decisions(answer, moved, allow_dangerous),
    ) {
        Ok(report) => report,
        Err(err) if err.code() == ErrorCode::ScanBlocked => {
            if ctx.json {
                print_json(&json!({
                    "schema": JSON_SCHEMA,
                    "error": error_json(&err),
                    "scans": [scan_json(&scan)],
                }));
            } else {
                eprintln!("error[{}]: {err}", err.code());
                eprintln!(
                    "Nothing was checked out. Review the findings; to go ahead anyway, run again with --allow-dangerous."
                );
            }
            return Ok(EXIT_SCAN_BLOCKED);
        }
        Err(err) => return Err(err),
    };
    if ctx.json {
        print_json(&json!({
            "schema": JSON_SCHEMA,
            "server": id,
            "checkout": super::path_json(&dir),
            "changed": true,
            "scan": scan_json(&scan),
            "apply": report.as_ref().map(|r| report_json(r, None)),
        }));
    } else {
        println!("Checkout of {id} is in {}.", dir.display());
        if let Some(report) = &report {
            print_report(report, None);
        }
    }
    Ok(report.as_ref().map_or(0, apply_exit_code))
}