graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
mcp: restart a closed stdio server on its next call (#1512)
justrach8d4c15f112ad
diff --git a/docs/adr/0270-a-closed-stdio-mcp-server-restarts-on-its-next-call.md b/docs/adr/0270-a-closed-stdio-mcp-server-restarts-on-its-next-call.mdnew file mode 100644index 00000000..f8d66f3c--- /dev/null+++ b/docs/adr/0270-a-closed-stdio-mcp-server-restarts-on-its-next-call.md@@ -0,0 +1,34 @@+# 0270. A closed stdio MCP server restarts on its next call++Status: accepted 2026-10-07++## Context++When a call to a stdio MCP server failed because its process closed the+connection, graff withdrew every tool the server offered and told the model+to restart the service and the session (#1467). A server that exited once,+for any reason, was gone for the rest of the session even though graff+already knew how to start it: stdio servers with a cached catalog start on+first use (`mcp_lazy.zig`). Issue #1512 asked for recovery without a session+restart.++## Decision++A stdio server keeps the launch config it started from. When a call on it+fails with a closed connection, graff reaps the dead child and returns the+server to dormant with that config; its tools stay advertised. The next call+spawns and handshakes a fresh process exactly as a first use does.++- The call that saw the close is never replayed: it may have run. Its error+ says so and says that state held by the service is gone.+- After two restarts in a session the server is withdrawn as before, so a+ server that dies on every call stops costing turns.+- HTTP servers, and stdio servers without a launch config, are withdrawn as+ before.++## Consequences++One crash no longer removes a service for the rest of the session, and the+catalog does not change, so the provider prefix cache survives it. A restarted+server loses whatever it held (open pages, sessions, caches); the error text+tells the model. `mcp_restart.zig` owns the rule and its regression test.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 3e8e67e1..715f8746 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -285,6 +285,7 @@ record only when you need the evidence or the edge cases.| [0257](0257-a-slimmed-comment-list-names-its-issue.md) | A slimmed MCP comment list keeps the issue id its rows share (`{issue, n, latest_author}`), so parallel results name what they describe. || [0258](0258-gemini-chat-sends-repo-context-once.md) | On the Codegraff chat wire, Gemini root turns send the project instructions and layout as the conversation's first user message (ADR 0243's split), so the system prompt every request repeats no longer carries them. || [0259](0259-openai-routes-compact-only-server-side.md) | First-party Responses routes (direct API, Codegraff GPT, ChatGPT plan) compact only server-side: no client-summary fallback while the server arm is on. A compaction item's `encrypted_content` is metered at 16 bytes/token, not as text, so a blob-anchored history does not re-compact every step. |+| [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. |## When to write onediff --git a/src/mcp.zig b/src/mcp.zigindex 24e6cdf2..22040d58 100644--- a/src/mcp.zig+++ b/src/mcp.zig@@ -424,6 +424,7 @@ pub const Registry = struct {break :blk all.tools;};try @import("mcp_pages.zig").appendTools(a, tools, server_index, server, tools_v);+ if (server.transport == .stdio) server.transport.stdio.relaunch = .{ .cfg = try mcp_lazy.cloneMap(a, cfg) }; // ADR 0270mcp_rpc.bindNotes(server);@import("mcp_pages.zig").listen(server, a); // modern stdio: ask for tools/list_changedtry servers.append(a, server);@@ -469,6 +470,7 @@ pub const Registry = struct {};test {+ _ = @import("mcp_restart.zig"); // ADR 0270_ = @import("mcp_cache.zig");_ = @import("mcp_boot.zig");_ = @import("mcp_elicitation.zig");diff --git a/src/mcp_call.zig b/src/mcp_call.zigindex 198514be..28db8540 100644--- a/src/mcp_call.zig+++ b/src/mcp_call.zig@@ -34,6 +34,7 @@ const restart_hint = "Inspect /mcp, restart the service and this session, then rpub fn call(reg: *Registry, out_alloc: Allocator, qualified: []const u8, input: Value, context: ?@import("mcp_turn_context.zig").Snapshot) !CallResult {return invoke(reg, out_alloc, qualified, input, context) catch |err| switch (err) {error.McpClosed, error.ReadFailed, error.WriteFailed, error.BrokenPipe, error.ConnectionResetByPeer => blk: {+ if (try @import("mcp_restart.zig").closeForRestart(reg, out_alloc, qualified, @errorName(err))) |text| break :blk .{ .text = text, .is_error = true };try withdrawServer(reg, qualified, @errorName(err));break :blk .{.text = try std.fmt.allocPrint(out_alloc, "MCP service connection closed or failed ({s}). Its tools have been withdrawn from the catalog. The tool may not have completed; it was not retried automatically. " ++ restart_hint, .{@errorName(err)}),diff --git a/src/mcp_lazy.zig b/src/mcp_lazy.zigindex 7496ae79..595090fc 100644--- a/src/mcp_lazy.zig+++ b/src/mcp_lazy.zig@@ -119,14 +119,16 @@ 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;+ const dormant = server.transport.dormant;+ const cfg = dormant.cfg;const a = reg.arena();const spec = try stdioSpec(reg.io, reg.gpa, a, cfg);defer if (spec.env) |m| m.deinit();server.transport = try reg.spawnStdio(a, spec.argv, spec.env, spec.cwd);+ server.transport.stdio.relaunch = dormant;errdefer {mcp_stdio.stopChild(reg.io, &server.transport.stdio.child);- server.transport = .{ .dormant = .{ .cfg = cfg } };+ server.transport = .{ .dormant = dormant };server.initialized = false;}// Same rule as a cache hit at connect: legacy needs `initialize` on thediff --git a/src/mcp_restart.zig b/src/mcp_restart.zignew file mode 100644index 00000000..62271886--- /dev/null+++ b/src/mcp_restart.zig@@ -0,0 +1,77 @@+//! ADR 0270 (#1512): a stdio MCP server whose connection closes starts again+//! on its next call instead of leaving the session without its tools.+//!+//! The call that saw the close is never replayed: it may have run. The dead+//! child is reaped and the server goes back to dormant with the launch config+//! it started from, so the next call spawns and handshakes a fresh process+//! exactly as a first use does (mcp_lazy.wake). Its tools stay advertised.+//! A server that keeps closing is withdrawn after `max_restarts`, as before.+const std = @import("std");+const Allocator = std.mem.Allocator;+const Registry = @import("mcp.zig").Registry;+const mcp_stdio = @import("mcp_stdio.zig");++/// Restarts per server per session before its tools are withdrawn.+pub const max_restarts: u8 = 2;++/// After a transport failure on `qualified`'s server: return a stdio server+/// that can be relaunched to dormant and answer with the call's error text.+/// Null when it cannot restart (HTTP, no launch config, budget spent), so the+/// caller withdraws its tools. The registry lock is held by the caller.+pub fn closeForRestart(reg: *Registry, out_alloc: Allocator, qualified: []const u8, reason: []const u8) !?[]u8 {+ const tool = for (reg.tools) |t| {+ if (std.mem.eql(u8, t.qualified_name, qualified)) break t;+ } else return null;+ const server = reg.servers[tool.server_index];+ if (server.transport != .stdio) return null;+ const relaunch = server.transport.stdio.relaunch orelse return null;+ if (relaunch.restarts >= max_restarts) return null;+ mcp_stdio.stopChild(reg.io, &server.transport.stdio.child);+ server.transport = .{ .dormant = .{ .cfg = relaunch.cfg, .restarts = relaunch.restarts + 1 } };+ server.initialized = false;+ return try std.fmt.allocPrint(out_alloc, "MCP service connection closed or failed ({s}). The tool may not have completed; it was not retried automatically. The service starts again on its next call; anything it held (open pages, sessions, caches) is gone.", .{reason});+}++test "#1512: a stdio server that closes mid-call starts again on its next call" {+ if (@import("builtin").os.tag == .windows) return error.SkipZigTest; // /bin/sh+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;+ const dir_len = try tmp.dir.realPath(io, &path_buf);+ var reg = Registry.empty(gpa, io);+ defer reg.deinit();+ reg.stdio_probe = false;+ reg.lazy_stdio = false;+ // The first process exits on its first tools/call; the next one answers.+ const script = try std.fmt.allocPrint(reg.arena(),+ \\M='{s}/started'; first=0; [ -e "$M" ] || {{ first=1; : > "$M"; }}+ \\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":"whoami","description":"d","inputSchema":{{"type":"object"}}}}]}}}}\n' "$id" ;;+ \\ *'"method":"tools/call"'*) [ "$first" = 1 ] && exit 0; printf '{{"jsonrpc":"2.0","id":%s,"result":{{"content":[{{"type":"text","text":"fresh"}}]}}}}\n' "$id" ;;+ \\ *) printf '{{"jsonrpc":"2.0","id":%s,"error":{{"code":-32601,"message":"no"}}}}\n' "$id" ;;+ \\ esac+ \\done+ , .{path_buf[0..dir_len]});+ try std.testing.expectEqual(@as(usize, 1), try reg.addServer("fixture", "/bin/sh", &.{ "-c", script }));+ const args: std.json.Value = .{ .object = .empty };++ const closed = try reg.call(gpa, "mcp__fixture__whoami", args);+ defer gpa.free(closed.text);+ try std.testing.expect(closed.is_error);+ try std.testing.expect(std.mem.indexOf(u8, closed.text, "McpClosed") != null);+ try std.testing.expect(std.mem.indexOf(u8, closed.text, "starts again on its next call") != null);+ // Still advertised: nothing was withdrawn and the catalog is unchanged.+ try std.testing.expectEqual(@as(usize, 1), (try reg.snapshotTools(reg.arena())).len);+ try std.testing.expect(!reg.catalog_dirty.load(.acquire));++ const again = try reg.call(gpa, "mcp__fixture__whoami", args);+ defer gpa.free(again.text);+ try std.testing.expect(!again.is_error);+ try std.testing.expectEqualStrings("fresh", again.text);+}diff --git a/src/mcp_rpc.zig b/src/mcp_rpc.zigindex 73c68132..46151d36 100644--- a/src/mcp_rpc.zig+++ b/src/mcp_rpc.zig@@ -1,9 +1,8 @@//! MCP JSON-RPC transport plumbing, split out of mcp.zig to keep it under//! the repo's 600-line cap: the per-server transport union/state, the//! legacy `initialize` handshake, era detection, and raw request/notify-//! framing over either stdio or Streamable HTTP. mcp.zig keeps the-//! higher-level `Registry` (server lifecycle, tool discovery, tool-//! dispatch) and aliases `Server`/`Transport` from here.+//! framing over either stdio or Streamable HTTP. mcp.zig keeps the higher-level+//! `Registry` (lifecycle, discovery, dispatch) and aliases `Server`/`Transport`.const std = @import("std");const Io = std.Io;@@ -24,10 +23,11 @@ pub const StdioTransport = struct {child: std.process.Child,stdin_writer: Io.File.Writer,stdout_reader: Io.File.Reader,+ relaunch: ?DormantStdio = null, // ADR 0270: how to start it again after it closes};-/// A cached stdio server not spawned yet; woken before any request (mcp_lazy.zig).-pub const DormantStdio = struct { cfg: std.json.ObjectMap };+/// A stdio server not spawned (yet, or again); woken before any request (mcp_lazy.zig).+pub const DormantStdio = struct { cfg: std.json.ObjectMap, restarts: u8 = 0 };pub const Transport = union(enum) {stdio: StdioTransport,