Skip to content

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

Python

ACP session/new stops waiting on unreachable MCP servers

justrachb9be6817a844
diff --git a/src/acp_mcp_servers.zig b/src/acp_mcp_servers.zig
index a429033e..5a7a50f7 100644
--- a/src/acp_mcp_servers.zig
+++ b/src/acp_mcp_servers.zig
@@ -73,22 +73,47 @@ fn pairs(arena: Allocator, value: ?Value) !?std.json.ObjectMap {
return if (map.count() == 0) null else map;
}
-/// The live ACP session's hook (engine.Dispatch.mcp_servers): connect what
-/// the client named, then re-render the root's tool catalog so the model sees
-/// the new tools on its next request, as `/mcp add` does.
+/// 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;
+
+/// The live ACP session's hook (engine.Dispatch.mcp_servers): start what the
+/// client named, merge whatever connects within `attach_budget_ms`, then
+/// re-render the root's tool catalog so the model sees the new tools on its
+/// next request, as `/mcp add` does.
pub fn attach(ctx: *anyopaque, arena: Allocator, params: ?Value) anyerror!void {
const live: *@import("acp_live_turn.zig").LiveTurn = @ptrCast(@alignCast(ctx));
const root = live.root;
const reg = root.registry orelse return;
const specs = try parse(arena, params);
if (specs.len == 0) return;
- if (connect(reg, specs, null) == 0) return;
+ if (!joinWithin(reg, arena, specs, attach_budget_ms)) return;
root.invalidateRootTools();
@import("prompt_cache_hud.zig").noteBust(.mcp);
try root.ensureRootTools(root.provider.kind);
root.rebaseContextMeter();
}
+/// Queue every server's handshake, wait at most `budget_ms` for them, and
+/// merge the ones that finished. A server the thread pool cannot take is
+/// connected inline instead of dropped. True when anything joined.
+pub fn joinWithin(reg: *mcp.Registry, arena: Allocator, specs: []const Spec, budget_ms: u32) bool {
+ const mcp_boot = @import("mcp_boot.zig");
+ var queued: std.ArrayList([]const u8) = .empty;
+ var direct: std.ArrayList(Spec) = .empty;
+ for (specs) |spec| {
+ const list_ok = if (mcp_boot.queueConfig(reg, spec.name, spec.cfg)) queued.append(arena, spec.name) else direct.append(arena, spec);
+ list_ok catch return false;
+ }
+ const before = reg.servers.len;
+ _ = connect(reg, direct.items, null);
+ // Also consumes failed handshakes, which add nothing.
+ if (queued.items.len > 0) _ = mcp_boot.joinNamedWithin(reg, queued.items, budget_ms);
+ return reg.servers.len > before;
+}
+
/// Connect each server the registry does not already have by name, in order.
/// Returns how many joined; one that fails to start is reported on `notice`
/// and skipped, so a bad entry never costs the session. Run between turns.
@@ -179,6 +204,46 @@ test "connect: a server the registry already has by name is kept, not respawned"
reg.servers = &.{}; // not the registry's to free
}
+fn stdioSpec(a: Allocator, name: []const u8, command: []const u8, args: []const []const u8) !Spec {
+ var cfg: std.json.ObjectMap = .empty;
+ try cfg.put(a, "command", .{ .string = command });
+ var argv = std.json.Array.init(a);
+ for (args) |arg| try argv.append(.{ .string = arg });
+ try cfg.put(a, "args", .{ .array = argv });
+ return .{ .name = name, .cfg = cfg };
+}
+
+test "joinWithin (#1291): a server that fails fast ends the wait early" {
+ const io = std.testing.io;
+ var reg = mcp.Registry.empty(std.testing.allocator, io);
+ defer reg.deinit();
+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer state.deinit();
+ const a = state.allocator();
+ const specs = [_]Spec{try stdioSpec(a, "gone", "/nonexistent/graff-mcp-1291", &.{})};
+ const t0 = std.Io.Timestamp.now(io, .awake);
+ try std.testing.expect(!joinWithin(&reg, a, &specs, 10_000));
+ try std.testing.expect(t0.untilNow(io, .awake).toMilliseconds() < 5_000);
+ try std.testing.expectEqual(@as(usize, 0), reg.servers.len);
+}
+
+test "joinWithin (#1291): a stalled handshake returns at the budget and stays queued" {
+ if (@import("builtin").os.tag == .windows) return error.SkipZigTest; // needs /bin/sh
+ const io = std.testing.io;
+ var reg = mcp.Registry.empty(std.testing.allocator, io);
+ defer reg.deinit(); // joins the handshake once `sleep` exits
+ reg.stdio_probe = false;
+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer state.deinit();
+ const a = state.allocator();
+ // Starts fine and never answers the initialize request.
+ const specs = [_]Spec{try stdioSpec(a, "stalled", "/bin/sh", &.{ "-c", "sleep 2" })};
+ const t0 = std.Io.Timestamp.now(io, .awake);
+ try std.testing.expect(!joinWithin(&reg, a, &specs, 100));
+ try std.testing.expect(t0.untilNow(io, .awake).toMilliseconds() < 1_500);
+ try std.testing.expect(@import("mcp_boot.zig").alreadyStarting(&reg, "stalled"));
+}
+
test "handleLine: initialize advertises http MCP, session/new hands the hook its mcpServers first" {
const engine = @import("acp_engine.zig");
const Fixture = struct {
diff --git a/src/mcp_boot.zig b/src/mcp_boot.zig
index 5146617a..92fa310b 100644
--- a/src/mcp_boot.zig
+++ b/src/mcp_boot.zig
@@ -191,23 +191,60 @@ pub fn queueStdio(reg: *Registry, name: []const u8, command: []const u8, args: [
defer reg.mutex.unlock(reg.io);
if (alreadyStartingLocked(reg, name)) return;
const a = reg.arena();
- const n = a.dupe(u8, name) catch return;
var cfg: std.json.ObjectMap = .empty;
cfg.put(a, "command", .{ .string = a.dupe(u8, command) catch return }) catch return;
var argv = std.json.Array.init(a);
for (args) |arg| argv.append(.{ .string = a.dupe(u8, arg) catch return }) catch return;
cfg.put(a, "args", .{ .array = argv }) catch return;
+ _ = queueLocked(reg, name, cfg);
+}
+
+/// Queue any configured server (stdio or http) the same way (#1291). `cfg` is
+/// copied into the registry arena: the task reads it after the caller's
+/// request arena is gone. False when nothing was queued (no thread for the
+/// task, or out of memory); a server already live or queued counts as queued.
+pub fn queueConfig(reg: *Registry, name: []const u8, cfg: std.json.ObjectMap) bool {
+ reg.mutex.lockUncancelable(reg.io);
+ defer reg.mutex.unlock(reg.io);
+ if (alreadyStartingLocked(reg, name)) return true;
+ const owned = cloneValue(reg.arena(), .{ .object = cfg }) catch return false;
+ return queueLocked(reg, name, owned.object);
+}
+
+fn cloneValue(a: Allocator, v: std.json.Value) Allocator.Error!std.json.Value {
+ return switch (v) {
+ .string => |s| .{ .string = try a.dupe(u8, s) },
+ .number_string => |s| .{ .number_string = try a.dupe(u8, s) },
+ .array => |arr| blk: {
+ var out = std.json.Array.init(a);
+ try out.ensureTotalCapacity(arr.items.len);
+ for (arr.items) |item| out.appendAssumeCapacity(try cloneValue(a, item));
+ break :blk .{ .array = out };
+ },
+ .object => |obj| blk: {
+ var out: std.json.ObjectMap = .empty;
+ var it = obj.iterator();
+ while (it.next()) |e| try out.put(a, try a.dupe(u8, e.key_ptr.*), try cloneValue(a, e.value_ptr.*));
+ break :blk .{ .object = out };
+ },
+ else => v,
+ };
+}
+
+fn queueLocked(reg: *Registry, name: []const u8, cfg: std.json.ObjectMap) bool {
+ const a = reg.arena();
+ const n = a.dupe(u8, name) catch return false;
// Reserve both paired arrays before spawning: allocation failure must not
// abandon a task that still borrows registry configuration.
const old = reg.pending_starts;
- const next = reg.gpa.alloc(PendingStart, old.len + 1) catch return;
+ const next = reg.gpa.alloc(PendingStart, old.len + 1) catch return false;
const names = a.alloc([]const u8, old.len + 1) catch {
reg.gpa.free(next);
- return;
+ return false;
};
const flag = reg.gpa.create(std.atomic.Value(bool)) catch {
reg.gpa.free(next);
- return;
+ return false;
};
flag.* = .init(false);
var ctx = startCtx(reg);
@@ -215,7 +252,7 @@ pub fn queueStdio(reg: *Registry, name: []const u8, command: []const u8, args: [
const fut = reg.io.concurrent(startServerTask, .{ ctx, n, cfg }) catch {
reg.gpa.destroy(flag);
reg.gpa.free(next);
- return;
+ return false;
};
@memcpy(next[0..old.len], old);
next[old.len] = .{ .future = fut, .ready = flag };
@@ -224,6 +261,27 @@ pub fn queueStdio(reg: *Registry, name: []const u8, command: []const u8, args: [
if (old.len > 0) reg.gpa.free(old);
reg.pending_starts = next;
reg.pending_names = names;
+ return true;
+}
+
+/// Wait at most `budget_ms` for the named queued handshakes, then merge every
+/// finished one (#1291). A server that is still connecting stays queued and
+/// joins on a later request, like the rest of a deferred boot.
+pub fn joinNamedWithin(reg: *Registry, names: []const []const u8, budget_ms: u32) bool {
+ var waited: u32 = 0;
+ while (waited < budget_ms and anyNamedPending(reg, names)) : (waited += 20)
+ reg.io.sleep(.fromMilliseconds(20), .awake) catch break;
+ return joinReady(reg);
+}
+
+fn anyNamedPending(reg: *Registry, names: []const []const u8) bool {
+ reg.mutex.lockUncancelable(reg.io);
+ defer reg.mutex.unlock(reg.io);
+ for (reg.pending_starts, 0..) |*task, i| {
+ if (task.ready == null or task.finished() or i >= reg.pending_names.len) continue;
+ for (names) |n| if (std.mem.eql(u8, n, reg.pending_names[i])) return true;
+ }
+ return false;
}
fn mergeOutcomes(reg: *Registry, futures: []PendingStart) void {