graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(mcp): zero-stub deferral + tool search — the codex tool_search pattern
Rach Pradhana14bdf2940b2
diff --git a/src/agent_tests.zig b/src/agent_tests.zigindex 3dd57eb7..f103777c 100644--- a/src/agent_tests.zig+++ b/src/agent_tests.zig@@ -68,12 +68,16 @@ pub fn lazyRootTools(comptime Agent: type) !void {agent.tools_responses = "";try agent.ensureRootTools(.responses);- try std.testing.expect(std.mem.indexOf(u8, agent.tools_responses, "mcp__bench__search") != null);+ // Deferred tools ship no catalog entry (#476): the qualified name is+ // absent and discovery rides the meta tool's server listing instead.+ try std.testing.expect(std.mem.indexOf(u8, agent.tools_responses, "mcp__bench__search") == null);+ try std.testing.expect(std.mem.indexOf(u8, agent.tools_responses, "bench (search)") != null);try std.testing.expectEqual(@as(usize, 0), agent.tools_openai.len);try std.testing.expectEqual(@as(usize, 0), agent.tools_anthropic.len);agent.invalidateRootTools();try agent.ensureRootTools(.anthropic);- try std.testing.expect(std.mem.indexOf(u8, agent.tools_anthropic, "mcp__bench__search") != null);+ try std.testing.expect(std.mem.indexOf(u8, agent.tools_anthropic, "mcp__bench__search") == null);+ try std.testing.expect(std.mem.indexOf(u8, agent.tools_anthropic, "bench (search)") != null);try std.testing.expectEqual(@as(usize, 0), agent.tools_responses.len);}diff --git a/src/mcp_schema_gate.zig b/src/mcp_schema_gate.zigindex bbf28457..4f3bc757 100644--- a/src/mcp_schema_gate.zig+++ b/src/mcp_schema_gate.zig@@ -83,9 +83,9 @@ pub const env_eager = "GRAFF_MCP_EAGER"; // comma-separated server names; "*" pi/// entry and no import cycle. The description is spliced into a raw JSON/// string, so it must stay free of characters needing JSON escapes.pub const tool_name = "load_tool_schemas";-pub const tool_desc = "Load the full JSON input schemas for deferred tools and enable them for the rest of this session. MCP servers with large schemas — and folded native power tools (workflow, imagegen, learn_candidate, eval, clock_sleep) — are registered up front by name and a one-line description only, so that thousands of tokens of JSON Schema stay out of every request. A tool whose schema has not been loaded CANNOT be called: calling it returns an error telling you to load it first. Pass tools with exact names (mcp__server__tool for MCP, or a folded native name like workflow), or pass server to load every deferred tool on one MCP server. Call it with no arguments to list what is currently deferred. Loading is permanent for this session and free to repeat, because the schemas are cached.";+pub const tool_desc = "Load the full JSON input schemas for deferred tools and enable them for the rest of this session. Deferred MCP tools — and folded native power tools (workflow, imagegen, learn_candidate, eval, clock_sleep) — ship no schemas up front, so that thousands of tokens of JSON Schema stay out of every request; any deferred servers and their tool names are listed at the end of this description. A tool whose schema has not been loaded CANNOT be called: calling it returns an error telling you to load it first. Pass tools with exact names (mcp__server__tool for MCP, or a folded native name like workflow), pass server to load every deferred tool on one MCP server, or pass query with keywords to search deferred tools by name and description (the top 8 matches load). Call it with no arguments to list what is currently deferred. Loading is permanent for this session and free to repeat, because the schemas are cached.";pub const tool_schema =- \\{"type": "object", "properties": {"tools": {"type": "array", "items": {"type": "string"}, "description": "Exact qualified MCP tool names to load, e.g. mcp__deepwiki__ask_question"}, "server": {"type": "string", "description": "Load every deferred tool on this MCP server instead of naming them one by one"}}}+ \\{"type": "object", "properties": {"tools": {"type": "array", "items": {"type": "string"}, "description": "Exact qualified MCP tool names to load, e.g. mcp__deepwiki__ask_question"}, "server": {"type": "string", "description": "Load every deferred tool on this MCP server instead of naming them one by one"}, "query": {"type": "string", "description": "Search deferred tools by keyword (matches name and description, loads the top 8 matches) — use when you know what you need but not the exact tool name"}}};/// How this session decides eager vs deferred. Set once by `configure`.@@ -347,6 +347,16 @@ pub fn loadInto(arena: Allocator, all: []const mcp.Tool, input: Value) !Loaded {if (found) |i| try wanted.append(arena, i) else try missing.append(arena, item.string);}};+ // codex tool_search pattern: keyword discovery when the exact name is not+ // known — top matches join `wanted` and load exactly like named tools.+ if (tools_mod.strField(input, "query")) |q| {+ const matched = try matchQuery(arena, all, q);+ if (matched.len == 0) {+ const rest = try listing(arena, all, &.{});+ return .{ .text = try std.fmt.allocPrint(arena, "no deferred tool matched query '{s}'. {s}", .{ q, rest }), .is_error = true };+ }+ for (matched) |i| try wanted.append(arena, i);+ }if (missing.items.len > 0) return .{ .text = try listing(arena, all, missing.items), .is_error = true };if (wanted.items.len == 0) return .{ .text = try listing(arena, all, &.{}), .is_error = false };@@ -373,6 +383,103 @@ pub fn loadInto(arena: Allocator, all: []const mcp.Tool, input: Value) !Loaded {return .{ .text = head.writer.buffered(), .loaded = fresh };}+/// The short tool name within its server: mcp__codedbpro__read -> read.+fn shortName(qualified: []const u8) []const u8 {+ if (!std.mem.startsWith(u8, qualified, "mcp__")) return qualified;+ const rest = qualified[5..];+ const sep = std.mem.indexOf(u8, rest, "__") orelse return qualified;+ return rest[sep + 2 ..];+}++/// Case-insensitive substring search (std.ascii has no indexOfIgnoreCase in+/// this toolchain): windowed eqlIgnoreCase, fine at description sizes.+fn containsIgnoreCase(haystack: []const u8, needle: []const u8) bool {+ if (needle.len > haystack.len) return false;+ var i: usize = 0;+ while (i + needle.len <= haystack.len) : (i += 1)+ if (std.ascii.eqlIgnoreCase(haystack[i .. i + needle.len], needle)) return true;+ return false;+}++/// Keyword search over deferred tools (the load tool's `query` arm): score+/// each deferred tool by how many query tokens appear, case-insensitively, in+/// its qualified name or description; return the top 8, best first. A token+/// that matches nothing simply does not score — there is no fuzzier fallback,+/// because the no-match path returns the full deferred listing anyway.+fn matchQuery(arena: Allocator, all: []const mcp.Tool, query: []const u8) ![]usize {+ const top_k = 8;+ var best: [top_k]struct { score: usize, idx: usize } = undefined;+ var n_best: usize = 0;+ for (all, 0..) |t, i| {+ if (!isDeferred(all, t)) continue;+ var score: usize = 0;+ var tok = std.mem.tokenizeAny(u8, query, " \t,;:/_-");+ while (tok.next()) |w| {+ if (w.len < 2) continue;+ if (containsIgnoreCase(t.qualified_name, w) or containsIgnoreCase(t.description, w)) score += 1;+ }+ if (score == 0) continue;+ if (n_best < top_k) {+ best[n_best] = .{ .score = score, .idx = i };+ n_best += 1;+ } else {+ // Replace the weakest entry when this one beats it.+ var weakest: usize = 0;+ for (best[0..n_best], 0..) |b, k| if (b.score < best[weakest].score) {+ weakest = k;+ };+ if (score <= best[weakest].score) continue;+ best[weakest] = .{ .score = score, .idx = i };+ }+ }+ const out = try arena.alloc(usize, n_best);+ // Selection-sort descending so the strongest match loads first.+ for (out, 0..) |*slot, k| {+ var top: usize = 0;+ for (best[0..n_best], 0..) |b, j| if (b.score > best[top].score) {+ top = j;+ };+ slot.* = best[top].idx;+ best[top].score = 0;+ _ = k;+ }+ return out;+}++/// The load tool's live catalog description: the static base plus, while+/// anything is deferred, a compact source listing (server: short tool names).+/// Deferred tools ship NO per-tool catalog entries of their own — this+/// listing is how the model learns what exists (codex's tool_search source+/// listing), and `query` covers discovery beyond it (#476).+pub fn descWithListing(arena: Allocator, all: []const mcp.Tool) ![]const u8 {+ if (!anyDeferred(all)) return tool_desc;+ var servers: std.ArrayList([]const u8) = .empty;+ for (all) |t| {+ if (!isDeferred(all, t)) continue;+ const sv = serverOf(t.qualified_name);+ const seen = for (servers.items) |s| {+ if (std.mem.eql(u8, s, sv)) break true;+ } else false;+ if (!seen) try servers.append(arena, sv);+ }+ var aw: Io.Writer.Allocating = .init(arena);+ try aw.writer.writeAll(tool_desc);+ try aw.writer.writeAll(" Deferred now:");+ for (servers.items) |sv| {+ try aw.writer.print(" {s} (", .{sv});+ var first = true;+ for (all) |t| {+ if (!isDeferred(all, t)) continue;+ if (!std.mem.eql(u8, serverOf(t.qualified_name), sv)) continue;+ if (!first) try aw.writer.writeAll(", ");+ try aw.writer.writeAll(shortName(t.qualified_name));+ first = false;+ }+ try aw.writer.writeAll(");");+ }+ return aw.writer.buffered();+}+/// What is deferred right now, names + short descriptions. Doubles as the/// unknown-name error, which must say what DOES exist.fn listing(arena: Allocator, all: []const mcp.Tool, unknown: []const []const u8) ![]const u8 {diff --git a/src/mcp_schema_gate_tests.zig b/src/mcp_schema_gate_tests.zigindex f16b68c3..6036880c 100644--- a/src/mcp_schema_gate_tests.zig+++ b/src/mcp_schema_gate_tests.zig@@ -259,6 +259,29 @@ test "one tool named twice in a call is emitted once, not duplicated" {try testing.expectEqual(@as(usize, 2), gate.rendersForTest());}+test "query mode: keywords load the matching deferred tools, a miss lists what exists" {+ withDefaults();+ defer withDefaults();+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const fat = try fixture(arena, "fat", 3, 2000);++ const hit = try std.json.parseFromSliceLeaky(Value, arena, "{\"query\":\"first line\"}", .{ .allocate = .alloc_always });+ const loaded = try gate.loadInto(arena, fat, hit);+ try testing.expect(!loaded.is_error);+ try testing.expect(loaded.loaded > 0);+ for (fat) |t| try testing.expect(!gate.isDeferred(fat, t)); // all matched + enabled+ try testing.expect(std.mem.indexOf(u8, loaded.text, "input_schema") != null); // full schemas ride the result++ gate.reset();+ const miss = try std.json.parseFromSliceLeaky(Value, arena, "{\"query\":\"zzqqx\"}", .{ .allocate = .alloc_always });+ const none = try gate.loadInto(arena, fat, miss);+ try testing.expect(none.is_error);+ try testing.expect(std.mem.startsWith(u8, none.text, "no deferred tool matched query 'zzqqx'."));+ try testing.expect(std.mem.indexOf(u8, none.text, "mcp__fat__t0") != null); // the listing follows+}+test "an unknown name errors and lists what is actually deferred; no args just lists" {withDefaults();defer withDefaults();diff --git a/src/schema.zig b/src/schema.zigindex f821cc7a..b84775f8 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -302,16 +302,15 @@ pub fn renderRootTools(if (mcp_schema_gate.hiddenSpec(t.name, mcp_tools) and !native_fold.anyFolded()) continue; // #416: load_tool_schemas hides only with nothing deferred OR foldedif (native_fold.servePlaceholder(t.name)) // native fold layer 1: name + one-liner + placeholder until load_tool_schemas unfoldstry writeToolEntry(&s, kind, t.name, mcp_schema_gate.shortDesc(t.desc), .{ .raw = mcp_schema_gate.placeholder_schema })+ else if (std.mem.eql(u8, t.name, mcp_schema_gate.tool_name))+ try writeToolEntry(&s, kind, t.name, try mcp_schema_gate.descWithListing(out, mcp_tools), .{ .raw = t.schema })elsetry writeToolEntry(&s, kind, t.name, t.desc, .{ .raw = t.schema });}- // #416 layer 1: a deferred tool is still REGISTERED (name + a one-line- // description, so the model knows it exists and can ask for it), but its- // schema is a placeholder until load_tool_schemas enables it. exec.zig is- // layer 2, and refuses a call that arrives before that.- for (mcp_tools) |m| if (mcp_schema_gate.isDeferred(mcp_tools, m))- try writeToolEntry(&s, kind, m.qualified_name, mcp_schema_gate.shortDesc(m.description), .{ .raw = mcp_schema_gate.placeholder_schema })- else+ // Deferred tools ship no catalog entries at all (codex tool_search+ // pattern): the meta tool's description lists what exists, exec.zig's+ // layer-2 refusal still guards a call that arrives before its load.+ for (mcp_tools) |m| if (!mcp_schema_gate.isDeferred(mcp_tools, m))try writeToolEntry(&s, kind, m.qualified_name, m.description, .{ .value = m.input_schema });try s.endArray();return aw.toOwnedSlice();diff --git a/src/tool_schema_tests.zig b/src/tool_schema_tests.zigindex 00f219a7..8697fa0c 100644--- a/src/tool_schema_tests.zig+++ b/src/tool_schema_tests.zig@@ -232,6 +232,8 @@ test "#416: deferring a real MCP server's schemas cuts the served catalog in hal}const tools = try realServerTools(arena);try testing.expectEqual(@as(usize, 13), tools.len);+ // Include the meta tool spec so its deferred-listing description renders.+ const meta_spec = [_]schema.ToolSpec{.{ .name = gate.tool_name, .desc = gate.tool_desc, .schema = gate.tool_schema }};// Pre-#416 behavior, still reachable with the escape-hatch pin.gate.g_policy = .{ .eager = &.{"*"} };@@ -241,7 +243,7 @@ test "#416: deferring a real MCP server's schemas cuts the served catalog in hal// over even the old 4 KiB budget, so it deferred under that policy too.gate.g_policy = .{};try testing.expect(gate.serverCost(tools, "smolify") > gate.default_budget);- const deferred = try schema.renderRootTools(arena, .anthropic, &.{}, tools);+ const deferred = try schema.renderRootTools(arena, .anthropic, &meta_spec, tools);// The measurement this issue exists for: the MCP half of the catalog on// its own (no built-in specs), so the number is the saving and nothing@@ -251,11 +253,14 @@ test "#416: deferring a real MCP server's schemas cuts the served catalog in hal// that grows a little does not turn the guard red.try testing.expect(deferred.len * 2 < eager.len);- // Every tool is still REGISTERED — deferral hides schemas, not tools.- for (tools) |t| try testing.expect(std.mem.indexOf(u8, deferred, t.qualified_name) != null);- // ...with a one-line description, and no schema body. These property names- // appear in the real schemas and in no description, so finding one would- // mean a schema leaked through.+ // Deferred tools ship NO catalog entries of their own (codex tool_search+ // pattern, #476): their qualified names appear nowhere in the catalog,+ // and discovery rides the meta tool's description listing (short names).+ for (tools) |t| try testing.expect(std.mem.indexOf(u8, deferred, t.qualified_name) == null);+ try testing.expect(std.mem.indexOf(u8, deferred, gate.tool_name) != null);+ try testing.expect(std.mem.indexOf(u8, deferred, "search_docs") != null); // short name in the listing+ // ...and no schema body leaks. These property names appear in the real+ // schemas and in no description, so finding one would mean a leak.for ([_][]const u8{ "pathHints", "maxTokens", "lineCount" }) |only_in_schema| {try testing.expect(std.mem.indexOf(u8, eager, only_in_schema) != null);try testing.expect(std.mem.indexOf(u8, deferred, only_in_schema) == null);@@ -286,7 +291,7 @@ test "#416: deferring a real MCP server's schemas cuts the served catalog in halconst loaded = try gate.loadInto(arena, tools, req);try testing.expect(!loaded.is_error);try testing.expectEqual(@as(usize, 1), loaded.loaded);- const after = try schema.renderRootTools(arena, .anthropic, &.{}, tools);+ const after = try schema.renderRootTools(arena, .anthropic, &meta_spec, tools);try testing.expect(std.mem.indexOf(u8, after, "lineCount") != null); // read_public_source's own schema is backtry testing.expect(std.mem.indexOf(u8, after, "pathHints") == null); // build_docs_context's is nottry testing.expect(after.len > deferred.len and after.len < eager.len);