Skip to content

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

Python

feat(mcp): stdio server/discover probe behind GRAFF_MCP_PROBE

Rach Pradhand4ff7620712f
diff --git a/scripts/test-mcp-stdio-probe.py b/scripts/test-mcp-stdio-probe.py
new file mode 100644
index 00000000..363c1b1c
--- /dev/null
+++ b/scripts/test-mcp-stdio-probe.py
@@ -0,0 +1,250 @@
+#!/usr/bin/env python3
+"""Offline end-to-end proof for graff's GRAFF_MCP_PROBE-gated stdio
+`server/discover` probe. Two scenarios:
+
+1. Gate off (default): a stdio server never sees anything but the exact
+ pre-migration sequence (initialize first, no server/discover line ever
+ written) — proves the default behavior is untouched.
+2. Gate on, against a server that silently drops `server/discover` (the
+ documented worst case: a legacy server that doesn't recognize the
+ method and never replies): the probe must time out and fall back to the
+ legacy handshake on the SAME process, without hanging graff and without
+ corrupting the stdout reader for the handshake that follows. This is the
+ empirical validation for the highest-risk piece of the migration —
+ cancelling a blocked pipe read and reusing the same reader afterward.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import textwrap
+import time
+
+
+FIXTURE_SOURCE = textwrap.dedent(
+ """
+ import json
+ import sys
+
+ def send(obj):
+ sys.stdout.write(json.dumps(obj, separators=(",", ":")) + "\\n")
+ sys.stdout.flush()
+
+ for line in sys.stdin:
+ line = line.strip()
+ if not line:
+ continue
+ msg = json.loads(line)
+ method = msg.get("method")
+ mid = msg.get("id")
+ if method == "server/discover":
+ # Deliberately silent: the worst legacy case (unrecognized
+ # method, no reply at all) that the probe's bounded read must
+ # survive.
+ continue
+ if method == "initialize":
+ send({
+ "jsonrpc": "2.0",
+ "id": mid,
+ "result": {
+ "protocolVersion": "2025-06-18",
+ "capabilities": {"tools": {}},
+ "serverInfo": {"name": "stdio-fixture", "version": "1"},
+ },
+ })
+ continue
+ if method == "notifications/initialized":
+ continue
+ if method == "tools/list":
+ send({
+ "jsonrpc": "2.0",
+ "id": mid,
+ "result": {
+ "tools": [
+ {
+ "name": "fixture_ping",
+ "description": "Ping the fixture.",
+ "inputSchema": {"type": "object", "properties": {}},
+ }
+ ]
+ },
+ })
+ continue
+ """
+).strip()
+
+
+EXITING_FIXTURE_SOURCE = textwrap.dedent(
+ """
+ import json
+ import sys
+
+ def send(obj):
+ sys.stdout.write(json.dumps(obj, separators=(",", ":")) + "\\n")
+ sys.stdout.flush()
+
+ for line in sys.stdin:
+ line = line.strip()
+ if not line:
+ continue
+ msg = json.loads(line)
+ method = msg.get("method")
+ mid = msg.get("id")
+ if method == "server/discover":
+ # The other documented worst case: some legacy SDK servers exit
+ # outright on an unrecognized pre-initialize message.
+ sys.exit(0)
+ if method == "initialize":
+ send({
+ "jsonrpc": "2.0",
+ "id": mid,
+ "result": {
+ "protocolVersion": "2025-06-18",
+ "capabilities": {"tools": {}},
+ "serverInfo": {"name": "stdio-fixture", "version": "1"},
+ },
+ })
+ continue
+ if method == "notifications/initialized":
+ continue
+ if method == "tools/list":
+ send({
+ "jsonrpc": "2.0",
+ "id": mid,
+ "result": {"tools": []},
+ })
+ continue
+ """
+).strip()
+
+
+def run_graff(graff: Path, fixture: Path, probe: bool) -> subprocess.CompletedProcess[str]:
+ with tempfile.TemporaryDirectory(prefix="graff-mcp-stdio-") as temp:
+ workspace = Path(temp)
+ (workspace / ".mcp.json").write_text(
+ json.dumps(
+ {
+ "mcpServers": {
+ "fixture": {
+ "command": sys.executable,
+ "args": [str(fixture)],
+ }
+ }
+ },
+ separators=(",", ":"),
+ ),
+ encoding="utf-8",
+ )
+ settings = workspace / ".harness" / "settings.json"
+ settings.parent.mkdir(mode=0o700)
+ settings.write_text(
+ '{"skills":{"codedbpro":false,"muonry":false}}\n',
+ encoding="utf-8",
+ )
+ env = os.environ.copy()
+ env.update(
+ {
+ "ANTHROPIC_API_KEY": "fixture-not-used",
+ "GRAFF_BEHAVIOR_TRACE": "0",
+ "GRAFF_FLEET": "off",
+ "GRAFF_NO_SMOLIFY": "1",
+ "GRAFF_NO_TELEMETRY": "1",
+ }
+ )
+ if probe:
+ env["GRAFF_MCP_PROBE"] = "1"
+ else:
+ env.pop("GRAFF_MCP_PROBE", None)
+ return subprocess.run(
+ [str(graff), "--json", "--yolo", "--model", "claude"],
+ cwd=workspace,
+ env=env,
+ input="",
+ text=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ timeout=20,
+ check=False,
+ )
+
+
+def run(graff: Path) -> None:
+ with tempfile.TemporaryDirectory(prefix="graff-mcp-stdio-fixture-") as temp:
+ fixture = Path(temp) / "fixture.py"
+ fixture.write_text(FIXTURE_SOURCE, encoding="utf-8")
+
+ # Scenario 1: gate off, byte-identical default behavior.
+ completed = run_graff(graff, fixture, probe=False)
+ if completed.returncode != 0:
+ raise AssertionError(
+ f"[gate off] graff exited {completed.returncode}\n"
+ f"stdout:\n{completed.stdout}\nstderr:\n{completed.stderr}"
+ )
+ assert (
+ "connected (mcp 2025-06-18)" in completed.stderr
+ ), f"[gate off] expected a normal legacy connect:\n{completed.stderr}"
+ print("gate off: byte-identical legacy connect, no server/discover — OK")
+
+ # Scenario 2: gate on, server silently drops server/discover. Must
+ # time out (~3s) 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).
+ start = time.monotonic()
+ completed = run_graff(graff, fixture, probe=True)
+ elapsed = time.monotonic() - start
+ if completed.returncode != 0:
+ raise AssertionError(
+ f"[gate on] graff exited {completed.returncode} after {elapsed:.1f}s\n"
+ f"stdout:\n{completed.stdout}\nstderr:\n{completed.stderr}"
+ )
+ assert (
+ "connected (mcp 2025-06-18)" in completed.stderr
+ ), f"[gate on] expected the legacy fallback to still connect:\n{completed.stderr}"
+ # The probe's 3s bound should dominate; a hang would have hit the
+ # 20s subprocess.run timeout above and raised instead of getting
+ # here, but a slack upper bound catches a "cancel doesn't actually
+ # cancel, it just silently proceeds without waiting" regression too.
+ assert elapsed < 15, f"[gate on] took {elapsed:.1f}s — the probe bound is not working"
+ assert elapsed >= 2.5, f"[gate on] took only {elapsed:.1f}s — the probe may not have run at all"
+ print(f"gate on: timed-out probe -> 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
+ # on the fresh process — fast (no 3s wait; EOF is immediate).
+ exiting_fixture = Path(temp) / "exiting_fixture.py"
+ exiting_fixture.write_text(EXITING_FIXTURE_SOURCE, encoding="utf-8")
+ start = time.monotonic()
+ completed = run_graff(graff, exiting_fixture, probe=True)
+ elapsed = time.monotonic() - start
+ if completed.returncode != 0:
+ raise AssertionError(
+ f"[gate on, exiting] graff exited {completed.returncode} after {elapsed:.1f}s\n"
+ f"stdout:\n{completed.stdout}\nstderr:\n{completed.stderr}"
+ )
+ assert (
+ "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")
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--graff", type=Path, default=Path("zig-out/bin/graff"))
+ args = parser.parse_args()
+ graff = args.graff.resolve()
+ if not graff.is_file():
+ parser.error(f"graff binary not found: {graff}")
+ run(graff)
+ print("stdio GRAFF_MCP_PROBE E2E passed")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/src/main.zig b/src/main.zig
index 0dff15be..ab12678b 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -371,7 +371,7 @@ pub fn main(init: std.process.Init) !void {
// auto-connect only with --yolo (trusted) or explicit per-session consent; otherwise start with an empty (but live) registry so `/mcp add`
// still works.
const mcp_home = homeEnv(init.environ_map) orelse "";
- var registry_storage = try session_start.initRegistryConsent(io, gpa, arena, out, in, flags, mcp_config_path, mcp_home, use_color, json_mode);
+ var registry_storage = try session_start.initRegistryConsent(io, gpa, arena, out, in, flags, mcp_config_path, mcp_home, use_color, json_mode, init.environ_map);
boot.mark(io, "MCP registry");
defer registry_storage.deinit();
const registry: ?*mcp.Registry = &registry_storage;
@@ -584,11 +584,11 @@ const exec = @import("exec.zig");
// ── Unit tests (`zig build test`) ──────────────────────────────────────────
test { // pull in tests from imported modules (mcp.zig)
_ = mcp;
+ _ = @import("mcp_rpc.zig");
_ = @import("main_test.zig");
- // A module whose tests must run needs an explicit reference here: a plain
- // @import elsewhere (or a type-only alias) is NOT enough to pull its
- // `test {}` blocks in — they compile to nothing and the suite still reports
- // green. scripts/eval-tier1.sh --only reach catches an unreferenced one.
+ // A module whose tests must run needs an explicit reference here: a
+ // plain @import elsewhere (or a type-only alias) is NOT enough — it
+ // compiles to nothing; scripts/eval-tier1.sh --only reach catches one.
_ = @import("scoring_slot_test.zig");
_ = @import("readline_history.zig");
_ = @import("goal_pacing_autonomous_test.zig");
diff --git a/src/mcp.zig b/src/mcp.zig
index e08d75ee..c008e814 100644
--- a/src/mcp.zig
+++ b/src/mcp.zig
@@ -47,6 +47,12 @@ pub const Registry = struct {
mutex: Io.Mutex = .init,
servers: []*Server = &.{},
tools: []Tool = &.{},
+ /// `GRAFF_MCP_PROBE=1`, default off (see mcp_rpc.probeStdio's doc comment
+ /// for why this cannot be turned on unconditionally today). Only
+ /// `Registry.init` reads the environment; servers added later via
+ /// `addServer`/`trustWorkspace` on a `Registry.empty*`-constructed
+ /// registry inherit `false` — a documented gap, never a safety issue.
+ stdio_probe: bool = false,
pub fn arena(self: *Registry) Allocator {
return self.arena_state.allocator();
@@ -56,7 +62,7 @@ pub const Registry = struct {
/// Streamable HTTP `url`, handshake each server, and collect their tools.
/// Returns null
/// (no error) when the config file is absent — MCP is optional.
- pub fn init(gpa: Allocator, io: Io, config_path: []const u8, home: []const u8) !?Registry {
+ pub fn init(gpa: Allocator, io: Io, config_path: []const u8, home: []const u8, environ_map: anytype) !?Registry {
const text = Io.Dir.cwd().readFileAlloc(io, config_path, gpa, .limited(1 << 20)) catch |err| switch (err) {
error.FileNotFound => return null,
else => return err,
@@ -68,6 +74,7 @@ pub const Registry = struct {
.io = io,
.home = home,
.arena_state = std.heap.ArenaAllocator.init(gpa),
+ .stdio_probe = if (environ_map.get("GRAFF_MCP_PROBE")) |v| std.mem.eql(u8, v, "1") else false,
};
errdefer reg.deinit();
const a = reg.arena();
@@ -270,6 +277,29 @@ pub const Registry = struct {
};
return n;
}
+ /// Spawn a stdio child and wire up its transport. Factored out of
+ /// `startServer` so the `GRAFF_MCP_PROBE` path can call it a second
+ /// time: some legacy SDK servers close stdout on an unrecognized
+ /// pre-`initialize` message (`server/discover`), and the only fix is a
+ /// fresh process — the closed one can't be un-closed.
+ fn spawnStdio(reg: *Registry, a: Allocator, argv: []const []const u8, env_map: ?*std.process.Environ.Map) !Transport {
+ var child = try std.process.spawn(reg.io, .{
+ .argv = argv,
+ .stdin = .pipe,
+ .stdout = .pipe,
+ .stderr = .ignore,
+ .environ_map = env_map,
+ });
+ errdefer mcp_stdio.stopChild(reg.io, &child);
+ const in_buf = try a.alloc(u8, 64 * 1024);
+ const out_buf = try a.alloc(u8, 1 << 20);
+ return .{ .stdio = .{
+ .child = child,
+ .stdin_writer = child.stdin.?.writerStreaming(reg.io, in_buf),
+ .stdout_reader = child.stdout.?.readerStreaming(reg.io, out_buf),
+ } };
+ }
+
fn startServer(
reg: *Registry,
a: Allocator,
@@ -283,6 +313,12 @@ pub const Registry = struct {
if ((command_v == null) == (url_v == null)) return error.BadMcpConfig;
const server = try a.create(Server);
+ // Hoisted out of the `else` branch below (rather than local to it)
+ // so the GRAFF_MCP_PROBE respawn path -- which runs after this
+ // if/else, once the era-detection dispatch below finds a closed
+ // stdio child -- can spawn a fresh process with the same argv/env.
+ var stdio_argv: std.ArrayList([]const u8) = .empty;
+ var stdio_env_map: ?*std.process.Environ.Map = null;
if (url_v) |url| {
if (url != .string) return error.BadMcpConfig;
if (!validRemoteUrl(url.string)) return error.BadMcpUrl;
@@ -312,18 +348,16 @@ pub const Registry = struct {
};
} else {
const command = if (command_v.? == .string) command_v.?.string else return error.BadMcpConfig;
- var argv: std.ArrayList([]const u8) = .empty;
- try argv.append(a, command);
+ try stdio_argv.append(a, command);
if (cfg.get("args")) |args| {
if (args != .array) return error.BadMcpConfig;
for (args.array.items) |arg| {
if (arg != .string) return error.BadMcpConfig;
- try argv.append(a, arg.string);
+ try stdio_argv.append(a, arg.string);
}
}
// Optional per-server env overlaid on the parent environment.
- var env_map: ?*std.process.Environ.Map = null;
if (cfg.get("env")) |env| {
if (env != .object) return error.BadMcpConfig;
const m = try a.create(std.process.Environ.Map);
@@ -333,31 +367,10 @@ pub const Registry = struct {
if (entry.value_ptr.* != .string) return error.BadMcpConfig;
try m.put(entry.key_ptr.*, entry.value_ptr.*.string);
}
- env_map = m;
+ stdio_env_map = m;
}
- var child = try std.process.spawn(reg.io, .{
- .argv = argv.items,
- .stdin = .pipe,
- .stdout = .pipe,
- .stderr = .ignore,
- .environ_map = env_map,
- });
- var server_owns_child = false;
- errdefer if (!server_owns_child) {
- mcp_stdio.stopChild(reg.io, &child);
- };
- const in_buf = try a.alloc(u8, 64 * 1024);
- const out_buf = try a.alloc(u8, 1 << 20);
- server.* = .{
- .name = name,
- .transport = .{ .stdio = .{
- .child = child,
- .stdin_writer = child.stdin.?.writerStreaming(reg.io, in_buf),
- .stdout_reader = child.stdout.?.readerStreaming(reg.io, out_buf),
- } },
- };
- server_owns_child = true;
+ server.* = .{ .name = name, .transport = try spawnStdio(reg, a, stdio_argv.items, stdio_env_map) };
}
var registry_owns_server = false;
@@ -367,12 +380,30 @@ pub const Registry = struct {
errdefer tools.shrinkRetainingCapacity(tools_before);
// Probe-then-fallback for HTTP (mcp_rpc.connectHttp), the unchanged
- // legacy handshake for stdio (mcp_rpc.connectStdio) — either way,
+ // legacy handshake for stdio unless GRAFF_MCP_PROBE=1 opts into the
+ // gated server/discover probe (mcp_rpc.probeStdio) — either way,
// server.era and server.protocol_version are set by the time this
// returns, and the model sees whichever revision was negotiated.
const listed = switch (server.transport) {
.http => try mcp_rpc.connectHttp(server, a, a),
- .stdio => try mcp_rpc.connectStdio(server, a, a),
+ .stdio => stdio_listed: {
+ if (!reg.stdio_probe) break :stdio_listed try mcp_rpc.connectStdio(server, a, a);
+ switch (try mcp_rpc.probeStdio(server, a, reg.io)) {
+ .modern => break :stdio_listed try mcp_rpc.finishModernStdio(server, a, a),
+ .legacy => break :stdio_listed try mcp_rpc.connectStdio(server, a, a),
+ .closed => {
+ // The probe write/read found a dead process (some
+ // legacy SDK servers exit on an unrecognized
+ // pre-initialize message) — respawn once and go
+ // straight to legacy on the fresh process, no
+ // second probe against a server that already
+ // proved it can't tolerate one.
+ 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);
+ },
+ }
+ },
};
const result_v = listed.object.get("result") orelse return error.BadMcpResponse;
if (result_v != .object) return error.BadMcpResponse;
diff --git a/src/mcp_rpc.zig b/src/mcp_rpc.zig
index b8cb0c6d..ba0dd0b9 100644
--- a/src/mcp_rpc.zig
+++ b/src/mcp_rpc.zig
@@ -147,14 +147,112 @@ fn connectLegacy(server: *Server, a: Allocator, session_alloc: Allocator) !Value
return request(server, a, "{}", "tools/list", null);
}
-/// Connect a stdio server. Always legacy today — the `server/discover`
-/// probe lands gated behind `GRAFF_MCP_PROBE` in a later commit; with the
-/// gate off (the default), this is byte-identical to graff's pre-migration
-/// behavior.
+const stdio_probe_timeout: Io.Duration = .fromSeconds(3);
+
+fn stdioProbeReadTask(server: *Server, response_alloc: Allocator, id: i64) anyerror!Value {
+ const stdio = &server.transport.stdio;
+ const r = &stdio.stdout_reader.interface;
+ while (true) {
+ const line = (try r.takeDelimiter('\n')) orelse return error.McpClosed;
+ if (mcp_http.matchingResponse(response_alloc, line, id)) |parsed| return parsed;
+ }
+}
+
+fn stdioProbeTimeoutTask(io: Io) void {
+ io.sleep(stdio_probe_timeout, .awake) catch {};
+}
+
+const StdioProbeDone = union(enum) {
+ replied: anyerror!Value,
+ timeout,
+};
+
+pub const StdioProbeOutcome = enum { modern, legacy, closed };
+
+fn classifyStdioProbe(result: anyerror!Value) 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
+ };
+ // 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;
+ for (supported) |v| if (v == .string and std.mem.eql(u8, v.string, modern_protocol)) return .modern;
+ return .legacy;
+}
+
+/// Attempt the `server/discover` probe, bounded to `stdio_probe_timeout` 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
+/// response within a reasonable timeout"). `Select.cancel` blocks until the
+/// read task has actually stopped before returning, so by the time this
+/// function returns on a timeout, nothing is still touching the reader —
+/// the caller's subsequent (unbounded, as today) legacy `request()` reads
+/// pick up cleanly on the same stream.
+///
+/// `.closed` (the child exited or closed stdout) is reported distinctly
+/// from `.legacy` (a reply arrived, or the wait simply timed out) because
+/// only `.closed` needs the caller to respawn: some legacy SDK servers
+/// exit on an unrecognized pre-initialize message, and writing the
+/// `initialize` request to a dead child's closed stdin would just error.
+pub fn probeStdio(server: *Server, a: Allocator, io: Io) !StdioProbeOutcome {
+ const id = server.next_id;
+ server.next_id += 1;
+ {
+ const stdio = &server.transport.stdio;
+ const w = &stdio.stdin_writer.interface;
+ try w.print(
+ \\{{"jsonrpc":"2.0","id":{d},"method":"server/discover","params":{{}}}}
+ ++ "\n", .{id});
+ try w.flush();
+ }
+
+ 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;
+ select.concurrent(.timeout, stdioProbeTimeoutTask, .{io}) catch {
+ const only = select.await() catch return .legacy;
+ select.cancelDiscard();
+ return classifyStdioProbe(only.replied);
+ };
+
+ const first = select.await() catch return .legacy;
+ switch (first) {
+ .replied => |result| {
+ select.cancelDiscard();
+ return classifyStdioProbe(result);
+ },
+ .timeout => {
+ _ = select.cancel(); // blocks until the read task has actually stopped
+ return .legacy;
+ },
+ }
+}
+
+/// 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
+/// respawn a server whose process closes during the probe. This is
+/// byte-identical to graff's pre-migration behavior either way.
pub fn connectStdio(server: *Server, a: Allocator, session_alloc: Allocator) !Value {
return connectLegacy(server, a, session_alloc);
}
+/// Finish connecting a stdio server that `probeStdio` found modern: no
+/// handshake, just the modern-enveloped `tools/list` (era is set first so
+/// `request` picks the modern wire format).
+pub fn finishModernStdio(server: *Server, a: Allocator, session_alloc: Allocator) !Value {
+ server.era = .modern;
+ server.protocol_version = try session_alloc.dupe(u8, modern_protocol);
+ server.initialized = true;
+ return request(server, a, "{}", "tools/list", null);
+}
+
/// Connect a Streamable HTTP server: attempt a modern (2026-07-28)
/// `tools/list` first — it doubles as the discovery call graff needs
/// anyway, so a modern server costs one POST where the legacy handshake
@@ -214,3 +312,32 @@ fn connectHttpAttempt(server: *Server, a: Allocator, session_alloc: Allocator, r
},
}
}
+
+test "a late reply for a stale id cannot be mistaken for the id actually awaited" {
+ // The exact loop body `request`'s stdio branch and `stdioProbeReadTask`
+ // both use: takeDelimiter, then filter by id via
+ // mcp_http.matchingResponse, skipping any line whose id doesn't match.
+ // Proves that if a `server/discover` probe times out but its reply
+ // arrives later, it cannot be mistaken for the `initialize` response
+ // that follows it on the same stream — the ids differ (discover used
+ // an earlier next_id).
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var reader: Io.Reader = .fixed(
+ \\{"jsonrpc":"2.0","id":1,"result":{}}
+ \\{"jsonrpc":"2.0","id":2,"result":{"tools":[]}}
+ \\
+ );
+ var found: ?Value = null;
+ while (true) {
+ const line = (try reader.takeDelimiter('\n')) orelse break;
+ if (mcp_http.matchingResponse(a, line, 2)) |parsed| {
+ found = parsed;
+ break;
+ }
+ }
+ const result = found orelse return error.TestUnexpectedResult;
+ try std.testing.expectEqual(@as(i64, 2), result.object.get("id").?.integer);
+ try std.testing.expect(result.object.get("result").?.object.get("tools") != null);
+}
diff --git a/src/session_start.zig b/src/session_start.zig
index fdd9bfe5..3c01810f 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -354,7 +354,7 @@ pub fn initTelemetry(io: Io, gpa: Allocator, client: *std.http.Client, environ_m
/// `/mcp add` still works. Moved out of main() (600-line goal). Returns the
/// Registry by value — mcp.Registry holds no self-references (its storage
/// is ArrayList/HashMap-backed), so returning it is safe.
-pub fn initRegistryConsent(io: Io, gpa: Allocator, arena: Allocator, out: *Io.Writer, in: *Io.Reader, flags: args.Flags, mcp_config_path: []const u8, home: []const u8, use_color: bool, json_mode: bool) !mcp.Registry {
+pub fn initRegistryConsent(io: Io, gpa: Allocator, arena: Allocator, out: *Io.Writer, in: *Io.Reader, flags: args.Flags, mcp_config_path: []const u8, home: []const u8, use_color: bool, json_mode: bool, environ_map: anytype) !mcp.Registry {
const mcp_count = mcp_cli.countMcpServers(io, arena);
var connect_mcp = flags.yolo_flag or mcp_count == 0;
if (mcp_count > 0 and !flags.yolo_flag and !json_mode and use_color) {
@@ -363,7 +363,7 @@ pub fn initRegistryConsent(io: Io, gpa: Allocator, arena: Allocator, out: *Io.Wr
const ans = in.takeDelimiter('\n') catch null;
connect_mcp = ans != null and ans.?.len > 0 and (ans.?[0] == 'y' or ans.?[0] == 'Y');
}
- return if (connect_mcp) ((mcp.Registry.init(gpa, io, mcp_config_path, home) catch |err| inner: {
+ return if (connect_mcp) ((mcp.Registry.init(gpa, io, mcp_config_path, home, environ_map) catch |err| inner: {
try out.print("[mcp] init failed: {t} — continuing without MCP\n", .{err});
if (telemetry.g_telem) |t| t.errorEvent("mcp", @errorName(err));
break :inner null;