Skip to content

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

Python

mcp: remember start failures; GRAFF_NO_BROWSER for mcp login

justrach748fea4a110b
diff --git a/docs/adr/0280-mcp-servers-report-state-and-reconnect.md b/docs/adr/0280-mcp-servers-report-state-and-reconnect.md
index 35404af4..dc770322 100644
--- a/docs/adr/0280-mcp-servers-report-state-and-reconnect.md
+++ b/docs/adr/0280-mcp-servers-report-state-and-reconnect.md
@@ -43,7 +43,11 @@ nothing said why and nothing could fix it short of a new session:
- **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.
+ failure is recorded by name so `/mcp` can say why. The last failure of each
+ server is also kept in `~/.codegraff/mcp-failures.json` (keyed like the
+ cache) until a real start succeeds, so `graff mcp status` reports a server
+ that broke in an earlier session without starting it. A server restored
+ dormant from the cache clears nothing.
## Consequences
diff --git a/scripts/test-mcp-status.py b/scripts/test-mcp-status.py
index 7b42a659..2e960eac 100644
--- a/scripts/test-mcp-status.py
+++ b/scripts/test-mcp-status.py
@@ -77,8 +77,11 @@ def main():
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.
+ # Cached per cwd: the next listing keeps each server's own tools, and a
+ # failed server stays failed (with its own words) until it starts.
rows = graff(binary, work, env, 'status')
+ assert rows['broken']['state'] == 'failed', rows['broken']
+ assert rows['broken']['detail'] == 'broken: not licensed. Run: broken activate', rows['broken']
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']
diff --git a/src/mcp.zig b/src/mcp.zig
index 09d12d07..6428fe77 100644
--- a/src/mcp.zig
+++ b/src/mcp.zig
@@ -461,4 +461,5 @@ test {
_ = @import("mcp_status_cli.zig");
_ = @import("mcp_reconnect.zig");
_ = @import("mcp_listing.zig");
+ _ = @import("mcp_failures.zig");
}
diff --git a/src/mcp_failures.zig b/src/mcp_failures.zig
new file mode 100644
index 00000000..f2e38cca
--- /dev/null
+++ b/src/mcp_failures.zig
@@ -0,0 +1,132 @@
+//! The last start failure of each MCP server, kept across sessions so
+//! `graff mcp status` (the desktop app's MCP servers page, the fullscreen
+//! client's `/mcp`) can say a server is broken, and why, without starting it.
+//!
+//! The desktop app starts a new graff for every turn. Without this, a server
+//! that failed in the last turn read as "not checked yet" until someone
+//! reconnected it. Keyed like the catalog cache (mcp_cache.keyFor: command,
+//! args, cwd, env), recorded on every failed start, and cleared by the next
+//! real start that succeeds. A server restored dormant from the cache did not
+//! start, so it clears nothing.
+
+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");
+const util = @import("util.zig");
+
+const rel_path = ".codegraff/mcp-failures.json";
+
+pub const Failure = struct {
+ /// The error name (`FileNotFound`, `McpClosed`).
+ code: []const u8,
+ /// Human text for it (mcp_status.errorText).
+ text: []const u8,
+ /// The server's own last stderr line, when a reconnect read it.
+ detail: ?[]const u8 = null,
+ at_ms: i64 = 0,
+};
+
+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 readServers(io: Io, arena: Allocator, p: []const u8) std.json.ObjectMap {
+ const text = Io.Dir.cwd().readFileAlloc(io, p, arena, .limited(1 << 20)) catch return .empty;
+ const root = std.json.parseFromSliceLeaky(Value, arena, text, .{ .allocate = .alloc_always }) catch return .empty;
+ if (root != .object) return .empty;
+ const servers = root.object.get("servers") orelse return .empty;
+ return if (servers == .object) servers.object else .empty;
+}
+
+fn str(obj: std.json.ObjectMap, field: []const u8) ?[]const u8 {
+ const v = obj.get(field) orelse return null;
+ return if (v == .string) v.string else null;
+}
+
+pub fn get(io: Io, arena: Allocator, home: []const u8, key: []const u8) ?Failure {
+ const p = path(arena, home) orelse return null;
+ const entry = readServers(io, arena, p).get(key) orelse return null;
+ if (entry != .object) return null;
+ return .{
+ .code = str(entry.object, "code") orelse return null,
+ .text = str(entry.object, "text") orelse "failed to start",
+ .detail = str(entry.object, "detail"),
+ .at_ms = if (entry.object.get("atMs")) |v| (if (v == .integer) v.integer else 0) else 0,
+ };
+}
+
+/// Write `failure` for `key`, or remove it when null. Best-effort, locked like
+/// the catalog cache: servers fail concurrently at startup.
+fn update(io: Io, arena: Allocator, home: []const u8, key: []const u8, failure: ?Failure) void {
+ if (key.len == 0) return;
+ const p = path(arena, home) orelse return;
+ if (failure == null) {
+ // Most starts succeed: only touch the file when there is something to clear.
+ if (readServers(io, arena, p).get(key) == null) return;
+ }
+ if (std.fs.path.dirname(p)) |dir| Io.Dir.cwd().createDirPath(io, dir) catch {};
+ const lock_path = std.fmt.allocPrint(arena, "{s}.lock", .{p}) catch return;
+ const lock = Io.Dir.cwd().createFile(io, lock_path, .{ .truncate = false, .lock = .exclusive }) catch return;
+ defer lock.close(io);
+ var servers = readServers(io, arena, p);
+ if (failure) |f| {
+ var entry: std.json.ObjectMap = .empty;
+ entry.put(arena, "code", .{ .string = f.code }) catch return;
+ entry.put(arena, "text", .{ .string = f.text }) catch return;
+ if (f.detail) |d| entry.put(arena, "detail", .{ .string = d }) catch return;
+ entry.put(arena, "atMs", .{ .integer = util.unixMs(io) }) catch return;
+ servers.put(arena, key, .{ .object = entry }) catch return;
+ } else if (!servers.swapRemove(key)) return;
+ var root: std.json.ObjectMap = .empty;
+ root.put(arena, "servers", .{ .object = servers }) catch return;
+ var aw: Io.Writer.Allocating = .init(arena);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ s.write(Value{ .object = root }) catch return;
+ credential_store.replaceFile(io, Io.Dir.cwd(), p, aw.writer.buffered(), .default_file) catch {};
+}
+
+pub fn record(io: Io, arena: Allocator, home: []const u8, key: []const u8, failure: Failure) void {
+ update(io, arena, home, key, failure);
+}
+
+pub fn clear(io: Io, arena: Allocator, home: []const u8, key: []const u8) void {
+ update(io, arena, home, key, null);
+}
+
+/// Both from a `gpa` caller (pool threads have no arena of their own).
+pub fn recordErr(io: Io, gpa: Allocator, home: []const u8, cfg: std.json.ObjectMap, err: anyerror, detail: ?[]const u8) void {
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ record(io, a, home, @import("mcp_cache.zig").keyFor(a, cfg), .{ .code = @errorName(err), .text = @import("mcp_status.zig").errorText(err), .detail = detail });
+}
+
+pub fn clearCfg(io: Io, gpa: Allocator, home: []const u8, cfg: std.json.ObjectMap) void {
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ clear(io, a, home, @import("mcp_cache.zig").keyFor(a, cfg));
+}
+
+test "a start failure is kept across sessions until the next real start" {
+ 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});
+ try std.testing.expect(get(io, a, home, "cmd:a") == null);
+ clear(io, a, home, "cmd:a"); // nothing to clear: no file is written
+ record(io, a, home, "cmd:a", .{ .code = "McpClosed", .text = "the server exited during startup", .detail = "a: not licensed" });
+ record(io, a, home, "cmd:b", .{ .code = "FileNotFound", .text = "command not found" });
+ const f = get(io, a, home, "cmd:a").?;
+ try std.testing.expectEqualStrings("McpClosed", f.code);
+ try std.testing.expectEqualStrings("a: not licensed", f.detail.?);
+ clear(io, a, home, "cmd:a");
+ try std.testing.expect(get(io, a, home, "cmd:a") == null);
+ try std.testing.expectEqualStrings("command not found", get(io, a, home, "cmd:b").?.text);
+}
diff --git a/src/mcp_lazy.zig b/src/mcp_lazy.zig
index 3b148fb4..fb69be49 100644
--- a/src/mcp_lazy.zig
+++ b/src/mcp_lazy.zig
@@ -131,6 +131,14 @@ pub fn dormantFromCache(io: Io, a: Allocator, home: []const u8, name: []const u8
/// Spawn and handshake a dormant server before its first request. On failure
/// it stays dormant, so a later call tries again.
pub fn wake(reg: anytype, server: *mcp_rpc.Server) !void {
+ const cfg = server.transport.dormant.cfg;
+ wakeInner(reg, server) catch |err| {
+ @import("mcp_failures.zig").recordErr(reg.io, reg.gpa, reg.home, cfg, err, null); // `graff mcp status` says why
+ return err;
+ };
+}
+
+fn wakeInner(reg: anytype, server: *mcp_rpc.Server) !void {
const dormant = server.transport.dormant;
const cfg = dormant.cfg;
const a = reg.arena();
@@ -153,6 +161,7 @@ pub fn wake(reg: anytype, server: *mcp_rpc.Server) !void {
mcp_rpc.bindNotes(server);
@import("mcp_pages.zig").listen(server, a);
if (reg.show_diagnostics) std.debug.print(" [mcp:{s}] started on first use\n", .{server.name});
+ @import("mcp_failures.zig").clearCfg(reg.io, reg.gpa, reg.home, cfg);
refreshCache(reg, server, cfg);
}
diff --git a/src/mcp_oauth.zig b/src/mcp_oauth.zig
index a3ee0124..ff9dd2f6 100644
--- a/src/mcp_oauth.zig
+++ b/src/mcp_oauth.zig
@@ -429,7 +429,8 @@ fn loginInner(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, server
defer listener.deinit(io);
try out.print("\nOpen this URL to authorize (the browser should open automatically):\n\n{s}\n\nWaiting for the callback on {s} …\n", .{ authorization_url, redirect_uri });
try out.flush();
- openBrowser(io, authorization_url);
+ // GRAFF_NO_BROWSER: a client (the fullscreen TUI) opens the printed URL itself.
+ if (!@import("main.zig").g_no_browser) openBrowser(io, authorization_url);
// Only this attempt's redirect (its state) ends the wait.
var read_buffer: [16 * 1024]u8 = undefined;
diff --git a/src/mcp_reconnect.zig b/src/mcp_reconnect.zig
index e898229c..4f0a0384 100644
--- a/src/mcp_reconnect.zig
+++ b/src/mcp_reconnect.zig
@@ -50,7 +50,9 @@ pub fn probe(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, merged:
}
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);
+ const cfg = merged.servers.get(row.name).?.object;
+ row.detail = stderrHint(io, gpa, arena, cfg);
+ if (row.detail != null) @import("mcp_failures.zig").record(io, arena, home, mcp_cache.keyFor(arena, cfg), .{ .code = row.errorCode orelse "failed", .text = row.@"error" orelse "failed to start", .detail = row.detail });
};
return rows.items;
}
@@ -94,6 +96,7 @@ fn apply(io: Io, arena: Allocator, row: *mcp_status.Row, outcome: StartOutcome)
row.state = .ready;
row.@"error" = null;
row.errorCode = null;
+ row.detail = null;
row.tools = tools.items;
row.toolCount = tools.items.len;
mcp_rpc.deinitServer(server, io, .init(io, mcp_teardown.teardown_grace));
@@ -134,9 +137,11 @@ pub fn live(reg: *mcp.Registry, merged: mcp_config.Merged, name: []const u8) Liv
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);
+ @import("mcp_failures.zig").recordErr(reg.io, reg.gpa, reg.home, cfg, err, null);
return .{ .failed = err };
};
mcp_start.clear(name);
+ @import("mcp_failures.zig").clearCfg(reg.io, reg.gpa, reg.home, cfg);
return swapIn(reg, index, servers.items[0], tools.items) catch |err| .{ .failed = err };
}
diff --git a/src/mcp_start.zig b/src/mcp_start.zig
index cc147e54..96d7d35b 100644
--- a/src/mcp_start.zig
+++ b/src/mcp_start.zig
@@ -33,15 +33,16 @@ pub fn task(ctx: Ctx, name: []const u8, cfg: std.json.ObjectMap) StartOutcome {
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);
+ if (attempt(ctx, name, cfg)) |outcome| return outcome else |again| return failed(ctx, name, cfg, again);
}
- return failed(ctx, name, first);
+ return failed(ctx, name, cfg, first);
};
}
-fn failed(ctx: Ctx, name: []const u8, err: anyerror) StartOutcome {
+fn failed(ctx: Ctx, name: []const u8, cfg: std.json.ObjectMap, err: anyerror) StartOutcome {
if (ctx.show_diagnostics) std.debug.print(" [mcp:{s}] failed to start: {t}\n", .{ name, err });
note(name, err);
+ @import("mcp_failures.zig").recordErr(ctx.io, ctx.gpa, ctx.home, cfg, err, null);
return .{};
}
@@ -65,6 +66,8 @@ fn attempt(ctx: Ctx, name: []const u8, cfg: std.json.ObjectMap) !StartOutcome {
defer tmp.arena_state.deinit();
try tmp.startServer(a, &servers, &tools, name, cfg);
clear(name);
+ // Restored dormant from the cache is not a start: it proves nothing.
+ if (servers.items[0].transport != .dormant) @import("mcp_failures.zig").clearCfg(ctx.io, ctx.gpa, ctx.home, cfg);
return .{ .server = servers.items[0], .tools = tools.items, .arena_state = arena_state };
}
diff --git a/src/mcp_status.zig b/src/mcp_status.zig
index 41dc111d..56f77512 100644
--- a/src/mcp_status.zig
+++ b/src/mcp_status.zig
@@ -178,11 +178,20 @@ pub fn offline(io: Io, arena: Allocator, home: []const u8, merged: mcp_config.Me
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| {
+ const key = mcp_cache.keyFor(arena, cfg);
+ if (mcp_cache.lookupAnyAge(io, arena, home, key)) |hit| {
row.tools = cachedTools(arena, hit.tools);
row.toolCount = row.tools.len;
if (row.enabled) row.state = .on_demand;
}
+ // The last start failed (this session or an earlier one) and nothing
+ // has started it since: say so, keeping its last-known tools.
+ if (row.enabled) if (@import("mcp_failures.zig").get(io, arena, home, key)) |f| {
+ row.state = if (std.mem.eql(u8, f.code, "McpAuthenticationRequired")) .needs_login else .failed;
+ row.@"error" = f.text;
+ row.errorCode = f.code;
+ row.detail = f.detail;
+ };
try rows.append(arena, row);
}
return rows.items;