agent-config 0.3.2

Install hooks/integrations into AI coding harnesses (Claude Code, Cursor, Gemini CLI, OpenCode, Codex CLI, Cline, Windsurf, ...) without learning each one's filesystem layout.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
//! Shared MCP installer for harnesses that key servers by name inside a JSON
//! object.
//!
//! Different agents use different top-level keys and server-entry shapes:
//! `mcpServers` for Claude/Cursor/Gemini/Cline/Roo/Windsurf/Antigravity,
//! `servers` for VS Code Copilot, and object-based `mcp` for OpenCode/Kilo.
//! This module centralizes ownership, JSON/JSONC parsing, and uninstall
//! behavior so each agent only supplies its file path and serializer.

use std::collections::BTreeMap;
use std::path::Path;

use serde_json::{Map, Value};

use crate::error::AgentConfigError;
use crate::integration::{InstallReport, UninstallReport};
use crate::plan::{has_refusal, PlannedChange, RefusalReason};
use crate::spec::{McpSpec, McpTransport};
use crate::status::ConfigPresence;
use crate::util::{file_lock, fs_atomic, json5_patch, json_patch, ownership, planning};

/// The on-disk syntax to accept when reading the config.
#[derive(Debug, Clone, Copy)]
pub(crate) enum ConfigFormat {
    /// Strict JSON.
    Json,
    /// JSON with comments and trailing commas accepted.
    Jsonc,
    /// JSON5 with comments, trailing commas, unquoted keys, and single quotes.
    Json5,
}

/// Builder for one server entry under the chosen object key.
pub(crate) type ServerBuilder = fn(&McpSpec) -> Value;

/// Returns true if `name` exists in the MCP ownership ledger.
pub(crate) fn is_installed(ledger_path: &Path, name: &str) -> Result<bool, AgentConfigError> {
    ownership::contains(ledger_path, name)
}

/// Probe whether `name` is present in the named-object MCP config at
/// `config_path`. Parse failures are converted to
/// [`ConfigPresence::Invalid`] so callers can surface them as drift instead
/// of propagating an error.
pub(crate) fn config_presence(
    config_path: &Path,
    servers_path: &[&str],
    name: &str,
    format: ConfigFormat,
) -> Result<ConfigPresence, AgentConfigError> {
    if !config_path.exists() {
        return Ok(ConfigPresence::Absent);
    }
    let root = match read_or_empty(config_path, format) {
        Ok(v) => v,
        Err(AgentConfigError::JsonInvalid { source, .. }) => {
            return Ok(ConfigPresence::Invalid {
                reason: source.to_string(),
            });
        }
        Err(AgentConfigError::Other(e)) => {
            return Ok(ConfigPresence::Invalid {
                reason: e.to_string(),
            });
        }
        Err(e) => return Err(e),
    };
    Ok(if json_patch::contains_named(&root, servers_path, name) {
        ConfigPresence::Single
    } else {
        ConfigPresence::Absent
    })
}

/// Install or update an MCP server in a named object.
pub(crate) fn install(
    config_path: &Path,
    ledger_path: &Path,
    spec: &McpSpec,
    servers_path: &[&str],
    build_server: ServerBuilder,
    format: ConfigFormat,
) -> Result<InstallReport, AgentConfigError> {
    file_lock::with_lock(config_path, || {
        let mut report = InstallReport::default();

        let mut root = read_or_empty(config_path, format)?;
        let in_config = json_patch::contains_named(&root, servers_path, &spec.name);
        let prior_owner = ownership::owner_of(ledger_path, &spec.name)?;
        let adopting = spec.adopt_unowned && in_config && prior_owner.is_none();
        ownership::require_owner_with_policy(
            ledger_path,
            &spec.name,
            &spec.owner_tag,
            "mcp server",
            in_config,
            spec.adopt_unowned,
        )?;

        let value = build_server(spec);
        // Hash the canonical (compact) serialization of the *owned entry* so
        // that sibling installs to the same file do not invalidate this
        // entry's recorded hash. `to_vec` is byte-stable for `serde_json::Value`
        // (preserve_order is enabled) and must be used identically on the
        // uninstall side via `check_entry_drift`.
        let current_entry_hash = ownership::hash_entry_value(&value);
        let changed =
            json_patch::upsert_named_object_entry(&mut root, servers_path, &spec.name, value)?;

        let owner_changed = prior_owner.as_deref() != Some(spec.owner_tag.as_str());

        if changed {
            let bytes = json_patch::to_pretty(&root);
            let outcome = fs_atomic::write_atomic(config_path, &bytes, true)?;
            if outcome.existed {
                report.patched.push(outcome.path.clone());
            } else {
                report.created.push(outcome.path.clone());
            }
            if let Some(b) = outcome.backup {
                report.backed_up.push(b);
            }
        }

        // `adopting` forces the ledger record even when content is byte-identical:
        // the whole point of adoption is to write the missing ledger entry.
        if changed || owner_changed || adopting {
            ownership::record_install(
                ledger_path,
                &spec.name,
                &spec.owner_tag,
                Some(&current_entry_hash),
            )?;
        }

        if !changed && !owner_changed && !adopting {
            report.already_installed = true;
        }
        Ok(report)
    })
}

/// Plan installing or updating an MCP server in a named object.
pub(crate) fn plan_install(
    config_path: &Path,
    ledger_path: &Path,
    spec: &McpSpec,
    servers_path: &[&str],
    build_server: ServerBuilder,
    format: ConfigFormat,
) -> Result<Vec<PlannedChange>, AgentConfigError> {
    let mut changes = Vec::new();

    let mut root = match read_or_empty(config_path, format) {
        Ok(root) => root,
        Err(AgentConfigError::JsonInvalid { .. }) | Err(AgentConfigError::Other(_)) => {
            changes.push(PlannedChange::Refuse {
                path: Some(config_path.to_path_buf()),
                reason: RefusalReason::InvalidConfig,
            });
            return Ok(changes);
        }
        Err(e) => return Err(e),
    };
    let in_config = json_patch::contains_named(&root, servers_path, &spec.name);
    let prior_owner = ownership::owner_of(ledger_path, &spec.name)?;

    let adopting = spec.adopt_unowned && in_config && prior_owner.is_none();
    match (prior_owner.as_deref(), in_config) {
        (Some(owner), _) if owner != spec.owner_tag => {
            changes.push(PlannedChange::Refuse {
                path: Some(ledger_path.to_path_buf()),
                reason: RefusalReason::OwnerMismatch,
            });
            return Ok(changes);
        }
        (None, true) if !spec.adopt_unowned => {
            changes.push(PlannedChange::Refuse {
                path: Some(config_path.to_path_buf()),
                reason: RefusalReason::UserInstalledEntry,
            });
            return Ok(changes);
        }
        _ => {}
    }

    let value = build_server(spec);
    let changed =
        json_patch::upsert_named_object_entry(&mut root, servers_path, &spec.name, value)?;
    let owner_changed = prior_owner.as_deref() != Some(spec.owner_tag.as_str());

    if changed {
        let bytes = match format {
            ConfigFormat::Json | ConfigFormat::Jsonc | ConfigFormat::Json5 => {
                json_patch::to_pretty(&root)
            }
        };
        planning::plan_write_file(&mut changes, config_path, &bytes, true)?;
    }

    if !has_refusal(&changes) && (changed || owner_changed || adopting) {
        planning::plan_write_ledger(&mut changes, ledger_path, &spec.name, &spec.owner_tag);
    }

    if changes.is_empty() {
        changes.push(PlannedChange::NoOp {
            path: config_path.to_path_buf(),
            reason: "MCP server is already up to date".into(),
        });
    }

    Ok(changes)
}

/// Uninstall the server identified by `name`. Refuses on owner mismatch or
/// hand-installed entries.
pub(crate) fn uninstall(
    config_path: &Path,
    ledger_path: &Path,
    name: &str,
    owner_tag: &str,
    kind: &'static str,
    servers_path: &[&str],
    format: ConfigFormat,
) -> Result<UninstallReport, AgentConfigError> {
    if !config_path.exists() && !ledger_path.exists() {
        return Ok(UninstallReport {
            not_installed: true,
            ..UninstallReport::default()
        });
    }

    file_lock::with_lock(config_path, || {
        let mut report = UninstallReport::default();

        let mut root = read_or_empty(config_path, format)?;
        let in_config = json_patch::contains_named(&root, servers_path, name);
        let in_ledger = ownership::contains(ledger_path, name)?;

        if !in_config && !in_ledger {
            report.not_installed = true;
            return Ok(report);
        }

        ownership::require_owner(ledger_path, name, owner_tag, kind, in_config)?;

        if in_config {
            // Per-entry drift: extract the current entry value, hash it
            // canonically, and compare to the hash recorded at install time.
            // If a user (or another consumer's bug) edited our entry, refuse
            // to remove it instead of silently clobbering their change.
            let current_value = json_patch::lookup_named(&root, servers_path, name)
                .expect("contains_named was true; entry must exist");
            let current_bytes =
                serde_json::to_vec(current_value).expect("Value serializes to JSON");
            ownership::check_entry_drift(ledger_path, name, config_path, &current_bytes)?;

            let removed = json_patch::remove_named_object_entry(&mut root, servers_path, name)?;
            debug_assert!(removed);

            let now_empty = root.as_object().map(Map::is_empty).unwrap_or(true);
            let bytes = json_patch::to_pretty(&root);
            if now_empty && fs_atomic::restore_backup_if_matches(config_path, &bytes)? {
                report.restored.push(config_path.to_path_buf());
            } else if now_empty {
                fs_atomic::remove_if_exists(config_path)?;
                report.removed.push(config_path.to_path_buf());
            } else {
                fs_atomic::write_atomic(config_path, &bytes, false)?;
                report.patched.push(config_path.to_path_buf());
            }
        }

        ownership::record_uninstall(ledger_path, name)?;

        if report.removed.is_empty() && report.patched.is_empty() && report.restored.is_empty() {
            report.not_installed = true;
        }
        Ok(report)
    })
}

/// Plan uninstalling an MCP server from a named object.
pub(crate) fn plan_uninstall(
    config_path: &Path,
    ledger_path: &Path,
    name: &str,
    owner_tag: &str,
    kind: &'static str,
    servers_path: &[&str],
    format: ConfigFormat,
) -> Result<Vec<PlannedChange>, AgentConfigError> {
    let mut changes = Vec::new();
    let mut root = match read_or_empty(config_path, format) {
        Ok(root) => root,
        Err(AgentConfigError::JsonInvalid { .. }) | Err(AgentConfigError::Other(_)) => {
            changes.push(PlannedChange::Refuse {
                path: Some(config_path.to_path_buf()),
                reason: RefusalReason::InvalidConfig,
            });
            return Ok(changes);
        }
        Err(e) => return Err(e),
    };
    let in_config = json_patch::contains_named(&root, servers_path, name);
    let actual_owner = ownership::owner_of(ledger_path, name)?;

    if !in_config && actual_owner.is_none() {
        changes.push(PlannedChange::NoOp {
            path: config_path.to_path_buf(),
            reason: format!("{kind} is already absent"),
        });
        return Ok(changes);
    }

    match (actual_owner.as_deref(), in_config) {
        (Some(owner), _) if owner != owner_tag => {
            changes.push(PlannedChange::Refuse {
                path: Some(ledger_path.to_path_buf()),
                reason: RefusalReason::OwnerMismatch,
            });
            return Ok(changes);
        }
        (None, true) => {
            changes.push(PlannedChange::Refuse {
                path: Some(config_path.to_path_buf()),
                reason: RefusalReason::UserInstalledEntry,
            });
            return Ok(changes);
        }
        _ => {}
    }

    if in_config {
        let removed = json_patch::remove_named_object_entry(&mut root, servers_path, name)?;
        debug_assert!(removed);
        let now_empty = root.as_object().map(Map::is_empty).unwrap_or(true);
        if now_empty {
            let bytes = match format {
                ConfigFormat::Json | ConfigFormat::Jsonc | ConfigFormat::Json5 => {
                    json_patch::to_pretty(&root)
                }
            };
            planning::plan_restore_backup_or_remove(&mut changes, config_path, &bytes)?;
        } else {
            let bytes = match format {
                ConfigFormat::Json | ConfigFormat::Jsonc | ConfigFormat::Json5 => {
                    json_patch::to_pretty(&root)
                }
            };
            planning::plan_write_file(&mut changes, config_path, &bytes, false)?;
        }
    }

    if actual_owner.is_some() {
        planning::plan_remove_ledger_entry(&mut changes, ledger_path, name);
    }

    if changes.is_empty() {
        changes.push(PlannedChange::NoOp {
            path: config_path.to_path_buf(),
            reason: format!("{kind} is already absent"),
        });
    }

    Ok(changes)
}

/// Standard `mcpServers.<name>` entry shape (Claude/Cursor/Gemini/etc.).
pub(crate) fn mcp_servers_value(spec: &McpSpec) -> Value {
    named_object_value(spec, false)
}

/// VS Code MCP `servers.<name>` entry shape — same as `mcp_servers_value`
/// but with an explicit `"type": "stdio"` discriminant on stdio entries.
#[allow(dead_code)]
pub(crate) fn vscode_servers_value(spec: &McpSpec) -> Value {
    named_object_value(spec, true)
}

fn named_object_value(spec: &McpSpec, include_stdio_type: bool) -> Value {
    let mut obj = Map::new();
    match &spec.transport {
        McpTransport::Stdio { command, args, env } => {
            if include_stdio_type {
                obj.insert("type".into(), Value::String("stdio".into()));
            }
            obj.insert("command".into(), Value::String(command.clone()));
            obj.insert(
                "args".into(),
                Value::Array(args.iter().cloned().map(Value::String).collect()),
            );
            if !env.is_empty() {
                obj.insert("env".into(), string_map_value(env));
            }
        }
        McpTransport::Http { url, headers } => insert_remote(&mut obj, "http", url, headers),
        McpTransport::Sse { url, headers } => insert_remote(&mut obj, "sse", url, headers),
    }
    Value::Object(obj)
}

fn insert_remote(
    obj: &mut Map<String, Value>,
    type_tag: &str,
    url: &str,
    headers: &BTreeMap<String, String>,
) {
    obj.insert("type".into(), Value::String(type_tag.into()));
    obj.insert("url".into(), Value::String(url.into()));
    if !headers.is_empty() {
        obj.insert("headers".into(), string_map_value(headers));
    }
}

/// OpenCode/Kilo object-based `mcp.<name>` entry shape.
pub(crate) fn command_array_value(spec: &McpSpec) -> Value {
    let mut obj = Map::new();
    match &spec.transport {
        McpTransport::Stdio { command, args, env } => {
            obj.insert("type".into(), Value::String("local".into()));
            let command_array = std::iter::once(command.clone())
                .chain(args.iter().cloned())
                .map(Value::String)
                .collect();
            obj.insert("command".into(), Value::Array(command_array));
            if !env.is_empty() {
                obj.insert("environment".into(), string_map_value(env));
            }
        }
        McpTransport::Http { url, headers } | McpTransport::Sse { url, headers } => {
            insert_remote(&mut obj, "remote", url, headers);
        }
    }
    Value::Object(obj)
}

fn read_or_empty(path: &Path, format: ConfigFormat) -> Result<Value, AgentConfigError> {
    match format {
        ConfigFormat::Json => json_patch::read_or_empty(path),
        ConfigFormat::Jsonc => read_jsonc_or_empty(path),
        ConfigFormat::Json5 => json5_patch::read_or_empty(path),
    }
}

/// Read a JSONC file, returning `Value::Object(empty)` when the file is
/// missing or whitespace-only. Comments and trailing commas are accepted;
/// invalid JSONC is surfaced as [`AgentConfigError::Other`].
///
/// Exposed `pub(crate)` so harnesses whose primary config is JSONC (Crush,
/// Kilo) can read their host file with the same parser the MCP layer uses.
pub(crate) fn read_jsonc_or_empty(path: &Path) -> Result<Value, AgentConfigError> {
    let text = fs_atomic::read_to_string_or_empty(path)?;
    if text.trim().is_empty() {
        return Ok(Value::Object(Map::new()));
    }
    jsonc_parser::parse_to_serde_value::<Value>(&text, &Default::default()).map_err(|e| {
        AgentConfigError::Other(anyhow::anyhow!(
            "invalid JSONC in {}: {}",
            path.display(),
            e
        ))
    })
}

fn string_map_value(map: &BTreeMap<String, String>) -> Value {
    let mut obj = Map::new();
    for (k, v) in map {
        obj.insert(k.clone(), Value::String(v.clone()));
    }
    Value::Object(obj)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use tempfile::tempdir;

    fn paths(dir: &Path) -> (std::path::PathBuf, std::path::PathBuf) {
        (dir.join("config.jsonc"), dir.join(".agent-config-mcp.json"))
    }

    fn stdio_spec(name: &str, owner: &str) -> McpSpec {
        McpSpec::builder(name)
            .owner(owner)
            .stdio("npx", ["-y", "@example/server"])
            .env("FOO", "bar")
            .build()
    }

    #[test]
    fn install_mcp_servers_object() {
        let dir = tempdir().unwrap();
        let (cfg, led) = paths(dir.path());
        install(
            &cfg,
            &led,
            &stdio_spec("github", "myapp"),
            &["mcpServers"],
            mcp_servers_value,
            ConfigFormat::Json,
        )
        .unwrap();
        let v: Value = serde_json::from_slice(&std::fs::read(&cfg).unwrap()).unwrap();
        assert_eq!(v["mcpServers"]["github"]["command"], json!("npx"));
        assert_eq!(v["mcpServers"]["github"]["env"]["FOO"], json!("bar"));
    }

    #[test]
    fn install_vscode_servers_object() {
        let dir = tempdir().unwrap();
        let (cfg, led) = paths(dir.path());
        install(
            &cfg,
            &led,
            &stdio_spec("memory", "myapp"),
            &["servers"],
            vscode_servers_value,
            ConfigFormat::Json,
        )
        .unwrap();
        let v: Value = serde_json::from_slice(&std::fs::read(&cfg).unwrap()).unwrap();
        assert_eq!(v["servers"]["memory"]["type"], json!("stdio"));
        assert_eq!(v["servers"]["memory"]["command"], json!("npx"));
    }

    #[test]
    fn install_command_array_object_from_jsonc_with_comments() {
        let dir = tempdir().unwrap();
        let (cfg, led) = paths(dir.path());
        std::fs::write(
            &cfg,
            r#"{
  // user comment
  "mcp": {
    "user": {
      "type": "local",
      "command": ["uvx", "user-server"],
    },
  },
}
"#,
        )
        .unwrap();
        install(
            &cfg,
            &led,
            &stdio_spec("github", "myapp"),
            &["mcp"],
            command_array_value,
            ConfigFormat::Jsonc,
        )
        .unwrap();
        let v: Value = serde_json::from_slice(&std::fs::read(&cfg).unwrap()).unwrap();
        assert_eq!(v["mcp"]["github"]["type"], json!("local"));
        assert_eq!(
            v["mcp"]["github"]["command"],
            json!(["npx", "-y", "@example/server"])
        );
        assert_eq!(v["mcp"]["github"]["environment"]["FOO"], json!("bar"));
        assert_eq!(v["mcp"]["user"]["command"][0], json!("uvx"));
    }

    #[test]
    fn install_refuses_other_owner() {
        let dir = tempdir().unwrap();
        let (cfg, led) = paths(dir.path());
        install(
            &cfg,
            &led,
            &stdio_spec("github", "app-a"),
            &["mcpServers"],
            mcp_servers_value,
            ConfigFormat::Json,
        )
        .unwrap();
        let err = install(
            &cfg,
            &led,
            &stdio_spec("github", "app-b"),
            &["mcpServers"],
            mcp_servers_value,
            ConfigFormat::Json,
        )
        .unwrap_err();
        assert!(matches!(err, AgentConfigError::NotOwnedByCaller { .. }));
    }

    #[test]
    fn install_refuses_hand_installed_same_name() {
        let dir = tempdir().unwrap();
        let (cfg, led) = paths(dir.path());
        std::fs::write(
            &cfg,
            r#"{ "mcpServers": { "github": { "command": "user-cmd" } } }"#,
        )
        .unwrap();
        let err = install(
            &cfg,
            &led,
            &stdio_spec("github", "myapp"),
            &["mcpServers"],
            mcp_servers_value,
            ConfigFormat::Json,
        )
        .unwrap_err();
        assert!(matches!(
            err,
            AgentConfigError::NotOwnedByCaller { actual: None, .. }
        ));
    }

    #[test]
    fn install_with_adopt_unowned_takes_over_existing_entry() {
        // Simulates the crash window: a previous install wrote the harness
        // config but never recorded the ledger entry. With `.adopt_unowned(true)`
        // the next install records ownership and the existing config stays put
        // (or is updated to the new spec).
        let dir = tempdir().unwrap();
        let (cfg, led) = paths(dir.path());

        // Write the harness config exactly as a prior install would have, but
        // leave the ledger empty.
        let prior_value = mcp_servers_value(&stdio_spec("github", "myapp"));
        let mut root = serde_json::Map::new();
        let mut servers = serde_json::Map::new();
        servers.insert("github".into(), prior_value);
        root.insert("mcpServers".into(), Value::Object(servers));
        std::fs::write(
            &cfg,
            serde_json::to_vec_pretty(&Value::Object(root)).unwrap(),
        )
        .unwrap();
        assert!(!led.exists());

        // Plain install must refuse — config present, ledger missing.
        let plain_err = install(
            &cfg,
            &led,
            &stdio_spec("github", "myapp"),
            &["mcpServers"],
            mcp_servers_value,
            ConfigFormat::Json,
        )
        .unwrap_err();
        assert!(matches!(
            plain_err,
            AgentConfigError::NotOwnedByCaller { actual: None, .. }
        ));

        // Adoption succeeds: ledger entry written, owner recorded.
        let adopt_spec = McpSpec::builder("github")
            .owner("myapp")
            .stdio("npx", ["-y", "@example/server"])
            .env("FOO", "bar")
            .adopt_unowned(true)
            .build();
        install(
            &cfg,
            &led,
            &adopt_spec,
            &["mcpServers"],
            mcp_servers_value,
            ConfigFormat::Json,
        )
        .unwrap();

        assert_eq!(
            ownership::owner_of(&led, "github").unwrap().as_deref(),
            Some("myapp")
        );

        // Subsequent normal install (no adopt flag) is now idempotent.
        let r = install(
            &cfg,
            &led,
            &stdio_spec("github", "myapp"),
            &["mcpServers"],
            mcp_servers_value,
            ConfigFormat::Json,
        )
        .unwrap();
        assert!(r.already_installed);
    }

    #[test]
    fn install_with_adopt_unowned_still_refuses_owner_mismatch() {
        let dir = tempdir().unwrap();
        let (cfg, led) = paths(dir.path());

        // Pre-populate ledger with a different owner.
        install(
            &cfg,
            &led,
            &stdio_spec("github", "other-owner"),
            &["mcpServers"],
            mcp_servers_value,
            ConfigFormat::Json,
        )
        .unwrap();

        let adopt_spec = McpSpec::builder("github")
            .owner("myapp")
            .stdio("npx", ["-y", "@example/server"])
            .env("FOO", "bar")
            .adopt_unowned(true)
            .build();
        let err = install(
            &cfg,
            &led,
            &adopt_spec,
            &["mcpServers"],
            mcp_servers_value,
            ConfigFormat::Json,
        )
        .unwrap_err();
        assert!(matches!(
            err,
            AgentConfigError::NotOwnedByCaller {
                actual: Some(_),
                ..
            }
        ));
    }

    #[test]
    fn uninstall_refuses_hand_installed_entry() {
        let dir = tempdir().unwrap();
        let (cfg, led) = paths(dir.path());
        std::fs::write(
            &cfg,
            r#"{ "mcp": { "user": { "type": "remote", "url": "x" } } }"#,
        )
        .unwrap();
        let err = uninstall(
            &cfg,
            &led,
            "user",
            "myapp",
            "mcp server",
            &["mcp"],
            ConfigFormat::Json,
        )
        .unwrap_err();
        assert!(matches!(
            err,
            AgentConfigError::NotOwnedByCaller { actual: None, .. }
        ));
    }

    #[test]
    fn uninstall_succeeds_after_sibling_install_does_not_trigger_drift() {
        let dir = tempdir().unwrap();
        let (cfg, led) = paths(dir.path());
        install(
            &cfg,
            &led,
            &stdio_spec("alpha", "app-a"),
            &["mcpServers"],
            mcp_servers_value,
            ConfigFormat::Json,
        )
        .unwrap();
        install(
            &cfg,
            &led,
            &stdio_spec("beta", "app-b"),
            &["mcpServers"],
            mcp_servers_value,
            ConfigFormat::Json,
        )
        .unwrap();

        let report = uninstall(
            &cfg,
            &led,
            "alpha",
            "app-a",
            "mcp server",
            &["mcpServers"],
            ConfigFormat::Json,
        )
        .unwrap();

        assert_eq!(report.patched, vec![cfg.clone()]);
        let v: Value = serde_json::from_slice(&std::fs::read(&cfg).unwrap()).unwrap();
        assert!(v["mcpServers"].get("alpha").is_none());
        assert_eq!(v["mcpServers"]["beta"]["command"], json!("npx"));
        assert!(!ownership::contains(&led, "alpha").unwrap());
        assert!(ownership::contains(&led, "beta").unwrap());
    }

    #[test]
    fn uninstall_refuses_when_entry_was_edited() {
        let dir = tempdir().unwrap();
        let (cfg, led) = paths(dir.path());
        install(
            &cfg,
            &led,
            &stdio_spec("alpha", "app-a"),
            &["mcpServers"],
            mcp_servers_value,
            ConfigFormat::Json,
        )
        .unwrap();

        let mut v: Value = serde_json::from_slice(&std::fs::read(&cfg).unwrap()).unwrap();
        v["mcpServers"]["alpha"]["command"] = json!("uvx");
        std::fs::write(&cfg, json_patch::to_pretty(&v)).unwrap();

        let err = uninstall(
            &cfg,
            &led,
            "alpha",
            "app-a",
            "mcp server",
            &["mcpServers"],
            ConfigFormat::Json,
        )
        .unwrap_err();

        assert!(matches!(err, AgentConfigError::ConfigDrifted { .. }));
        let v: Value = serde_json::from_slice(&std::fs::read(&cfg).unwrap()).unwrap();
        assert_eq!(v["mcpServers"]["alpha"]["command"], json!("uvx"));
        assert!(ownership::contains(&led, "alpha").unwrap());
    }
}