Skip to content

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

Python

fix(mcp): a legacy fallback must be earned and visible, never silent (#327)

justrach50101bd9e808
diff --git a/scripts/test-mcp-stdio-probe.py b/scripts/test-mcp-stdio-probe.py
index 6e4939ea..b47a9009 100644
--- a/scripts/test-mcp-stdio-probe.py
+++ b/scripts/test-mcp-stdio-probe.py
@@ -201,7 +201,7 @@ def run(graff: Path) -> None:
print("gate off: byte-identical legacy connect, no server/discover — OK")
# Scenario 2: gate on, server silently drops server/discover. Must time
- # out (the probe bound, see mcp_rpc.stdio_probe_timeout) and fall back
+ # out (the probe bound, see mcp_rpc.stdio_probe_timeout_ms) and fall back
# to the legacy handshake on the same process, completing well inside
# the outer 20s subprocess timeout (which would fire and fail this
# script if the probe hung).
@@ -225,7 +225,13 @@ def run(graff: Path) -> None:
f"[gate on] the server never received server/discover, so the probe did not run:\n{completed.stderr}"
)
assert elapsed < 15, f"[gate on] took {elapsed:.1f}s — the probe bound is not working"
- print(f"gate on: timed-out probe -> legacy fallback in {elapsed:.1f}s — OK")
+ # #327: the downgrade must be legible. A fallback that reads exactly
+ # like a server which only ever spoke legacy is how a whole population
+ # of companions ran degraded without anyone noticing.
+ assert "raise GRAFF_MCP_PROBE_MS" in completed.stderr, (
+ f"[gate on] the timeout fallback was not reported on the connect line:\n{completed.stderr}"
+ )
+ print(f"gate on: timed-out probe -> reported legacy fallback in {elapsed:.1f}s — OK")
# Scenario 3: gate on, server exits on server/discover (the other
# documented worst case). Must respawn once and connect via legacy
@@ -244,7 +250,10 @@ def run(graff: Path) -> None:
"connected (mcp 2025-06-18)" in completed.stderr
), f"[gate on, exiting] expected a respawn-then-legacy connect:\n{completed.stderr}"
assert elapsed < 10, f"[gate on, exiting] took {elapsed:.1f}s — respawn should be fast"
- print(f"gate on, server exits on discover: respawn -> legacy fallback in {elapsed:.1f}s — OK")
+ assert "exited during the probe" in completed.stderr, (
+ f"[gate on, exiting] the respawn fallback was not reported (#327):\n{completed.stderr}"
+ )
+ print(f"gate on, server exits on discover: respawn -> reported legacy fallback in {elapsed:.1f}s — OK")
def main() -> int:
diff --git a/src/commands_misc.zig b/src/commands_misc.zig
index 3a7206f1..84f29255 100644
--- a/src/commands_misc.zig
+++ b/src/commands_misc.zig
@@ -304,7 +304,12 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
} else {
try out.print("{d} MCP server(s), {d} tool(s):\n", .{ reg.servers.len, reg.tools.len });
for (reg.servers, 0..) |srv, i| {
- try out.print(" {s}{s}{s} (mcp {s}, {d} tool(s))\n", .{ style.accent, srv.name, style.reset, srv.protocol_version, reg.toolCount(i) });
+ // #327: if the modern probe ran and this connection landed on
+ // legacy anyway, say why — a silent downgrade is invisible here
+ // otherwise, since a fallback and a genuinely-legacy server
+ // print the identical revision.
+ const probe_note = if (srv.probe_fallback) |reason| reason.note() else "";
+ try out.print(" {s}{s}{s} (mcp {s}, {d} tool(s)){s}{s}{s}\n", .{ style.accent, srv.name, style.reset, srv.protocol_version, reg.toolCount(i), style.dim, probe_note, style.reset });
}
for (reg.tools) |t| try out.print(" {s}{s}{s}\n", .{ style.dim, t.qualified_name, style.reset });
try out.writeAll(" add more: /mcp add <name> <command> [args...]\n");
diff --git a/src/mcp.zig b/src/mcp.zig
index fdec3ff9..af73248e 100644
--- a/src/mcp.zig
+++ b/src/mcp.zig
@@ -102,7 +102,7 @@ pub const Registry = struct {
.stdio_probe = if (environ_map.get("GRAFF_MCP_PROBE")) |v| !std.mem.eql(u8, v, "0") else true,
.global_config_path = global_path,
};
- mcp_rpc.applyHandshakeTimeoutEnv(environ_map); // #275: GRAFF_MCP_HANDSHAKE_SECS, read on the same pass as the probe flag
+ 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();
const a = reg.arena();
@@ -414,9 +414,17 @@ pub const Registry = struct {
.http => try mcp_rpc.connectHttp(server, a, a),
.stdio => stdio_listed: {
if (!reg.stdio_probe) break :stdio_listed try mcp_rpc.connectStdio(server, a, a, reg.io);
- switch (try mcp_rpc.probeStdio(server, a, reg.io)) {
+ // #327: every legacy landing records WHY (and a probe that
+ // could not run is retried before it is allowed to downgrade
+ // anything), so a fallback shows up in the connect line and
+ // `/mcp` instead of being indistinguishable from a server
+ // that genuinely speaks only the legacy protocol.
+ switch (try mcp_rpc.probeStdioResilient(server, a, reg.io)) {
.modern => break :stdio_listed try mcp_rpc.finishModernStdio(server, a, a, reg.io),
- .legacy => break :stdio_listed try mcp_rpc.connectStdio(server, a, a, reg.io),
+ .legacy => |reason| {
+ server.probe_fallback = reason;
+ break :stdio_listed try mcp_rpc.connectStdio(server, a, a, reg.io);
+ },
.closed => {
// The probe write/read found a dead process (some
// legacy SDK servers exit on an unrecognized
@@ -424,6 +432,7 @@ pub const Registry = struct {
// straight to legacy on the fresh process, no
// second probe against a server that already
// proved it can't tolerate one.
+ server.probe_fallback = .server_exited;
mcp_stdio.stopChild(reg.io, &server.transport.stdio.child);
server.transport = try spawnStdio(reg, a, stdio_argv.items, stdio_env_map);
break :stdio_listed try mcp_rpc.connectStdio(server, a, a, reg.io);
@@ -456,7 +465,8 @@ pub const Registry = struct {
}
try servers.append(a, server);
registry_owns_server = true;
- std.debug.print(" [mcp:{s}] connected (mcp {s}) — {d} tool(s)\n", .{ name, server.protocol_version, tools_v.array.items.len });
+ const probe_note = if (server.probe_fallback) |reason| reason.note() else ""; // #327: a downgrade is never silent
+ std.debug.print(" [mcp:{s}] connected (mcp {s}) — {d} tool(s){s}\n", .{ name, server.protocol_version, tools_v.array.items.len, probe_note });
}
/// One shared window bounds the whole teardown: the loop is sequential, so
diff --git a/src/mcp_rpc.zig b/src/mcp_rpc.zig
index 90133353..d5ff73c9 100644
--- a/src/mcp_rpc.zig
+++ b/src/mcp_rpc.zig
@@ -42,6 +42,11 @@ pub const Server = struct {
/// Revision the server negotiated (legacy) or `modern_protocol` (modern),
/// shown in `/mcp` so version skew is visible.
protocol_version: []const u8 = "?",
+ /// Set when the modern probe ran and the connection landed on the legacy
+ /// protocol anyway: WHY it did. Rendered on the connect line and in
+ /// `/mcp` — a downgrade the user cannot see is the whole of #327. Null
+ /// when no probe ran (probe disabled, HTTP) or when it found modern.
+ probe_fallback: ?LegacyReason = null,
};
pub fn deinitServer(server: *Server, io: Io, budget: mcp_teardown.Budget) void {
@@ -70,11 +75,28 @@ pub var stdio_handshake_timeout_ms: i64 = 15_000;
/// ignored if unparseable or 0; clamped to <=1 day. Lives here rather than in
/// session_run.zig, which is at the 600-line cap.
pub fn applyHandshakeTimeoutEnv(environ_map: anytype) void {
+ applyProbeTimeoutEnv(environ_map);
const v = environ_map.get("GRAFF_MCP_HANDSHAKE_SECS") orelse return;
const secs = std.fmt.parseInt(u64, std.mem.trim(u8, v, " \t"), 10) catch return;
if (secs > 0) stdio_handshake_timeout_ms = @intCast(@min(secs, 86_400) * 1000);
}
+/// GRAFF_MCP_PROBE_MS raises/lowers `stdio_probe_timeout_ms` (default 600).
+/// The escape hatch for #327: a server that is slow to its FIRST answer gets
+/// classified legacy for the session even though it speaks the modern
+/// protocol. Measured, not hypothetical — a second concurrent codedb-pro
+/// process takes ~1.5s to answer its first request where the first takes 2ms,
+/// which is why the companion lands on legacy exactly when a workspace stdio
+/// server connected before it. The default stays low because a genuinely
+/// legacy server pays the whole bound before falling back; raise it when the
+/// connect line reports a probe-deadline fallback. Milliseconds; ignored if
+/// unparseable or 0; clamped to <=60s.
+pub fn applyProbeTimeoutEnv(environ_map: anytype) void {
+ const v = environ_map.get("GRAFF_MCP_PROBE_MS") orelse return;
+ const ms = std.fmt.parseInt(u64, std.mem.trim(u8, v, " \t"), 10) catch return;
+ if (ms > 0) stdio_probe_timeout_ms = @intCast(@min(ms, 60_000));
+}
+
fn stdioHandshakeTimeoutTask(io: Io) void {
io.sleep(.fromMilliseconds(stdio_handshake_timeout_ms), .awake) catch {};
}
@@ -220,7 +242,9 @@ fn connectLegacy(server: *Server, a: Allocator, session_alloc: Allocator, bound_
/// the probe existed - so the cost of guessing wrong is latency, never
/// function (stdio spec: fall back on "no response within a reasonable
/// timeout", never keyed to a specific error code).
-const stdio_probe_timeout: Io.Duration = .fromMilliseconds(600);
+/// A `var` only so a test can widen it off a loaded CI box; production never
+/// writes it.
+pub var stdio_probe_timeout_ms: i64 = 600;
fn stdioProbeReadTask(server: *Server, response_alloc: Allocator, id: i64) anyerror!Value {
const stdio = &server.transport.stdio;
@@ -232,7 +256,7 @@ fn stdioProbeReadTask(server: *Server, response_alloc: Allocator, id: i64) anyer
}
fn stdioProbeTimeoutTask(io: Io) void {
- io.sleep(stdio_probe_timeout, .awake) catch {};
+ io.sleep(.fromMilliseconds(stdio_probe_timeout_ms), .awake) catch {};
}
const StdioProbeDone = union(enum) {
@@ -240,25 +264,73 @@ const StdioProbeDone = union(enum) {
timeout,
};
-pub const StdioProbeOutcome = enum { modern, legacy, closed };
+/// Why a probe concluded a stdio server is legacy. Every value is a CLEAN
+/// negotiation outcome — the server answered (or deliberately did not answer)
+/// in a way the spec says to downgrade on — except `probe_unavailable`, which
+/// is graff's own limitation and is labelled as such. A transport or decode
+/// failure is deliberately NOT in this set: it propagates as an error instead
+/// of silently degrading the connection for the rest of the session (#327).
+pub const LegacyReason = enum {
+ /// The server answered `server/discover` with a JSON-RPC error object.
+ rejected,
+ /// It answered, but `result.supportedVersions` does not list
+ /// `modern_protocol` (or is missing/malformed — an answer, just not a
+ /// modern one).
+ no_modern_version,
+ /// No answer inside `stdio_probe_timeout_ms`. The stdio spec's own fallback
+ /// trigger: "no response within a reasonable timeout".
+ timeout,
+ /// graff could not run the bounded probe at all (no concurrency for the
+ /// reader/deadline pair, twice). Says nothing about the server, so it is
+ /// reported distinctly rather than passed off as a negotiated result.
+ probe_unavailable,
+ /// The child exited or closed stdout during the probe; the caller
+ /// respawned it and connected legacy on the fresh process.
+ server_exited,
+
+ /// Suffix for the connect line / `/mcp`, empty-safe to concatenate. A
+ /// legacy landing is never invisible: #327 was exactly a fallback nobody
+ /// could see.
+ pub fn note(reason: LegacyReason) []const u8 {
+ return switch (reason) {
+ .rejected => " [legacy: server rejected server/discover]",
+ .no_modern_version => " [legacy: server does not list " ++ modern_protocol ++ "]",
+ .timeout => " [legacy: no server/discover answer before the probe deadline; raise GRAFF_MCP_PROBE_MS]",
+ .probe_unavailable => " [legacy: graff could not run the modern probe]",
+ .server_exited => " [legacy: server exited during the probe, respawned]",
+ };
+ }
+};
+
+pub const StdioProbeOutcome = union(enum) {
+ modern,
+ legacy: LegacyReason,
+ closed,
+};
-fn classifyStdioProbe(result: anyerror!Value) StdioProbeOutcome {
+/// Classify one `server/discover` reply. Errors that are not `McpClosed` are
+/// PROPAGATED, not swallowed into `.legacy`: a broken pipe, a cancelled read
+/// or an I/O failure is a transport problem, and pinning the era to legacy on
+/// one would leave the connection degraded for its whole life with nothing to
+/// see (#327). Only an actual answer downgrades.
+pub fn classifyStdioProbe(result: anyerror!Value) anyerror!StdioProbeOutcome {
const response = result catch |err| switch (err) {
error.McpClosed => return .closed,
- else => return .legacy, // any other error (incl. a malformed line) — never treat as modern
+ else => return err,
};
+ if (response != .object) return .{ .legacy = .no_modern_version };
// A recognized modern *error* here (-32020/-32021/-32022) still reads as
// legacy for stdio specifically: unlike the HTTP probe, graff has no
// real modern stdio server to validate a "fail loudly" path against
// (population ~0 today), so the conservative choice is the one that
// degrades to the handshake graff already knows works.
- if (response.object.get("error") != null) return .legacy;
- const supported = mcp_protocol.discoverSupportedVersions(response) catch return .legacy;
+ if (response.object.get("error") != null) return .{ .legacy = .rejected };
+ const supported = mcp_protocol.discoverSupportedVersions(response) catch return .{ .legacy = .no_modern_version };
for (supported) |v| if (v == .string and std.mem.eql(u8, v.string, modern_protocol)) return .modern;
- return .legacy;
+ return .{ .legacy = .no_modern_version };
}
-/// Attempt the `server/discover` probe, bounded to `stdio_probe_timeout` so
+/// Attempt the `server/discover` probe, bounded to `stdio_probe_timeout_ms` so
/// a legacy server that silently ignores an unrecognized pre-`initialize`
/// method can never hang graff at startup (stdio § Backward Compatibility:
/// fall back "on any error that is not a recognized modern error, or no
@@ -292,14 +364,25 @@ pub fn probeStdio(server: *Server, a: Allocator, io: Io) !StdioProbeOutcome {
var done_buf: [2]StdioProbeDone = undefined;
var select: Io.Select(StdioProbeDone) = .init(io, &done_buf);
- select.concurrent(.replied, stdioProbeReadTask, .{ server, a, id }) catch return .legacy;
+ // #327: failing to SPAWN the probe tasks says nothing about the server's
+ // protocol. These two arms used to `catch return .legacy`, which pinned
+ // the era to legacy for the process lifetime with no way for anyone to
+ // tell — deterministically so for the second stdio server in a session
+ // (the auto-connected companion, i.e. the server most users have).
+ // `error.McpProbeUnavailable` hands the decision back to the caller.
+ select.concurrent(.replied, stdioProbeReadTask, .{ server, a, id }) catch return error.McpProbeUnavailable;
select.concurrent(.timeout, stdioProbeTimeoutTask, .{io}) catch {
- const only = select.await() catch return .legacy;
+ // The reader is already running with no deadline behind it. Reap it
+ // (cancel blocks until it has actually stopped) rather than wait on
+ // it unbounded at startup, which is the #275 hang in another form.
select.cancelDiscard();
- return classifyStdioProbe(only.replied);
+ return error.McpProbeUnavailable;
};
- const first = select.await() catch return .legacy;
+ const first = select.await() catch |err| {
+ select.cancelDiscard();
+ return err;
+ };
switch (first) {
.replied => |result| {
select.cancelDiscard();
@@ -307,11 +390,28 @@ pub fn probeStdio(server: *Server, a: Allocator, io: Io) !StdioProbeOutcome {
},
.timeout => {
_ = select.cancel(); // blocks until the read task has actually stopped
- return .legacy;
+ return .{ .legacy = .timeout };
},
}
}
+/// `probeStdio` plus the recovery policy for the one failure that is graff's
+/// own and not the server's: a probe that could not be spawned is retried
+/// once, and only then downgraded — visibly, via `.probe_unavailable`, so a
+/// degraded connect is legible in the connect line and `/mcp` instead of
+/// looking exactly like a server that genuinely speaks only the legacy
+/// protocol (#327). Transport errors still propagate: those mean the pipe is
+/// broken, and a legacy handshake over a broken pipe should fail loudly.
+pub fn probeStdioResilient(server: *Server, a: Allocator, io: Io) !StdioProbeOutcome {
+ return probeStdio(server, a, io) catch |err| switch (err) {
+ error.McpProbeUnavailable => probeStdio(server, a, io) catch |retry_err| switch (retry_err) {
+ error.McpProbeUnavailable => .{ .legacy = .probe_unavailable },
+ else => retry_err,
+ },
+ else => err,
+ };
+}
+
/// Connect a stdio server. Always legacy — the gated `server/discover`
/// probe (`GRAFF_MCP_PROBE=1`, default off) is orchestrated by mcp.zig's
/// `startServer` instead of here: only it has the argv/env needed to
@@ -400,6 +500,10 @@ fn connectHttpAttempt(server: *Server, a: Allocator, session_alloc: Allocator, r
}
}
+test { // #327 probe-classification/fallback coverage (this file is at the 600-line cap)
+ _ = @import("mcp_rpc_tests.zig");
+}
+
// #275: a stdio server that accepts the connection and then never answers must
// not hang startup. The child here holds stdout open and writes nothing, which
// is precisely the reported repro. Before the bound, connectStdio's initialize
diff --git a/src/mcp_rpc_tests.zig b/src/mcp_rpc_tests.zig
new file mode 100644
index 00000000..24dd5417
--- /dev/null
+++ b/src/mcp_rpc_tests.zig
@@ -0,0 +1,210 @@
+//! #327 regression tests for the stdio `server/discover` probe: which
+//! outcomes may downgrade a connection to the legacy protocol, and which must
+//! not. Split out of mcp_rpc.zig (already near the 600-line ceiling) and
+//! pulled in by its trailing `test { _ = @import("mcp_rpc_tests.zig"); }`.
+//!
+//! The bug these pin: every failure arm of `probeStdio` used to
+//! `catch return .legacy`, so a probe that could not even be *spawned* was
+//! indistinguishable from a server that answered "I only speak the legacy
+//! protocol" — and the resulting downgrade was invisible in the connect line
+//! and in `/mcp`.
+const std = @import("std");
+const Io = std.Io;
+const builtin = @import("builtin");
+const Value = std.json.Value;
+
+const mcp_rpc = @import("mcp_rpc.zig");
+const mcp_stdio = @import("mcp_stdio.zig");
+const modern_protocol = @import("mcp_protocol.zig").modern_protocol;
+const Server = mcp_rpc.Server;
+
+fn parse(a: std.mem.Allocator, json: []const u8) !Value {
+ return std.json.parseFromSliceLeaky(Value, a, json, .{ .allocate = .alloc_always });
+}
+
+test "classifyStdioProbe: a modern supportedVersions list is the only path to .modern" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ const modern = try parse(a,
+ \\{"jsonrpc":"2.0","id":1,"result":{"supportedVersions":["2026-07-28"],"serverInfo":{"name":"fixture","version":"1"}}}
+ );
+ try std.testing.expectEqual(mcp_rpc.StdioProbeOutcome.modern, try mcp_rpc.classifyStdioProbe(modern));
+}
+
+test "classifyStdioProbe: a clean rejection falls back, and says which kind" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ // The server answered `server/discover` with a JSON-RPC error: it does
+ // not speak the modern protocol. A legitimate, spec-sanctioned downgrade.
+ const rejected = try parse(a,
+ \\{"jsonrpc":"2.0","id":1,"error":{"code":-32601,"message":"Method not found"}}
+ );
+ try std.testing.expectEqual(mcp_rpc.LegacyReason.rejected, (try mcp_rpc.classifyStdioProbe(rejected)).legacy);
+
+ // It answered, but lists only pre-modern revisions.
+ const old_only = try parse(a,
+ \\{"jsonrpc":"2.0","id":1,"result":{"supportedVersions":["2025-11-25","2025-06-18"]}}
+ );
+ try std.testing.expectEqual(mcp_rpc.LegacyReason.no_modern_version, (try mcp_rpc.classifyStdioProbe(old_only)).legacy);
+
+ // An answer with no version list at all is still an answer, not a fault.
+ const no_list = try parse(a,
+ \\{"jsonrpc":"2.0","id":1,"result":{"serverInfo":{"name":"fixture","version":"1"}}}
+ );
+ try std.testing.expectEqual(mcp_rpc.LegacyReason.no_modern_version, (try mcp_rpc.classifyStdioProbe(no_list)).legacy);
+}
+
+test "classifyStdioProbe (#327): a transport error propagates instead of downgrading" {
+ // The regression in one line: a read that FAILED says nothing about the
+ // server's protocol, so it must never be answered with `.legacy` — that
+ // pinned the era for the whole process life with nothing to see.
+ const failed: anyerror!Value = error.ReadFailed;
+ try std.testing.expectError(error.ReadFailed, mcp_rpc.classifyStdioProbe(failed));
+ const canceled: anyerror!Value = error.Canceled;
+ try std.testing.expectError(error.Canceled, mcp_rpc.classifyStdioProbe(canceled));
+
+ // `McpClosed` is the one error with a defined meaning: the child exited.
+ // It stays a distinct outcome (the caller respawns), not a silent legacy.
+ const closed: anyerror!Value = error.McpClosed;
+ try std.testing.expectEqual(mcp_rpc.StdioProbeOutcome.closed, try mcp_rpc.classifyStdioProbe(closed));
+}
+
+test "GRAFF_MCP_PROBE_MS (#327): the deadline that decides the fallback is tunable" {
+ const saved = mcp_rpc.stdio_probe_timeout_ms;
+ defer mcp_rpc.stdio_probe_timeout_ms = saved;
+
+ var env = std.process.Environ.Map.init(std.testing.allocator);
+ defer env.deinit();
+
+ // The measured #327 case: a server whose first answer takes ~1.5s is
+ // modern, but 600ms says legacy. This is the way out of that.
+ try env.put("GRAFF_MCP_PROBE_MS", "2500");
+ mcp_rpc.applyProbeTimeoutEnv(&env);
+ try std.testing.expectEqual(@as(i64, 2500), mcp_rpc.stdio_probe_timeout_ms);
+
+ // Garbage and 0 leave the previous bound alone rather than disabling it.
+ try env.put("GRAFF_MCP_PROBE_MS", "not-a-number");
+ mcp_rpc.applyProbeTimeoutEnv(&env);
+ try std.testing.expectEqual(@as(i64, 2500), mcp_rpc.stdio_probe_timeout_ms);
+ try env.put("GRAFF_MCP_PROBE_MS", "0");
+ mcp_rpc.applyProbeTimeoutEnv(&env);
+ try std.testing.expectEqual(@as(i64, 2500), mcp_rpc.stdio_probe_timeout_ms);
+
+ // Clamped, so a fat-fingered value cannot re-create the #275 hang.
+ try env.put("GRAFF_MCP_PROBE_MS", "99999999");
+ mcp_rpc.applyProbeTimeoutEnv(&env);
+ try std.testing.expectEqual(@as(i64, 60_000), mcp_rpc.stdio_probe_timeout_ms);
+}
+
+/// A stdio child that answers the first line it is fed with `reply`, then
+/// holds both pipes open so nothing races on teardown. The probe always uses
+/// id 1 (`Server.next_id` starts there), so `reply` can be a canned line.
+fn spawnReplying(a: std.mem.Allocator, io: Io, script: []const u8) !struct { child: std.process.Child, server: *Server } {
+ var child = try std.process.spawn(io, .{
+ .argv = &.{ "/bin/sh", "-c", script },
+ .stdin = .pipe,
+ .stdout = .pipe,
+ .stderr = .ignore,
+ });
+ errdefer mcp_stdio.stopChild(io, &child);
+ const server = try a.create(Server);
+ server.* = .{
+ .name = "fixture",
+ .transport = .{ .stdio = .{
+ .child = child,
+ .stdin_writer = child.stdin.?.writerStreaming(io, try a.alloc(u8, 4096)),
+ .stdout_reader = child.stdout.?.readerStreaming(io, try a.alloc(u8, 4096)),
+ } },
+ };
+ return .{ .child = child, .server = server };
+}
+
+test "probeStdio: a server that answers with a modern version list negotiates modern" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest; // /bin/sh
+ const io = std.testing.io;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ const saved = mcp_rpc.stdio_probe_timeout_ms;
+ mcp_rpc.stdio_probe_timeout_ms = 10_000; // the classification is under test, not the deadline
+ defer mcp_rpc.stdio_probe_timeout_ms = saved;
+
+ var spawned = try spawnReplying(a, io,
+ \\read line; printf '%s\n' '{"jsonrpc":"2.0","id":1,"result":{"supportedVersions":["2026-07-28"]}}'; cat >/dev/null
+ );
+ defer mcp_stdio.stopChild(io, &spawned.child);
+
+ try std.testing.expectEqual(mcp_rpc.StdioProbeOutcome.modern, try mcp_rpc.probeStdio(spawned.server, a, io));
+ try std.testing.expect(spawned.server.probe_fallback == null);
+}
+
+test "probeStdio: a server that rejects server/discover falls back to legacy, with a reason" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest; // /bin/sh
+ const io = std.testing.io;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ const saved = mcp_rpc.stdio_probe_timeout_ms;
+ mcp_rpc.stdio_probe_timeout_ms = 10_000;
+ defer mcp_rpc.stdio_probe_timeout_ms = saved;
+
+ var spawned = try spawnReplying(a, io,
+ \\read line; printf '%s\n' '{"jsonrpc":"2.0","id":1,"error":{"code":-32601,"message":"Method not found"}}'; cat >/dev/null
+ );
+ defer mcp_stdio.stopChild(io, &spawned.child);
+
+ const outcome = try mcp_rpc.probeStdio(spawned.server, a, io);
+ try std.testing.expectEqual(mcp_rpc.LegacyReason.rejected, outcome.legacy);
+ // Reported, not silent: the reason renders into the connect line / `/mcp`.
+ try std.testing.expect(std.mem.indexOf(u8, outcome.legacy.note(), "rejected") != null);
+}
+
+test "probeStdio (#327): a probe that cannot be spawned errors instead of silently degrading" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest; // /bin/sh
+ const io = std.testing.io;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ // Reads stdin so the probe write still succeeds; the failure under test is
+ // graff's own, on the client side.
+ var spawned = try spawnReplying(a, io, "cat >/dev/null");
+ defer mcp_stdio.stopChild(io, &spawned.child);
+
+ // An Io that refuses concurrency reproduces the exact arm that used to
+ // read `select.concurrent(...) catch return .legacy`: no reader task, no
+ // deadline task, and — before the fix — a permanent, invisible downgrade
+ // of a server that was never even asked.
+ const no_concurrency = std.Io.Threaded.global_single_threaded.io();
+ try std.testing.expectError(error.McpProbeUnavailable, mcp_rpc.probeStdio(spawned.server, a, no_concurrency));
+ try std.testing.expect(spawned.server.probe_fallback == null);
+}
+
+test "probeStdioResilient (#327): retries, then downgrades only with a visible reason" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest; // /bin/sh
+ const io = std.testing.io;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ var spawned = try spawnReplying(a, io, "cat >/dev/null");
+ defer mcp_stdio.stopChild(io, &spawned.child);
+
+ const no_concurrency = std.Io.Threaded.global_single_threaded.io();
+ const outcome = try mcp_rpc.probeStdioResilient(spawned.server, a, no_concurrency);
+ // Connecting still succeeds (never worse than before), but the era is
+ // attributed to graff, not to the server, and it is printed.
+ try std.testing.expectEqual(mcp_rpc.LegacyReason.probe_unavailable, outcome.legacy);
+ try std.testing.expect(std.mem.indexOf(u8, outcome.legacy.note(), "graff could not run") != null);
+ // Every reason renders something a user can read.
+ for ([_]mcp_rpc.LegacyReason{ .rejected, .no_modern_version, .timeout, .probe_unavailable, .server_exited }) |reason| {
+ try std.testing.expect(reason.note().len > 0);
+ }
+ try std.testing.expect(std.mem.indexOf(u8, mcp_rpc.LegacyReason.no_modern_version.note(), modern_protocol) != null);
+}