Skip to content

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

Python

mcp: per-server status, reconnect, and on/off switches

justrachc546285a41ae
diff --git a/assets/skills/mcp-config.md b/assets/skills/mcp-config.md
index 3e271d94..05452766 100644
--- a/assets/skills/mcp-config.md
+++ b/assets/skills/mcp-config.md
@@ -57,6 +57,9 @@ graff mcp add <name> --env KEY=VALUE -- <command> # with env
graff mcp add <name> --url https://host/mcp # remote server
graff mcp add <name> --url https://host/mcp --header KEY=VALUE
graff mcp login <name> # OAuth for a remote server
+graff mcp status [--json] # each server's state and tools, starts nothing
+graff mcp reconnect <name> | --all # fresh handshake; refreshes its cached tools
+graff mcp enable|disable <name> # switch a server on or off everywhere
```
`graff mcp add` and `/mcp add` write the project `.mcp.json`; only
@@ -75,6 +78,8 @@ repo) or a token the user supplies at runtime.
connect one live and persist it
- `/mcp trust` - connect the servers that were skipped at startup, project and
global alike
+- `/mcp reconnect <name>` - start one server again (a failed one joins for the
+ first time) without a new session
## When a server is not connected
@@ -85,6 +90,11 @@ 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.
+`/mcp` says why each other server is not connected: failed (with the cause),
+off (`graff mcp disable`, or `"enabled": false` in its own entry), optional
+(`graff mcp enable <name>` opts in), or not started (consent). `graff mcp
+reconnect <name>` retries one and prints the server's own last error line.
+
After that, in likelihood order: the command is not on PATH, the package name
is wrong, the server needs a token that is not set, the URL is not HTTPS, or
the server needs an OAuth login (`graff mcp login <name>`).
diff --git a/build.zig b/build.zig
index 9c57f9bd..4ad20d9a 100644
--- a/build.zig
+++ b/build.zig
@@ -170,6 +170,9 @@ pub fn build(b: *std.Build) void {
const mcp_add_test = b.addSystemCommand(&.{ "python3", "scripts/test-mcp-add.py" });
mcp_add_test.addArtifactArg(exe);
test_step.dependOn(&mcp_add_test.step);
+ const mcp_status_test = b.addSystemCommand(&.{ "python3", "scripts/test-mcp-status.py" });
+ mcp_status_test.addArtifactArg(exe);
+ test_step.dependOn(&mcp_status_test.step);
const acp_v2_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-v2.py" });
acp_v2_test.addArtifactArg(exe);
test_step.dependOn(&acp_v2_test.step);
diff --git a/docs/adr/0280-mcp-servers-report-state-and-reconnect.md b/docs/adr/0280-mcp-servers-report-state-and-reconnect.md
new file mode 100644
index 00000000..35404af4
--- /dev/null
+++ b/docs/adr/0280-mcp-servers-report-state-and-reconnect.md
@@ -0,0 +1,54 @@
+# 0280. MCP servers report their state and reconnect on request
+
+Status: accepted 2026-10-11
+
+## Context
+
+MCP servers connect in the background (ADR 0230), and local ones start on
+first use from a cached catalog (`mcp_lazy.zig`). When one did not work,
+nothing said why and nothing could fix it short of a new session:
+
+- The catalog cache was keyed by command line alone. Plugin servers often
+ share one launcher command and differ only in `cwd`, so each advertised
+ the others' tools until a live re-list overwrote the entry. Calls then
+ failed until something re-listed.
+- A per-server `env` replaced the child's whole environment, so an entry
+ that set one token lost `PATH` and `HOME`, and an `npx` server exited at
+ once.
+- Entries their own file switched off (`"enabled": false`,
+ `"disabled": true`) were started anyway.
+- `/mcp` folded every server that was not connected into "not connected —
+ /mcp trust", including ones that failed, were optional, or were off.
+- A desktop client starts a new graff per run, so a mid-session reconnect
+ alone does not help it. It needs to see each server's state and refresh a
+ server's catalog between runs.
+
+## Decision
+
+- **One status row per configured server** (`mcp_status.zig`): source,
+ transport, a secret-free origin, enabled, state (`ready`, `on_demand`,
+ `connecting`, `failed`, `needs_login`, `off`, `opt_in`, `not_started`,
+ `unknown`), the failure's text and error name, the server's own last
+ stderr line after a failed reconnect, and its tools. `graff mcp status
+ --json` builds it from config, cache and stored sign-ins without starting
+ anything. The in-session `/mcp` builds it from the registry.
+- **Reconnect is a real handshake.** `graff mcp reconnect <name>|--all`
+ drops the cached catalog, starts the server fresh, stores what it lists,
+ and stops it. `/mcp reconnect <name>` replaces the server in a session's
+ registry at the same index and brings back tools withdrawn after a close.
+- **On/off is the user's, kept apart from the configs**:
+ `~/.codegraff/mcp-state.json` (`graff mcp enable|disable`). `disabled`
+ wins everywhere. `enabled` opts in an optional server and overrides an
+ entry's own off switch. An entry its file switched off stays off otherwise.
+- **The cache key includes `cwd` and a hash of `env`**, and per-server `env`
+ overlays graff's own environment.
+- **A transient start failure is retried once** (`mcp_start.zig`), and every
+ failure is recorded by name so `/mcp` can say why.
+
+## Consequences
+
+Clients (the desktop app's MCP servers page and the fullscreen client's
+`/mcp`) read one JSON shape and act through four commands. Existing caches
+re-list once for entries with a `cwd` or `env`, because their key changed. A
+failed reconnect starts the server a second time for up to three seconds to
+read its stderr. That only happens when a person asked for the reconnect.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 92ceaf64..2c526269 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -289,6 +289,7 @@ record only when you need the evidence or the edge cases.
| [0260](0260-clef-compaction-replaces-client-summary.md) | `GRAFF_CLEF_COMPACT=1` routes client-summary compactions through the gateway's server-side `POST /v1/compact` (Clef decision-model pruning, text verbatim); OpenAI-family server paths are untouched and any failure falls back to the summary. |
| [0261](0261-client-summary-stays-the-compactor.md) | The client summary stays the compactor: `GRAFF_CLEF_COMPACT` defaults off (Clef rarely pruned and mostly fell back to the summary in measurement); first-party Responses routes use only the provider's own compaction. Supersedes 0260's default. |
| [0270](0270-a-closed-stdio-mcp-server-restarts-on-its-next-call.md) | A stdio MCP server whose connection closes goes back to dormant with its launch config and restarts on its next call; the failed call is never replayed, and after two restarts in a session its tools are withdrawn as before. |
+| [0280](0280-mcp-servers-report-state-and-reconnect.md) | Every configured MCP server has one status row (`graff mcp status --json`, `/mcp`); `graff mcp reconnect` / `/mcp reconnect` run a real handshake and refresh its catalog; `graff mcp enable|disable` live in `~/.codegraff/mcp-state.json`; the catalog cache keys on cwd + env, and server `env` overlays graff's own. |
## When to write one
diff --git a/scripts/test-mcp-status.py b/scripts/test-mcp-status.py
new file mode 100644
index 00000000..7b42a659
--- /dev/null
+++ b/scripts/test-mcp-status.py
@@ -0,0 +1,103 @@
+#!/usr/bin/env python3
+"""`graff mcp status | reconnect | enable | disable` against scripted servers.
+
+Offline: no model, no network. Covers:
+- two servers sharing one launcher command, differing only in `cwd`, get
+ their own cached catalogs (they used to advertise each other's tools)
+- a server's `env` overlays graff's environment (PATH survives)
+- "enabled": false in an entry keeps it off until `graff mcp enable`
+- `graff mcp disable` switches a server off and reconnect --all skips it
+- a server that fails to start reports its own last stderr line
+"""
+import json, os, shutil, subprocess, sys, tempfile
+from pathlib import Path
+
+SERVER = r"""
+import json, os, sys
+if os.environ.get("STATUS_FAIL"):
+ sys.stderr.write("starting\n" + os.environ["STATUS_FAIL"] + "\n"); sys.exit(2)
+name = os.path.basename(os.getcwd()) + ("_has_path" if os.environ.get("PATH") else "_no_path")
+def out(o): sys.stdout.write(json.dumps(o) + "\n"); sys.stdout.flush()
+for line in sys.stdin:
+ try: m = json.loads(line)
+ except ValueError: continue
+ mid = m.get("id"); meth = m.get("method")
+ if mid is None: continue
+ if meth == "initialize":
+ out({"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": "2025-11-25", "capabilities": {"tools": {}}, "serverInfo": {"name": "s", "version": "1"}}})
+ elif meth == "tools/list":
+ out({"jsonrpc": "2.0", "id": mid, "result": {"tools": [{"name": name, "description": "tool of " + name + "\nmore", "inputSchema": {"type": "object"}}]}})
+ elif meth == "server/discover":
+ out({"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "Method not found"}})
+ else:
+ out({"jsonrpc": "2.0", "id": mid, "result": {}})
+"""
+
+
+def graff(binary, work, env, *args):
+ proc = subprocess.run([binary, 'mcp', *args, '--json'], cwd=work, env=env, capture_output=True, text=True, timeout=120)
+ assert proc.returncode == 0, (args, proc.stdout, proc.stderr)
+ return {row['name']: row for row in json.loads(proc.stdout)['servers']}
+
+
+def main():
+ binary = str(Path(sys.argv[1] if len(sys.argv) > 1 else 'zig-out/bin/graff').resolve())
+ temp = Path(tempfile.mkdtemp(prefix='graff-mcp-status-'))
+ try:
+ (temp / 'server.py').write_text(SERVER)
+ work = temp / 'proj'
+ work.mkdir()
+ for d in ('alpha', 'beta'):
+ (temp / d).mkdir()
+ launcher = {'command': sys.executable, 'args': [str(temp / 'server.py')]}
+ cfg = {'mcpServers': {
+ 'alpha': {**launcher, 'cwd': str(temp / 'alpha')},
+ 'beta': {**launcher, 'cwd': str(temp / 'beta')},
+ 'tokened': {**launcher, 'cwd': str(temp / 'alpha'), 'env': {'SOME_TOKEN': 'x'}},
+ 'parked': {**launcher, 'cwd': str(temp / 'beta'), 'enabled': False},
+ 'broken': {**launcher, 'env': {'STATUS_FAIL': 'broken: not licensed. Run: broken activate'}},
+ }}
+ (work / '.mcp.json').write_text(json.dumps(cfg))
+ env = {k: v for k, v in os.environ.items() if not k.endswith('_API_KEY')}
+ env.update(HOME=str(temp), GRAFF_NO_TELEMETRY='1', GRAFF_FLEET='off', GRAFF_NO_PLUGINS='1')
+
+ rows = graff(binary, work, env, 'status')
+ assert set(rows) == {'alpha', 'beta', 'tokened', 'parked', 'broken'}, rows
+ assert rows['alpha']['state'] == 'unknown' and rows['alpha']['source'] == 'project', rows['alpha']
+ assert rows['parked']['state'] == 'off' and not rows['parked']['enabled'], rows['parked']
+
+ rows = graff(binary, work, env, 'reconnect', '--all')
+ assert 'parked' not in rows, rows # switched off: not started
+ assert rows['alpha']['state'] == 'ready', rows['alpha']
+ assert [t['name'] for t in rows['alpha']['tools']] == ['alpha_has_path'], rows['alpha']
+ assert [t['name'] for t in rows['beta']['tools']] == ['beta_has_path'], rows['beta']
+ assert rows['alpha']['tools'][0]['description'] == 'tool of alpha_has_path', rows['alpha']
+ # env overlays the parent environment: PATH is still there.
+ assert [t['name'] for t in rows['tokened']['tools']] == ['alpha_has_path'], rows['tokened']
+ assert rows['broken']['state'] == 'failed', rows['broken']
+ assert rows['broken']['detail'] == 'broken: not licensed. Run: broken activate', rows['broken']
+
+ # Cached per cwd: the next listing keeps each server's own tools.
+ rows = graff(binary, work, env, 'status')
+ assert rows['alpha']['state'] == 'on_demand' and rows['alpha']['tools'][0]['name'] == 'alpha_has_path', rows['alpha']
+ assert rows['beta']['tools'][0]['name'] == 'beta_has_path', rows['beta']
+
+ rows = graff(binary, work, env, 'enable', 'parked')
+ # Same launch as beta, so beta's reconnect already cached its tools.
+ assert rows['parked']['enabled'] and rows['parked']['state'] == 'on_demand', rows['parked']
+ rows = graff(binary, work, env, 'reconnect', 'parked')
+ assert rows['parked']['state'] == 'ready', rows['parked']
+
+ rows = graff(binary, work, env, 'disable', 'beta')
+ assert rows['beta']['state'] == 'off', rows['beta']
+ rows = graff(binary, work, env, 'reconnect', '--all')
+ assert 'beta' not in rows and rows['alpha']['state'] == 'ready', rows
+ state = json.loads((temp / '.codegraff' / 'mcp-state.json').read_text())
+ assert state == {'disabled': ['beta'], 'enabled': ['parked']}, state
+ print('mcp status: ok')
+ finally:
+ shutil.rmtree(temp, ignore_errors=True)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/src/command_catalog.zig b/src/command_catalog.zig
index 8e4be7fb..0ecf5e63 100644
--- a/src/command_catalog.zig
+++ b/src/command_catalog.zig
@@ -125,7 +125,7 @@ pub const commands = [_]Item{
.{ .name = "/animation", .desc = "pick the thinking animation; persists to settings" },
.{ .name = "/theme", .usage = "/theme [name]", .desc = "pick a color theme; /theme off resets to your terminal default; persists" },
.{ .name = "/fleet", .usage = "/fleet [on|off]", .desc = "federated DGM contribution (propose/submit/elite_pull)" },
- .{ .name = "/mcp", .usage = "/mcp [add …]", .desc = "list MCP servers/tools; /mcp add <name> <cmd> [args...] connects one live" },
+ .{ .name = "/mcp", .usage = "/mcp [add … | reconnect <name>]", .desc = "list MCP servers/tools; /mcp add <name> <cmd> [args...] connects one live; /mcp reconnect <name> starts one again" },
.{ .name = "/import-claude", .desc = "copy Claude/Cursor setup and import this project's Claude conversations for /resume" },
.{ .name = "/help", .desc = "list every command" },
};
diff --git a/src/commands_misc.zig b/src/commands_misc.zig
index e57019de..a6d90770 100644
--- a/src/commands_misc.zig
+++ b/src/commands_misc.zig
@@ -229,6 +229,15 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
root.invalidateRootTools();
try root.ensureRootTools(root.provider.kind);
}
+ if (std.mem.startsWith(u8, arg, "reconnect")) {
+ if (try @import("mcp_listing.zig").reconnect(reg, arena, out, mcp_config_path, std.mem.trim(u8, arg["reconnect".len..], " \t"))) {
+ root.invalidateRootTools();
+ @import("prompt_cache_hud.zig").noteBust(.mcp);
+ try root.ensureRootTools(root.provider.kind);
+ root.rebaseContextMeter();
+ }
+ return true;
+ }
if (std.mem.startsWith(u8, arg, "add")) {
// /mcp add <name> <command> [args...] or <name> --url <URL>
var it = std.mem.tokenizeAny(u8, arg["add".len..], " \t");
@@ -304,7 +313,6 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
return true;
}
// Plain /mcp: list servers (with tool counts) then tools.
- const pending = reg.pendingWorkspace(mcp_config_path);
if (reg.servers.len == 0) {
try out.writeAll("no MCP servers connected.\n add one: /mcp add <name> <command> [args...]\n e.g. /mcp add fs npx -y @modelcontextprotocol/server-filesystem .\n");
} else {
@@ -322,9 +330,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
for (reg.tools) |t| try out.print(" {s}{s}{s}{s}\n", .{ style.dim, t.qualified_name, if (mcp_schema_gate.isDeferred(reg.tools, t)) " schema deferred (#416); the model loads it on demand" else "", style.reset });
try out.writeAll(" add more: /mcp add <name> <command> [args...]\n");
}
- const still = @import("mcp_connect_notice.zig").connecting(reg, arena);
- if (still.len > 0) try out.print(" {s}still connecting: {s}{s}\n", .{ style.dim, try std.mem.join(arena, ", ", still), 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 @import("mcp_listing.zig").notConnected(reg, arena, out, mcp_config_path); // why each other server is not connected
try out.flush();
return true;
}
diff --git a/src/mcp.zig b/src/mcp.zig
index 22040d58..09d12d07 100644
--- a/src/mcp.zig
+++ b/src/mcp.zig
@@ -216,10 +216,12 @@ pub const Registry = struct {
try tools.appendSlice(a, reg.tools);
const before = servers.items.len;
+ const state = @import("mcp_state.zig").load(reg.io, a, reg.home);
var it = merged.servers.iterator();
while (it.next()) |entry| {
const name = entry.key_ptr.*;
- if (entry.value_ptr.* != .object) continue;
+ if (entry.value_ptr.* != .object or state.isDisabled(name)) continue; // switched off: graff mcp disable
+ if (!state.isEnabled(name) and @import("mcp_state.zig").offInConfig(entry.value_ptr.*.object)) continue; // off in its own file
// Already connected (auto-activated muonry, or a prior /mcp trust)? skip.
var present = false;
for (reg.servers) |s| if (std.mem.eql(u8, s.name, name)) {
@@ -229,6 +231,7 @@ pub const Registry = struct {
if (present) continue;
reg.startServer(a, &servers, &tools, try a.dupe(u8, name), entry.value_ptr.*.object) catch |err| {
if (reg.show_diagnostics) std.debug.print(" [mcp:{s}] failed to start: {t}\n", .{ name, err });
+ @import("mcp_start.zig").note(name, err); // /mcp says why
};
}
reg.servers = try a.dupe(*Server, servers.items);
@@ -236,28 +239,6 @@ pub const Registry = struct {
return servers.items.len - before;
}
- /// 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 merged = mcp_config.load(reg.io, a, Io.Dir.cwd(), config_path, reg.global_config_path, reg.home, reg.global_is_override);
- var n: usize = 0;
- var it = merged.servers.iterator();
- while (it.next()) |entry| {
- if (entry.value_ptr.* != .object) continue;
- var present = false;
- for (reg.servers) |s| if (std.mem.eql(u8, s.name, entry.key_ptr.*)) {
- present = true;
- break;
- };
- // Still connecting in the background is not "not connected" (ADR 0230).
- if (!present and !mcp_boot.alreadyStarting(reg, entry.key_ptr.*)) n += 1;
- }
- return n;
- }
-
/// Number of tools a given server (by index) contributed — for `/mcp`.
pub fn toolCount(reg: *Registry, server_index: usize) usize {
var n: usize = 0;
@@ -474,4 +455,10 @@ test {
_ = @import("mcp_cache.zig");
_ = @import("mcp_boot.zig");
_ = @import("mcp_elicitation.zig");
+ _ = @import("mcp_start.zig");
+ _ = @import("mcp_state.zig");
+ _ = @import("mcp_status.zig");
+ _ = @import("mcp_status_cli.zig");
+ _ = @import("mcp_reconnect.zig");
+ _ = @import("mcp_listing.zig");
}
diff --git a/src/mcp_boot.zig b/src/mcp_boot.zig
index c80e1cb1..ac978210 100644
--- a/src/mcp_boot.zig
+++ b/src/mcp_boot.zig
@@ -56,45 +56,9 @@ pub const PendingStart = struct {
}
};
-const StartCtx = struct {
- gpa: Allocator,
- io: Io,
- home: []const u8,
- show_diagnostics: bool,
- stdio_probe: bool,
- lazy_stdio: bool = true,
- ready: ?*std.atomic.Value(bool) = null,
-};
+const StartCtx = @import("mcp_start.zig").Ctx; // one start + its one retry
+const startServerTask = @import("mcp_start.zig").task;
-fn startServerTask(ctx: StartCtx, name: []const u8, cfg: std.json.ObjectMap) StartOutcome {
- defer if (ctx.ready) |flag| flag.store(true, .release);
- var outcome: StartOutcome = .{};
- var arena_state = std.heap.ArenaAllocator.init(ctx.gpa);
- const a = arena_state.allocator();
- var servers: std.ArrayList(*mcp_rpc.Server) = .empty;
- var tools: std.ArrayList(mcp.Tool) = .empty;
- // Task-local Registry: only gpa/io/home/flags are read by startServer.
- // Must not point at init()'s stack `reg` — that dies when defer_join returns.
- var tmp: Registry = .{
- .gpa = ctx.gpa,
- .io = ctx.io,
- .home = ctx.home,
- .arena_state = std.heap.ArenaAllocator.init(ctx.gpa),
- .stdio_probe = ctx.stdio_probe,
- .lazy_stdio = ctx.lazy_stdio,
- .show_diagnostics = ctx.show_diagnostics,
- };
- defer tmp.arena_state.deinit();
- tmp.startServer(a, &servers, &tools, name, cfg) catch |err| {
- if (ctx.show_diagnostics) std.debug.print(" [mcp:{s}] failed to start: {t}\n", .{ name, err });
- arena_state.deinit();
- return outcome;
- };
- outcome.server = servers.items[0];
- outcome.tools = tools.items;
- outcome.arena_state = arena_state;
- return outcome;
-}
/// Load the workspace `.mcp.json` merged with the user-level global config,
/// then handshake every server CONCURRENTLY. Returns null (no error) when
/// neither file exists — MCP is optional. `global_path` is borrowed: it must
@@ -112,6 +76,7 @@ pub fn init(gpa: Allocator, io: Io, config_path: []const u8, global_path: ?[]con
.global_config_path = global_path,
.global_is_override = mcp_config.isEnvOverride(environ_map),
};
+ @import("mcp_lazy.zig").remember(environ_map); // the base each server `env` overlays
mcp_rpc.applyHandshakeTimeoutEnv(environ_map); // #275 GRAFF_MCP_HANDSHAKE_SECS + #327 GRAFF_MCP_PROBE_MS, on the same pass as the probe flag
errdefer reg.deinit();
@@ -128,8 +93,9 @@ pub fn init(gpa: Allocator, io: Io, config_path: []const u8, global_path: ?[]con
const Entry = struct { name: []const u8, cfg: std.json.ObjectMap };
var entries: std.ArrayList(Entry) = .empty;
var it = merged.servers.iterator();
+ const state = @import("mcp_state.zig").load(io, a, home); // `graff mcp enable|disable`
while (it.next()) |entry| {
- if (@import("tool_surface.zig").skipOptionalAtBoot(entry.key_ptr.*, environ_map, merged.isGlobalOnly(entry.key_ptr.*))) continue;
+ if (@import("mcp_state.zig").skipReason(state, entry.key_ptr.*, if (entry.value_ptr.* == .object) entry.value_ptr.*.object else null, environ_map, merged.isGlobalOnly(entry.key_ptr.*)) != .none) continue;
if (entry.value_ptr.* != .object) continue;
try entries.append(a, .{ .name = try a.dupe(u8, entry.key_ptr.*), .cfg = entry.value_ptr.*.object });
}
diff --git a/src/mcp_cache.zig b/src/mcp_cache.zig
index f0fd0261..6f0cf5dc 100644
--- a/src/mcp_cache.zig
+++ b/src/mcp_cache.zig
@@ -26,6 +26,12 @@ pub const Hit = struct {
tools: Value,
};
+/// The cache identity of a config entry. A stdio entry is its command line
+/// plus its `cwd` and `env`: plugin servers often share one launcher command
+/// (`sh -c 'exec node ./server.mjs'`) and differ only in the directory they
+/// start in, and keyed by the command alone each advertised the others'
+/// tools until a live re-list overwrote the entry. Env values are hashed so
+/// no secret lands in the cache file.
pub fn keyFor(arena: Allocator, cfg: std.json.ObjectMap) []const u8 {
if (cfg.get("url")) |u| if (u == .string) {
return std.fmt.allocPrint(arena, "url:{s}", .{u.string}) catch "";
@@ -38,9 +44,55 @@ pub fn keyFor(arena: Allocator, cfg: std.json.ObjectMap) []const u8 {
aw.writer.print(" {s}", .{arg.string}) catch {};
};
};
+ if (cfg.get("cwd")) |cwd| if (cwd == .string and cwd.string.len > 0) {
+ aw.writer.print(" cwd:{s}", .{cwd.string}) catch {};
+ };
+ if (cfg.get("env")) |env| if (env == .object and env.object.count() > 0) {
+ aw.writer.print(" env:{x:0>16}", .{envHash(arena, env.object)}) catch {};
+ };
return aw.writer.buffered();
}
+/// Order-independent hash of an `env` object's pairs.
+fn envHash(arena: Allocator, env: std.json.ObjectMap) u64 {
+ const keys = arena.dupe([]const u8, env.keys()) catch return 0;
+ std.mem.sort([]const u8, keys, {}, struct {
+ fn lt(_: void, x: []const u8, y: []const u8) bool {
+ return std.mem.lessThan(u8, x, y);
+ }
+ }.lt);
+ var h = std.hash.Wyhash.init(0);
+ for (keys) |k| {
+ h.update(k);
+ h.update("=");
+ if (env.get(k)) |v| if (v == .string) h.update(v.string);
+ h.update("\x00");
+ }
+ return h.final();
+}
+
+/// Drop one server's cached catalog so its next start lists tools afresh
+/// (`graff mcp reconnect`). Best-effort, under the same lock as `store`.
+pub fn forget(io: Io, arena: Allocator, home: []const u8, key: []const u8) void {
+ if (key.len == 0 or home.len == 0) return;
+ const path = cachePath(arena, home);
+ if (path.len == 0) return;
+ const lock_path = std.fmt.allocPrint(arena, "{s}.lock", .{path}) catch return;
+ const lock = Io.Dir.cwd().createFile(io, lock_path, .{ .truncate = false, .lock = .exclusive }) catch return;
+ defer lock.close(io);
+ const data = readFile(io, arena, home) orelse return;
+ var root_map = parseRoot(arena, data) orelse return;
+ const servers = root_map.get("servers") orelse return;
+ if (servers != .object) return;
+ var servers_map = servers.object;
+ if (!servers_map.swapRemove(key)) return;
+ root_map.put(arena, "servers", .{ .object = servers_map }) catch return;
+ var aw: Io.Writer.Allocating = .init(arena);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ s.write(Value{ .object = root_map }) catch return;
+ credential_store.replaceFile(io, Io.Dir.cwd(), path, aw.writer.buffered(), .default_file) catch {};
+}
+
fn cachePath(arena: Allocator, home: []const u8) []const u8 {
if (home.len == 0) return "";
return std.fmt.allocPrint(arena, "{s}/" ++ rel_path, .{home}) catch "";
@@ -212,6 +264,45 @@ test "keyFor distinguishes url and command+args" {
try std.testing.expectEqualStrings("cmd:npx -y foo", keyFor(a, cmd_cfg));
}
+test "one launcher command in two directories caches two catalogs" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const home = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{&tmp.sub_path});
+ var args = std.json.Array.init(a);
+ try args.append(.{ .string = "-c" });
+ try args.append(.{ .string = "exec node ./server.mjs" });
+ var review: std.json.ObjectMap = .empty;
+ try review.put(a, "command", .{ .string = "/bin/sh" });
+ try review.put(a, "args", .{ .array = args });
+ try review.put(a, "cwd", .{ .string = "/plugins/review" });
+ var apptools = try review.clone(a);
+ try apptools.put(a, "cwd", .{ .string = "/plugins/app-tools" });
+ const review_key = keyFor(a, review);
+ try std.testing.expect(!std.mem.eql(u8, review_key, keyFor(a, apptools)));
+
+ // Env values change the key but never appear in it.
+ var env: std.json.ObjectMap = .empty;
+ try env.put(a, "TOKEN", .{ .string = "s3cret" });
+ var with_env = try review.clone(a);
+ try with_env.put(a, "env", .{ .object = env });
+ const env_key = keyFor(a, with_env);
+ try std.testing.expect(!std.mem.eql(u8, review_key, env_key));
+ try std.testing.expect(std.mem.indexOf(u8, env_key, "s3cret") == null);
+
+ // forget drops one entry and leaves the other.
+ var result: std.json.ObjectMap = .empty;
+ try result.put(a, "tools", .{ .array = std.json.Array.init(a) });
+ store(io, a, home, review_key, .legacy, "2025-11-25", .{ .object = result }, 1_000);
+ store(io, a, home, env_key, .legacy, "2025-11-25", .{ .object = result }, 1_000);
+ forget(io, a, home, review_key);
+ try std.testing.expect(lookupAnyAge(io, a, home, review_key) == null);
+ try std.testing.expect(lookupAnyAge(io, a, home, env_key) != null);
+}
+
test "ttlFromResult honors CacheableResult ttlMs and clamps" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
diff --git a/src/mcp_call.zig b/src/mcp_call.zig
index 28db8540..59831ab7 100644
--- a/src/mcp_call.zig
+++ b/src/mcp_call.zig
@@ -28,7 +28,7 @@ pub const CallResult = struct { text: []u8, is_error: bool };
/// instead of reporting a tool that was never registered.
pub const Withdrawn = struct { qualified_name: []const u8, server: []const u8, reason: []const u8 };
-const restart_hint = "Inspect /mcp, restart the service and this session, then reload its tool schemas.";
+const restart_hint = "Inspect /mcp; `/mcp reconnect <server>` starts it again without a new session, then reload its tool schemas.";
/// The registry lock is held throughout. Never replay a possibly executed call.
pub fn call(reg: *Registry, out_alloc: Allocator, qualified: []const u8, input: Value, context: ?@import("mcp_turn_context.zig").Snapshot) !CallResult {
@@ -105,7 +105,7 @@ fn invoke(reg: *Registry, out_alloc: Allocator, qualified: []const u8, input: Va
// first; this call then reports the same closed service.
if (withdrawnTool(reg, qualified)) |w| return .{ .text = try std.fmt.allocPrint(out_alloc, "MCP service connection closed or failed earlier in this session ({s}). Its tools have been withdrawn from the catalog; this call was not sent. " ++ restart_hint, .{w.reason}), .is_error = true };
reg.catalog_dirty.store(true, .release);
- return .{ .text = try out_alloc.dupe(u8, "MCP tool is not registered in the current connection. Its loaded schema may be stale. The next catalog will reflect the current registration. Inspect /mcp, restart the session to reconnect the configured service, then reload its schema before retrying."), .is_error = true };
+ return .{ .text = try out_alloc.dupe(u8, "MCP tool is not registered in the current connection. Its loaded schema may be stale. The next catalog will reflect the current registration. Inspect /mcp; `/mcp reconnect <server>` starts the configured service again, then reload its schema before retrying."), .is_error = true };
};
const server = reg.servers[tool.server_index];
diff --git a/src/mcp_cli.zig b/src/mcp_cli.zig
index 5336509c..2d4a21e4 100644
--- a/src/mcp_cli.zig
+++ b/src/mcp_cli.zig
@@ -215,6 +215,9 @@ fn mcpCliUsage(w: *Io.Writer) !void {
\\ graff mcp add … --everywhere save to ~/.codegraff/mcp.json (every project) instead of ./.mcp.json
\\ graff mcp add <name> --url <https://...> [--header KEY=VALUE ...]
\\ graff mcp login <name> OAuth login for a remote server
+ \\ graff mcp status [--json] each server's state and tools, without starting any
+ \\ graff mcp reconnect <name>|--all [--json] start fresh and refresh the cached tools
+ \\ graff mcp enable|disable <name> switch a server on or off everywhere
\\ graff mcp add <name> [--env KEY=VALUE ...] -- <command> [args...]
\\ graff mcp add <name> <command> [args...]
\\
@@ -277,6 +280,7 @@ fn addInferred(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, envir
}
pub fn mcpCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, environ_map: anytype, args: []const []const u8) !void {
+ @import("mcp_lazy.zig").remember(environ_map); // add/reconnect start servers too
if (args.len > 0 and std.mem.eql(u8, args[0], "install")) {
// The installer sets up a launchd/systemd service; spawning it on
// Windows failed with a bare FileNotFound.
@@ -325,6 +329,11 @@ pub fn mcpCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, en
return;
}
+ if (args.len > 0) if (@import("mcp_status_cli.zig").verb(args[0])) {
+ const merged = mcp_config.load(io, arena, Io.Dir.cwd(), mcp_config_path, global_path, home, mcp_config.isEnvOverride(environ_map));
+ return @import("mcp_status_cli.zig").run(io, gpa, arena, home, merged, args, &out.interface, environ_map);
+ };
+
if (args.len == 0 or std.mem.eql(u8, args[0], "list")) {
const merged = mcp_config.load(io, arena, Io.Dir.cwd(), mcp_config_path, global_path, home, mcp_config.isEnvOverride(environ_map));
try mcp_config.reportInvalid(merged, &out.interface, mcp_config_path, global_path, "", "");
diff --git a/src/mcp_config.zig b/src/mcp_config.zig
index 2f3f9ff5..2c810907 100644
--- a/src/mcp_config.zig
+++ b/src/mcp_config.zig
@@ -44,6 +44,9 @@ pub const Merged = struct {
/// 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,
+ /// The user-level file's half, so a status row can say where an entry
+ /// came from (project, global, or imported from another client).
+ global: std.json.ObjectMap = .empty,
/// Whether either file existed. `mcp.Registry.init` returns null (MCP stays
/// optional) only when neither did.
found: bool = false,
@@ -130,6 +133,7 @@ pub fn load(io: Io, arena: Allocator, dir: Io.Dir, project_path: []const u8, glo
// as "no config" and then pick up a project file on a later read.
if (global_is_override and merged.found and !merged.invalid_global and global.count() == 0)
return merged;
+ merged.global = global;
merged.project = readServers(io, arena, dir, project_path, &merged.found, &merged.invalid_project);
diff --git a/src/mcp_lazy.zig b/src/mcp_lazy.zig
index 595090fc..3b148fb4 100644
--- a/src/mcp_lazy.zig
+++ b/src/mcp_lazy.zig
@@ -55,11 +55,14 @@ pub fn stdioSpec(io: Io, gpa: Allocator, a: Allocator, cfg: ObjectMap) !Spec {
if (cwd != .string or cwd.string.len == 0) return error.BadMcpConfig;
spec.cwd = cwd.string;
}
- // Optional per-server env overlaid on the parent environment.
+ // Optional per-server env overlaid on the parent environment. A spawn's
+ // `environ_map` REPLACES the child's environment, so the overlay starts
+ // from a copy of graff's own: an entry that sets one token must not lose
+ // PATH and HOME (an `npx` server then cannot find `node` and exits).
if (cfg.get("env")) |env| {
if (env != .object) return error.BadMcpConfig;
const m = try a.create(std.process.Environ.Map);
- m.* = std.process.Environ.Map.init(gpa);
+ m.* = if (parent_env) |p| try p.clone(gpa) else std.process.Environ.Map.init(gpa);
errdefer m.deinit();
var it = env.object.iterator();
while (it.next()) |entry| {
@@ -71,6 +74,15 @@ pub fn stdioSpec(io: Io, gpa: Allocator, a: Allocator, cfg: ObjectMap) !Spec {
return spec;
}
+/// graff's own environment, the base every per-server `env` overlays. Set
+/// where MCP is set up (`remember`); null in unit tests.
+pub var parent_env: ?*const std.process.Environ.Map = null;
+
+pub fn remember(environ_map: anytype) void {
+ const T = @TypeOf(environ_map);
+ if (T == *std.process.Environ.Map or T == *const std.process.Environ.Map) parent_env = environ_map;
+}
+
/// A stdio entry that did not ask to start with the session.
pub fn wantsLazy(cfg: ObjectMap) bool {
if (cfg.get("command") == null) return false;
@@ -187,3 +199,22 @@ test "cloneMap survives the source arena" {
try std.testing.expectEqualStrings("/tmp", spec.cwd.?);
try std.testing.expectEqualStrings("t", spec.env.?.get("TOKEN").?);
}
+
+test "a server's env overlays graff's own environment instead of replacing it" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var parent = std.process.Environ.Map.init(std.testing.allocator);
+ defer parent.deinit();
+ try parent.put("PATH", "/usr/bin:/bin");
+ try parent.put("TOKEN", "from-parent");
+ const saved = parent_env;
+ defer parent_env = saved;
+ remember(&parent);
+ const cfg = (try std.json.parseFromSliceLeaky(Value, a, "{\"command\":\"npx\",\"env\":{\"TOKEN\":\"from-entry\"}}", .{})).object;
+ const spec = try stdioSpec(std.testing.io, std.testing.allocator, a, cfg);
+ const env = spec.env.?;
+ defer env.deinit();
+ try std.testing.expectEqualStrings("/usr/bin:/bin", env.get("PATH").?);
+ try std.testing.expectEqualStrings("from-entry", env.get("TOKEN").?);
+}
diff --git a/src/mcp_listing.zig b/src/mcp_listing.zig
new file mode 100644
index 00000000..88ad63b4
--- /dev/null
+++ b/src/mcp_listing.zig
@@ -0,0 +1,71 @@
+//! The session's `/mcp` lines for servers that are not connected, and
+//! `/mcp reconnect <name>`. Each server not connected says why (failed with
+//! its cause, switched off, optional, still connecting, or never started
+//! because startup consent was declined), so the `/mcp trust` hint appears
+//! only when trust is actually the reason.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const mcp = @import("mcp.zig");
+const mcp_config = @import("mcp_config.zig");
+const mcp_status = @import("mcp_status.zig");
+const style = &@import("ansi.zig").style;
+
+const NoEnv = struct {
+ pub fn get(_: NoEnv, _: []const u8) ?[]const u8 {
+ return null;
+ }
+};
+
+fn merged(reg: *mcp.Registry, arena: Allocator, config_path: []const u8) mcp_config.Merged {
+ return mcp_config.load(reg.io, arena, Io.Dir.cwd(), config_path, reg.global_config_path, reg.home, reg.global_is_override);
+}
+
+/// After the connected servers: one line per configured server that is not.
+pub fn notConnected(reg: *mcp.Registry, arena: Allocator, out: *Io.Writer, config_path: []const u8) !void {
+ const rows = try mcp_status.live(reg, arena, merged(reg, arena, config_path), NoEnv{});
+ var untrusted: usize = 0;
+ var failed = false;
+ for (rows) |row| switch (row.state) {
+ .ready, .on_demand => {},
+ .not_started => untrusted += 1,
+ else => {
+ failed = failed or row.state == .failed or row.state == .needs_login;
+ try out.print(" {s}{s} {s}{s}{s}{s}\n", .{ style.dim, row.name, mcp_status.label(row), if (row.@"error" != null) " — " else "", row.@"error" orelse "", style.reset });
+ },
+ };
+ if (failed) try out.print(" {s}/mcp reconnect <name> tries a failed server again; graff mcp login <name> signs in{s}\n", .{ style.dim, style.reset });
+ if (untrusted > 0) try out.print(" {s}{d} configured server(s) not started — /mcp trust to connect them{s}\n", .{ style.dim, untrusted, style.reset });
+}
+
+/// `/mcp reconnect <name>`. True when the registry changed and the caller
+/// must re-render its catalog.
+pub fn reconnect(reg: *mcp.Registry, arena: Allocator, out: *Io.Writer, config_path: []const u8, name: []const u8) !bool {
+ defer out.flush() catch {};
+ if (name.len == 0) {
+ try out.writeAll("usage: /mcp reconnect <name>\n");
+ return false;
+ }
+ switch (@import("mcp_reconnect.zig").live(reg, merged(reg, arena, config_path), name)) {
+ .reconnected => |n| try out.print("{s}✓{s} reconnected {s}{s}{s} — {d} tool(s)\n", .{ style.green, style.reset, style.accent, name, style.reset, n }),
+ .connected => |n| try out.print("{s}✓{s} connected {s}{s}{s} — {d} tool(s)\n", .{ style.green, style.reset, style.accent, name, style.reset, n }),
+ .still_connecting => {
+ try out.print("{s} is still connecting; /mcp shows when it is ready.\n", .{name});
+ return false;
+ },
+ .switched_off => {
+ try out.print("{s} is switched off — graff mcp enable {s}, then start a new session.\n", .{ name, name });
+ return false;
+ },
+ .not_configured => {
+ try out.print("no MCP server named {s} — /mcp lists them.\n", .{name});
+ return false;
+ },
+ .failed => |err| {
+ try out.print("{s}✗ {s} did not connect: {s} ({t}){s}\n", .{ style.red, name, mcp_status.errorText(err), err, style.reset });
+ return false;
+ },
+ }
+ return true;
+}
diff --git a/src/mcp_oauth.zig b/src/mcp_oauth.zig
index c9ccf85f..a3ee0124 100644
--- a/src/mcp_oauth.zig
+++ b/src/mcp_oauth.zig
@@ -326,6 +326,15 @@ fn credentialPath(arena: Allocator, home: []const u8, resource_url: []const u8)
return std.fmt.allocPrint(arena, "{s}/.simple-harness-mcp/{s}.json", .{ home, &hex });
}
+/// Whether a sign-in for `resource_url` is stored (`graff mcp status`; no
+/// network, no refresh).
+pub fn hasCredentials(io: Io, arena: Allocator, home: []const u8, resource_url: []const u8) bool {
+ if (home.len == 0) return false;
+ const path = credentialPath(arena, home, resource_url) catch return false;
+ _ = Io.Dir.cwd().statFile(io, path, .{}) catch return false;
+ return true;
+}
+
fn secureWindowsCredentials(io: Io, dir: []const u8, path: []const u8) !void {
// Zig 0.16 does not implement chmod on Windows. Remove inherited ACLs and
// grant full control only to the file owner, using a fixed SID and a
diff --git a/src/mcp_reconnect.zig b/src/mcp_reconnect.zig
new file mode 100644
index 00000000..e898229c
--- /dev/null
+++ b/src/mcp_reconnect.zig
@@ -0,0 +1,247 @@
+//! Reconnect an MCP server: drop its cached catalog and run a real handshake.
+//!
+//! - `probe` (`graff mcp reconnect <name>|--all`, the desktop app's Reconnect
+//! and "Check all"): start each server fresh, record its live catalog for
+//! the next session, report a status row, and stop it again. The desktop app
+//! starts a new graff per run, so this is what makes the *next* turn see a
+//! server's real tools.
+//! - `live` (`/mcp reconnect <name>` in a session): replace the server in the
+//! session's registry at the same index, so tools other parts of the session
+//! already hold keep pointing at the right server. A server that failed at
+//! startup joins the registry for the first time.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const mcp = @import("mcp.zig");
+const mcp_cache = @import("mcp_cache.zig");
+const mcp_config = @import("mcp_config.zig");
+const mcp_rpc = @import("mcp_rpc.zig");
+const mcp_start = @import("mcp_start.zig");
+const mcp_state = @import("mcp_state.zig");
+const mcp_status = @import("mcp_status.zig");
+const mcp_teardown = @import("mcp_teardown.zig");
+const StartOutcome = @import("mcp_boot.zig").StartOutcome;
+
+/// Fresh handshakes for `names` (every switched-on server when null), run
+/// concurrently. Rows come back in config order; switched-off servers are
+/// reported as such and not started.
+pub fn probe(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, merged: mcp_config.Merged, names: ?[]const []const u8, environ_map: anytype) ![]mcp_status.Row {
+ const all = try mcp_status.offline(io, arena, home, merged, environ_map);
+ var rows: std.ArrayList(mcp_status.Row) = .empty;
+ next: for (all) |row| {
+ if (names) |wanted| {
+ for (wanted) |n| {
+ if (std.mem.eql(u8, n, row.name)) break;
+ } else continue :next;
+ } else if (!row.enabled) continue;
+ try rows.append(arena, row);
+ }
+ const futures = try arena.alloc(?Io.Future(StartOutcome), rows.items.len);
+ @memset(futures, null);
+ for (rows.items, futures, 0..) |row, *fut, i| {
+ if (!row.enabled) continue;
+ const cfg = merged.servers.get(row.name).?.object;
+ mcp_cache.forget(io, arena, home, mcp_cache.keyFor(arena, cfg));
+ const ctx: mcp_start.Ctx = .{ .gpa = gpa, .io = io, .home = home, .show_diagnostics = false, .stdio_probe = true, .lazy_stdio = false };
+ fut.* = io.concurrent(mcp_start.task, .{ ctx, row.name, cfg }) catch null;
+ // No thread for it: run it here rather than skip it.
+ if (fut.* == null) apply(io, arena, &rows.items[i], mcp_start.task(ctx, row.name, cfg));
+ }
+ for (rows.items, futures) |*row, *fut| if (fut.*) |*f| apply(io, arena, row, f.await(io));
+ for (rows.items) |*row| if (row.state == .failed and row.transport[0] == 's' and !std.mem.eql(u8, row.errorCode orelse "", "FileNotFound")) {
+ row.detail = stderrHint(io, gpa, arena, merged.servers.get(row.name).?.object);
+ };
+ return rows.items;
+}
+
+/// After a local server failed to start: run it once more with no input for
+/// a moment and keep the last line it wrote to stderr, which is usually the
+/// reason a person can act on. Only ever on an explicit reconnect.
+fn stderrHint(io: Io, gpa: Allocator, arena: Allocator, cfg: std.json.ObjectMap) ?[]const u8 {
+ const spec = @import("mcp_lazy.zig").stdioSpec(io, gpa, arena, cfg) catch return null;
+ defer if (spec.env) |m| m.deinit();
+ const run = @import("process_runner.zig").runCappedWithOptions(arena, io, spec.argv, 4096, 16 * 1024, 3_000, .{
+ .cwd = if (spec.cwd) |p| .{ .path = p } else .inherit,
+ .environ_map = spec.env,
+ .kill_process_tree = true,
+ }) catch return null;
+ return lastLine(arena, run.stderr);
+}
+
+fn lastLine(arena: Allocator, text: []const u8) ?[]const u8 {
+ var lines = std.mem.splitBackwardsScalar(u8, text, '\n');
+ while (lines.next()) |raw| {
+ const line = std.mem.trim(u8, @import("acp_engine.zig").stripSgr(arena, raw) catch raw, " \t\r");
+ if (line.len > 0) return line[0..@min(line.len, 240)];
+ }
+ return null;
+}
+
+/// Fold one start into its row, then stop the server: a probe leaves nothing
+/// running.
+fn apply(io: Io, arena: Allocator, row: *mcp_status.Row, outcome: StartOutcome) void {
+ var o = outcome;
+ const server = o.server orelse {
+ if (mcp_start.failure(row.name)) |err| mcp_status.failedRow(row, err) else row.state = .failed;
+ return;
+ };
+ var tools: std.ArrayList(mcp_status.ToolRow) = .empty;
+ for (o.tools) |t| tools.append(arena, .{
+ .name = arena.dupe(u8, t.original_name) catch continue,
+ .description = arena.dupe(u8, firstLine(t.description)) catch "",
+ }) catch break;
+ row.state = .ready;
+ row.@"error" = null;
+ row.errorCode = null;
+ row.tools = tools.items;
+ row.toolCount = tools.items.len;
+ mcp_rpc.deinitServer(server, io, .init(io, mcp_teardown.teardown_grace));
+ if (o.arena_state) |*a| a.deinit();
+}
+
+fn firstLine(text: []const u8) []const u8 {
+ const line = text[0 .. std.mem.indexOfScalar(u8, text, '\n') orelse text.len];
+ return std.mem.trim(u8, line[0..@min(line.len, 200)], " \t\r");
+}
+
+pub const LiveResult = union(enum) {
+ reconnected: usize,
+ connected: usize,
+ still_connecting,
+ switched_off,
+ not_configured,
+ failed: anyerror,
+};
+
+/// Restart `name` inside the session. The caller re-renders its catalog.
+pub fn live(reg: *mcp.Registry, merged: mcp_config.Merged, name: []const u8) LiveResult {
+ if (@import("mcp_boot.zig").alreadyStarting(reg, name) and !present(reg, name)) return .still_connecting;
+ reg.mutex.lockUncancelable(reg.io);
+ defer reg.mutex.unlock(reg.io);
+ const a = reg.arena();
+ if (mcp_state.load(reg.io, a, reg.home).isDisabled(name)) return .switched_off;
+ const index: ?usize = for (reg.servers, 0..) |s, i| {
+ if (std.mem.eql(u8, s.name, name)) break i;
+ } else null;
+ const cfg = configFor(reg, merged, name, index) orelse return .not_configured;
+ mcp_cache.forget(reg.io, a, reg.home, mcp_cache.keyFor(a, cfg));
+
+ var servers: std.ArrayList(*mcp_rpc.Server) = .empty;
+ var tools: std.ArrayList(mcp.Tool) = .empty;
+ const lazy = reg.lazy_stdio;
+ reg.lazy_stdio = false; // asked for a reconnect: really start it
+ defer reg.lazy_stdio = lazy;
+ reg.startServer(a, &servers, &tools, a.dupe(u8, name) catch return .{ .failed = error.OutOfMemory }, cfg) catch |err| {
+ mcp_start.note(name, err);
+ return .{ .failed = err };
+ };
+ mcp_start.clear(name);
+ return swapIn(reg, index, servers.items[0], tools.items) catch |err| .{ .failed = err };
+}
+
+fn present(reg: *mcp.Registry, name: []const u8) bool {
+ reg.mutex.lockUncancelable(reg.io);
+ defer reg.mutex.unlock(reg.io);
+ for (reg.servers) |s| if (std.mem.eql(u8, s.name, name)) return true;
+ return false;
+}
+
+fn swapIn(reg: *mcp.Registry, index: ?usize, server: *mcp_rpc.Server, fresh: []mcp.Tool) !LiveResult {
+ const a = reg.arena();
+ var servers: std.ArrayList(*mcp_rpc.Server) = .empty;
+ try servers.appendSlice(a, reg.servers);
+ const at = index orelse servers.items.len;
+ if (index) |i| {
+ mcp_rpc.deinitServer(servers.items[i], reg.io, .init(reg.io, mcp_teardown.teardown_grace));
+ servers.items[i] = server;
+ } else try servers.append(a, server);
+ var tools: std.ArrayList(mcp.Tool) = .empty;
+ for (reg.tools) |t| if (t.server_index != at) try tools.append(a, t);
+ for (fresh) |t| {
+ var copy = t;
+ copy.server_index = at;
+ try tools.append(a, copy);
+ }
+ // Tools withdrawn after an earlier close are back.
+ var withdrawn: std.ArrayList(@import("mcp_call.zig").Withdrawn) = .empty;
+ for (reg.withdrawn) |w| if (!std.mem.eql(u8, w.server, server.name)) try withdrawn.append(a, w);
+ reg.servers = servers.items;
+ reg.tools = tools.items;
+ reg.withdrawn = withdrawn.items;
+ reg.catalog_dirty.store(true, .release);
+ return if (index != null) .{ .reconnected = fresh.len } else .{ .connected = fresh.len };
+}
+
+/// The config to start `name` from: its config entry, else how the session
+/// launched it (`/mcp add`, a client-provided server).
+fn configFor(reg: *mcp.Registry, merged: mcp_config.Merged, name: []const u8, index: ?usize) ?std.json.ObjectMap {
+ if (merged.servers.get(name)) |v| if (v == .object) return v.object;
+ const i = index orelse return null;
+ const a = reg.arena();
+ return switch (reg.servers[i].transport) {
+ .stdio => |s| if (s.relaunch) |r| r.cfg else null,
+ .dormant => |d| d.cfg,
+ .http => |h| blk: {
+ var cfg: std.json.ObjectMap = .empty;
+ cfg.put(a, "url", .{ .string = h.url }) catch break :blk null;
+ if (h.headers.len > 0) {
+ var headers: std.json.ObjectMap = .empty;
+ for (h.headers) |hd| headers.put(a, hd.name, .{ .string = hd.value }) catch break :blk null;
+ cfg.put(a, "headers", .{ .object = headers }) catch break :blk null;
+ }
+ break :blk cfg;
+ },
+ };
+}
+
+test "a failed reconnect keeps the server's last stderr line" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ try std.testing.expectEqualStrings("tool: not licensed. Run: tool activate", lastLine(a, "starting\n\x1b[31mtool: not licensed. Run: tool activate\x1b[0m\n\n").?);
+ try std.testing.expect(lastLine(a, " \n") == null);
+}
+
+test "live reconnect swaps a server in place and brings back withdrawn tools" {
+ if (@import("builtin").os.tag == .windows) return error.SkipZigTest; // /bin/sh
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var reg = mcp.Registry.empty(gpa, io);
+ defer reg.deinit();
+ reg.stdio_probe = false;
+ reg.lazy_stdio = false;
+ const script =
+ \\while read -r l; do
+ \\ id=$(printf '%s' "$l" | sed -n 's/^{"jsonrpc":"2.0","id":\([0-9]*\),.*/\1/p')
+ \\ [ -z "$id" ] && continue
+ \\ case "$l" in
+ \\ *'"method":"initialize"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":"2025-06-18","capabilities":{"tools":{}},"serverInfo":{"name":"f","version":"1"}}}\n' "$id" ;;
+ \\ *'"method":"tools/list"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"tools":[{"name":"ping","description":"d","inputSchema":{"type":"object"}}]}}\n' "$id" ;;
+ \\ *) printf '{"jsonrpc":"2.0","id":%s,"result":{"content":[{"type":"text","text":"pong"}]}}\n' "$id" ;;
+ \\ esac
+ \\done
+ ;
+ _ = try reg.addServer("first", "/bin/sh", &.{ "-c", script });
+ _ = try reg.addServer("second", "/bin/sh", &.{ "-c", script });
+ const old_second = reg.servers[1];
+ reg.withdrawn = try reg.arena().dupe(@import("mcp_call.zig").Withdrawn, &.{.{ .qualified_name = "mcp__second__ping", .server = "second", .reason = "McpClosed" }});
+
+ const merged: mcp_config.Merged = .{};
+ const result = live(&reg, merged, "second");
+ try std.testing.expectEqual(@as(usize, 1), result.reconnected);
+ try std.testing.expectEqual(@as(usize, 2), reg.servers.len);
+ try std.testing.expect(reg.servers[1] != old_second);
+ try std.testing.expectEqualStrings("second", reg.servers[1].name);
+ try std.testing.expectEqual(@as(usize, 0), reg.withdrawn.len);
+ var second_tools: usize = 0;
+ for (reg.tools) |t| if (t.server_index == 1) {
+ second_tools += 1;
+ };
+ try std.testing.expectEqual(@as(usize, 1), second_tools);
+ const args: std.json.Value = .{ .object = .empty };
+ const out = try reg.call(gpa, "mcp__second__ping", args);
+ defer gpa.free(out.text);
+ try std.testing.expectEqualStrings("pong", out.text);
+ try std.testing.expectEqual(LiveResult.not_configured, live(&reg, merged, "missing"));
+}
diff --git a/src/mcp_rpc_tests.zig b/src/mcp_rpc_tests.zig
index a0437883..1689bcef 100644
--- a/src/mcp_rpc_tests.zig
+++ b/src/mcp_rpc_tests.zig
@@ -55,7 +55,7 @@ test "MCP recovery #1467: first call EOF returns restart guidance without replay
defer std.testing.allocator.free(result.text);
try std.testing.expect(result.is_error);
try std.testing.expect(std.mem.indexOf(u8, result.text, "McpClosed") != null);
- try std.testing.expect(std.mem.indexOf(u8, result.text, "restart the service and this session") != null);
+ try std.testing.expect(std.mem.indexOf(u8, result.text, "/mcp reconnect <server>") != null);
try std.testing.expectEqual(@as(i64, 2), spawned.server.next_id);
try std.testing.expectEqual(@as(usize, 0), (try reg.snapshotTools(reg.arena())).len);
try std.testing.expect(reg.catalog_dirty.load(.acquire));
diff --git a/src/mcp_start.zig b/src/mcp_start.zig
new file mode 100644
index 00000000..cc147e54
--- /dev/null
+++ b/src/mcp_start.zig
@@ -0,0 +1,153 @@
+//! One server's background connect (split from mcp_boot.zig under the 600-line
+//! ceiling), with the two things a failed start used to lose:
+//!
+//! - A transient failure (the process closed during the handshake, a timeout,
+//! a refused or reset connection) is retried once after a short pause. A
+//! server that is still starting up the first time a session asks no longer
+//! stays down for the whole session.
+//! - The reason is recorded by name (`failure`), so `/mcp`, `graff mcp status`
+//! and the desktop app's MCP page can say *why* a server is not connected
+//! instead of folding it into "not connected — /mcp trust".
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const mcp = @import("mcp.zig");
+const mcp_rpc = @import("mcp_rpc.zig");
+const StartOutcome = @import("mcp_boot.zig").StartOutcome;
+
+pub const Ctx = struct {
+ gpa: Allocator,
+ io: Io,
+ home: []const u8,
+ show_diagnostics: bool,
+ stdio_probe: bool,
+ lazy_stdio: bool = true,
+ ready: ?*std.atomic.Value(bool) = null,
+ /// Pause before the one retry of a transient failure.
+ retry_ms: u32 = 1_500,
+};
+
+pub fn task(ctx: Ctx, name: []const u8, cfg: std.json.ObjectMap) StartOutcome {
+ defer if (ctx.ready) |flag| flag.store(true, .release);
+ return attempt(ctx, name, cfg) catch |first| {
+ if (transient(first)) {
+ ctx.io.sleep(.fromMilliseconds(ctx.retry_ms), .awake) catch {};
+ if (attempt(ctx, name, cfg)) |outcome| return outcome else |again| return failed(ctx, name, again);
+ }
+ return failed(ctx, name, first);
+ };
+}
+
+fn failed(ctx: Ctx, name: []const u8, err: anyerror) StartOutcome {
+ if (ctx.show_diagnostics) std.debug.print(" [mcp:{s}] failed to start: {t}\n", .{ name, err });
+ note(name, err);
+ return .{};
+}
+
+fn attempt(ctx: Ctx, name: []const u8, cfg: std.json.ObjectMap) !StartOutcome {
+ var arena_state = std.heap.ArenaAllocator.init(ctx.gpa);
+ errdefer arena_state.deinit();
+ const a = arena_state.allocator();
+ var servers: std.ArrayList(*mcp_rpc.Server) = .empty;
+ var tools: std.ArrayList(mcp.Tool) = .empty;
+ // Task-local Registry: only gpa/io/home/flags are read by startServer.
+ // Must not point at init()'s stack `reg` — that dies when defer_join returns.
+ var tmp: mcp.Registry = .{
+ .gpa = ctx.gpa,
+ .io = ctx.io,
+ .home = ctx.home,
+ .arena_state = std.heap.ArenaAllocator.init(ctx.gpa),
+ .stdio_probe = ctx.stdio_probe,
+ .lazy_stdio = ctx.lazy_stdio,
+ .show_diagnostics = ctx.show_diagnostics,
+ };
+ defer tmp.arena_state.deinit();
+ try tmp.startServer(a, &servers, &tools, name, cfg);
+ clear(name);
+ return .{ .server = servers.items[0], .tools = tools.items, .arena_state = arena_state };
+}
+
+/// Failures worth one more try: the server may simply not have been ready.
+/// A missing binary, a bad config or a sign-in will fail the same way again.
+pub fn transient(err: anyerror) bool {
+ return switch (err) {
+ error.McpClosed,
+ error.McpHandshakeTimeout,
+ error.McpRequestTimedOut,
+ error.McpHttpStatus,
+ error.McpSessionExpired,
+ error.ConnectionRefused,
+ error.ConnectionResetByPeer,
+ error.ConnectionTimedOut,
+ error.BrokenPipe,
+ error.EndOfStream,
+ => true,
+ else => false,
+ };
+}
+
+/// Why each server last failed to start in this process, by name. Written by
+/// connect tasks on pool threads; read by `/mcp` on the session thread.
+var mutex: std.atomic.Mutex = .unlocked;
+var names: [32][64]u8 = undefined;
+var name_lens: [32]u8 = @splat(0);
+var errors: [32]anyerror = undefined;
+var count: usize = 0;
+
+fn lock() void {
+ while (!mutex.tryLock()) std.atomic.spinLoopHint();
+}
+
+fn slotLocked(name: []const u8) ?usize {
+ for (0..count) |i| if (std.mem.eql(u8, names[i][0..name_lens[i]], name)) return i;
+ return null;
+}
+
+pub fn note(name: []const u8, err: anyerror) void {
+ if (name.len > 64) return;
+ lock();
+ defer mutex.unlock();
+ const i = slotLocked(name) orelse blk: {
+ if (count == names.len) return;
+ count += 1;
+ break :blk count - 1;
+ };
+ @memcpy(names[i][0..name.len], name);
+ name_lens[i] = @intCast(name.len);
+ errors[i] = err;
+}
+
+pub fn clear(name: []const u8) void {
+ lock();
+ defer mutex.unlock();
+ if (slotLocked(name)) |i| name_lens[i] = 0;
+}
+
+/// The last start failure recorded for `name`, if it has not since connected.
+pub fn failure(name: []const u8) ?anyerror {
+ lock();
+ defer mutex.unlock();
+ const i = slotLocked(name) orelse return null;
+ return if (name_lens[i] == 0) null else errors[i];
+}
+
+test "a transient start failure is retried once; a missing binary is not" {
+ try std.testing.expect(transient(error.McpClosed));
+ try std.testing.expect(transient(error.McpHandshakeTimeout));
+ try std.testing.expect(!transient(error.FileNotFound));
+ try std.testing.expect(!transient(error.McpAuthenticationRequired));
+ try std.testing.expect(!transient(error.BadMcpConfig));
+}
+
+test "start failures are remembered by name until the server connects" {
+ note("fixture-a", error.FileNotFound);
+ note("fixture-b", error.McpClosed);
+ try std.testing.expectEqual(@as(?anyerror, error.FileNotFound), failure("fixture-a"));
+ note("fixture-a", error.McpHandshakeTimeout);
+ try std.testing.expectEqual(@as(?anyerror, error.McpHandshakeTimeout), failure("fixture-a"));
+ clear("fixture-a");
+ try std.testing.expect(failure("fixture-a") == null);
+ try std.testing.expectEqual(@as(?anyerror, error.McpClosed), failure("fixture-b"));
+ try std.testing.expect(failure("never-seen") == null);
+}
diff --git a/src/mcp_state.zig b/src/mcp_state.zig
new file mode 100644
index 00000000..cf221ff7
--- /dev/null
+++ b/src/mcp_state.zig
@@ -0,0 +1,142 @@
+//! Per-user on/off choices for MCP servers: `graff mcp enable|disable <name>`
+//! and the desktop app's MCP servers page.
+//!
+//! `~/.codegraff/mcp-state.json` holds `{"disabled":[…], "enabled":[…]}`. It
+//! is separate from the server configs on purpose: entries imported from other
+//! clients' files (plugins.zig) can be switched off without rewriting a file
+//! graff does not own. `disabled` keeps a server from starting anywhere;
+//! `enabled` opts in a server that is off by default (deepwiki, mobbin — see
+//! tool_surface.skipOptionalServer), alongside the existing env opt-ins.
+
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+const credential_store = @import("credential_store.zig");
+
+pub const rel_path = ".codegraff/mcp-state.json";
+
+pub const State = struct {
+ disabled: []const []const u8 = &.{},
+ enabled: []const []const u8 = &.{},
+
+ pub fn isDisabled(s: State, name: []const u8) bool {
+ return contains(s.disabled, name);
+ }
+
+ pub fn isEnabled(s: State, name: []const u8) bool {
+ return contains(s.enabled, name);
+ }
+};
+
+/// Why a configured server does not start with the session, if it does not.
+pub const Skip = enum { none, off, opt_in };
+
+/// The boot rule every reader shares (mcp_boot.init, /mcp trust, status rows):
+/// switched off by the user, switched off in the entry itself, or an optional
+/// server nobody opted in to. An explicit `graff mcp enable` beats the entry.
+pub fn skipReason(state: State, name: []const u8, cfg: ?std.json.ObjectMap, environ_map: anytype, global_only: bool) Skip {
+ if (state.isDisabled(name)) return .off;
+ if (state.isEnabled(name)) return .none;
+ if (cfg) |c| if (offInConfig(c)) return .off;
+ if (@import("tool_surface.zig").skipOptionalAtBoot(name, environ_map, global_only)) return .opt_in;
+ return .none;
+}
+
+/// `"enabled": false` (Codex plugin manifests) or `"disabled": true` (Claude
+/// and Cursor configs): the file that declares the server has it off, so
+/// graff must not start it either.
+pub fn offInConfig(cfg: std.json.ObjectMap) bool {
+ if (cfg.get("enabled")) |v| if (v == .bool and !v.bool) return true;
+ if (cfg.get("disabled")) |v| if (v == .bool and v.bool) return true;
+ return false;
+}
+
+fn contains(list: []const []const u8, name: []const u8) bool {
+ for (list) |n| if (std.mem.eql(u8, n, name)) return true;
+ return false;
+}
+
+fn path(arena: Allocator, home: []const u8) ?[]const u8 {
+ if (home.len == 0) return null;
+ return std.fmt.allocPrint(arena, "{s}/" ++ rel_path, .{home}) catch null;
+}
+
+fn names(arena: Allocator, obj: std.json.ObjectMap, field: []const u8) []const []const u8 {
+ const v = obj.get(field) orelse return &.{};
+ if (v != .array) return &.{};
+ var out: std.ArrayList([]const u8) = .empty;
+ for (v.array.items) |item| if (item == .string and item.string.len > 0) out.append(arena, item.string) catch break;
+ return out.items;
+}
+
+/// Best-effort: a missing or malformed file is "no choices made".
+pub fn load(io: Io, arena: Allocator, home: []const u8) State {
+ const p = path(arena, home) orelse return .{};
+ const text = Io.Dir.cwd().readFileAlloc(io, p, arena, .limited(1 << 20)) catch return .{};
+ const parsed = std.json.parseFromSliceLeaky(Value, arena, text, .{ .allocate = .alloc_always }) catch return .{};
+ if (parsed != .object) return .{};
+ return .{ .disabled = names(arena, parsed.object, "disabled"), .enabled = names(arena, parsed.object, "enabled") };
+}
+
+/// Switch `name` on or off and persist it. On removes it from `disabled` and
+/// records the opt-in; off does the reverse.
+pub fn set(io: Io, arena: Allocator, home: []const u8, name: []const u8, on: bool) !void {
+ const p = path(arena, home) orelse return error.NoHomeDirectory;
+ const current = load(io, arena, home);
+ var disabled: std.ArrayList([]const u8) = .empty;
+ var enabled: std.ArrayList([]const u8) = .empty;
+ for (current.disabled) |n| if (!std.mem.eql(u8, n, name)) try disabled.append(arena, n);
+ for (current.enabled) |n| if (!std.mem.eql(u8, n, name)) try enabled.append(arena, n);
+ try (if (on) &enabled else &disabled).append(arena, name);
+ var aw: Io.Writer.Allocating = .init(arena);
+ try std.json.Stringify.value(.{ .disabled = disabled.items, .enabled = enabled.items }, .{ .whitespace = .indent_2 }, &aw.writer);
+ try aw.writer.writeByte('\n');
+ if (std.fs.path.dirname(p)) |dir| Io.Dir.cwd().createDirPath(io, dir) catch {};
+ try credential_store.replaceFile(io, Io.Dir.cwd(), p, aw.writer.buffered(), .default_file);
+}
+
+const NoEnv = struct {
+ pub fn get(_: NoEnv, _: []const u8) ?[]const u8 {
+ return null;
+ }
+};
+
+test "mcp state: off wins, on opts in an optional server, choices persist" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const home = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{&tmp.sub_path});
+
+ var state = load(io, a, home);
+ try std.testing.expectEqual(Skip.none, skipReason(state, "github", null, NoEnv{}, true));
+ try std.testing.expectEqual(Skip.opt_in, skipReason(state, "deepwiki", null, NoEnv{}, true));
+ // A project that lists the optional server opts it in on its own.
+ try std.testing.expectEqual(Skip.none, skipReason(state, "deepwiki", null, NoEnv{}, false));
+
+ try set(io, a, home, "github", false);
+ try set(io, a, home, "deepwiki", true);
+ state = load(io, a, home);
+ try std.testing.expectEqual(Skip.off, skipReason(state, "github", null, NoEnv{}, true));
+ try std.testing.expectEqual(Skip.off, skipReason(state, "github", null, NoEnv{}, false));
+ try std.testing.expectEqual(Skip.none, skipReason(state, "deepwiki", null, NoEnv{}, true));
+
+ // An entry its own file switched off stays off until enabled here.
+ const off_cfg = (try std.json.parseFromSliceLeaky(Value, a, "{\"command\":\"x\",\"enabled\":false}", .{})).object;
+ try std.testing.expectEqual(Skip.off, skipReason(state, "plugin", off_cfg, NoEnv{}, true));
+ const disabled_cfg = (try std.json.parseFromSliceLeaky(Value, a, "{\"command\":\"x\",\"disabled\":true}", .{})).object;
+ try std.testing.expectEqual(Skip.off, skipReason(state, "plugin", disabled_cfg, NoEnv{}, true));
+ try set(io, a, home, "plugin", true);
+ try std.testing.expectEqual(Skip.none, skipReason(load(io, a, home), "plugin", off_cfg, NoEnv{}, true));
+
+ // Switching back on clears the off and is idempotent.
+ try set(io, a, home, "github", true);
+ try set(io, a, home, "github", true);
+ state = load(io, a, home);
+ try std.testing.expectEqual(Skip.none, skipReason(state, "github", null, NoEnv{}, true));
+ try std.testing.expectEqual(@as(usize, 0), state.disabled.len);
+ try std.testing.expectEqual(@as(usize, 3), state.enabled.len);
+}
diff --git a/src/mcp_status.zig b/src/mcp_status.zig
new file mode 100644
index 00000000..41dc111d
--- /dev/null
+++ b/src/mcp_status.zig
@@ -0,0 +1,342 @@
+//! What each configured MCP server is doing, as one row per server: the data
+//! behind `/mcp`, `graff mcp status --json` and the desktop app's MCP servers
+//! page (and the fullscreen client's `/mcp`).
+//!
+//! Two views of the same row:
+//! - `offline`: config + the catalog cache + stored sign-ins. Spawns nothing
+//! and touches no network, so a settings page can list servers instantly.
+//! - `live`: the session's registry, which also knows what is connected,
+//! still connecting, or failed to start (mcp_start.failure).
+//! A real handshake is `graff mcp reconnect` (mcp_reconnect.zig).
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const mcp = @import("mcp.zig");
+const mcp_cache = @import("mcp_cache.zig");
+const mcp_config = @import("mcp_config.zig");
+const mcp_state = @import("mcp_state.zig");
+
+pub const State = enum {
+ /// Connected; its tools are live.
+ ready,
+ /// Known tools; the server starts (or connects) on its first call.
+ on_demand,
+ /// Starting in the background.
+ connecting,
+ failed,
+ needs_login,
+ /// Switched off by the user.
+ off,
+ /// Off by default until opted in.
+ opt_in,
+ /// Configured but not started this session (startup consent declined).
+ not_started,
+ /// Never checked: no cached catalog yet.
+ unknown,
+};
+
+pub const ToolRow = struct { name: []const u8, description: []const u8 };
+
+pub const Row = struct {
+ name: []const u8,
+ /// project | global | imported | session
+ source: []const u8,
+ /// stdio | http
+ transport: []const u8,
+ /// Command basename or URL origin; never args, env or headers.
+ origin: []const u8,
+ enabled: bool,
+ state: State,
+ @"error": ?[]const u8 = null,
+ errorCode: ?[]const u8 = null,
+ /// The server's own last stderr line after a failed reconnect, which
+ /// usually names the fix ("not licensed", "missing API key").
+ detail: ?[]const u8 = null,
+ /// none | bearer | oauth | unknown
+ auth: []const u8,
+ toolCount: usize,
+ tools: []const ToolRow,
+};
+
+pub fn sourceOf(merged: mcp_config.Merged, name: []const u8) []const u8 {
+ if (merged.project.get(name) != null) return "project";
+ if (merged.global.get(name) != null) return "global";
+ if (merged.servers.get(name) != null) return "imported";
+ return "session";
+}
+
+/// A short, secret-free label for where the server runs.
+pub fn originOf(arena: Allocator, cfg: std.json.ObjectMap) []const u8 {
+ if (cfg.get("url")) |u| if (u == .string) {
+ const sep = std.mem.indexOf(u8, u.string, "://") orelse return "remote";
+ var rest = u.string[sep + 3 ..];
+ rest = rest[0 .. std.mem.indexOfAny(u8, rest, "/?#") orelse rest.len];
+ if (std.mem.lastIndexOfScalar(u8, rest, '@')) |at| rest = rest[at + 1 ..]; // drop user:password
+ return std.fmt.allocPrint(arena, "{s}://{s}", .{ u.string[0..sep], rest }) catch "remote";
+ };
+ const command = if (cfg.get("command")) |c| (if (c == .string) c.string else "") else "";
+ const base = std.fs.path.basename(command);
+ // A package runner names the package, not itself.
+ const runners = [_][]const u8{ "npx", "uvx", "bunx", "pnpx", "pipx" };
+ for (runners) |r| if (std.mem.eql(u8, base, r)) {
+ if (cfg.get("args")) |args| if (args == .array) for (args.array.items) |arg| {
+ if (arg == .string and arg.string.len > 0 and arg.string[0] != '-')
+ return std.fmt.allocPrint(arena, "{s} {s}", .{ base, arg.string }) catch base;
+ };
+ };
+ return base;
+}
+
+fn transportOf(cfg: std.json.ObjectMap) []const u8 {
+ return if (cfg.get("url") != null) "http" else "stdio";
+}
+
+fn authOf(io: Io, arena: Allocator, home: []const u8, cfg: std.json.ObjectMap) []const u8 {
+ const url = cfg.get("url") orelse return "none";
+ if (cfg.get("headers")) |h| if (h == .object) {
+ var it = h.object.iterator();
+ while (it.next()) |e| if (std.ascii.eqlIgnoreCase(e.key_ptr.*, "authorization")) return "bearer";
+ };
+ if (url == .string and @import("mcp_oauth.zig").hasCredentials(io, arena, home, url.string)) return "oauth";
+ return "unknown";
+}
+
+/// The first line of a tool description, capped for a list view.
+fn summary(text: []const u8) []const u8 {
+ const line = text[0 .. std.mem.indexOfScalar(u8, text, '\n') orelse text.len];
+ return std.mem.trim(u8, line[0..@min(line.len, 200)], " \t\r");
+}
+
+fn cachedTools(arena: Allocator, tools: std.json.Value) []const ToolRow {
+ if (tools != .array) return &.{};
+ var out: std.ArrayList(ToolRow) = .empty;
+ for (tools.array.items) |t| {
+ if (t != .object or !@import("mcp_apps.zig").modelVisible(t)) continue; // as the session lists them
+ const name = t.object.get("name") orelse continue;
+ if (name != .string) continue;
+ const desc = if (t.object.get("description")) |d| (if (d == .string) d.string else "") else "";
+ out.append(arena, .{ .name = name.string, .description = summary(desc) }) catch break;
+ }
+ return out.items;
+}
+
+/// Human text for a start failure; `errorCode` keeps the raw name.
+pub fn errorText(err: anyerror) []const u8 {
+ return switch (err) {
+ error.FileNotFound => "command not found",
+ error.AccessDenied, error.PermissionDenied => "command is not executable",
+ error.McpClosed, error.EndOfStream, error.BrokenPipe, error.WriteFailed => "the server exited during startup",
+ error.McpHandshakeTimeout, error.McpRequestTimedOut, error.ConnectionTimedOut => "the server did not answer in time",
+ error.McpAuthenticationRequired => "sign-in required",
+ error.ConnectionRefused => "connection refused",
+ error.McpHttpStatus => "the server returned an HTTP error",
+ error.BadMcpConfig => "invalid config entry",
+ error.BadMcpUrl => "invalid URL",
+ error.McpIncompatibleProtocolVersion => "unsupported MCP protocol version",
+ else => "failed to start",
+ };
+}
+
+pub fn failedRow(row: *Row, err: anyerror) void {
+ row.state = if (err == error.McpAuthenticationRequired) .needs_login else .failed;
+ row.@"error" = errorText(err);
+ row.errorCode = @errorName(err);
+}
+
+fn baseRow(io: Io, arena: Allocator, home: []const u8, merged: mcp_config.Merged, name: []const u8, cfg: std.json.ObjectMap) Row {
+ return .{
+ .name = name,
+ .source = sourceOf(merged, name),
+ .transport = transportOf(cfg),
+ .origin = originOf(arena, cfg),
+ .enabled = true,
+ .state = .unknown,
+ .auth = authOf(io, arena, home, cfg),
+ .toolCount = 0,
+ .tools = &.{},
+ };
+}
+
+fn applySkip(row: *Row, skip: mcp_state.Skip) bool {
+ switch (skip) {
+ .none => return false,
+ .off => row.state = .off,
+ .opt_in => row.state = .opt_in,
+ }
+ row.enabled = false;
+ return true;
+}
+
+/// Every configured server from config, cache and stored sign-ins alone.
+pub fn offline(io: Io, arena: Allocator, home: []const u8, merged: mcp_config.Merged, environ_map: anytype) ![]Row {
+ const state = mcp_state.load(io, arena, home);
+ var rows: std.ArrayList(Row) = .empty;
+ var it = merged.servers.iterator();
+ while (it.next()) |e| {
+ if (e.value_ptr.* != .object) continue;
+ const cfg = e.value_ptr.*.object;
+ var row = baseRow(io, arena, home, merged, e.key_ptr.*, cfg);
+ _ = applySkip(&row, mcp_state.skipReason(state, row.name, cfg, environ_map, merged.isGlobalOnly(row.name)));
+ if (mcp_cache.lookupAnyAge(io, arena, home, mcp_cache.keyFor(arena, cfg))) |hit| {
+ row.tools = cachedTools(arena, hit.tools);
+ row.toolCount = row.tools.len;
+ if (row.enabled) row.state = .on_demand;
+ }
+ try rows.append(arena, row);
+ }
+ return rows.items;
+}
+
+fn liveTools(arena: Allocator, reg: *const mcp.Registry, index: usize) []const ToolRow {
+ var out: std.ArrayList(ToolRow) = .empty;
+ for (reg.tools) |t| if (t.server_index == index)
+ out.append(arena, .{ .name = t.original_name, .description = summary(t.description) }) catch break;
+ return out.items;
+}
+
+/// The session's view: configured servers plus any added at runtime.
+pub fn live(reg: *mcp.Registry, arena: Allocator, merged: mcp_config.Merged, environ_map: anytype) ![]Row {
+ const state = mcp_state.load(reg.io, arena, reg.home);
+ var rows: std.ArrayList(Row) = .empty;
+ var it = merged.servers.iterator();
+ while (it.next()) |e| {
+ if (e.value_ptr.* != .object) continue;
+ var row = baseRow(reg.io, arena, reg.home, merged, e.key_ptr.*, e.value_ptr.*.object);
+ // A recorded failure means it was tried, whatever its opt-in says.
+ if (!liveState(reg, arena, &row)) if (@import("mcp_start.zig").failure(row.name)) |err| failedRow(&row, err) else if (!applySkip(&row, mcp_state.skipReason(state, row.name, e.value_ptr.*.object, environ_map, merged.isGlobalOnly(row.name)))) {
+ row.state = .not_started;
+ };
+ try rows.append(arena, row);
+ }
+ for (reg.servers, 0..) |server, i| {
+ if (merged.servers.get(server.name) != null) continue;
+ try rows.append(arena, .{
+ .name = server.name,
+ .source = "session",
+ .transport = if (server.transport == .http) "http" else "stdio",
+ .origin = "",
+ .enabled = true,
+ .state = if (server.transport == .dormant) .on_demand else .ready,
+ .auth = "none",
+ .toolCount = reg.toolCount(i),
+ .tools = liveTools(arena, reg, i),
+ });
+ }
+ return rows.items;
+}
+
+/// Connected or still connecting: true when the registry decided the state.
+fn liveState(reg: *mcp.Registry, arena: Allocator, row: *Row) bool {
+ for (reg.servers, 0..) |server, i| if (std.mem.eql(u8, server.name, row.name)) {
+ row.state = if (server.transport == .dormant) .on_demand else .ready;
+ row.tools = liveTools(arena, reg, i);
+ row.toolCount = row.tools.len;
+ return true;
+ };
+ for (@import("mcp_connect_notice.zig").connecting(reg, arena)) |n| if (std.mem.eql(u8, n, row.name)) {
+ row.state = .connecting;
+ return true;
+ };
+ return false;
+}
+
+pub fn writeJson(rows: []const Row, w: *Io.Writer) !void {
+ try std.json.Stringify.value(.{ .version = 1, .servers = rows }, .{ .emit_null_optional_fields = false }, w);
+ try w.writeByte('\n');
+}
+
+/// One line per state for `/mcp`.
+pub fn label(row: Row) []const u8 {
+ return switch (row.state) {
+ .ready => "connected",
+ .on_demand => "starts on first use",
+ .connecting => "connecting",
+ .failed => "failed",
+ .needs_login => "sign-in required",
+ .off => "off",
+ .opt_in => "off (optional)",
+ .not_started => "not started",
+ .unknown => "not checked yet",
+ };
+}
+
+const testing = std.testing;
+
+test "mcp status rows: origin hides args and secrets; failures name the cause" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const parse = struct {
+ fn f(al: Allocator, s: []const u8) std.json.ObjectMap {
+ return (std.json.parseFromSliceLeaky(std.json.Value, al, s, .{}) catch unreachable).object;
+ }
+ }.f;
+ try testing.expectEqualStrings("npx @scope/server-x", originOf(a, parse(a, "{\"command\":\"npx\",\"args\":[\"-y\",\"@scope/server-x\",\"--token\",\"abc\"]}")));
+ try testing.expectEqualStrings("codedb", originOf(a, parse(a, "{\"command\":\"/opt/bin/codedb\",\"args\":[\"mcp\"]}")));
+ try testing.expectEqualStrings("https://mcp.example.com", originOf(a, parse(a, "{\"url\":\"https://user:[email protected]/mcp?key=s3cret\"}")));
+
+ var row: Row = .{ .name = "x", .source = "global", .transport = "stdio", .origin = "x", .enabled = true, .state = .unknown, .auth = "none", .toolCount = 0, .tools = &.{} };
+ failedRow(&row, error.McpAuthenticationRequired);
+ try testing.expectEqual(State.needs_login, row.state);
+ failedRow(&row, error.FileNotFound);
+ try testing.expectEqual(State.failed, row.state);
+ try testing.expectEqualStrings("command not found", row.@"error".?);
+
+ var aw: Io.Writer.Allocating = .init(a);
+ try writeJson(&.{row}, &aw.writer);
+ const out = aw.writer.buffered();
+ try testing.expect(std.mem.indexOf(u8, out, "\"state\":\"failed\"") != null);
+ try testing.expect(std.mem.indexOf(u8, out, "\"errorCode\":\"FileNotFound\"") != null);
+ try testing.expect(std.mem.indexOf(u8, out, "\"version\":1") != null);
+}
+
+test "offline status: cached catalog means on demand; off and optional say so" {
+ const io = testing.io;
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const home = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{&tmp.sub_path});
+ try tmp.dir.writeFile(io, .{ .sub_path = "global.json", .data =
+ \\{"mcpServers":{"cached":{"command":"srv-a"},"fresh":{"command":"srv-b"},"deepwiki":{"url":"https://mcp.deepwiki.com/mcp"},"muted":{"command":"srv-c"}}}
+ });
+ var cfg: std.json.ObjectMap = .empty;
+ try cfg.put(a, "command", .{ .string = "srv-a" });
+ var result: std.json.ObjectMap = .empty;
+ var tools = std.json.Array.init(a);
+ var tool: std.json.ObjectMap = .empty;
+ try tool.put(a, "name", .{ .string = "search" });
+ try tool.put(a, "description", .{ .string = "Find things.\nLong detail." });
+ try tools.append(.{ .object = tool });
+ try result.put(a, "tools", .{ .array = tools });
+ mcp_cache.store(io, a, home, mcp_cache.keyFor(a, cfg), .modern, "2026-07-28", .{ .object = result }, 1_000);
+ try mcp_state.set(io, a, home, "muted", false);
+
+ const merged = mcp_config.load(io, a, tmp.dir, ".mcp.json", "global.json", "", false);
+ const NoEnv = struct {
+ pub fn get(_: @This(), _: []const u8) ?[]const u8 {
+ return null;
+ }
+ };
+ const rows = try offline(io, a, home, merged, NoEnv{});
+ var seen: usize = 0;
+ for (rows) |r| {
+ try testing.expectEqualStrings("global", r.source);
+ if (std.mem.eql(u8, r.name, "cached")) {
+ try testing.expectEqual(State.on_demand, r.state);
+ try testing.expectEqualStrings("Find things.", r.tools[0].description);
+ } else if (std.mem.eql(u8, r.name, "fresh")) {
+ try testing.expectEqual(State.unknown, r.state);
+ } else if (std.mem.eql(u8, r.name, "deepwiki")) {
+ try testing.expectEqual(State.opt_in, r.state);
+ try testing.expectEqualStrings("unknown", r.auth);
+ } else if (std.mem.eql(u8, r.name, "muted")) {
+ try testing.expectEqual(State.off, r.state);
+ try testing.expect(!r.enabled);
+ } else continue;
+ seen += 1;
+ }
+ try testing.expectEqual(@as(usize, 4), seen);
+}
diff --git a/src/mcp_status_cli.zig b/src/mcp_status_cli.zig
new file mode 100644
index 00000000..1d22fde6
--- /dev/null
+++ b/src/mcp_status_cli.zig
@@ -0,0 +1,70 @@
+//! `graff mcp status | reconnect | enable | disable`: the CLI the desktop app's
+//! MCP servers page and the fullscreen client's `/mcp` run (with `--json`).
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const mcp_config = @import("mcp_config.zig");
+const mcp_state = @import("mcp_state.zig");
+const mcp_status = @import("mcp_status.zig");
+
+pub fn verb(arg: []const u8) bool {
+ const verbs = [_][]const u8{ "status", "reconnect", "enable", "disable" };
+ for (verbs) |v| if (std.mem.eql(u8, arg, v)) return true;
+ return false;
+}
+
+pub fn run(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, merged: mcp_config.Merged, args: []const []const u8, out: *Io.Writer, environ_map: anytype) !void {
+ var json = false;
+ var all = false;
+ var names: std.ArrayList([]const u8) = .empty;
+ for (args[1..]) |arg| {
+ if (std.mem.eql(u8, arg, "--json")) json = true else if (std.mem.eql(u8, arg, "--all")) all = true else try names.append(arena, arg);
+ }
+ const cmd = args[0];
+ if (std.mem.eql(u8, cmd, "enable") or std.mem.eql(u8, cmd, "disable")) {
+ if (names.items.len != 1) return usage(out, "graff mcp enable|disable <name>");
+ const name = names.items[0];
+ if (merged.servers.get(name) == null) std.process.fatal("mcp {s}: server '{s}' is not configured (see `graff mcp status`)", .{ cmd, name });
+ try mcp_state.set(io, arena, home, name, cmd[0] == 'e');
+ return report(try only(try mcp_status.offline(io, arena, home, merged, environ_map), names.items), json, out);
+ }
+ if (std.mem.eql(u8, cmd, "reconnect")) {
+ if (names.items.len == 0 and !all) return usage(out, "graff mcp reconnect <name>... | --all [--json]");
+ for (names.items) |n| if (merged.servers.get(n) == null) std.process.fatal("mcp reconnect: server '{s}' is not configured (see `graff mcp status`)", .{n});
+ @import("mcp_rpc.zig").applyHandshakeTimeoutEnv(environ_map);
+ const rows = try @import("mcp_reconnect.zig").probe(io, gpa, arena, home, merged, if (all) null else names.items, environ_map);
+ return report(rows, json, out);
+ }
+ const rows = try mcp_status.offline(io, arena, home, merged, environ_map);
+ return report(if (names.items.len > 0) try only(rows, names.items) else rows, json, out);
+}
+
+fn only(rows: []mcp_status.Row, names: []const []const u8) ![]mcp_status.Row {
+ var n: usize = 0;
+ for (rows) |row| for (names) |want| if (std.mem.eql(u8, row.name, want)) {
+ rows[n] = row;
+ n += 1;
+ break;
+ };
+ return rows[0..n];
+}
+
+fn usage(out: *Io.Writer, text: []const u8) !void {
+ try out.print("usage: {s}\n", .{text});
+ try out.flush();
+}
+
+fn report(rows: []const mcp_status.Row, json: bool, out: *Io.Writer) !void {
+ if (json) {
+ try mcp_status.writeJson(rows, out);
+ } else if (rows.len == 0) {
+ try out.writeAll("no MCP servers configured.\n");
+ } else for (rows) |row| {
+ try out.print(" {s} {s}", .{ row.name, mcp_status.label(row) });
+ if (row.toolCount > 0) try out.print(" · {d} tool(s)", .{row.toolCount});
+ if (row.@"error") |e| try out.print(" — {s} ({s})", .{ e, row.errorCode orelse "?" });
+ try out.print(" ({s}{s}{s})\n", .{ row.source, if (row.origin.len > 0) ", " else "", row.origin });
+ }
+ try out.flush();
+}
diff --git a/src/mcp_watch.zig b/src/mcp_watch.zig
index fb57c8b8..b8b2452a 100644
--- a/src/mcp_watch.zig
+++ b/src/mcp_watch.zig
@@ -83,6 +83,8 @@ pub fn poll(reg: *mcp.Registry) bool {
if (isKnown(name)) continue;
g.known.append(alloc, nameHash(name)) catch {};
if (e.value_ptr.* != .object or mcp_boot.alreadyStarting(reg, name)) continue;
+ const state = @import("mcp_state.zig").load(reg.io, reg.arena(), reg.home);
+ if (state.isDisabled(name) or (!state.isEnabled(name) and @import("mcp_state.zig").offInConfig(e.value_ptr.*.object))) continue;
if (!mcp_boot.queueConfig(reg, name, e.value_ptr.*.object)) continue;
names.append(alloc, name) catch continue;
if (@import("engine_sink.zig").hostedSink()) |sink| {
diff --git a/src/session_start.zig b/src/session_start.zig
index b1f7d062..0b2df328 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -450,6 +450,7 @@ pub fn initRegistryConsent(io: Io, gpa: Allocator, arena: Allocator, out: *Io.Wr
// Grok/Codex MCP trees. applyEnvKnobs sets it too, but only after the
// registry has already connected their servers.
@import("plugins.zig").applyEnv(environ_map);
+ @import("mcp_lazy.zig").remember(environ_map); // also for /mcp add|trust after a declined consent
const global_path = mcp_config.globalPath(arena, home, environ_map);
const sink = engine_sink.writerSink(out);
// First interactive session copies Claude/Cursor MCP into ~/.codegraff once.