graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
MCP connects in the background in every session but --json (ADR 0230)
justrach425433f67772
diff --git a/build.zig b/build.zigindex b6519aab..15ffaad3 100644--- a/build.zig+++ b/build.zig@@ -172,6 +172,9 @@ pub fn build(b: *std.Build) void {const mcp_lazy_test = b.addSystemCommand(&.{ "python3", "scripts/test-mcp-lazy.py" });mcp_lazy_test.addArtifactArg(exe);test_step.dependOn(&mcp_lazy_test.step);+ const mcp_async_test = b.addSystemCommand(&.{ "python3", "scripts/test-mcp-async-start.py" });+ mcp_async_test.addArtifactArg(exe);+ test_step.dependOn(&mcp_async_test.step);const mcp_add_test = b.addSystemCommand(&.{ "python3", "scripts/test-mcp-add.py" });mcp_add_test.addArtifactArg(exe);test_step.dependOn(&mcp_add_test.step);diff --git a/docs/adr/0230-mcp-connects-in-the-background.md b/docs/adr/0230-mcp-connects-in-the-background.mdnew file mode 100644index 00000000..bfa5e370--- /dev/null+++ b/docs/adr/0230-mcp-connects-in-the-background.md@@ -0,0 +1,44 @@+# 0230. MCP connects in the background in every session but `--json`++Status: accepted 2026-10-01. Extends ADR 0035, which covered `--yolo` and+`-p`, to interactive sessions and ACP.++## Context++An interactive session without `--yolo` asked for MCP consent, then waited+for every server's handshake before the prompt was usable: a server that took+five seconds to answer `initialize` held the first message for five seconds.+ACP's `session/new` waited up to three seconds for the servers a client+passed. `--yolo` and `-p` already connected in the background (ADR 0035).++Codex starts every MCP server concurrently in the background, lets a turn go+ahead without a server that is not ready, and reports each server's startup.++## Decision++- `deferMcpJoin`: every session but `--json` connects in the background:+ interactive after consent, `--yolo`, `-p` and ACP. `--json` keeps its+ blocking connect so the protocol stream does not race a late catalog+ merge. The companion auto-connect follows the same gate.+- No model request waits for a handshake. Each request merges the starts+ that have finished (ADR 0035, 0221), and the catalog rebuilds when one+ joined.+- The root request reports what changed: "MCP still connecting — native+ tools this turn" on the first request that goes out while servers connect,+ then "mcp: NAME connected (N tool(s))" or "mcp: NAME did not connect" when+ a start finishes. The registry queues the notices under its lock; the root+ agent's request emits them through the agent's own sink, which is what the+ TUI shows.+- ACP `session/new` and `session/load` wait at most 250 ms for the servers+ the client named: enough for one restored from the tool cache, never a+ real handshake.+- `/mcp` lists without waiting and names the servers still connecting.+ `/mcp add` and `/mcp trust` still join pending starts first.++## Consequences++MCP no longer holds up a session's start. A server that is still connecting+is missing from the first request's tools; they join a later request, as on+`-p` since ADR 0035. The consent prompt still waits for an answer. `--json`+clients still wait; moving them to the background needs startup events in+the protocol.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex c6f9d084..7ea12ffe 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -256,6 +256,7 @@ record only when you need the evidence or the edge cases.| [0227](0227-children-inherit-the-roots-loaded-mcp-tools.md) | A spawned child's catalog gains the MCP tools its root loaded, with full schemas (`worker_mcp.inherit` into `Agent.worker_tools`, served first by `toolsJson`). Unloaded tools stay out; children still have no load tool. || [0228](0228-read-only-child-calls-declared-read-only-mcp-tools.md) | An MCP tool is a read when its server declares `readOnlyHint: true` (`mcp.Tool.read_only`). A read-only (informational) child may call those and inherits only those from its root; undeclared MCP tools stay refused. || [0229](0229-every-chatgpt-login-is-chatgpt-new.md) | The Codex client's login no longer works, so every ChatGPT login name (`chatgpt`, `codex`, `openai`, `gpt`, `oai`) and the model picker run the `chatgpt-new` sign-in, and `chatgpt-new` precedes `codex` in the provider table. The `codex` provider stays for an existing Codex CLI `auth.json`. Replaces ADR 0221's "Codex first". |+| [0230](0230-mcp-connects-in-the-background.md) | Every session but `--json` connects MCP servers in the background (interactive after consent, `--yolo`, `-p`, ACP); no request waits for a handshake, finished starts join the next request, and the root request says which server connected or did not. ACP `session/new` waits at most 250 ms; `/mcp` lists without waiting. || [0231](0231-no-round-trip-the-model-does-not-need.md) | No call the task did not ask for: a named small MCP server (and subagents, when asked for) loads with the first request, with the slim-shape note; `write_file` refuses to replace an unread file unless `replace: true` and reports created/replaced and JSON validity; inherited child MCP tools are never deferred; a piped bracketed paste is one prompt; unwatched (`-p`, piped) sessions get no `ask_user` and no low-effort reasoning summaries. |## When to write onediff --git a/scripts/test-mcp-async-start.py b/scripts/test-mcp-async-start.pynew file mode 100644index 00000000..75ac8d19--- /dev/null+++ b/scripts/test-mcp-async-start.py@@ -0,0 +1,107 @@+#!/usr/bin/env python3+"""A slow MCP handshake never holds up an interactive start (ADR 0230).++An interactive graff (no --yolo) in a pty, one project MCP server that sleeps+before answering `initialize`, and a scripted model. After the consent prompt+is answered, the first message reaches the model while the handshake is still+running, and the request after it finishes names the server as connected.+"""+import json, os, select, sys, tempfile, time+from pathlib import Path++if sys.platform == "win32":+ print("skip no pty on Windows")+ sys.exit(0)+import pty # noqa: E402++sys.path.insert(0, str(Path(__file__).resolve().parent / "eval"))+from mock_model import ScriptedModel # noqa: E402++HANDSHAKE_S = 5.0+SERVER = r"""+import json, sys, time+for line in sys.stdin:+ req = json.loads(line)+ if "id" not in req:+ continue+ if req["method"] == "initialize":+ time.sleep(float(sys.argv[1]))+ result = {"protocolVersion": "2025-06-18", "capabilities": {"tools": {}}, "serverInfo": {"name": "slow", "version": "1"}}+ elif req["method"] == "tools/list":+ result = {"tools": [{"name": "slow_echo", "description": "Echo text.", "inputSchema": {"type": "object", "properties": {"text": {"type": "string"}}}}]}+ else:+ result = {}+ print(json.dumps({"jsonrpc": "2.0", "id": req["id"], "result": result}), flush=True)+"""+++class Timed(ScriptedModel):+ def __init__(self, *a, **k):+ super().__init__(*a, **k)+ self.arrivals = []++ def next_reply(self, body):+ self.arrivals.append(time.monotonic())+ return super().next_reply(body)+++def main():+ binary = str(Path(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff").resolve())+ model = Timed([{"text": "ok"}, {"text": "ok again"}])+ port = model.start(0)+ with tempfile.TemporaryDirectory(prefix="graff-mcp-async-") as tmp:+ root = Path(tmp)+ (root / "server.py").write_text(SERVER)+ work = root / "proj"+ work.mkdir()+ (work / ".mcp.json").write_text(json.dumps({"mcpServers": {"slow": {+ "command": sys.executable, "args": [str(root / "server.py"), str(HANDSHAKE_S)]}}}))+ # NO_COLOR (zig build sets it) turns off the interactive consent path.+ env = {k: v for k, v in os.environ.items() if not k.endswith("_API_KEY") and k != "NO_COLOR"}+ env.update(HOME=str(root), AI_GATEWAY_API_KEY="local", GRAFF_VERCEL_URL=f"http://127.0.0.1:{port}/v1/chat/completions",+ GRAFF_NO_PLUGINS="1", GRAFF_MCP_PROBE="0", GRAFF_FLEET="off", GRAFF_NO_SMOLIFY="1",+ GRAFF_NO_CODEDB_GUARD="1", GRAFF_NO_TELEMETRY="1", GRAFF_BEHAVIOR_TRACE="0",+ TERM="xterm-256color", COLUMNS="120", LINES="40")+ pid, fd = pty.fork()+ if pid == 0:+ os.chdir(work)+ os.execve(binary, [binary, "--model", "vercel"], env)+ out = bytearray()++ def read_until(pred, limit):+ end = time.monotonic() + limit+ while time.monotonic() < end and not pred():+ ready, _, _ = select.select([fd], [], [], 0.05)+ if ready:+ try:+ out.extend(os.read(fd, 65536))+ except OSError:+ break+ return pred()++ try:+ assert read_until(lambda: b"[y/N]" in out, 30), "no MCP consent prompt:\n" + out[-600:].decode("utf-8", "replace")+ consent = time.monotonic()+ os.write(fd, b"y\r")+ time.sleep(0.3)+ os.write(fd, b"say ok\r")+ assert read_until(lambda: len(model.arrivals) >= 1, HANDSHAKE_S + 20), "the first message never reached the model"+ first = model.arrivals[0] - consent+ assert first < 3.0, f"the first message waited {first:.1f}s for a {HANDSHAKE_S:.0f}s MCP handshake"+ print(f"PASS the first message reached the model {first:.2f}s after consent, during a {HANDSHAKE_S:.0f}s handshake", flush=True)++ time.sleep(max(0.0, HANDSHAKE_S + 1.0 - (time.monotonic() - consent)))+ os.write(fd, b"again\r")+ assert read_until(lambda: b"slow connected" in out, 20), "no notice that the slow server joined:\n" + out[-800:].decode("utf-8", "replace")+ print("PASS the request after the handshake names the server as connected", flush=True)+ finally:+ try:+ os.kill(pid, 9)+ os.waitpid(pid, 0)+ except (ProcessLookupError, ChildProcessError):+ pass+ model.stop()+++if __name__ == "__main__":+ main()diff --git a/src/acp_mcp_servers.zig b/src/acp_mcp_servers.zigindex 5a7a50f7..6082161e 100644--- a/src/acp_mcp_servers.zig+++ b/src/acp_mcp_servers.zig@@ -74,10 +74,11 @@ fn pairs(arena: Allocator, value: ?Value) !?std.json.ObjectMap {}/// How long session/new and session/load wait on the client's servers-/// (#1291). Local stdio servers handshake well inside it. One stuck on DNS or-/// an unreachable host no longer holds the reply for minutes: it keeps-/// connecting in the background and joins on a later model request.-pub const attach_budget_ms: u32 = 3000;+/// (#1291, ADR 0230). Long enough for a server restored from the tool cache,+/// so the first request's catalog already has it; never long enough to hold+/// the session for a real handshake, which keeps connecting in the background+/// and joins on a later model request.+pub const attach_budget_ms: u32 = 250;/// The live ACP session's hook (engine.Dispatch.mcp_servers): start what the/// client named, merge whatever connects within `attach_budget_ms`, thendiff --git a/src/agent_request.zig b/src/agent_request.zigindex 3352f687..c595f57e 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -102,6 +102,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {var tools_now = tools_in;const stale = self.toolsJson();const joined = if (self.registry) |reg| @import("mcp_pages.zig").beforeRequest(reg) else false; // joins deferred starts, re-lists changed servers+ if (self.registry) |reg| if (!self.sub) @import("mcp_connect_notice.zig").drain(reg, @import("engine_sink.zig").forAgent(self), self.io); // ADR 0230const preloaded = @import("mcp_preload.zig").namedServers(self); // ADR 0231: a named server's schemas ride this requestif (joined or preloaded or @import("additional_tools.zig").staleCatalog(self)) {self.invalidateRootTools();diff --git a/src/commands_misc.zig b/src/commands_misc.zigindex 05181e48..7def96e6 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -221,7 +221,11 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,try out.flush();return true;}- if (@import("mcp_boot.zig").joinPending(reg)) {+ // Plain /mcp lists without waiting on servers still connecting (ADR+ // 0230); add and trust change the registry, so they join them first.+ const boot = @import("mcp_boot.zig");+ const listing = !std.mem.startsWith(u8, arg, "add") and !std.mem.eql(u8, arg, "trust");+ if (if (listing) boot.joinReady(reg) else boot.joinPending(reg)) {root.invalidateRootTools();try root.ensureRootTools(root.provider.kind);}@@ -318,6 +322,8 @@ 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 out.flush();return true;diff --git a/src/companion_boot.zig b/src/companion_boot.zigindex b9519ac5..eb8a22a7 100644--- a/src/companion_boot.zig+++ b/src/companion_boot.zig@@ -1,11 +1,11 @@//! Companion auto-connect (codedb-pro / muonry), split out of session_start//! so the TUI boot path can name the hang and stay under 600 lines.//!-//! Interactive `--yolo` used to call `Registry.addServer` on the main thread-//! after the plugin receipt. The registry is still empty on a deferred MCP-//! boot (ADR 0035), so a PATH-installed companion looked "not connected" and-//! the handshake (stdio probe + 15s cap) sat in front of the first paint.-//! Queue it onto `pending_starts` instead; native tools run now.+//! An interactive session used to call `Registry.addServer` on the main+//! thread after the plugin receipt. The registry is still empty on a deferred+//! MCP boot (ADR 0035, 0230), so a PATH-installed companion looked "not+//! connected" and the handshake (stdio probe + 15s cap) sat in front of the+//! first paint. Queue it onto `pending_starts` instead; native tools run now.const std = @import("std");const Io = std.Io;@@ -19,9 +19,10 @@ const mcp_boot = @import("mcp_boot.zig");const mcp_schema_gate = @import("mcp_schema_gate.zig");const skills = @import("skills.zig");-/// Same gate as MCP `defer_join`: interactive yolo, including ACP, not CLI `--json` / `-p`.+/// Same gate as MCP `defer_join` (ADR 0230): every interactive session,+/// including ACP, not CLI `--json` / `-p`.pub fn deferCompanion(flags: args.Flags, json_mode: bool) bool {- return flags.oneshot_prompt == null and mcp_boot.deferMcpJoin(flags.effectiveYolo(), json_mode, mcp_boot.isAcp(flags.positionals.items));+ return flags.oneshot_prompt == null and mcp_boot.deferMcpJoin(json_mode, mcp_boot.isAcp(flags.positionals.items));}pub fn probeLicensed(gpa: Allocator, io: Io) bool {@@ -55,7 +56,7 @@ fn interactive(flags: args.Flags, json_mode: bool) bool {}/// Spawn the first PATH-installed companion that is not already connected-/// or queued. Interactive `--yolo` queues a background handshake (ADR 0035);+/// or queued. An interactive session queues a background handshake (ADR 0230);/// every other path still `addServer`s on this thread.pub fn connectCompanion(io: Io, arena: Allocator, registry: *mcp.Registry, flags: args.Flags, out: *Io.Writer, json_mode: bool, environ_map: anytype) !void {const sink = engine_sink.writerSink(out);@@ -84,11 +85,11 @@ pub fn connectCompanion(io: Io, arena: Allocator, registry: *mcp.Registry, flags}}-test "deferCompanion: interactive yolo only" {+test "deferCompanion: every interactive session, not -p or --json (ADR 0230)" {try std.testing.expect(deferCompanion(.{ .yolo_flag = true }, false));+ try std.testing.expect(deferCompanion(.{}, false)); // interactive without --yolotry std.testing.expect(!deferCompanion(.{ .yolo_flag = true }, true));try std.testing.expect(!deferCompanion(.{ .yolo_flag = true, .oneshot_prompt = "hi" }, false));- try std.testing.expect(!deferCompanion(.{}, false));try std.testing.expect(!deferCompanion(.{ .oneshot_prompt = "hi" }, false));}diff --git a/src/mcp.zig b/src/mcp.zigindex a20dbfa8..577eddfb 100644--- a/src/mcp.zig+++ b/src/mcp.zig@@ -119,6 +119,8 @@ pub const Registry = struct {pending_names: []const []const u8 = &.{},/// First model call already declined to wait on `pending_starts` (ADR 0035).first_request_join_skipped: bool = false,+ /// Background connects to report on the next root request (ADR 0230).+ connect_notices: @import("mcp_connect_notice.zig").Joined = .{},pub fn arena(self: *Registry) Allocator {return self.arena_state.allocator();@@ -253,7 +255,8 @@ pub const Registry = struct {present = true;break;};- if (!present) n += 1;+ // 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;}diff --git a/src/mcp_boot.zig b/src/mcp_boot.zigindex 1af17285..c80e1cb1 100644--- a/src/mcp_boot.zig+++ b/src/mcp_boot.zig@@ -7,11 +7,11 @@//! resulting tool list is identical to the serial build — only the wait is//! shorter: max(latency) instead of sum(latency).//!-//! `--yolo` (including `-p`) sets `defer_join`: tasks start immediately but-//! the first model call is not blocked. `joinBeforeRequest` merges each one-//! that has finished (ADR 0035, 0221). Lean `-p` with no project `.mcp.json`-//! skips imported global/plugin handshakes (ADR 0029 is the project file).-//! `joinPending` still blocks for `/mcp` and teardown.+//! Every session but `--json` sets `defer_join` (ADR 0230): tasks start at+//! once, nothing waits for them, and `joinBeforeRequest` merges each one that+//! has finished (ADR 0035, 0221). Lean `-p` with no project `.mcp.json` skips+//! imported global/plugin handshakes (ADR 0029 is the project file).+//! `joinPending` still blocks for `/mcp add|trust` and teardown.const std = @import("std");@@ -42,7 +42,7 @@ pub const PendingStart = struct {ready: ?*std.atomic.Value(bool) = null,await_entered: ?*Io.Event = null,- fn finished(self: *const PendingStart) bool {+ pub fn finished(self: *const PendingStart) bool {return if (self.ready) |flag| flag.load(.acquire) else true;}@@ -337,12 +337,12 @@ pub fn isAcp(positionals: []const []const u8) bool {return positionals.len > 0 and std.mem.eql(u8, positionals[0], "acp");}-/// ADR 0035: `--yolo` (including `-p`, which implies yolo) starts MCP in the-/// background. `--json` keeps a blocking connect so the protocol stream does-/// not race a late catalog merge. ACP shares stdout discipline, but its-/// interactive protocol must remain responsive while optional servers connect.-pub fn deferMcpJoin(yolo: bool, json_mode: bool, acp: bool) bool {- return yolo and (!json_mode or acp);+/// ADR 0230: every session connects MCP in the background, interactive+/// (after consent) as well as `--yolo`, `-p` and ACP, so no handshake holds up+/// the start. `--json` keeps a blocking connect so the protocol stream does+/// not race a late catalog merge; ACP shares its stdout but must stay live.+pub fn deferMcpJoin(json_mode: bool, acp: bool) bool {+ return !json_mode or acp;}/// Lean `-p` connects workspace `.mcp.json` (ADR 0029). It does not handshake@@ -352,14 +352,6 @@ pub fn oneshotSkipsImportedMcp(oneshot: bool, lean: bool, project_servers: usizereturn oneshot and lean and project_servers == 0;}-fn noteMcpDeferred(io: Io) void {- const sink = @import("engine_sink.zig").hostedSink() orelse return;- sink.emit(io, .{ .session_notice = .{- .text = "MCP still connecting — native tools this turn",- .tone = .dim,- } });-}-/// No model request waits out a deferred MCP handshake (ADR 0035), but each/// merges the ones already finished, the first included: a dormant server/// restored from cache that merged later would change the catalog mid-session@@ -367,11 +359,13 @@ fn noteMcpDeferred(io: Io) void {/// request 100 ms for it). `/mcp` and teardown may wait.pub fn joinBeforeRequest(reg: *Registry) bool {reg.mutex.lockUncancelable(reg.io);+ defer reg.mutex.unlock(reg.io);const decision = firstRequestJoin(reg.pending_starts.len, ®.first_request_join_skipped);+ // Queued for the root request to report (mcp_connect_notice.drain).+ if (decision != .none) reg.connect_notices.collect(reg); // named before the merge consumes themconst merged = if (decision != .none) joinReadyLocked(reg) else false;- const waiting = reg.pending_starts.len > 0;- reg.mutex.unlock(reg.io);- if (decision == .skip and waiting) noteMcpDeferred(reg.io);+ if (merged) reg.connect_notices.resolve(reg);+ if (decision == .skip and reg.pending_starts.len > 0) reg.connect_notices.still_connecting = true;return merged;}@@ -481,10 +475,9 @@ test "firstRequestJoin skips once, then joins" {try std.testing.expectEqual(.none, firstRequestJoin(0, &skipped));}-test "deferMcpJoin covers -p yolo and leaves --json blocking" {- try std.testing.expect(deferMcpJoin(true, false, false));- try std.testing.expect(!deferMcpJoin(true, true, false));- try std.testing.expect(!deferMcpJoin(false, false, false));+test "deferMcpJoin: every session but --json connects in the background (ADR 0230)" {+ try std.testing.expect(deferMcpJoin(false, false)); // interactive, --yolo, -p+ try std.testing.expect(!deferMcpJoin(true, false)); // --json}test "oneshotSkipsImportedMcp is lean -p with no project .mcp.json" {@@ -592,7 +585,6 @@ test "ACP stdout discipline does not block optional startup handshakes" {try std.testing.expect(isAcp(&.{"acp"}));try std.testing.expect(!isAcp(&.{}));try std.testing.expect(!isAcp(&.{ "repl", "acp" }));- try std.testing.expect(deferMcpJoin(true, true, isAcp(&.{"acp"})));- try std.testing.expect(!deferMcpJoin(false, true, true));- try std.testing.expect(!deferMcpJoin(true, true, isAcp(&.{"repl"})));+ try std.testing.expect(deferMcpJoin(true, isAcp(&.{"acp"})));+ try std.testing.expect(!deferMcpJoin(true, isAcp(&.{"repl"})));}diff --git a/src/mcp_connect_notice.zig b/src/mcp_connect_notice.zignew file mode 100644index 00000000..5c6bad3f--- /dev/null+++ b/src/mcp_connect_notice.zig@@ -0,0 +1,111 @@+//! What a background MCP connect tells the session (ADR 0230). Handshakes no+//! longer hold up the start, so the session says when the first request goes+//! out while servers are still connecting, and the request that merges a+//! finished one names it: connected with its tool count, or did not connect.+//! The registry queues them under its lock; the root agent's request drains+//! them through the agent's own sink (`drain`), which is what a TUI shows.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const mcp = @import("mcp.zig");+const EngineSink = @import("engine_sink.zig").EngineSink;++/// Notices for the next root request, read under the registry lock.+pub const Joined = struct {+ names: [8][]const u8 = undefined,+ tools: [8]?usize = undefined, // null: did not connect+ n: usize = 0,+ /// The first request went out while servers were still connecting.+ still_connecting: bool = false,++ /// Record the finished, not yet merged starts. Caller holds reg.mutex.+ pub fn collect(self: *Joined, reg: *const mcp.Registry) void {+ for (reg.pending_starts, 0..) |*task, i| {+ if (self.n == self.names.len) return;+ if (task.ready == null or !task.finished() or i >= reg.pending_names.len) continue;+ self.names[self.n] = reg.pending_names[i];+ self.tools[self.n] = null;+ self.n += 1;+ }+ }++ /// After the merge: which of them is a live server now, with its tools.+ pub fn resolve(self: *Joined, reg: *mcp.Registry) void {+ for (self.names[0..self.n], 0..) |name, k| {+ for (reg.servers, 0..) |server, i| if (std.mem.eql(u8, server.name, name)) {+ self.tools[k] = reg.toolCount(i);+ break;+ };+ }+ }++ fn emitTo(self: *const Joined, sink: EngineSink, io: Io) void {+ if (self.still_connecting) notice(sink, io, "MCP still connecting — native tools this turn");+ for (self.names[0..self.n], self.tools[0..self.n]) |name, tools| {+ var buf: [192]u8 = undefined;+ notice(sink, io, (if (tools) |count|+ std.fmt.bufPrint(&buf, "mcp: {s} connected ({d} tool(s))", .{ name, count })+ else+ std.fmt.bufPrint(&buf, "mcp: {s} did not connect", .{name})) catch continue);+ }+ }+};++fn notice(sink: EngineSink, io: Io, text: []const u8) void {+ sink.emit(io, .{ .session_notice = .{ .text = text, .tone = .dim } });+}++/// Emit and clear the queued notices. Called by the root agent's request.+pub fn drain(reg: *mcp.Registry, sink: EngineSink, io: Io) void {+ reg.mutex.lockUncancelable(reg.io);+ const queued = reg.connect_notices;+ reg.connect_notices = .{};+ reg.mutex.unlock(reg.io);+ queued.emitTo(sink, io);+}++/// Servers whose start is still running, for `/mcp`. Call after `joinReady`+/// has merged the finished ones.+pub fn connecting(reg: *mcp.Registry, arena: Allocator) []const []const u8 {+ reg.mutex.lockUncancelable(reg.io);+ defer reg.mutex.unlock(reg.io);+ var names: std.ArrayList([]const u8) = .empty;+ for (reg.pending_starts, 0..) |task, i| {+ if (task.ready == null or i >= reg.pending_names.len or reg.pending_names[i].len == 0) continue;+ names.append(arena, reg.pending_names[i]) catch break;+ }+ return names.items;+}++test "a finished start is named once it merges; an unfinished one stays connecting" {+ const io = std.testing.io;+ var reg = mcp.Registry.empty(std.testing.allocator, io);+ defer reg.deinit();+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const boot = @import("mcp_boot.zig");+ const done = try reg.gpa.create(std.atomic.Value(bool));+ done.* = .init(true);+ const busy = try reg.gpa.create(std.atomic.Value(bool));+ busy.* = .init(false);+ reg.pending_starts = try reg.gpa.alloc(boot.PendingStart, 2);+ @memset(reg.pending_starts, .{});+ reg.pending_starts[0].ready = done;+ reg.pending_starts[1].ready = busy;+ reg.pending_names = try reg.arena().dupe([]const u8, &.{ "fails", "slow" });++ var joined: Joined = .{};+ joined.collect(®);+ try std.testing.expectEqual(@as(usize, 1), joined.n);+ try std.testing.expectEqualStrings("fails", joined.names[0]);+ _ = boot.joinReady(®);+ joined.resolve(®);+ try std.testing.expect(joined.tools[0] == null); // its start produced no server+ const still = connecting(®, arena);+ try std.testing.expectEqual(@as(usize, 1), still.len);+ try std.testing.expectEqualStrings("slow", still[0]);+ busy.store(true, .release);+ _ = boot.joinPending(®);+}diff --git a/src/session_start.zig b/src/session_start.zigindex 0f36b7b7..805959b7 100644--- a/src/session_start.zig+++ b/src/session_start.zig@@ -497,22 +497,12 @@ pub fn initRegistryConsent(io: Io, gpa: Allocator, arena: Allocator, out: *Io.Wrsink.emit(io, dimNotice(try std.fmt.allocPrint(arena, "ignoring ~/" ++ mcp_config.unsupported_rel_path ++ ": unsupported path — use ~/" ++ mcp_config.global_rel_path ++ " (global) or {s} (project)", .{mcp_config_path})));}const mcp_count = mcp_cli.countMcpServers(merged);- const defer_join = mcp_boot.deferMcpJoin(flags.effectiveYolo(), json_mode, mcp_boot.isAcp(flags.positionals.items));+ const defer_join = mcp_boot.deferMcpJoin(json_mode, mcp_boot.isAcp(flags.positionals.items)); // ADR 0230const skip_imported = mcp_boot.oneshotSkipsImportedMcp(flags.oneshot_prompt != null,leanMode(flags.effectiveLean(), environ_map),merged.project.count(),);- // Name the next phase the way `plugins:` already does. Without this, a- // handshake that still runs on this thread looks like a hung boot.- if (!json_mode and flags.oneshot_prompt == null and mcp_count > 0) {- const mcp_line = if (defer_join)- try std.fmt.allocPrint(arena, "mcp: {d} server(s) in background", .{mcp_count})- else- try std.fmt.allocPrint(arena, "mcp: connecting {d} server(s)...", .{mcp_count});- sink.emit(io, dimNotice(mcp_line));- }- const mcp_t0 = Io.Timestamp.now(io, .awake);// Lean folds schemas (deferAllRuntime); it does not skip connect.// --yolo / -p still connect so `.mcp.json` works on the default one-shot// (ADR 0029). Interactive without --yolo still asks.@@ -524,6 +514,17 @@ pub fn initRegistryConsent(io: Io, gpa: Allocator, arena: Allocator, out: *Io.Wrconst ans = in.takeDelimiter('\n') catch null;connect_mcp = ans != null and ans.?.len > 0 and (ans.?[0] == 'y' or ans.?[0] == 'Y');}+ // Name the next phase the way `plugins:` already does, once the servers+ // are actually connecting. Without this, a handshake that still runs on+ // this thread looks like a hung boot.+ if (!json_mode and flags.oneshot_prompt == null and mcp_count > 0 and connect_mcp and !skip_imported) {+ const mcp_line = if (defer_join)+ try std.fmt.allocPrint(arena, "mcp: connecting {d} server(s) in the background", .{mcp_count})+ else+ try std.fmt.allocPrint(arena, "mcp: connecting {d} server(s)...", .{mcp_count});+ sink.emit(io, dimNotice(mcp_line));+ }+ const mcp_t0 = Io.Timestamp.now(io, .awake);var registry: mcp.Registry = if (connect_mcp and !skip_imported) ((mcp.Registry.init(gpa, io, mcp_config_path, global_path, home, json_mode or flags.oneshot_prompt != null or environ_map.get("GRAFF_REPL_DEBUG") != null, environ_map, defer_join) catch |err| inner: {sink.emit(io, .{ .session_notice = .{ .text = try std.fmt.allocPrint(arena, "[mcp] init failed: {t} — continuing without MCP", .{err}) } });if (telemetry.g_telem) |t| t.errorEvent("mcp", @errorName(err));diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 45585fbd..c159d75e 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -334,6 +334,7 @@ test {_ = @import("mcp_preload.zig"); // ADR 0231_ = @import("write_file.zig"); // ADR 0231_ = @import("piped_paste.zig"); // ADR 0231+ _ = @import("mcp_connect_notice.zig"); // ADR 0230_ = @import("oauth_callback.zig");_ = @import("cache_key_tests.zig"); // ADR 0223: moved off http_headers.zig (600-line cap)_ = @import("mcp_shapes_tests.zig"); // ADR 0225: moved off mcp_shapes.zig (600-line cap)