Skip to content

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

Python

mcp: report a closed service consistently after its tools are withdrawn (#1523)

justrachc16cd7c86fe7
diff --git a/src/mcp.zig b/src/mcp.zig
index 6a0fb0fc..24e6cdf2 100644
--- a/src/mcp.zig
+++ b/src/mcp.zig
@@ -58,6 +58,8 @@ pub const Registry = struct {
mutex: Io.Mutex = .init,
servers: []*Server = &.{},
tools: []Tool = &.{},
+ /// Tools withdrawn after their connection closed (#1523, mcp_call.zig).
+ withdrawn: []const @import("mcp_call.zig").Withdrawn = &.{},
/// Transport failure withdrew tools; owner thread rebuilds its next catalog.
catalog_dirty: std.atomic.Value(bool) = .init(false),
/// Startup connection/failure lines are developer diagnostics, not normal REPL output.
diff --git a/src/mcp_call.zig b/src/mcp_call.zig
index 9be82fa3..198514be 100644
--- a/src/mcp_call.zig
+++ b/src/mcp_call.zig
@@ -23,13 +23,20 @@ const McpCall = struct {
pub const CallResult = struct { text: []u8, is_error: bool };
+/// A tool whose server connection closed or failed this session (#1523).
+/// Remembered so a later call or schema load names the closed service
+/// instead of reporting a tool that was never registered.
+pub const Withdrawn = struct { qualified_name: []const u8, server: []const u8, reason: []const u8 };
+
+const restart_hint = "Inspect /mcp, restart the service and this session, then reload its tool schemas.";
+
/// The registry lock is held throughout. Never replay a possibly executed call.
pub 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: {
- try withdrawServer(reg, qualified);
+ 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. Inspect /mcp, restart the service and this session, then reload its tool schemas.", .{@errorName(err)}),
+ .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)}),
.is_error = true,
};
},
@@ -37,21 +44,65 @@ pub fn call(reg: *Registry, out_alloc: Allocator, qualified: []const u8, input:
};
}
-fn withdrawServer(reg: *Registry, qualified: []const u8) !void {
+fn withdrawServer(reg: *Registry, qualified: []const u8, reason: []const u8) !void {
const server_index = for (reg.tools) |tool| {
if (std.mem.eql(u8, tool.qualified_name, qualified)) break tool.server_index;
} else return;
var available: std.ArrayList(@import("mcp.zig").Tool) = .empty;
- for (reg.tools) |tool| if (tool.server_index != server_index) try available.append(reg.arena(), tool);
+ var withdrawn: std.ArrayList(Withdrawn) = .empty;
+ try withdrawn.appendSlice(reg.arena(), reg.withdrawn);
+ for (reg.tools) |tool| {
+ if (tool.server_index != server_index) {
+ try available.append(reg.arena(), tool);
+ } else try withdrawn.append(reg.arena(), .{ .qualified_name = tool.qualified_name, .server = tool.serverName(), .reason = reason });
+ }
// Replace the slice instead of mutating snapshots held by in-flight callers.
reg.tools = try available.toOwnedSlice(reg.arena());
+ reg.withdrawn = try withdrawn.toOwnedSlice(reg.arena());
reg.catalog_dirty.store(true, .release);
}
+fn withdrawnTool(reg: *const Registry, qualified: []const u8) ?Withdrawn {
+ for (reg.withdrawn) |w| if (std.mem.eql(u8, w.qualified_name, qualified)) return w;
+ return null;
+}
+
+fn isLive(reg: *const Registry, qualified: []const u8) bool {
+ for (reg.tools) |t| if (std.mem.eql(u8, t.qualified_name, qualified)) return true;
+ return false;
+}
+
+/// #1523: `load_tool_schemas` for a tool or server whose connection closed
+/// this session answers with the unavailable service, not an enabled schema
+/// or an unknown name. Null when nothing requested was withdrawn.
+pub fn unavailableLoad(reg: *Registry, a: Allocator, input: Value) ?[]const u8 {
+ reg.mutex.lockUncancelable(reg.io);
+ defer reg.mutex.unlock(reg.io);
+ const hit: Withdrawn = found: {
+ if (@import("tools.zig").strField(input, "server")) |want| {
+ const live = for (reg.tools) |t| {
+ if (std.mem.eql(u8, t.serverName(), want)) break true;
+ } else false;
+ if (!live) for (reg.withdrawn) |w| if (std.mem.eql(u8, w.server, want)) break :found w;
+ }
+ if (input == .object) if (input.object.get("tools")) |list| if (list == .array) {
+ for (list.array.items) |item| {
+ if (item != .string or isLive(reg, item.string)) continue;
+ if (withdrawnTool(reg, item.string)) |w| break :found w;
+ }
+ };
+ return null;
+ };
+ return std.fmt.allocPrint(a, "MCP service {s} is unavailable: its connection closed or failed earlier in this session ({s}) and its tools were withdrawn, so nothing was loaded and {s} cannot be called. " ++ restart_hint, .{ hit.server, hit.reason, hit.qualified_name }) catch null;
+}
+
fn invoke(reg: *Registry, out_alloc: Allocator, qualified: []const u8, input: Value, context: ?@import("mcp_turn_context.zig").Snapshot) !CallResult {
const tool = for (reg.tools) |t| {
if (std.mem.eql(u8, t.qualified_name, qualified)) break t;
} else {
+ // #1523: a sibling call in the same batch can close the connection
+ // first; this call then reports the same closed service.
+ if (withdrawnTool(reg, qualified)) |w| return .{ .text = try std.fmt.allocPrint(out_alloc, "MCP service connection closed or failed earlier in this session ({s}). Its tools have been withdrawn from the catalog; this call was not sent. " ++ restart_hint, .{w.reason}), .is_error = true };
reg.catalog_dirty.store(true, .release);
return .{ .text = try out_alloc.dupe(u8, "MCP tool is not registered in the current connection. Its loaded schema may be stale. The next catalog will reflect the current registration. Inspect /mcp, restart the session to reconnect the configured service, then reload its schema before retrying."), .is_error = true };
};
diff --git a/src/mcp_rpc_tests.zig b/src/mcp_rpc_tests.zig
index 881b2c89..a0437883 100644
--- a/src/mcp_rpc_tests.zig
+++ b/src/mcp_rpc_tests.zig
@@ -138,6 +138,43 @@ test "MCP recovery during MRTR withdraws tools without replay" {
try std.testing.expect(reg.catalog_dirty.load(.acquire));
}
+test "MCP recovery #1523: after a sibling call closes the connection, later calls and loads name the closed service" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ var reg = Registry.empty(std.testing.allocator, std.testing.io);
+ defer reg.deinit();
+ const spawned = try spawnReplying(reg.arena(), reg.io, "read line; exit 0");
+ try fixtureRegistry(&reg, spawned.server);
+ const a = reg.arena();
+ var both: std.ArrayList(@import("mcp.zig").Tool) = .empty;
+ try both.appendSlice(a, reg.tools);
+ var search = reg.tools[0];
+ search.original_name = "search";
+ search.qualified_name = "mcp__fixture__search";
+ try both.append(a, search);
+ reg.tools = both.items;
+ const call_mod = @import("mcp_call.zig");
+ try std.testing.expect(call_mod.unavailableLoad(&reg, a, try parse(a, "{\"tools\":[\"mcp__fixture__search\"]}")) == null);
+
+ const first = try reg.call(std.testing.allocator, "mcp__fixture__whoami", try parse(a, "{}"));
+ defer std.testing.allocator.free(first.text);
+ try std.testing.expect(std.mem.indexOf(u8, first.text, "McpClosed") != null);
+ // The sibling in the same batch reports the same closed service, not an
+ // unregistered tool with a stale schema.
+ const sibling = try reg.call(std.testing.allocator, "mcp__fixture__search", try parse(a, "{}"));
+ defer std.testing.allocator.free(sibling.text);
+ try std.testing.expect(sibling.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, sibling.text, "closed or failed earlier in this session (McpClosed)") != null);
+ try std.testing.expect(std.mem.indexOf(u8, sibling.text, "not registered") == null);
+ try std.testing.expectEqual(@as(i64, 2), spawned.server.next_id); // nothing more was sent
+
+ // Loading its schema now names the unavailable service instead of enabling it.
+ const by_tool = call_mod.unavailableLoad(&reg, a, try parse(a, "{\"tools\":[\"mcp__fixture__search\"]}")) orelse return error.TestUnexpectedResult;
+ try std.testing.expect(std.mem.indexOf(u8, by_tool, "MCP service fixture is unavailable") != null);
+ try std.testing.expect(std.mem.indexOf(u8, by_tool, "McpClosed") != null);
+ try std.testing.expect(call_mod.unavailableLoad(&reg, a, try parse(a, "{\"server\":\"fixture\"}")) != null);
+ try std.testing.expect(call_mod.unavailableLoad(&reg, a, try parse(a, "{\"tools\":[\"mcp__other__x\"]}")) == null);
+}
+
fn parse(a: std.mem.Allocator, json: []const u8) !Value {
return std.json.parseFromSliceLeaky(Value, a, json, .{ .allocate = .alloc_always });
}
diff --git a/src/mcp_schema_gate.zig b/src/mcp_schema_gate.zig
index 1dd1a9f0..12aa3dc8 100644
--- a/src/mcp_schema_gate.zig
+++ b/src/mcp_schema_gate.zig
@@ -577,6 +577,7 @@ fn listing(arena: Allocator, all: []const mcp.Tool, unknown: []const []const u8)
pub fn handleLoad(agent: anytype, input: Value) ExecResult {
if (agent.sub) return .{ .text = "load_tool_schemas is root-only; a subagent has no MCP registry of its own", .is_error = true };
const reg = agent.registry orelse return .{ .text = "no MCP servers are connected, so there are no schemas to load", .is_error = true };
+ if (@import("mcp_call.zig").unavailableLoad(reg, agent.arena, input)) |text| return .{ .text = text, .is_error = true }; // #1523
const catalog = reg.snapshotTools(agent.arena) catch return .{ .text = "load_tool_schemas failed to render the requested schemas", .is_error = true };
const r = loadInto(agent.arena, catalog, input) catch
return .{ .text = "load_tool_schemas failed to render the requested schemas", .is_error = true };