Repository navigation
[AI-1225] MCP auto-config foundation: canonical server list + generic MCP config writer #282
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
alexeyzimarev
merged 10 commits into
main
from
tonyyoung/ai-1225-mcp-autoconfig-foundation
Jul 7, 2026
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
03052a3
feat(mcp): canonical kcap MCP server list; Codex consumes it
realtonyyoung 8fa1a8d
feat(mcp): per-harness MCP config shape descriptor
realtonyyoung e65bf0a
feat(mcp): ownership sidecar marker (user-scope + central-state)
realtonyyoung bb773d5
fix(mcp): McpMarker.Owns must not throw on non-string array command
realtonyyoung 6ff4b9e
feat(mcp): generic non-destructive JSON MCP config writer
realtonyyoung b8c8702
fix(mcp): JsonMcpConfigWriter.Register self-heals stale owned entries…
realtonyyoung ab95f42
test(mcp): anti-drift contract — bundled configs match canonical list
realtonyyoung e3b3edb
fix(mcp): McpMarker — validate marker config/harness, guard Owns on n…
realtonyyoung 40dc40f
fix(mcp): normalize marker config identity via Path.GetFullPath
realtonyyoung 215932f
fix(mcp): per-config user-scope marker sidecar (no same-dir record co…
realtonyyoung File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| using System.Text.Json; | ||
| using System.Text.Json.Nodes; | ||
|
|
||
| namespace Capacitor.Cli.Core.Mcp; | ||
|
|
||
| /// <summary> | ||
| /// Read-modify-write engine for a harness's JSON MCP config file. Mirrors | ||
| /// <c>CodexConfigToml</c>: fail-closed on a malformed/wrong-type file (never clobber), | ||
| /// non-destructive (preserves user servers + surrounding config), idempotent, atomic. | ||
| /// Uses the JsonNode DOM — reflection-free and AOT-safe. | ||
| /// </summary> | ||
| public static class JsonMcpConfigWriter { | ||
| static readonly Lock _writeLock = new(); | ||
| static readonly JsonSerializerOptions WriteOpts = new() { WriteIndented = true }; | ||
|
|
||
| public enum Change { Unchanged, Updated, Failed } | ||
|
|
||
| public static Change Register(string configPath, IReadOnlyList<KcapMcpServer> servers, | ||
| McpConfigShape shape, string? cwd, IMcpMarker marker) => | ||
| Update(configPath, root => { | ||
| var block = GetOrAddObject(root, shape.BlockKey); // throws on wrong-type → Failed | ||
| var changed = false; | ||
| var written = new List<string>(); | ||
|
|
||
| foreach (var s in servers) { | ||
| var rendered = RenderEntry(s, shape, cwd); | ||
| if (block[s.Name] is JsonNode existing) { | ||
| if (!marker.Owns(configPath, s.Name, existing)) continue; // user look-alike — never clobber | ||
| written.Add(s.Name); // kcap-owned → keep recorded | ||
| if (JsonNode.DeepEquals(existing, rendered)) continue; // identical → idempotent no-op | ||
| block[s.Name] = rendered; // stale/old shape → heal to canonical | ||
| changed = true; | ||
| continue; | ||
| } | ||
| block[s.Name] = rendered; // missing → add | ||
| written.Add(s.Name); | ||
| changed = true; | ||
| } | ||
|
|
||
| if (changed) marker.Record(configPath, written); | ||
| return changed; | ||
| }); | ||
|
|
||
| public static Change Unregister(string configPath, McpConfigShape shape, IMcpMarker marker) => | ||
| Update(configPath, root => { | ||
| if (root[shape.BlockKey] is not JsonObject block) return false; | ||
| var changed = false; | ||
|
|
||
| foreach (var name in marker.Owned(configPath).ToArray()) | ||
| if (block[name] is JsonNode entry && marker.Owns(configPath, name, entry) && block.Remove(name)) | ||
| changed = true; | ||
|
|
||
| if (block.Count == 0 && root.Remove(shape.BlockKey)) changed = true; | ||
| if (changed) marker.Clear(configPath); | ||
| return changed; | ||
| }); | ||
|
|
||
| static JsonObject RenderEntry(KcapMcpServer s, McpConfigShape shape, string? cwd) { | ||
| var o = new JsonObject(); | ||
| if (shape.TypeValue is not null) o["type"] = shape.TypeValue; | ||
|
|
||
| if (shape.CommandAsArgvArray) { | ||
| // Use the implicit string -> JsonValue conversion (cast to JsonNode?) rather | ||
| // than JsonValue.Create / collection expressions, which lower to generic | ||
| // Add<T> and trip NativeAOT (IL3050). Matches ReviewLaunchBuilder's pattern. | ||
| var argv = new JsonArray(); | ||
| argv.Add((JsonNode?)KcapMcpServers.Command); | ||
| foreach (var a in s.Args) argv.Add((JsonNode?)a); | ||
| o["command"] = argv; | ||
| } else { | ||
| o["command"] = KcapMcpServers.Command; | ||
| var args = new JsonArray(); | ||
| foreach (var a in s.Args) args.Add((JsonNode?)a); | ||
| o["args"] = args; | ||
| } | ||
|
|
||
| if (cwd is not null && s.NeedsProjectCwd) o["cwd"] = cwd; | ||
| if (shape.Enable == EnableStyle.EnabledTrue) o["enabled"] = true; | ||
| return o; | ||
| } | ||
|
|
||
| static Change Update(string configPath, Func<JsonObject, bool> mutate) { | ||
| lock (_writeLock) { | ||
| JsonObject root; | ||
|
|
||
| if (File.Exists(configPath)) { | ||
| try { | ||
| var parsed = JsonNode.Parse(File.ReadAllText(configPath)); | ||
| if (parsed is not JsonObject obj) return Change.Failed; // wrong top-level type | ||
| root = obj; | ||
| } catch { | ||
| return Change.Failed; // malformed — never clobber | ||
| } | ||
| } else { | ||
| root = new JsonObject(); | ||
| } | ||
|
|
||
| bool changed; | ||
| try { changed = mutate(root); } | ||
| catch { return Change.Failed; } // e.g. wrong-type block | ||
|
|
||
| if (!changed) return Change.Unchanged; | ||
|
|
||
| try { | ||
| var dir = Path.GetDirectoryName(configPath); | ||
| if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); | ||
| WriteAtomic(configPath, root); | ||
| return Change.Updated; | ||
| } catch { return Change.Failed; } | ||
| } | ||
| } | ||
|
|
||
| static JsonObject GetOrAddObject(JsonObject parent, string key) { | ||
| if (parent.TryGetPropertyValue(key, out var v)) { | ||
| if (v is JsonObject obj) return obj; | ||
| throw new InvalidOperationException($"`{key}` is present but not an object; refusing to overwrite."); | ||
| } | ||
| var created = new JsonObject(); | ||
| parent[key] = created; | ||
| return created; | ||
| } | ||
|
|
||
| static void WriteAtomic(string path, JsonNode root) { | ||
| var tmp = path + ".tmp-" + Environment.ProcessId + "-" + Guid.NewGuid().ToString("N"); | ||
| File.WriteAllText(tmp, root.ToJsonString(WriteOpts)); | ||
| try { File.Move(tmp, path, overwrite: true); } | ||
| catch { try { File.Delete(tmp); } catch { /* best-effort */ } throw; } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| namespace Capacitor.Cli.Core.Mcp; | ||
|
|
||
| /// <summary>One kcap MCP server, described semantically (no harness field names).</summary> | ||
| public sealed record KcapMcpServer(string Name, string[] Args, bool NeedsProjectCwd, string? Description); | ||
|
|
||
| /// <summary>The single source of truth for the kcap MCP servers. Every writer | ||
| /// (Codex TOML, the JSON harnesses, the bundled `.mcp.json`) derives from this.</summary> | ||
| public static class KcapMcpServers { | ||
| public const string Command = "kcap"; | ||
|
|
||
| public static readonly IReadOnlyList<KcapMcpServer> All = [ | ||
| new("kcap-review", ["mcp", "review"], NeedsProjectCwd: false, | ||
| "PR review context tools — query implementation session transcripts."), | ||
| new("kcap-sessions", ["mcp", "sessions"], NeedsProjectCwd: true, null), | ||
| new("kcap-flows", ["mcp", "flows"], NeedsProjectCwd: true, | ||
| "Structured AI agent flows — launches a SEPARATE hosted participant agent; requires login + a running daemon."), | ||
| new("kcap-memory", ["mcp", "memory"], NeedsProjectCwd: true, | ||
| "Team memory — search, read, and save durable learnings."), | ||
| ]; | ||
|
|
||
| /// <summary>Codex omits `kcap-flows` (AI-1056: paid hosted reviewer, Claude-only).</summary> | ||
| public static IReadOnlyList<KcapMcpServer> ForCodex => | ||
| All.Where(s => s.Name != "kcap-flows").ToArray(); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| namespace Capacitor.Cli.Core.Mcp; | ||
|
|
||
| public enum EnableStyle { None, EnabledTrue } | ||
|
|
||
| /// <summary>How one harness renders an MCP server entry. The canonical | ||
| /// <see cref="KcapMcpServer"/> is field-name-agnostic; this maps it to a host's on-disk shape.</summary> | ||
| public sealed record McpConfigShape( | ||
| string BlockKey, // "mcpServers" (most) or "mcp" (OpenCode) | ||
| bool CommandAsArgvArray, // OpenCode: command = ["kcap","mcp","review"]; else command="kcap" + args=[...] | ||
| string? TypeValue, // "stdio" (Copilot), "local" (OpenCode), or null | ||
| string EnvKey, // "env" (most) or "environment" (OpenCode) — reserved for future env support | ||
| EnableStyle Enable // OpenCode wants "enabled": true | ||
| ) { | ||
| // Cursor / Gemini / Kiro / Antigravity all share the plain shape. | ||
| public static readonly McpConfigShape Standard = new("mcpServers", CommandAsArgvArray: false, TypeValue: null, EnvKey: "env", Enable: EnableStyle.None); | ||
| public static readonly McpConfigShape Copilot = new("mcpServers", CommandAsArgvArray: false, TypeValue: "stdio", EnvKey: "env", Enable: EnableStyle.None); | ||
| public static readonly McpConfigShape OpenCode = new("mcp", CommandAsArgvArray: true, TypeValue: "local", EnvKey: "environment", Enable: EnableStyle.EnabledTrue); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| using System.Security.Cryptography; | ||
| using System.Text; | ||
| using System.Text.Json; | ||
| using System.Text.Json.Nodes; | ||
|
|
||
| namespace Capacitor.Cli.Core.Mcp; | ||
|
|
||
| public interface IMcpMarker { | ||
| /// <summary>True if `entry` under `name` is a kcap-owned registration (name recorded in the marker | ||
| /// AND command == "kcap"), so overwrite/unregister may touch it. A user look-alike returns false.</summary> | ||
| bool Owns(string configPath, string name, JsonNode entry); | ||
| void Record(string configPath, IReadOnlyList<string> names); | ||
| IEnumerable<string> Owned(string configPath); | ||
| void Clear(string configPath); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Sidecar marker recording which `kcap-*` keys kcap wrote into a given config file. | ||
| /// Lives OUTSIDE the host MCP file (so it never alters the host's accepted schema): | ||
| /// - user-scope config → `.kcap-mcp-version` next to the config file; | ||
| /// - otherwise (project-scope / central) → `~/.kcap/mcp-markers/<harness>-<hash(abs path)>.json`. | ||
| /// The `markerPathFor` override lets tests point both cases at a temp dir. | ||
| /// </summary> | ||
| public sealed class McpMarker(string harness, Func<string, string>? markerPathFor = null) : IMcpMarker { | ||
| const int Version = 1; | ||
|
|
||
| public bool Owns(string configPath, string name, JsonNode entry) { | ||
| if (!Owned(configPath).Contains(name)) return false; | ||
| if (entry is not JsonObject obj) return false; // malformed/non-object entry → not ours; never throw | ||
| var cmd = obj["command"]; | ||
| return cmd is JsonValue v && v.TryGetValue(out string? s) && s == KcapMcpServers.Command | ||
| || cmd is JsonArray a && a.Count > 0 && a[0] is JsonValue fv && fv.TryGetValue(out string? fs) && fs == KcapMcpServers.Command; | ||
| } | ||
|
|
||
| public void Record(string configPath, IReadOnlyList<string> names) { | ||
| var path = MarkerPath(configPath); | ||
| var existing = ReadNames(path, configPath); | ||
| foreach (var n in names) existing.Add(n); | ||
| var doc = new JsonObject { | ||
| ["version"] = Version, | ||
| ["harness"] = harness, | ||
| ["config"] = Path.GetFullPath(configPath), | ||
| ["servers"] = new JsonArray(existing.Select(n => (JsonNode)n!).ToArray()) | ||
| }; | ||
| var dir = Path.GetDirectoryName(path); | ||
| if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); | ||
| File.WriteAllText(path, doc.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); | ||
| } | ||
|
|
||
| public IEnumerable<string> Owned(string configPath) => ReadNames(MarkerPath(configPath), configPath); | ||
|
|
||
| public void Clear(string configPath) { | ||
| var p = MarkerPath(configPath); | ||
| try { if (File.Exists(p)) File.Delete(p); } catch { /* best-effort */ } | ||
| } | ||
|
|
||
| HashSet<string> ReadNames(string markerPath, string configPath) { | ||
| try { | ||
| if (!File.Exists(markerPath)) return []; | ||
| if (JsonNode.Parse(File.ReadAllText(markerPath)) is not JsonObject root) return []; | ||
| // A user-scope sidecar is per-directory and could be shared; only trust a marker | ||
| // that pertains to THIS harness + config path (else treat as not-ours → preserve). | ||
| if ((string?)root["harness"] != harness) return []; | ||
| if ((string?)root["config"] != Path.GetFullPath(configPath)) return []; | ||
| return root["servers"] is JsonArray arr ? [.. arr.Select(n => (string)n!)] : []; | ||
| } catch { return []; } | ||
| } | ||
|
|
||
| string MarkerPath(string configPath) { | ||
| if (markerPathFor is not null) return markerPathFor(configPath); | ||
| // Heuristic: a config under the user's home harness dir → sidecar; else central state. | ||
| var dir = Path.GetDirectoryName(Path.GetFullPath(configPath))!; | ||
| var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); | ||
| var isUserScope = dir.StartsWith(home, StringComparison.Ordinal) | ||
| && !IsInsideRepo(dir); | ||
| // Per-config sidecar (include the config file name) so multiple configs sharing a | ||
| // directory never overwrite each other's ownership record. | ||
| if (isUserScope) return Path.Combine(dir, $".kcap-mcp-version-{Path.GetFileName(configPath)}"); | ||
|
|
||
| var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(Path.GetFullPath(configPath))))[..16].ToLowerInvariant(); | ||
| return Path.Combine(home, ".kcap", "mcp-markers", $"{harness}-{hash}.json"); | ||
| } | ||
|
|
||
| static bool IsInsideRepo(string dir) { | ||
| for (var cur = new DirectoryInfo(dir); cur is not null; cur = cur.Parent) { | ||
| var git = Path.Combine(cur.FullName, ".git"); | ||
| if (Directory.Exists(git) || File.Exists(git)) return true; // .git is a file in worktrees/submodules | ||
| } | ||
| return false; | ||
| } | ||
|
qodo-code-review[bot] marked this conversation as resolved.
Resolved
|
||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.