Repository navigation
Expand file tree
/
Copy pathintegrate.rs
More file actions
3652 lines (3474 loc) · 137 KB
/
Copy pathintegrate.rs
File metadata and controls
3652 lines (3474 loc) · 137 KB
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
//! Host integration: global DevMap MCP registration and project assets.
//!
//! `devmap integrate <host>` (the hosts are [`Host`]'s variants):
//! - writes/refreshes marker-guarded guides and `.cursor/rules/devmap.mdc`
//! - installs the five embedded DevMap skills into the host's skill layout
//! - registers `devmap mcp` (no `--db`) in the global Cursor / Claude configs,
//! except that Claude's user-scope entry is withheld — and an owned unpinned
//! one removed — while the enabled Dev Map plugin registers the same server
//! - rewrites per-project owned entries to `--root <abs>` (belt-and-braces;
//! insufficient for multi-tab Cursor — callers must still pass `repo_path`),
//! except that Claude's project `.mcp.json` gets the same withholding as its
//! user-scope entry while the plugin is enabled
//! - with `--servers-stdin`, registers a caller's servers (DevCouncil's
//! `devcouncil`) in each host's project document via [`register_server`]
use std::collections::BTreeMap;
use std::fs;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use anyhow::{anyhow, bail, Context};
use serde_json::{json, Map, Value};
use crate::claude::{self, CURSOR_HOOKS_MARKER, MCP_SERVER_NAME};
use crate::skills;
/// A host `devmap integrate` can configure.
///
/// The variants are the single list of *names*: clap derives the positional's
/// accepted values and its `--help` from them, and [`Host::parse`] and the
/// refusal it returns are generated from the same list, so none of the three
/// can advertise a host the others do not accept.
///
/// A new host still needs its arm in each match below — that is per-host
/// behaviour, and the compiler asks for it. What it no longer needs is for
/// anyone to remember a list of names written somewhere else.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum Host {
Cursor,
Claude,
Codex,
/// Google Antigravity CLI. Reads `.agents/mcp_config.json`, the same
/// `mcpServers` document shape Cursor and Claude use, and shares
/// `.agents/skills` with Codex.
Antigravity,
/// OpenCode. Reads `opencode.json` at the repository root — a *user-owned*
/// file, not a dot-directory this tool owns — under an `mcp` key whose
/// entries name the program as an argv array rather than command+args.
// clap's default rename would spell this `open-code`; the host is one word.
#[value(name = "opencode")]
OpenCode,
/// Warp / Oz. Reads `.devcouncil/integrations/warp-mcp.json`, a file
/// DevCouncil writes and passes explicitly via `oz agent run --mcp`, so
/// the document is a bare server map with no wrapper key.
Warp,
}
impl Host {
/// Parse a host name, for callers holding a string rather than a parsed
/// argument. `devmap integrate` itself gets its `Host` from clap.
///
/// Acceptance and refusal are both generated from the variant list, so the
/// message cannot name a set of hosts the parser does not accept — the way
/// the `--help` text came to promise three of six.
///
/// Retained, not wired: since the positional is typed, the only in-tree
/// caller is the test below. The attribute states that rather than letting
/// a blanket allow hide a later unwiring.
#[cfg_attr(not(test), allow(dead_code))]
pub fn parse(name: &str) -> anyhow::Result<Self> {
<Self as clap::ValueEnum>::from_str(name, false).map_err(|_| {
anyhow!(
"unsupported host {name:?}; expected {}",
Self::accepted_names()
)
})
}
/// The accepted names as prose: `a, b, or c`.
#[cfg_attr(not(test), allow(dead_code))]
fn accepted_names() -> String {
let names: Vec<&str> = <Self as clap::ValueEnum>::value_variants()
.iter()
.map(|host| host.as_str())
.collect();
match names.as_slice() {
// Unreachable while the enum has variants, but a refusal that had
// nothing to name must say so rather than trail off after "expected".
[] => "no host: this build accepts none".to_string(),
[only] => (*only).to_string(),
[rest @ .., last] => format!("{}, or {last}", rest.join(", ")),
}
}
/// The canonical name of this host, as typed on the command line.
///
/// Tied to clap's own accepted values by a test below. DevCouncil's Go host
/// keeps no copy of this list: it passes host names through to `devmap
/// integrate`, whose refusal of an unknown one prints clap's list.
pub fn as_str(self) -> &'static str {
match self {
Self::Cursor => "cursor",
Self::Claude => "claude",
Self::Codex => "codex",
Self::Antigravity => "antigravity",
Self::OpenCode => "opencode",
Self::Warp => "warp",
}
}
fn skill_destinations(self) -> &'static [&'static str] {
match self {
Self::Cursor => &[".cursor/skills"],
Self::Claude => &[".claude/skills"],
// Antigravity reads the same `.agents` tree Codex does, so the
// skills a Codex integration already installed are the skills it
// sees; writing them twice would be the same bytes.
Self::Codex | Self::Antigravity => &[".agents/skills"],
// Neither host documents a project skill directory. Writing one on
// a guess would leave files no host reads.
Self::OpenCode | Self::Warp => &[],
}
}
fn registers_global_mcp(self) -> bool {
matches!(self, Self::Cursor | Self::Claude)
}
fn registers_codex_mcp(self) -> bool {
matches!(self, Self::Codex)
}
}
#[derive(Debug, Default)]
pub struct IntegrateReport {
pub guides: Vec<devmap_query::guides::GuideOutcome>,
pub skills_written: Vec<PathBuf>,
pub skills_differing: Vec<PathBuf>,
pub global_mcp: Vec<McpMergeOutcome>,
pub project_mcp: Vec<McpMergeOutcome>,
pub hooks: Vec<McpMergeOutcome>,
/// The caller's servers from `--servers-stdin`, one outcome each.
pub servers: Vec<McpMergeOutcome>,
pub notes: Vec<String>,
/// Under `--check`, whether every asset already matched. The report is
/// returned either way, so a caller can see *which* file differs.
pub check_ok: bool,
}
impl IntegrateReport {
/// Every path this report says an apply has already changed on disk.
fn written_paths(&self) -> Vec<PathBuf> {
let mut paths: Vec<PathBuf> = self
.guides
.iter()
.filter(|g| g.changed())
.map(|g| g.path.clone())
.collect();
paths.extend(self.skills_written.iter().cloned());
paths.extend(
self.global_mcp
.iter()
.chain(&self.project_mcp)
.chain(&self.hooks)
.chain(&self.servers)
.filter(|m| m.changed)
.map(|m| m.path.clone()),
);
paths
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct McpMergeOutcome {
pub path: PathBuf,
pub changed: bool,
pub removed_stale_db: bool,
pub note: String,
}
/// Apply (or check / dry-run) DevMap host assets for one repository.
///
/// An apply is planned in full before it writes: every document, guide and
/// skill destination is examined by the same code in its read-only mode, so a
/// document that refuses (JSON with comments, an unparseable TOML, a layout the
/// editor cannot change without loss) stops the run with nothing written. A
/// failure after that point — a full disk, a file that changed underneath — is
/// reported with the list of what had already been written, because the
/// receipt of a half-applied install is the only way to put it back.
#[allow(clippy::too_many_arguments)]
pub fn integrate(
host: Host,
project_root: &Path,
executable: &Path,
map: &Value,
map_rel: &str,
graph_rel: &str,
store_rel: &str,
servers: &[ServerSpec],
dry_run: bool,
check: bool,
) -> anyhow::Result<IntegrateReport> {
let writes = !dry_run && !check;
if writes {
integrate(
host,
project_root,
executable,
map,
map_rel,
graph_rel,
store_rel,
servers,
true,
false,
)
.context("nothing was written: the plan was refused")?;
}
let mut report = IntegrateReport::default();
match integrate_into(
host,
project_root,
executable,
map,
map_rel,
graph_rel,
store_rel,
servers,
dry_run,
check,
&mut report,
) {
Ok(()) => Ok(report),
Err(err) if writes => {
let written = report.written_paths();
if written.is_empty() {
Err(err)
} else {
Err(err.context(format!(
"apply stopped part-way; already written: {}",
written
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", ")
)))
}
}
Err(err) => Err(err),
}
}
#[allow(clippy::too_many_arguments)]
fn integrate_into(
host: Host,
project_root: &Path,
executable: &Path,
map: &Value,
map_rel: &str,
graph_rel: &str,
store_rel: &str,
servers: &[ServerSpec],
dry_run: bool,
check: bool,
report: &mut IntegrateReport,
) -> anyhow::Result<()> {
let root = project_root
.canonicalize()
.with_context(|| format!("project root {}", project_root.display()))?;
// Every caller server is planned before DevMap writes anything: a
// document that refuses the caller's entry must not leave DevMap's half
// applied and the caller's missing.
for spec in servers {
register_server(host, &root, spec, true)?;
}
if dry_run || check {
// Guides: compare without writing.
let guide_text =
devmap_query::guides::agent_guide_text(map, map_rel, graph_rel, store_rel) + "\n";
for name in devmap_query::guides::GUIDE_FILENAMES {
let path = root.join(name);
let disposition = match read_host_config(&path) {
Ok(existing)
if existing.contains(devmap_query::guides::AGENT_GUIDE_MARKER)
|| existing.contains(devmap_query::guides::LEGACY_AGENT_GUIDE_MARKER) =>
{
if existing == guide_text {
devmap_query::guides::GuideDisposition::Unchanged
} else {
devmap_query::guides::GuideDisposition::Updated
}
}
Ok(_) => devmap_query::guides::GuideDisposition::NotOurs,
Err(_) if !path.exists() => devmap_query::guides::GuideDisposition::Created,
Err(_) => devmap_query::guides::GuideDisposition::NotOurs,
};
if matches!(
disposition,
devmap_query::guides::GuideDisposition::Created
| devmap_query::guides::GuideDisposition::Updated
) {
report
.guides
.push(devmap_query::guides::GuideOutcome { path, disposition });
}
}
let rule_path = root.join(devmap_query::guides::CURSOR_RULE_REL);
let rule_text = devmap_query::guides::cursor_rule_text(map_rel);
let rule_differs = read_host_config(&rule_path)
.map(|existing| existing != rule_text)
.unwrap_or(true);
if rule_differs {
report.guides.push(devmap_query::guides::GuideOutcome {
path: rule_path.clone(),
disposition: if rule_path.exists() {
devmap_query::guides::GuideDisposition::Updated
} else {
devmap_query::guides::GuideDisposition::Created
},
});
}
} else {
report.guides =
devmap_query::guides::write_agent_guides(&root, map, map_rel, graph_rel, store_rel)?;
}
// A host with no documented project skill directory installs no skills.
// That is a state, not a malformed request: the installer's 1-16
// destination bound guards against a caller passing nonsense, and handing
// it an empty slice to mean "nowhere" tripped that guard instead.
// Vacuously satisfied where nothing is installed: a check that had no
// destinations to inspect must not report the same failure as one that
// inspected a destination and found it wrong.
let mut skills_check_ok = true;
if host.skill_destinations().is_empty() {
report.notes.push(format!(
"{}: no project skill directory is documented for this host; \
skills were not installed",
host.as_str()
));
} else {
let skill_report =
skills::install_devmap_skills(&root, host.skill_destinations(), dry_run, check)?;
report.skills_written = skill_report.written;
report.skills_differing = skill_report.differing;
skills_check_ok = skill_report.check_ok;
}
// An enabled Dev Map plugin already registers `devmap` for Claude Code. A
// user- or project-scope entry beside it is a second server for the same
// host: Claude Code collapses same-named servers only across its own
// scopes, and drops a plugin server only when another has the same
// command, which the absolute path these entries carry never matches.
// Writing either one is what kept bringing the duplicate back.
let plugin_registration = match host {
Host::Claude => {
let install = claude::claude_plugin_install(&dirs_home()?);
let registration = claude_plugin_registration(&install);
if registration.is_none() {
// Unknown is not "no plugin": say the writes rest on it.
for error in install.record_error.iter().chain(&install.load_error) {
report.notes.push(format!(
"claude: could not tell whether the Dev Map plugin registers devmap \
({error}); the user- and project-scope entries were managed as if it \
does not"
));
}
}
registration
}
_ => None,
};
if host.registers_global_mcp() {
for path in global_mcp_paths(host)? {
let outcome = match &plugin_registration {
Some(plugin_mcp) => {
retire_beside_plugin(&path, plugin_mcp, "user-scope", dry_run || check)?
}
None => merge_global_mcp(&path, executable, dry_run || check)?,
};
report.global_mcp.push(outcome);
}
}
if host.registers_codex_mcp() {
let path = dirs_home()?.join(".codex").join("config.toml");
let outcome = merge_codex_mcp(&path, executable, dry_run || check)?;
report.global_mcp.push(outcome);
report.notes.push(
"Codex hooks require trust via `/hooks` after install (hash-based; \
regenerating hooks re-requires trust)"
.into(),
);
}
// Hosts whose project document this module owns end-to-end. Cursor and
// Claude are handled by the `mcpServers` merge further down, which also
// reaches their user-level files; these three have no user-level document.
if let Some(outcome) = merge_host_mcp(host, &root, executable, dry_run || check)? {
report.project_mcp.push(outcome);
}
// OpenCode has no hooks document: it loads an ES module named in
// `opencode.json`. Antigravity and Warp are absent here on purpose —
// neither documents a project hook mechanism, and a handler written on a
// guess is a file the host never calls.
if host == Host::OpenCode {
report
.hooks
.extend(merge_opencode_plugin(&root, executable, dry_run || check)?);
}
if host == Host::Cursor {
let path = root.join(".cursor").join("hooks.json");
let outcome = merge_cursor_hooks(&path, executable, dry_run || check)?;
report.hooks.push(outcome);
}
if host == Host::Codex {
let plugin_dir = root.join(".codex-plugin");
let hooks_dir = root.join("hooks");
let outcome =
write_codex_plugin_assets(&plugin_dir, &hooks_dir, executable, dry_run || check)?;
report.hooks.extend(outcome);
}
// Clean stale `--db` registrations, then offer `--root` when the project
// has no DevMap entry. `--root` is insufficient for multi-tab Cursor. A
// document the host loads is instead kept clear of `devmap` while the
// enabled plugin registers it.
for site in project_mcp_sites(host, &root) {
if let (true, Some(plugin_mcp)) = (site.loaded, &plugin_registration) {
report.project_mcp.push(retire_beside_plugin(
&site.path,
plugin_mcp,
"project-scope",
dry_run || check,
)?);
continue;
}
if let Some(outcome) = clean_project_mcp(&site.path, executable, dry_run || check)? {
report.project_mcp.push(outcome);
continue;
}
if site.loaded {
if let Some(outcome) = offer_project_mcp(&site.path, executable, dry_run || check)? {
report.project_mcp.push(outcome);
}
}
}
// The caller's servers go into the same project document, through the
// same per-host table, as DevMap's own entry.
for spec in servers {
report
.servers
.push(register_server(host, &root, spec, dry_run || check)?);
}
let guides_dirty = report.guides.iter().any(|g| g.changed());
let skills_dirty = !report.skills_differing.is_empty();
let mcp_dirty = report
.global_mcp
.iter()
.chain(report.project_mcp.iter())
.chain(report.hooks.iter())
.chain(report.servers.iter())
.any(|m| m.changed);
report.check_ok = !(guides_dirty || skills_dirty || mcp_dirty || !skills_check_ok);
Ok(())
}
fn global_mcp_paths(host: Host) -> anyhow::Result<Vec<PathBuf>> {
let home = dirs_home()?;
Ok(match host {
Host::Cursor => vec![home.join(".cursor").join("mcp.json")],
Host::Claude => vec![claude::claude_global_config(&home)],
// Project-scoped only. Antigravity and OpenCode keep their server list
// beside the repository, and Warp's file is handed to `oz` per run, so
// there is no user-level document to merge into for any of them.
Host::Codex | Host::Antigravity | Host::OpenCode | Host::Warp => Vec::new(),
})
}
/// One per-project `mcpServers` document the merge inspects.
struct ProjectMcpSite {
path: PathBuf,
/// Whether the host loads this document. Only a loaded one is offered a
/// new entry, and only a loaded one duplicates an enabled plugin.
loaded: bool,
}
fn project_mcp_sites(host: Host, root: &Path) -> Vec<ProjectMcpSite> {
let site = |path: PathBuf, loaded: bool| ProjectMcpSite { path, loaded };
match host {
Host::Cursor => vec![site(root.join(".cursor").join("mcp.json"), true)],
// Claude Code documents `<root>/.mcp.json` as its only project-scope
// file. `<root>/.claude/mcp.json` is named nowhere, so creating one
// left a file no host reads; an entry already there is still cleaned
// of a stale `--db`, but nothing new is written to it.
Host::Claude => vec![
site(root.join(".mcp.json"), true),
site(root.join(".claude").join("mcp.json"), false),
],
// The three below are written by `host_mcp_document`, which knows each
// one's container key and entry shape. They are deliberately absent
// here: this list feeds the `mcpServers` merge, and two of them do not
// use that key at all.
Host::Codex | Host::Antigravity | Host::OpenCode | Host::Warp => Vec::new(),
}
}
/// How a host's project document is encoded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DocFormat {
Json,
/// Codex. Written by [`merge_toml_server`], which keeps every byte
/// outside the one table it owns.
Toml,
}
/// Where one host keeps its project server list, and how that document is
/// shaped.
///
/// This is the one table of per-host documents. DevCouncil's Go host used to
/// carry a copy for the server it registers, pinned to this one by a test that
/// parsed this file; it now hands its server to `devmap integrate
/// --servers-stdin` instead, so both servers are written from here.
///
/// The shapes are load-bearing: Antigravity nests servers under `mcpServers`,
/// OpenCode under `mcp` with argv-array entries, Warp's file *is* the server
/// map, and Codex is TOML under `mcp_servers`.
struct HostMcpDoc {
/// Path relative to the repository root.
rel: &'static str,
format: DocFormat,
/// Key the server map lives under, or `None` when the document root is it.
container: Option<&'static str>,
/// Extra top-level keys to establish when creating the file.
preamble: &'static [(&'static str, &'static str)],
/// Whether entries name the program as an argv array (`command: [...]`)
/// instead of `command` + `args`.
argv_form: bool,
/// Whether the host honours a `cwd` key on an entry. Antigravity resolves
/// relative paths against its own working directory, and Codex documents
/// `cwd` for stdio servers; the others name no such key.
accepts_cwd: bool,
/// Whether [`merge_host_mcp`] writes DevMap's own entry here. Cursor and
/// Claude carry it through [`offer_project_mcp`], which also withholds it
/// beside the enabled plugin, and Codex in the user-level config.
carries_devmap: bool,
}
impl Host {
/// The project-scoped server document this host reads.
fn project_document(self) -> HostMcpDoc {
let json = |rel, container| HostMcpDoc {
rel,
format: DocFormat::Json,
container,
preamble: &[],
argv_form: false,
accepts_cwd: false,
carries_devmap: false,
};
match self {
Self::Cursor => json(".cursor/mcp.json", Some("mcpServers")),
Self::Claude => json(".mcp.json", Some("mcpServers")),
// Read by Codex for trusted projects only; the user-level
// `~/.codex/config.toml` is where DevMap's own entry goes.
Self::Codex => HostMcpDoc {
format: DocFormat::Toml,
accepts_cwd: true,
..json(".codex/config.toml", Some("mcp_servers"))
},
Self::Antigravity => HostMcpDoc {
accepts_cwd: true,
carries_devmap: true,
..json(".agents/mcp_config.json", Some("mcpServers"))
},
Self::OpenCode => HostMcpDoc {
// OpenCode validates against this schema; a file created
// without it loses editor completion for every other key.
preamble: &[("$schema", "https://opencode.ai/config.json")],
argv_form: true,
carries_devmap: true,
..json("opencode.json", Some("mcp"))
},
Self::Warp => HostMcpDoc {
carries_devmap: true,
..json(".devcouncil/integrations/warp-mcp.json", None)
},
}
}
/// The project document that carries DevMap's own entry, if this host has
/// one written by [`merge_host_mcp`].
fn mcp_document(self) -> Option<HostMcpDoc> {
Some(self.project_document()).filter(|doc| doc.carries_devmap)
}
}
/// Register `devmap` in one host's project server document.
///
/// The entry is always [`claude::mcp_entry_with_root`]'s shape — the absolute
/// path of the binary that was validated, and `--root <abs>` rather than a
/// pinned `--db`. Both halves matter and both were wrong in the configurations
/// this replaces: a bare `devmap` hands the host whichever build wins on PATH,
/// and a baked store path fixes the state layout as of the day it was written,
/// which is not a property of the binary but of the repository.
///
/// Every other key in the file survives. `opencode.json` in particular is a
/// *user's* configuration that happens to hold a server list, not a file this
/// tool owns, so a write that dropped an unrelated key would be a bug even if
/// the server entry came out right.
pub fn merge_host_mcp(
host: Host,
root: &Path,
executable: &Path,
dry_run: bool,
) -> anyhow::Result<Option<McpMergeOutcome>> {
let Some(doc) = host.mcp_document() else {
return Ok(None);
};
let entry = host_mcp_entry(&doc, executable, root)?;
merge_json_server(&root.join(doc.rel), &doc, MCP_SERVER_NAME, entry, dry_run).map(Some)
}
/// Fold one named server entry into a host's JSON project document.
fn merge_json_server(
path: &Path,
doc: &HostMcpDoc,
name: &str,
entry: Value,
dry_run: bool,
) -> anyhow::Result<McpMergeOutcome> {
let path = path.to_path_buf();
let mut document = match read_project_doc(&path)? {
None => empty_map(),
Some(text) if text.trim().is_empty() => empty_map(),
Some(text) => serde_json::from_str::<Value>(&text).map_err(|err| {
// Refuse rather than overwrite: an unparseable config is far more
// likely to be a file worth keeping than one worth replacing.
// serde_json reads no comments, so a commented file lands here
// too rather than losing them in the rewrite.
anyhow!(
"{}: not JSON ({err}); refuse to overwrite a host config this \
module cannot read",
path.display()
)
})?,
};
if !document.is_object() {
bail!(
"{}: top level is {}, not a JSON object",
path.display(),
kind_of(&document)
);
}
for (key, value) in doc.preamble {
document
.as_object_mut()
.expect("object checked above")
.entry(key.to_string())
.or_insert_with(|| json!(value));
}
let before = server_of(&document, doc, name).cloned();
if before.as_ref() == Some(&entry) {
return Ok(McpMergeOutcome {
path,
changed: false,
removed_stale_db: false,
note: format!("{} already current", doc.rel),
});
}
// Reported rather than folded into "changed": replacing a pinned store
// path is the repair this exists for, and a receipt that does not
// distinguish it from a first-time write cannot show the repair happened.
let removed_stale_db =
name == MCP_SERVER_NAME && before.as_ref().is_some_and(entry_names_a_store);
servers_mut(&mut document, doc)?.insert(name.to_string(), entry);
if !dry_run {
// No `create_dir_all` first: it would follow a linked parent out of
// the repository. `write_atomic` creates missing directories through
// pinned handles and refuses a link on the way.
write_json_pretty(&path, &document)?;
}
Ok(McpMergeOutcome {
path,
changed: true,
removed_stale_db,
note: if removed_stale_db {
format!("{}: replaced a pinned --db entry with --root", doc.rel)
} else {
format!("{}: registered {name}", doc.rel)
},
})
}
/// Read a project document without following a link at any component.
///
/// These files arrive with a clone, and so can a symlink in their place: a
/// read that followed one would copy an outside file's contents into the merged
/// result and then into the repository.
fn read_project_doc(path: &Path) -> anyhow::Result<Option<String>> {
use devmap_extract::safe_fs::{Access, Creation, SafeFile};
match SafeFile::open(path, Access::Read, Creation::Never) {
Ok(mut file) => file
.read_text(MAX_HOST_CONFIG_BYTES)
.map(Some)
.with_context(|| format!("reading {}", path.display())),
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(anyhow!("{}: {err}", path.display())),
}
}
/// The devmap entry in this host's spelling.
fn host_mcp_entry(doc: &HostMcpDoc, executable: &Path, root: &Path) -> anyhow::Result<Value> {
let standard = claude::mcp_entry_with_root(executable, root, None)?;
if !doc.argv_form {
return Ok(standard);
}
// OpenCode names the program and its arguments as one argv array. Build it
// from the standard entry rather than re-deriving the path and flags, so
// the two spellings cannot disagree about what gets run.
let command = standard
.get("command")
.and_then(Value::as_str)
.ok_or_else(|| anyhow!("mcp entry has no command"))?;
let args = standard
.get("args")
.and_then(Value::as_array)
.into_iter()
.flatten()
.cloned();
Ok(argv_entry(command, args, None))
}
/// OpenCode's entry: one argv array, a declared local type, and its own name
/// for the environment block.
fn argv_entry(
command: &str,
args: impl IntoIterator<Item = Value>,
environment: Option<&BTreeMap<String, String>>,
) -> Value {
let mut argv = vec![json!(command)];
argv.extend(args);
let mut entry = json!({
"type": "local",
"command": Value::Array(argv),
"enabled": true,
"timeout": 10_000,
});
if let Some(environment) = environment.filter(|env| !env.is_empty()) {
entry["environment"] = json!(environment);
}
entry
}
/// The most servers one `--servers-stdin` request may register.
const MAX_REQUESTED_SERVERS: usize = 8;
/// Bound on the request document itself.
pub const MAX_SERVER_REQUEST_BYTES: usize = 64 * 1024;
const MAX_SERVER_ARGS: usize = 64;
const MAX_SERVER_ENV: usize = 64;
const MAX_SERVER_STRING: usize = 4096;
/// A server another tool asks `devmap integrate` to register beside DevMap's
/// own — DevCouncil's `devcouncil` server is the caller this exists for.
///
/// DevMap owns every host's document shape; the caller owns only what its
/// server runs. That split is what lets one table describe each host.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServerSpec {
pub name: String,
/// Absolute path of the program. A bare name would hand the host whichever
/// build wins on PATH, which is the contract DevMap's own entry refuses.
pub command: String,
pub args: Vec<String>,
pub env: BTreeMap<String, String>,
/// Working directory, written only where the host honours one.
pub cwd: Option<String>,
}
/// Parse and validate `{"servers": [{name, command, args?, env?, cwd?}]}`.
///
/// Unknown keys are refused rather than ignored: a field the caller believes
/// was written and this reader dropped is a silent misconfiguration.
pub fn parse_server_request(bytes: &[u8]) -> anyhow::Result<Vec<ServerSpec>> {
if bytes.len() > MAX_SERVER_REQUEST_BYTES {
bail!("server request exceeds {MAX_SERVER_REQUEST_BYTES} bytes");
}
let request: Value = serde_json::from_slice(bytes)
.map_err(|err| anyhow!("server request is not JSON: {err}"))?;
let object = request
.as_object()
.ok_or_else(|| anyhow!("server request must be a JSON object"))?;
refuse_unknown_keys("server request", object, &["servers"])?;
let servers = object
.get("servers")
.and_then(Value::as_array)
.ok_or_else(|| anyhow!("server request needs a `servers` array"))?;
if servers.is_empty() || servers.len() > MAX_REQUESTED_SERVERS {
bail!("server request must name 1–{MAX_REQUESTED_SERVERS} servers");
}
let mut specs: Vec<ServerSpec> = Vec::with_capacity(servers.len());
for server in servers {
let spec = parse_server_spec(server)?;
if specs.iter().any(|seen| seen.name == spec.name) {
bail!("server {:?} is named twice", spec.name);
}
specs.push(spec);
}
Ok(specs)
}
fn parse_server_spec(value: &Value) -> anyhow::Result<ServerSpec> {
let object = value
.as_object()
.ok_or_else(|| anyhow!("each server must be a JSON object"))?;
refuse_unknown_keys("server", object, &["name", "command", "args", "env", "cwd"])?;
let string = |key: &str| -> anyhow::Result<Option<String>> {
match object.get(key) {
None => Ok(None),
Some(Value::String(text)) => Ok(Some(checked_string(key, text)?)),
Some(other) => bail!("server `{key}` is {}, not a string", kind_of(other)),
}
};
let name = string("name")?.ok_or_else(|| anyhow!("server needs a `name`"))?;
let valid_name = !name.is_empty()
&& name.len() <= 64
&& name
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
&& name.as_bytes()[0].is_ascii_alphanumeric();
if !valid_name {
bail!("server name {name:?} must be 1–64 of [a-z0-9_-], starting alphanumeric");
}
if name == MCP_SERVER_NAME {
bail!("server name {name:?} is DevMap's own entry, which `devmap integrate` writes itself");
}
let command = string("command")?.ok_or_else(|| anyhow!("server {name:?} needs a `command`"))?;
if !Path::new(&command).is_absolute() {
bail!("server {name:?}: command {command:?} must be an absolute path");
}
let cwd = string("cwd")?;
if let Some(cwd) = &cwd {
if !Path::new(cwd).is_absolute() {
bail!("server {name:?}: cwd {cwd:?} must be an absolute path");
}
}
let args = match object.get("args") {
None => Vec::new(),
Some(Value::Array(items)) => {
if items.len() > MAX_SERVER_ARGS {
bail!("server {name:?}: more than {MAX_SERVER_ARGS} args");
}
items
.iter()
.map(|item| match item {
Value::String(text) => checked_string("args", text),
other => bail!(
"server {name:?}: an arg is {}, not a string",
kind_of(other)
),
})
.collect::<anyhow::Result<_>>()?
}
Some(other) => bail!(
"server {name:?}: `args` is {}, not an array",
kind_of(other)
),
};
let env = match object.get("env") {
None => BTreeMap::new(),
Some(Value::Object(vars)) => {
if vars.len() > MAX_SERVER_ENV {
bail!("server {name:?}: more than {MAX_SERVER_ENV} env entries");
}
let mut env = BTreeMap::new();
for (key, value) in vars {
let valid_key = key.bytes().enumerate().all(|(i, b)| {
b == b'_' || b.is_ascii_alphabetic() || (i > 0 && b.is_ascii_digit())
}) && !key.is_empty();
if !valid_key {
bail!("server {name:?}: env name {key:?} is not an identifier");
}
let Value::String(text) = value else {
bail!(
"server {name:?}: env {key} is {}, not a string",
kind_of(value)
);
};
env.insert(key.clone(), checked_string("env", text)?);
}
env
}
Some(other) => bail!(
"server {name:?}: `env` is {}, not an object",
kind_of(other)
),
};
Ok(ServerSpec {
name,
command,
args,
env,
cwd,
})
}
fn checked_string(key: &str, text: &str) -> anyhow::Result<String> {
if text.len() > MAX_SERVER_STRING || text.contains('\0') {
bail!("server `{key}` value is over {MAX_SERVER_STRING} bytes or contains NUL");
}
Ok(text.to_string())
}
fn refuse_unknown_keys(
what: &str,
object: &Map<String, Value>,
known: &[&str],
) -> anyhow::Result<()> {
match object.keys().find(|key| !known.contains(&key.as_str())) {
Some(key) => bail!("{what}: unknown key {key:?}"),
None => Ok(()),
}
}
/// Register a caller's server in `host`'s project document.
pub fn register_server(
host: Host,
root: &Path,
spec: &ServerSpec,
dry_run: bool,
) -> anyhow::Result<McpMergeOutcome> {
let doc = host.project_document();
let path = root.join(doc.rel);
let cwd = spec.cwd.as_ref().filter(|_| doc.accepts_cwd);
match doc.format {
DocFormat::Json => {
let entry = if doc.argv_form {
argv_entry(
&spec.command,
spec.args.iter().map(|a| json!(a)),
Some(&spec.env),
)
} else {
let mut entry = json!({"command": spec.command, "args": spec.args});
if !spec.env.is_empty() {
entry["env"] = json!(spec.env);
}
if let Some(cwd) = cwd {
entry["cwd"] = json!(cwd);
}
entry
};
merge_json_server(&path, &doc, &spec.name, entry, dry_run)
}
DocFormat::Toml => {
let mut entry = toml::Table::new();
entry.insert("command".into(), toml::Value::String(spec.command.clone()));
entry.insert(
"args".into(),
toml::Value::Array(spec.args.iter().cloned().map(toml::Value::String).collect()),
);
if !spec.env.is_empty() {
let env: toml::Table = spec
.env
.iter()
.map(|(k, v)| (k.clone(), toml::Value::String(v.clone())))
.collect();
entry.insert("env".into(), toml::Value::Table(env));
}
if let Some(cwd) = cwd {
entry.insert("cwd".into(), toml::Value::String(cwd.clone()));
}
merge_toml_server(&path, &doc, &spec.name, entry, dry_run)
}
}
}
/// Fold one `[<container>.<name>]` table into a TOML document, keeping every
/// byte outside that table.
///
/// The document is the user's: `.codex/config.toml` holds their model, their
/// profiles and their other servers. Re-serialising it would drop comments
/// and reorder what remains, so the table is appended — or, when present,
/// replaced in place along with its own subtables — and the result is parsed
/// back and compared with the original plus our entry. Any difference beyond
/// our table, or a document whose layout keeps our table from being found as
/// one block (an inline `mcp_servers = {…}`, dotted keys), is a refusal.