Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

feat(mcp): user-level ~/.codegraff/mcp.json merged with project .mcp.json (#345)

Rach Pradhan62c77c53fedf
diff --git a/assets/skills/mcp-config.md b/assets/skills/mcp-config.md
index 6470faf8..05aaf54d 100644
--- a/assets/skills/mcp-config.md
+++ b/assets/skills/mcp-config.md
@@ -1,12 +1,15 @@
---
name: mcp-config
-description: Inspect or change this workspace's MCP servers - use when adding, removing, or authenticating an MCP server, when MCP tools are missing or a server did not connect, or when the user asks how MCP config works here.
+description: Inspect or change this workspace's MCP servers, or the user-level global ones - use when adding, removing, or authenticating an MCP server, when MCP tools are missing or a server did not connect, or when the user asks how MCP config works here.
---
# MCP configuration
-MCP servers are configured per workspace in `.mcp.json` at the project root.
-Their tools reach the model as `mcp__<server>__<tool>`.
+MCP servers are configured per workspace in `.mcp.json` at the project root, and
+per user in `~/.codegraff/mcp.json` for the servers you want in every project.
+The two files use the same schema and are merged; a project entry wins over a
+global one with the same name. Their tools reach the model as
+`mcp__<server>__<tool>`.
## The file
@@ -34,13 +37,15 @@ Their tools reach the model as `mcp__<server>__<tool>`.
localhost, and `headers` is for static tokens.
- `smolify` is a reserved core server; a workspace entry cannot shadow its
pinned endpoint.
-- Invalid JSON means zero servers load, quietly. If tools vanished after an
- edit, check the file parses first.
+- Invalid JSON in one file means zero servers load from THAT file; the other one
+ still loads. If tools vanished after an edit, check the file parses first.
+- `~/.mcpconfig.json` is not read - that path belongs to other MCP clients.
+ Startup says so once if it exists.
## Prefer the CLI for writes
```sh
-graff mcp # list configured servers
+graff mcp # list configured servers (global ones tagged)
graff mcp add <name> -- <command> [args...] # local server
graff mcp add <name> --env KEY=VALUE -- <command> # with env
graff mcp add <name> --url https://host/mcp # remote server
@@ -48,7 +53,9 @@ graff mcp add <name> --url https://host/mcp --header KEY=VALUE
graff mcp login <name> # OAuth for a remote server
```
-Editing `.mcp.json` with `edit_file` or `write_file` is equally valid, and it is
+`graff mcp add` and `/mcp add` always write the project `.mcp.json`, never the
+global file - adding a server to one repository must not edit every other one.
+Editing either file with `edit_file` or `write_file` is equally valid, and it is
how you remove a server (drop its key) or rename one. Do not commit a secret
into it: prefer `graff mcp login` (OAuth credentials are stored outside the
repo) or a token the user supplies at runtime.
@@ -59,13 +66,15 @@ repo) or a token the user supplies at runtime.
pending consent
- `/mcp add <name> <command> [args...]` and `/mcp add <name> --url <URL>` -
connect one live and persist it
-- `/mcp trust` - connect the workspace servers that were skipped at startup
+- `/mcp trust` - connect the servers that were skipped at startup, project and
+ global alike
## When a server is not connected
-A workspace `.mcp.json` launches arbitrary local commands, so graff never
-auto-spawns untrusted entries: it asks at startup, and without consent (or
-`--yolo`) it starts with an empty but live registry. `/mcp trust` is the
+Either config file launches arbitrary local commands, so graff never auto-spawns
+untrusted entries: it asks at startup, and without consent (or `--yolo`) it
+starts with an empty but live registry. A global entry gets no extra trust for
+being global - it just follows you into every project. `/mcp trust` is the
in-session fix and `/mcp` shows what is pending. Remote servers pass the same
gate, because their arguments leave the machine.
diff --git a/src/commands_misc.zig b/src/commands_misc.zig
index 6cee17ee..3a7206f1 100644
--- a/src/commands_misc.zig
+++ b/src/commands_misc.zig
@@ -277,21 +277,22 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
return true;
}
if (std.mem.eql(u8, arg, "trust")) {
- // Connect workspace .mcp.json servers that were skipped at startup
- // (consent declined / no --yolo), live, without a restart.
+ // Connect the .mcp.json / ~/.codegraff/mcp.json servers that were
+ // skipped at startup (consent declined / no --yolo), live, without
+ // a restart.
const n = reg.trustWorkspace(mcp_config_path) catch |err| {
try out.print("{s}✗ /mcp trust failed: {t}{s}\n", .{ style.red, err, style.reset });
try out.flush();
return true;
};
if (n == 0) {
- try out.writeAll("no untrusted workspace MCP server(s) to connect.\n");
+ try out.writeAll("no untrusted MCP server(s) left to connect.\n");
} else {
// Re-render the active catalog; other wire formats remain lazy.
root.invalidateRootTools();
try root.ensureRootTools(root.provider.kind);
root.rebaseContextMeter();
- try out.print("{s}✓{s} trusted workspace — connected {d} MCP server(s); {d} tool(s) total\n", .{ style.green, style.reset, n, reg.tools.len });
+ try out.print("{s}✓{s} trusted the configured servers — connected {d} MCP server(s); {d} tool(s) total\n", .{ style.green, style.reset, n, reg.tools.len });
}
try out.flush();
return true;
@@ -308,7 +309,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
for (reg.tools) |t| try out.print(" {s}{s}{s}\n", .{ style.dim, t.qualified_name, style.reset });
try out.writeAll(" add more: /mcp add <name> <command> [args...]\n");
}
- if (pending > 0) try out.print(" {s}{d} workspace server(s) not connected — /mcp trust to connect them{s}\n", .{ style.dim, pending, style.reset });
+ if (pending > 0) try out.print(" {s}{d} configured server(s) not connected — /mcp trust to connect them{s}\n", .{ style.dim, pending, style.reset });
try out.flush();
return true;
}
diff --git a/src/mcp.zig b/src/mcp.zig
index 7490f926..fdec3ff9 100644
--- a/src/mcp.zig
+++ b/src/mcp.zig
@@ -1,9 +1,11 @@
//! Minimal MCP (Model Context Protocol) client over stdio and Streamable HTTP.
//!
-//! A .mcp.json entry may contain either `command`/`args` (a child process using
-//! newline-delimited JSON-RPC on stdio) or `url` (JSON-RPC POSTs using MCP's
-//! Streamable HTTP transport). Both run the initialize -> initialized ->
-//! tools/list handshake and expose discovered tools to the agent.
+//! A config entry — from the workspace `.mcp.json`, from the user-level
+//! `~/.codegraff/mcp.json`, or from the two merged (mcp_config.zig) — may
+//! contain either `command`/`args` (a child process using newline-delimited
+//! JSON-RPC on stdio) or `url` (JSON-RPC POSTs using MCP's Streamable HTTP
+//! transport). Both run the initialize -> initialized -> tools/list handshake
+//! and expose discovered tools to the agent.
//!
//! Concurrency: tool calls arrive from agent pool threads, but transport state
//! (stdio pipes, HTTP session IDs) is sequential, so every request/response
@@ -14,6 +16,7 @@ const std = @import("std");
const Io = std.Io;
const Value = std.json.Value;
const Allocator = std.mem.Allocator;
+const mcp_config = @import("mcp_config.zig"); // #345: .mcp.json merged with the user-level ~/.codegraff/mcp.json
const mcp_http = @import("mcp_http.zig");
const mcp_protocol = @import("mcp_protocol.zig");
const mcp_stdio = @import("mcp_stdio.zig");
@@ -71,45 +74,56 @@ pub const Registry = struct {
/// the provider, so the same per-turn handoff refreshes it; false until it
/// does, so a result explains the drop rather than promising an attachment.
vision_capable: bool = false,
+ /// Resolved user-level MCP config (`~/.codegraff/mcp.json` or the
+ /// `GRAFF_MCP_CONFIG` override), borrowed from the caller. Null when there
+ /// is no global config. Kept on the registry because `/mcp trust` re-reads
+ /// it mid-session — including on the consent-declined path, where the
+ /// registry came from `empty*` and `init` never ran, so session_start sets
+ /// this field either way.
+ global_config_path: ?[]const u8 = null,
pub fn arena(self: *Registry) Allocator {
return self.arena_state.allocator();
}
- /// Load .mcp.json entries containing either `command`/`args`/`env` or a
- /// Streamable HTTP `url`, handshake each server, and collect their tools.
- /// Returns null
- /// (no error) when the config file is absent — MCP is optional.
- pub fn init(gpa: Allocator, io: Io, config_path: []const u8, home: []const u8, environ_map: anytype) !?Registry {
- const text = Io.Dir.cwd().readFileAlloc(io, config_path, gpa, .limited(1 << 20)) catch |err| switch (err) {
- error.FileNotFound => return null,
- else => return err,
- };
- defer gpa.free(text);
-
+ /// Load the workspace `.mcp.json` merged with the user-level global config
+ /// at `global_path` (see mcp_config.zig; project entries win on a name
+ /// clash), where an entry holds either `command`/`args`/`env` or a
+ /// Streamable HTTP `url`; handshake each server and collect their tools.
+ /// Returns null (no error) when NEITHER file exists — MCP is optional.
+ /// `global_path` is borrowed, not copied: it must outlive the registry,
+ /// which re-reads it on `/mcp trust`.
+ pub fn init(gpa: Allocator, io: Io, config_path: []const u8, global_path: ?[]const u8, home: []const u8, environ_map: anytype) !?Registry {
var reg: Registry = .{
.gpa = gpa,
.io = io,
.home = home,
.arena_state = std.heap.ArenaAllocator.init(gpa),
.stdio_probe = if (environ_map.get("GRAFF_MCP_PROBE")) |v| !std.mem.eql(u8, v, "0") else true,
+ .global_config_path = global_path,
};
mcp_rpc.applyHandshakeTimeoutEnv(environ_map); // #275: GRAFF_MCP_HANDSHAKE_SECS, read on the same pass as the probe flag
errdefer reg.deinit();
const a = reg.arena();
- const parsed = try std.json.parseFromSliceLeaky(Value, a, text, .{ .allocate = .alloc_always });
- const servers_obj = (parsed.object.get("mcpServers") orelse return reg).object;
-
+ const merged = mcp_config.load(io, a, Io.Dir.cwd(), config_path, global_path);
+ if (!merged.found) {
+ reg.arena_state.deinit(); // nothing was started; no transports to tear down
+ return null;
+ }
+ // An unparseable file contributes nothing and does not take the other
+ // half down. Naming it is session_start's job, not this one's: it runs
+ // on the consent-declined path too, where `init` is never reached.
var servers: std.ArrayList(*Server) = .empty;
var tools: std.ArrayList(Tool) = .empty;
- var it = servers_obj.iterator();
+ var it = merged.servers.iterator();
while (it.next()) |entry| {
// The core Smolify name is pinned below and cannot be shadowed by
- // repository configuration.
+ // repository or user configuration.
if (std.mem.eql(u8, entry.key_ptr.*, "smolify")) continue;
+ if (entry.value_ptr.* != .object) continue;
const name = try a.dupe(u8, entry.key_ptr.*);
const cfg = entry.value_ptr.*.object;
reg.startServer(a, &servers, &tools, name, cfg) catch |err| {
@@ -218,24 +232,19 @@ pub const Registry = struct {
return added;
}
- /// Connect any workspace `.mcp.json` servers not already running — the
- /// in-session equivalent of having started with `--yolo`, so a user who
- /// declined the startup consent prompt can opt in later without a restart.
- /// Replays the `init` connect path (so per-server `env` is preserved, which
- /// `addServer` drops), skipping servers already in the registry by name
- /// (idempotent: won't double-spawn an auto-activated muonry). Returns the
- /// number of servers newly connected. Caller must re-render its tool list.
- /// Run between turns only (no tool calls in flight).
+ /// Connect any configured server not already running — the in-session
+ /// equivalent of having started with `--yolo`, so a user who declined the
+ /// startup consent prompt can opt in later without a restart. Reads the
+ /// same merged project + global set `init` does, so a `~/.codegraff/mcp.json`
+ /// entry is trusted here too. Replays the `init` connect path (so
+ /// per-server `env` is preserved, which `addServer` drops), skipping
+ /// servers already in the registry by name (idempotent: won't double-spawn
+ /// an auto-activated muonry). Returns the number of servers newly
+ /// connected. Caller must re-render its tool list. Run between turns only
+ /// (no tool calls in flight).
pub fn trustWorkspace(reg: *Registry, config_path: []const u8) !usize {
const a = reg.arena();
- const text = Io.Dir.cwd().readFileAlloc(reg.io, config_path, a, .limited(1 << 20)) catch |err| switch (err) {
- error.FileNotFound => return 0,
- else => return err,
- };
- const parsed = try std.json.parseFromSliceLeaky(Value, a, text, .{ .allocate = .alloc_always });
- if (parsed != .object) return 0;
- const servers_v = parsed.object.get("mcpServers") orelse return 0;
- if (servers_v != .object) return 0;
+ const merged = mcp_config.load(reg.io, a, Io.Dir.cwd(), config_path, reg.global_config_path);
var servers: std.ArrayList(*Server) = .empty;
try servers.appendSlice(a, reg.servers);
@@ -243,7 +252,7 @@ pub const Registry = struct {
try tools.appendSlice(a, reg.tools);
const before = servers.items.len;
- var it = servers_v.object.iterator();
+ var it = merged.servers.iterator();
while (it.next()) |entry| {
const name = entry.key_ptr.*;
if (std.mem.eql(u8, name, "smolify")) continue;
@@ -264,18 +273,15 @@ pub const Registry = struct {
return servers.items.len - before;
}
- /// How many workspace `.mcp.json` servers are NOT yet connected — drives
- /// the `/mcp trust` discoverability hint. Mirrors `trustWorkspace`'s
- /// skip-by-name logic; best-effort (any read/parse failure → 0).
+ /// How many configured MCP servers are NOT yet connected — drives the
+ /// `/mcp trust` discoverability hint. Mirrors `trustWorkspace`'s
+ /// skip-by-name logic over the same merged (project + global) set;
+ /// best-effort (any read/parse failure contributes nothing).
pub fn pendingWorkspace(reg: *Registry, config_path: []const u8) usize {
const a = reg.arena();
- const text = Io.Dir.cwd().readFileAlloc(reg.io, config_path, a, .limited(1 << 20)) catch return 0;
- const parsed = std.json.parseFromSliceLeaky(Value, a, text, .{ .allocate = .alloc_always }) catch return 0;
- if (parsed != .object) return 0;
- const servers_v = parsed.object.get("mcpServers") orelse return 0;
- if (servers_v != .object) return 0;
+ const merged = mcp_config.load(reg.io, a, Io.Dir.cwd(), config_path, reg.global_config_path);
var n: usize = 0;
- var it = servers_v.object.iterator();
+ var it = merged.servers.iterator();
while (it.next()) |entry| {
if (std.mem.eql(u8, entry.key_ptr.*, "smolify")) continue;
if (entry.value_ptr.* != .object) continue;
diff --git a/src/mcp_cli.zig b/src/mcp_cli.zig
index 8e6cafe1..5882bb53 100644
--- a/src/mcp_cli.zig
+++ b/src/mcp_cli.zig
@@ -3,6 +3,12 @@
//! MCP consent prompt. Split out of main.zig (600-line goal). Back-imports main
//! for mcp_config_path (.mcp.json) and the companion_servers allowlist. main
//! aliases countMcpServers / persistMcpServer / mcpCommand back.
+//!
+//! Reads go through mcp_config.zig, so `list`, `login` and the consent count
+//! all see the workspace file merged with the user-level
+//! `~/.codegraff/mcp.json` (#345). Writes deliberately do not: `mcp add` and
+//! the `persistMcp*` helpers still target the project .mcp.json only, so
+//! adding a server to one repository never edits every other one.
const std = @import("std");
const Io = std.Io;
@@ -12,6 +18,7 @@ const Allocator = std.mem.Allocator;
const root = @import("main.zig");
const skills = @import("skills.zig");
const mcp = @import("mcp.zig");
+const mcp_config = @import("mcp_config.zig");
const mcp_oauth = @import("mcp_oauth.zig");
const mcp_config_path = root.mcp_config_path;
const companion_servers = skills.companion_servers;
@@ -31,20 +38,19 @@ fn trustedMcpEntry(name: []const u8, cfg: Value) bool {
return a0 == .string and std.mem.eql(u8, a0.string, "--mcp");
}
-/// Count the workspace .mcp.json servers that actually need consent at
-/// startup (0 if none/missing; trusted companion entries are exempt — see
-/// trustedMcpEntry). Used to gate auto-spawning untrusted workspace servers.
-pub fn countMcpServers(io: Io, arena: Allocator) usize {
- const data = Io.Dir.cwd().readFileAlloc(io, mcp_config_path, arena, .limited(1 << 20)) catch return 0;
- const v = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return 0;
- if (v != .object) return 0;
- const servers = v.object.get("mcpServers") orelse return 0;
- if (servers != .object) return 0;
+/// Count the servers in an already-merged config that actually need consent at
+/// startup (0 if none; trusted companion entries are exempt — see
+/// trustedMcpEntry). Takes the `Merged` rather than loading it so the caller
+/// keeps the invalid-file flags it needs to report, instead of the load
+/// happening twice with the diagnosis thrown away once. A global entry is no
+/// more trusted than a workspace one: it can run local commands or ship data
+/// off-box just the same, so it is counted and gated identically.
+pub fn countMcpServers(merged: mcp_config.Merged) usize {
var n: usize = 0;
- var it = servers.object.iterator();
+ var it = merged.servers.iterator();
while (it.next()) |entry| {
- // `smolify` is a reserved core server; workspace entries cannot shadow
- // its pinned endpoint and therefore need no workspace consent.
+ // `smolify` is a reserved core server; configured entries cannot shadow
+ // its pinned endpoint and therefore need no consent.
if (std.mem.eql(u8, entry.key_ptr.*, "smolify")) continue;
if (!trustedMcpEntry(entry.key_ptr.*, entry.value_ptr.*)) n += 1;
}
@@ -138,7 +144,7 @@ pub fn persistMcpUrl(io: Io, arena: Allocator, name: []const u8, url: []const u8
fn mcpCliUsage(w: *Io.Writer) !void {
try w.writeAll(
\\usage:
- \\ graff mcp list servers in .mcp.json
+ \\ graff mcp list servers in .mcp.json + ~/.codegraff/mcp.json
\\ graff mcp add <name> --url <https://...> [--header KEY=VALUE ...]
\\ graff mcp login <name> OAuth login for a remote server
\\ graff mcp add <name> [--env KEY=VALUE ...] -- <command> [args...]
@@ -155,30 +161,20 @@ fn mcpCliUsage(w: *Io.Writer) !void {
);
}
-pub fn mcpCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, args: []const []const u8) !void {
+pub fn mcpCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, environ_map: anytype, args: []const []const u8) !void {
var obuf: [4096]u8 = undefined;
var out = Io.File.stdout().writer(io, &obuf);
+ // Reads (list/login) see project + global; writes stay project-local.
+ const global_path = mcp_config.globalPath(arena, home, environ_map);
if (args.len == 0 or std.mem.eql(u8, args[0], "list")) {
- const data = Io.Dir.cwd().readFileAlloc(io, mcp_config_path, arena, .limited(1 << 20)) catch |err| switch (err) {
- error.FileNotFound => {
- try out.interface.writeAll("no .mcp.json yet. Add one with `graff mcp add <name> -- <command> [args...]`.\n");
- try out.interface.flush();
- return;
- },
- else => return err,
- };
- const v = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch {
- try out.interface.writeAll(".mcp.json is not valid JSON.\n");
- try out.interface.flush();
- return;
- };
- const servers = if (v == .object) v.object.get("mcpServers") else null;
- if (servers == null or servers.? != .object or servers.?.object.count() == 0) {
- try out.interface.writeAll("no MCP servers configured. Add one with `graff mcp add <name> -- <command> [args...]`.\n");
+ const merged = mcp_config.load(io, arena, Io.Dir.cwd(), mcp_config_path, global_path);
+ try mcp_config.reportInvalid(merged, &out.interface, mcp_config_path, global_path, "", "");
+ if (merged.servers.count() == 0) {
+ try out.interface.writeAll("no MCP servers configured. Add one with `graff mcp add <name> -- <command> [args...]`,\nor list servers for every project in ~/" ++ mcp_config.global_rel_path ++ ".\n");
} else {
- try out.interface.print("{d} MCP server(s) in .mcp.json:\n", .{servers.?.object.count()});
- var it = servers.?.object.iterator();
+ try out.interface.print("{d} MCP server(s):\n", .{merged.servers.count()});
+ var it = merged.servers.iterator();
while (it.next()) |entry| {
const cfg = entry.value_ptr.*;
if (cfg != .object) continue;
@@ -191,6 +187,9 @@ pub fn mcpCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, ar
if (arg == .string) try out.interface.print(" {s}", .{arg.string});
};
}
+ // Only what the project does not define is tagged: an entry the
+ // workspace overrides is the workspace's, not the user's.
+ if (merged.isGlobalOnly(entry.key_ptr.*)) try out.interface.writeAll(" (global)");
try out.interface.writeByte('\n');
}
}
@@ -214,14 +213,16 @@ pub fn mcpCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, ar
const url = if (std.mem.eql(u8, name, "smolify"))
mcp.smolify_url
else url: {
- const data = Io.Dir.cwd().readFileAlloc(io, mcp_config_path, arena, .limited(1 << 20)) catch
- std.process.fatal("mcp login: no .mcp.json; add the remote server first", .{});
- const config = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch
- std.process.fatal("mcp login: .mcp.json is not valid JSON", .{});
- if (config != .object) std.process.fatal("mcp login: .mcp.json is not an object", .{});
- const servers = config.object.get("mcpServers") orelse std.process.fatal("mcp login: server '{s}' is not configured", .{name});
- if (servers != .object) std.process.fatal("mcp login: mcpServers is not an object", .{});
- const entry = servers.object.get(name) orelse std.process.fatal("mcp login: server '{s}' is not configured", .{name});
+ // Global servers are loginable too — the merged set is the same one
+ // the session connects from.
+ const merged = mcp_config.load(io, arena, Io.Dir.cwd(), mcp_config_path, global_path);
+ // Say which file is broken before claiming the server is missing:
+ // "not configured" for a server that IS configured, in a file that
+ // does not parse, sends the user looking in the wrong place.
+ try mcp_config.reportInvalid(merged, &out.interface, mcp_config_path, global_path, "", "");
+ try out.interface.flush();
+ if (!merged.found) std.process.fatal("mcp login: no MCP config; add the remote server first", .{});
+ const entry = merged.servers.get(name) orelse std.process.fatal("mcp login: server '{s}' is not configured", .{name});
if (entry != .object) std.process.fatal("mcp login: server '{s}' has invalid config", .{name});
const remote = entry.object.get("url") orelse std.process.fatal("mcp login: server '{s}' is not a remote URL server", .{name});
if (remote != .string or !mcp.validRemoteUrl(remote.string)) std.process.fatal("mcp login: server '{s}' has an invalid URL", .{name});
diff --git a/src/mcp_config.zig b/src/mcp_config.zig
new file mode 100644
index 00000000..6c44d37d
--- /dev/null
+++ b/src/mcp_config.zig
@@ -0,0 +1,255 @@
+//! User-level (global) MCP configuration and its merge with the workspace file
+//! (#345).
+//!
+//! `mcpServers` used to come from the repository `.mcp.json` alone, so a remote
+//! server a user wants everywhere — DeepWiki, say — had to be re-declared in
+//! every checkout. The global file uses the identical `{"mcpServers": {...}}`
+//! schema and is merged with the project file at every read site, with PROJECT
+//! ENTRIES WINNING on a name conflict: a repository's own config must never be
+//! silently shadowed by whatever the user happens to have set up globally.
+//!
+//! The file lives under `~/.codegraff/`, this repo's home-scoped convention
+//! (see models_cache.zig and router_catalog.zig), rather than inventing a new
+//! `~/.graff/`. `GRAFF_MCP_CONFIG` overrides the location with an absolute
+//! path, which is also what keeps the tests below off the real `$HOME`.
+//!
+//! Global entries are NOT more trusted than project ones: they flow through the
+//! same untrusted-server consent gate at startup and the same in-session
+//! `/mcp trust`. Writes (`graff mcp add`, `/mcp add`) stay project-local — this
+//! module only ever reads.
+
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+
+/// Home-relative location of the user-level config.
+pub const global_rel_path = ".codegraff/mcp.json";
+
+/// Absolute-path override for the global config.
+pub const path_env = "GRAFF_MCP_CONFIG";
+
+/// A home-scoped path some other MCP clients read and graff does not. Startup
+/// mentions it once when it exists, so a config a user wrote is never ignored
+/// in complete silence.
+pub const unsupported_rel_path = ".mcpconfig.json";
+
+/// The merged `mcpServers` set plus the provenance callers need to describe it.
+pub const Merged = struct {
+ /// Every server graff should consider: global first, then project on top.
+ servers: std.json.ObjectMap = .empty,
+ /// The workspace half on its own, so `graff mcp list` can tag an entry the
+ /// project does not define as `(global)`.
+ project: std.json.ObjectMap = .empty,
+ /// Whether either file existed. `mcp.Registry.init` returns null (MCP stays
+ /// optional) only when neither did.
+ found: bool = false,
+ /// A file that existed but was not `{"mcpServers": {...}}`. The other half
+ /// still loads: one bad file must not disable MCP everywhere.
+ invalid_project: bool = false,
+ invalid_global: bool = false,
+
+ /// Whether `name` is defined by the global file only.
+ pub fn isGlobalOnly(self: Merged, name: []const u8) bool {
+ return self.project.get(name) == null;
+ }
+};
+
+/// Resolve the user-level config path: `GRAFF_MCP_CONFIG` when set (an absolute
+/// path, mainly for tests and sandboxes), else `{home}/.codegraff/mcp.json`.
+/// Null means simply "no global config" — never an error.
+pub fn globalPath(arena: Allocator, home: []const u8, environ_map: anytype) ?[]const u8 {
+ if (environ_map.get(path_env)) |override| if (override.len > 0) return override;
+ if (home.len == 0) return null;
+ return std.fmt.allocPrint(arena, "{s}/" ++ global_rel_path, .{home}) catch null;
+}
+
+/// Read `path` and return its `mcpServers` object. Best-effort throughout:
+/// only "no such file" reads as absent, everything else reads as invalid (and
+/// empty) so a caller can say which file it could not use.
+fn readServers(io: Io, arena: Allocator, dir: Io.Dir, path: []const u8, found: *bool, invalid: *bool) std.json.ObjectMap {
+ const text = dir.readFileAlloc(io, path, arena, .limited(1 << 20)) catch |err| switch (err) {
+ error.FileNotFound => return .empty,
+ // A directory, a permission denial or a file over the 1 MiB limit is a
+ // config the user meant graff to read. Silently treating it as "no
+ // config" is how a whole MCP setup disappears without a word.
+ else => {
+ found.* = true;
+ invalid.* = true;
+ return .empty;
+ },
+ };
+ found.* = true;
+ const parsed = std.json.parseFromSliceLeaky(Value, arena, text, .{ .allocate = .alloc_always }) catch {
+ invalid.* = true;
+ return .empty;
+ };
+ if (parsed != .object) {
+ invalid.* = true;
+ return .empty;
+ }
+ const servers = parsed.object.get("mcpServers") orelse return .empty;
+ if (servers != .object) {
+ invalid.* = true;
+ return .empty;
+ }
+ return servers.object;
+}
+
+/// Merge the user-level and workspace configs into one `mcpServers` set. `dir`
+/// is the workspace root (`Io.Dir.cwd()` in production, a tmp dir in tests) and
+/// `global_path` may be absolute — an absolute path ignores the directory
+/// handle it is opened through. Never fails: a missing or malformed file simply
+/// contributes nothing. Values stay arena-allocated, like the rest of the MCP
+/// config handling.
+pub fn load(io: Io, arena: Allocator, dir: Io.Dir, project_path: []const u8, global_path: ?[]const u8) Merged {
+ var merged: Merged = .{};
+ const global = if (global_path) |p|
+ readServers(io, arena, dir, p, &merged.found, &merged.invalid_global)
+ else
+ std.json.ObjectMap.empty;
+ merged.project = readServers(io, arena, dir, project_path, &merged.found, &merged.invalid_project);
+
+ // Global first, project second: the later `put` for a name overwrites, so
+ // the workspace keeps the final say over its own tooling.
+ var global_it = global.iterator();
+ while (global_it.next()) |entry| merged.servers.put(arena, entry.key_ptr.*, entry.value_ptr.*) catch return merged;
+ var project_it = merged.project.iterator();
+ while (project_it.next()) |entry| merged.servers.put(arena, entry.key_ptr.*, entry.value_ptr.*) catch return merged;
+ return merged;
+}
+
+/// Name every config file that existed but could not be used. A file graff
+/// cannot parse must never read back as "nothing configured" — that is exactly
+/// the case where the user needs to be told which file to look at, and with two
+/// files in play a bad project file would otherwise leave a healthy-looking
+/// global-only listing behind. `prefix`/`suffix` carry the caller's styling
+/// (dim/reset at startup, empty for the plain CLI).
+pub fn reportInvalid(merged: Merged, w: *Io.Writer, project_path: []const u8, global_path: ?[]const u8, prefix: []const u8, suffix: []const u8) !void {
+ const complaint = " is not valid MCP config (expected a JSON object with \"mcpServers\"); ignoring it.";
+ if (merged.invalid_project) try w.print("{s}{s}" ++ complaint ++ "{s}\n", .{ prefix, project_path, suffix });
+ if (merged.invalid_global) try w.print("{s}{s}" ++ complaint ++ "{s}\n", .{ prefix, global_path orelse "", suffix });
+}
+
+/// Whether `{home}/.mcpconfig.json` exists. That path belongs to other MCP
+/// clients and graff never reads it, so startup says so once instead of leaving
+/// the user to wonder why their servers never appeared.
+pub fn unsupportedConfigPresent(io: Io, arena: Allocator, home: []const u8) bool {
+ if (home.len == 0) return false;
+ const path = std.fmt.allocPrint(arena, "{s}/" ++ unsupported_rel_path, .{home}) catch return false;
+ if (Io.Dir.cwd().statFile(io, path, .{})) |_| return true else |_| return false;
+}
+
+const testing = std.testing;
+
+/// Stands in for `std.process.Environ.Map` — `globalPath` only ever calls
+/// `get`, and a real environment would not be hermetic.
+const TestEnv = struct {
+ override: ?[]const u8 = null,
+ fn get(self: TestEnv, key: []const u8) ?[]const u8 {
+ return if (std.mem.eql(u8, key, path_env)) self.override else null;
+ }
+};
+
+/// Both halves are read through the tmp dir handle, so no test touches `$HOME`
+/// or the real workspace.
+fn loadTmp(arena: Allocator, dir: Io.Dir) Merged {
+ return load(testing.io, arena, dir, ".mcp.json", "global.json");
+}
+
+test "global MCP path prefers the env override and otherwise lives under ~/.codegraff" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ try testing.expectEqualStrings("/home/alice/.codegraff/mcp.json", globalPath(arena, "/home/alice", TestEnv{}).?);
+ try testing.expectEqualStrings("/tmp/mcp.json", globalPath(arena, "/home/alice", TestEnv{ .override = "/tmp/mcp.json" }).?);
+ // An empty override falls back rather than resolving to the file "".
+ try testing.expectEqualStrings("/home/alice/.codegraff/mcp.json", globalPath(arena, "/home/alice", TestEnv{ .override = "" }).?);
+ // No HOME and no override is "no global config", not a crash.
+ try testing.expect(globalPath(arena, "", TestEnv{}) == null);
+}
+
+test "project MCP entries win over global entries with the same name" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(testing.io, .{ .sub_path = "global.json", .data = "{\"mcpServers\":{\"deepwiki\":{\"url\":\"https://global.example/mcp\"}}}" });
+ try tmp.dir.writeFile(testing.io, .{ .sub_path = ".mcp.json", .data = "{\"mcpServers\":{\"deepwiki\":{\"url\":\"https://project.example/mcp\"}}}" });
+
+ const merged = loadTmp(arena_state.allocator(), tmp.dir);
+ try testing.expect(merged.found);
+ try testing.expectEqual(@as(usize, 1), merged.servers.count());
+ try testing.expectEqualStrings("https://project.example/mcp", merged.servers.get("deepwiki").?.object.get("url").?.string);
+ try testing.expect(!merged.isGlobalOnly("deepwiki"));
+}
+
+test "merged MCP set carries global-only and project-only servers" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(testing.io, .{ .sub_path = "global.json", .data = "{\"mcpServers\":{\"deepwiki\":{\"url\":\"https://mcp.deepwiki.com/mcp\"}}}" });
+ try tmp.dir.writeFile(testing.io, .{ .sub_path = ".mcp.json", .data = "{\"mcpServers\":{\"local\":{\"command\":\"./srv\"}}}" });
+
+ const merged = loadTmp(arena_state.allocator(), tmp.dir);
+ try testing.expectEqual(@as(usize, 2), merged.servers.count());
+ try testing.expectEqualStrings("https://mcp.deepwiki.com/mcp", merged.servers.get("deepwiki").?.object.get("url").?.string);
+ try testing.expectEqualStrings("./srv", merged.servers.get("local").?.object.get("command").?.string);
+ try testing.expect(merged.isGlobalOnly("deepwiki"));
+ try testing.expect(!merged.isGlobalOnly("local"));
+}
+
+test "no MCP config anywhere is absent, not merely empty" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+
+ const merged = loadTmp(arena_state.allocator(), tmp.dir);
+ // `found` false is what keeps `mcp.Registry.init` returning null.
+ try testing.expect(!merged.found);
+ try testing.expectEqual(@as(usize, 0), merged.servers.count());
+ try testing.expect(!merged.invalid_project and !merged.invalid_global);
+}
+
+test "a malformed MCP config does not take the other half down" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ var bad_global = testing.tmpDir(.{});
+ defer bad_global.cleanup();
+ try bad_global.dir.writeFile(testing.io, .{ .sub_path = "global.json", .data = "{ not json" });
+ try bad_global.dir.writeFile(testing.io, .{ .sub_path = ".mcp.json", .data = "{\"mcpServers\":{\"local\":{\"command\":\"./srv\"}}}" });
+ const global_broken = loadTmp(arena, bad_global.dir);
+ try testing.expect(global_broken.invalid_global and !global_broken.invalid_project);
+ try testing.expectEqual(@as(usize, 1), global_broken.servers.count());
+ try testing.expect(global_broken.servers.get("local") != null);
+
+ var bad_project = testing.tmpDir(.{});
+ defer bad_project.cleanup();
+ // A well-formed file whose `mcpServers` is the wrong shape counts as
+ // invalid too — otherwise a typo reads as "no servers configured".
+ try bad_project.dir.writeFile(testing.io, .{ .sub_path = ".mcp.json", .data = "{\"mcpServers\":[]}" });
+ try bad_project.dir.writeFile(testing.io, .{ .sub_path = "global.json", .data = "{\"mcpServers\":{\"deepwiki\":{\"url\":\"https://mcp.deepwiki.com/mcp\"}}}" });
+ const project_broken = loadTmp(arena, bad_project.dir);
+ try testing.expect(project_broken.invalid_project and !project_broken.invalid_global);
+ try testing.expectEqual(@as(usize, 1), project_broken.servers.count());
+ try testing.expect(project_broken.isGlobalOnly("deepwiki"));
+}
+
+test "an unreadable MCP config is invalid, not absent" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ // A directory where a file was expected: the read fails with something other
+ // than FileNotFound, which must not read back as "no global config".
+ try tmp.dir.createDir(testing.io, "global.json", .default_dir);
+
+ const merged = loadTmp(arena_state.allocator(), tmp.dir);
+ try testing.expect(merged.found and merged.invalid_global);
+ try testing.expect(!merged.invalid_project);
+ try testing.expectEqual(@as(usize, 0), merged.servers.count());
+}
diff --git a/src/session_start.zig b/src/session_start.zig
index 3c01810f..dea2fffd 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -36,6 +36,7 @@ const skills = @import("skills.zig");
const anim = @import("anim.zig");
const mcp = @import("mcp.zig");
const mcp_cli = @import("mcp_cli.zig");
+const mcp_config = @import("mcp_config.zig");
const jobs = @import("jobs.zig");
const trace = @import("trace.zig");
const scoring = @import("scoring.zig");
@@ -347,30 +348,52 @@ pub fn initTelemetry(io: Io, gpa: Allocator, client: *std.http.Client, environ_m
};
}
-/// MCP servers from .mcp.json. SECURITY: a workspace .mcp.json launches
-/// arbitrary local commands, so opening an untrusted repo could run them.
-/// Auto-connect only with --yolo (trusted) or explicit per-session consent
-/// (prompted here); otherwise starts with an empty (but live) registry so
-/// `/mcp add` still works. Moved out of main() (600-line goal). Returns the
-/// Registry by value — mcp.Registry holds no self-references (its storage
-/// is ArrayList/HashMap-backed), so returning it is safe.
+/// MCP servers from the workspace .mcp.json merged with the user-level
+/// ~/.codegraff/mcp.json (#345). SECURITY: either file launches arbitrary local
+/// commands, so opening an untrusted repo could run them — and a global entry
+/// is no safer, it just follows the user everywhere. Auto-connect only with
+/// --yolo (trusted) or explicit per-session consent (prompted here); otherwise
+/// starts with an empty (but live) registry so `/mcp add` still works. Moved
+/// out of main() (600-line goal). Returns the Registry by value — mcp.Registry
+/// holds no self-references (its storage is ArrayList/HashMap-backed), so
+/// returning it is safe.
pub fn initRegistryConsent(io: Io, gpa: Allocator, arena: Allocator, out: *Io.Writer, in: *Io.Reader, flags: args.Flags, mcp_config_path: []const u8, home: []const u8, use_color: bool, json_mode: bool, environ_map: anytype) !mcp.Registry {
- const mcp_count = mcp_cli.countMcpServers(io, arena);
+ const global_path = mcp_config.globalPath(arena, home, environ_map);
+ // --json's stdout is a JSONL stream and a one-shot's is the answer; neither
+ // can carry chatter. With a global config `mcp_count > 0` in every project,
+ // so an unguarded line here would corrupt the head of every --json run.
+ const quiet = json_mode or flags.oneshot_prompt != null;
+ const merged = mcp_config.load(io, arena, Io.Dir.cwd(), mcp_config_path, global_path);
+ if (!quiet) {
+ // Reported here rather than in `Registry.init`, which never runs when
+ // consent is declined — a config that does not parse must be named
+ // either way.
+ try mcp_config.reportInvalid(merged, out, mcp_config_path, global_path, ansi.style.dim, ansi.style.reset);
+ // A config graff does not read is worse than no config: say so once.
+ if (mcp_config.unsupportedConfigPresent(io, arena, home))
+ try out.print("{s}ignoring ~/" ++ mcp_config.unsupported_rel_path ++ ": unsupported path — use ~/" ++ mcp_config.global_rel_path ++ " (global) or {s} (project){s}\n", .{ ansi.style.dim, mcp_config_path, ansi.style.reset });
+ }
+ const mcp_count = mcp_cli.countMcpServers(merged);
var connect_mcp = flags.yolo_flag or mcp_count == 0;
if (mcp_count > 0 and !flags.yolo_flag and !json_mode and use_color) {
- try out.print("{s}⚠ this workspace's .mcp.json defines {d} untrusted MCP server(s). They may run local commands or receive data over the network. Connect them this session? [y/N] {s}", .{ ansi.style.bold, mcp_count, ansi.style.reset });
+ try out.print("{s}⚠ {d} untrusted MCP server(s) are configured for this session (.mcp.json and/or ~/" ++ mcp_config.global_rel_path ++ "). They may run local commands or receive data over the network. Connect them this session? [y/N] {s}", .{ ansi.style.bold, mcp_count, ansi.style.reset });
try out.flush();
const ans = in.takeDelimiter('\n') catch null;
connect_mcp = ans != null and ans.?.len > 0 and (ans.?[0] == 'y' or ans.?[0] == 'Y');
}
- return if (connect_mcp) ((mcp.Registry.init(gpa, io, mcp_config_path, home, environ_map) catch |err| inner: {
+ var registry: mcp.Registry = if (connect_mcp) ((mcp.Registry.init(gpa, io, mcp_config_path, global_path, home, environ_map) catch |err| inner: {
try out.print("[mcp] init failed: {t} — continuing without MCP\n", .{err});
if (telemetry.g_telem) |t| t.errorEvent("mcp", @errorName(err));
break :inner null;
}) orelse mcp.Registry.emptyWithOAuthHome(gpa, io, home)) else outer: {
- if (mcp_count > 0) try out.print("{s}skipped {d} workspace MCP server(s) — /mcp trust to connect them now (or re-run with --yolo){s}\n", .{ ansi.style.dim, mcp_count, ansi.style.reset });
+ if (mcp_count > 0 and !quiet) try out.print("{s}skipped {d} MCP server(s) — /mcp trust to connect them now (or re-run with --yolo){s}\n", .{ ansi.style.dim, mcp_count, ansi.style.reset });
break :outer mcp.Registry.emptyWithOAuthHome(gpa, io, home);
};
+ // Set on every path, not just `init`'s: `/mcp trust` has to find the global
+ // file precisely when consent was declined and no `init` ever ran. `arena`
+ // is the session arena, so the path outlives the registry.
+ registry.global_config_path = global_path;
+ return registry;
}
/// Companion auto-activation: if the metered code-intelligence companion
diff --git a/src/startup.zig b/src/startup.zig
index 91ca33f5..b0e7ad8b 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -435,10 +435,12 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process
return true;
}
- // MCP list/add only use workspace config; OAuth login validates HOME itself.
+ // MCP list/login read the workspace config merged with the user-level
+ // ~/.codegraff/mcp.json (hence environ_map, for the GRAFF_MCP_CONFIG
+ // override); add still writes workspace-only. OAuth login validates HOME itself.
if (flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "mcp")) {
const home = keys_cli.homeEnv(init.environ_map) orelse "";
- try mcp_cli.mcpCommand(io, gpa, arena, home, flags.positionals.items[1..]);
+ try mcp_cli.mcpCommand(io, gpa, arena, home, init.environ_map, flags.positionals.items[1..]);
return true;
}
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 7fb19acc..43953f0d 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -47,6 +47,11 @@ const serve_create = @import("serve_create.zig");
// Moved off main.zig, which is at the 600-line cap.
const scoring_slot_test = @import("scoring_slot_test.zig");
+// #345: the global-vs-project MCP config merge. mcp.zig does reference its
+// decls, but the hook makes the coverage explicit rather than contingent on
+// that staying true.
+const mcp_config = @import("mcp_config.zig");
+
test {
_ = learn_holdout;
_ = learn_receipt;
@@ -63,4 +68,5 @@ test {
_ = serve_events;
_ = serve_create;
_ = scoring_slot_test;
+ _ = mcp_config;
}