Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 9 additions & 26 deletions src/Capacitor.Cli.Core/CodexConfigToml.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Capacitor.Cli.Core.Mcp;
using Tomlyn;
using Tomlyn.Model;
using Tomlyn.Serialization;
Expand All @@ -24,23 +25,6 @@ public enum Change { Unchanged, Updated, Failed }

static string DefaultConfigPath => Path.Combine(CodexPaths.Home(), "config.toml");

/// <summary>
/// The kcap MCP servers auto-registered for Codex CLI in <c>~/.codex/config.toml</c>.
/// Codex reads MCP servers from the snake_case <c>[mcp_servers]</c> TOML table — note
/// this is NOT the camelCase <c>mcpServers</c> key used by the Claude/Codex plugin
/// *descriptor* JSON. <c>kcap-flows</c> is intentionally excluded: it launches a paid
/// hosted reviewer and stays Claude-only (AI-1056). <c>kcap-memory</c> IS included
/// (AI-1146): it is a free, harness-agnostic team-memory server, so Codex users going
/// through <c>kcap setup</c> get it alongside review/sessions.
/// </summary>
static readonly (string Name, string[] Args)[] KcapMcpServers = [
("kcap-review", ["mcp", "review"]),
("kcap-sessions", ["mcp", "sessions"]),
("kcap-memory", ["mcp", "memory"])
];

const string McpServerCommand = "kcap";

/// <summary>
/// AI-794 — enable network access for Codex's <c>workspace-write</c> sandbox so
/// kcap skills (which shell out to <c>kcap …</c>) can reach the Capacitor server.
Expand Down Expand Up @@ -260,18 +244,17 @@ static bool MutateRegisterMcpServers(TomlTable root) {
var servers = GetOrAddTable(root, "mcp_servers");
var changed = false;

foreach (var (name, args) in KcapMcpServers) {
foreach (var server in KcapMcpServers.ForCodex) {
// Never clobber an existing entry: a prior kcap registration is already
// correct, and a user may have customized it (e.g. an absolute-path command
// for a GUI host). Only create the server when it's missing entirely.
if (servers.ContainsKey(name)) continue;
if (servers.ContainsKey(server.Name)) continue;

var entry = new TomlTable {
["command"] = McpServerCommand,
["args"] = ToTomlArray(args)
servers[server.Name] = new TomlTable {
["command"] = KcapMcpServers.Command,
["args"] = ToTomlArray(server.Args)
};
servers[name] = entry;
changed = true;
changed = true;
}

return changed;
Expand All @@ -282,8 +265,8 @@ static bool MutateUnregisterMcpServers(TomlTable root) {

var changed = false;

foreach (var (name, _) in KcapMcpServers)
if (servers.Remove(name)) changed = true;
foreach (var server in KcapMcpServers.ForCodex)
if (servers.Remove(server.Name)) changed = true;

// Don't leave a bare [mcp_servers] behind if we emptied it.
if (servers.Count == 0 && root.Remove("mcp_servers")) changed = true;
Expand Down
129 changes: 129 additions & 0 deletions src/Capacitor.Cli.Core/Mcp/JsonMcpConfigWriter.cs
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; }
}
}
24 changes: 24 additions & 0 deletions src/Capacitor.Cli.Core/Mcp/KcapMcpServers.cs
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();
}
18 changes: 18 additions & 0 deletions src/Capacitor.Cli.Core/Mcp/McpConfigShape.cs
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);
}
91 changes: 91 additions & 0 deletions src/Capacitor.Cli.Core/Mcp/McpMarker.cs
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/&lt;harness&gt;-&lt;hash(abs path)&gt;.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;
}
Comment thread
qodo-code-review[bot] marked this conversation as resolved.
Resolved

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;
}
Comment thread
qodo-code-review[bot] marked this conversation as resolved.
Resolved
}
Loading
Loading