Skip to content

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

Python

feat(mcp): auto-load deferred MCP schemas on a confident call

Rach Pradhan645f3cbcfba4
diff --git a/scripts/test-no-local-tools.py b/scripts/test-no-local-tools.py
index 94b9bd61..fe24481b 100644
--- a/scripts/test-no-local-tools.py
+++ b/scripts/test-no-local-tools.py
@@ -26,6 +26,7 @@ import argparse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
+import re
from pathlib import Path
import subprocess
import tempfile
@@ -146,6 +147,24 @@ def tool_names(request: RecordedRequest) -> list[str]:
return [t.get("name") for t in tools] if isinstance(tools, list) else []
+def catalog_names(request: RecordedRequest) -> list[str]:
+ """Wire tools plus the deferred catalog: zero-stub deferral (a14bdf2) and
+ the native fold moved names out of the wire tools array into
+ load_tool_schemas' description — 'server (a, b)' MCP groups and the static
+ folded-native prose ('native tools (workflow, ...)')."""
+ names = list(tool_names(request))
+ tools = request.body.get("tools")
+ if isinstance(tools, list):
+ for tool in tools:
+ if isinstance(tool, dict) and tool.get("name") == "load_tool_schemas":
+ for server, group in re.findall(r"([a-z0-9_]+) \(([^)]*)\)", tool.get("description", "")):
+ for n in group.split(","):
+ n = n.strip()
+ if n and re.fullmatch(r"[a-z0-9_]+", n): # prose parens carry spaces
+ names.append(n if server == "tools" else f"mcp__{server}__{n}")
+ return names
+
+
def mcp_tool_name(names: list[str]) -> str:
remote = [n for n in names if isinstance(n, str) and n.startswith("mcp__")]
if len(remote) != 1:
@@ -162,7 +181,7 @@ def script(request: RecordedRequest) -> list[dict]:
names = tool_names(request)
seen = json.dumps(request.body.get("input"), separators=(",", ":"))
tag = f"resp_{request.ordinal}"
- if "subagent" not in names: # a child: its catalog is base tools only
+ if "load_tool_schemas" not in names: # a child: the root-only meta tool is absent
if CHILD_BASH_CALL not in seen:
return response_events(
call_item("bash", CHILD_BASH_CALL, {"command": BASH_COMMAND}), tag
@@ -186,7 +205,7 @@ def script(request: RecordedRequest) -> list[dict]:
)
if MCP_CALL not in seen:
return response_events(
- call_item(mcp_tool_name(names), MCP_CALL, {"command": "ls /"}), tag
+ call_item(mcp_tool_name(catalog_names(request)), MCP_CALL, {"command": "ls /"}), tag
)
return response_events(message_item(FINAL_TEXT, f"msg_{tag}"), tag)
@@ -277,8 +296,8 @@ def tool_results(events: list[dict], name: str) -> list[dict]:
def assert_gated(requests: list[RecordedRequest], events: list[dict]) -> None:
- root = [r for r in requests if "subagent" in tool_names(r)]
- child = [r for r in requests if "subagent" not in tool_names(r)]
+ root = [r for r in requests if "load_tool_schemas" in tool_names(r)]
+ child = [r for r in requests if "load_tool_schemas" not in tool_names(r)]
if not root or not child:
raise AssertionError(
f"expected both root and child requests, saw {len(root)}/{len(child)}"
@@ -286,10 +305,11 @@ def assert_gated(requests: list[RecordedRequest], events: list[dict]) -> None:
# Layer 1, root: nothing local advertised; webfetch, orchestration and the
# MCP-sourced sandbox tool all survive.
- names = tool_names(root[0])
- leaked = [n for n in names if n in GATED_TOOLS]
+ wire = tool_names(root[0])
+ leaked = [n for n in wire if n in GATED_TOOLS]
if leaked:
raise AssertionError(f"root catalog still advertises {leaked!r}")
+ names = catalog_names(root[0])
for expected in ("webfetch", "subagent", "workflow", "todo_write"):
if expected not in names:
raise AssertionError(f"root catalog lost {expected}: {names!r}")
diff --git a/src/exec.zig b/src/exec.zig
index 589868bc..26860f4e 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -235,13 +235,11 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
.text = try gpa.dupe(u8, "MCP not available in this context"),
.is_error = true,
};
- // #416 layer 2. Deliberately HERE, inside execToolInner: this runs
- // downstream of agent_tool_gate.gateTool, so the consent prompt is
- // still reached in exactly the cases (and the order) it was before —
- // deferral can only subtract a call consent already allowed, never
- // add one, and never short-circuits an approval check.
- if (mcp_schema_gate.blocked(reg.tools, call.name))
- return .{ .text = try mcp_schema_gate.refusalText(gpa, call.name), .is_error = true };
+ // #416 layer 2, auto-load era: a confident call to a deferred tool
+ // loads its schema inline and runs — the refusal round trip is gone
+ // (same user direction as the native fold). Still downstream of
+ // agent_tool_gate.gateTool: consent is already settled.
+ mcp_schema_gate.autoLoad(gpa, reg.tools, call.name);
const r = reg.call(gpa, call.name, call.input) catch |err| {
codedbpro_report.onFailure(ctx, call.name, @errorName(err));
return failure(gpa, err);
diff --git a/src/mcp_schema_gate.zig b/src/mcp_schema_gate.zig
index a58b0bc2..82bebec4 100644
--- a/src/mcp_schema_gate.zig
+++ b/src/mcp_schema_gate.zig
@@ -304,6 +304,20 @@ pub fn shortDesc(desc: []const u8) []const u8 {
// --- layer 2: refuse a call whose schema was never loaded -------------------
+/// exec.zig's MCP dispatch calls this where it used to refuse: a confident
+/// call to a deferred tool renders + publishes its schema and proceeds (user
+/// direction — same rule as the native fold's markIfFolded). The catalog's
+/// zero-stub listing is unchanged; the call itself was already provider-legal.
+pub fn autoLoad(arena: Allocator, all: []const mcp.Tool, qualified: []const u8) void {
+ if (!blocked(all, qualified)) return;
+ for (all) |t| {
+ if (std.mem.eql(u8, t.qualified_name, qualified)) {
+ _ = enable(arena, t) catch {};
+ return;
+ }
+ }
+}
+
/// Whether calling `qualified` right now must be refused. False for an eager
/// tool, for one already loaded, and for a name the registry does not know
/// (mcp.Registry.call owns that error, unchanged).
@@ -315,19 +329,6 @@ pub fn blocked(all: []const mcp.Tool, qualified: []const u8) bool {
return false;
}
-/// The refusal a blocked call gets: never a bare "unknown tool", always the
-/// exact next action.
-pub fn refusalText(gpa: Allocator, qualified: []const u8) ![]u8 {
- return std.fmt.allocPrint(
- gpa,
- "{s} is registered but its schema is not loaded, so it cannot be called yet. " ++
- "Call {s} with {{\"tools\": [\"{s}\"]}} first — that returns the full input schema and enables the tool " ++
- "for the rest of this session — then call {s} again with arguments matching that schema. " ++
- "This is a context-cost deferral only; it does not change approvals or trust.",
- .{ qualified, tool_name, qualified, qualified },
- );
-}
-
// --- the load tool ---------------------------------------------------------
pub const Loaded = struct {
diff --git a/src/mcp_schema_gate_tests.zig b/src/mcp_schema_gate_tests.zig
index 963834de..c39ede6d 100644
--- a/src/mcp_schema_gate_tests.zig
+++ b/src/mcp_schema_gate_tests.zig
@@ -191,14 +191,8 @@ test "load_tool_schemas returns the full schemas and enables the tools" {
const arena = arena_state.allocator();
const fat = try fixture(arena, "fat", 4, 2000);
- // Before: every tool blocked, with an actionable refusal.
+ // Before: every tool blocked (the refusal itself is gone — auto-load).
try testing.expect(gate.blocked(fat, "mcp__fat__t0"));
- const refusal = try gate.refusalText(testing.allocator, "mcp__fat__t0");
- defer testing.allocator.free(refusal);
- try testing.expect(std.mem.indexOf(u8, refusal, gate.tool_name) != null);
- try testing.expect(std.mem.indexOf(u8, refusal, "mcp__fat__t0") != null);
- try testing.expect(std.mem.indexOf(u8, refusal, "does not change approvals") != null);
- try testing.expect(std.mem.indexOf(u8, refusal, "unknown") == null); // never a bare unknown-tool
const req = try std.json.parseFromSliceLeaky(Value, arena, "{\"tools\":[\"mcp__fat__t0\"]}", .{ .allocate = .alloc_always });
const r = try gate.loadInto(arena, fat, req);