graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(mcp): defer large MCP tool schemas until asked for (#416)
Rach Pradhanab2524b7d9de
diff --git a/sdk/py/harness_sdk.py b/sdk/py/harness_sdk.pyindex b2c91d4c..89c9c239 100644--- a/sdk/py/harness_sdk.py+++ b/sdk/py/harness_sdk.py@@ -14,7 +14,7 @@ import urllib.requestfrom typing import Iterator, OptionalMODELS = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-build", "k3", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mlx-community/Qwen3.6-27B-OptiQ-4bit"]-TOOLS = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "imagegen"]+TOOLS = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "imagegen"]PROVIDERS = ["anthropic", "codegraff", "deepseek", "openai", "minimax", "xiaomi", "kimi", "moonshot", "xai", "zai", "fugu", "fireworks", "mlx", "lmstudio", "codex"]diff --git a/sdk/ts/harness.ts b/sdk/ts/harness.tsindex 386da965..66be86f1 100644--- a/sdk/ts/harness.ts+++ b/sdk/ts/harness.ts@@ -11,7 +11,7 @@ import { createInterface } from "node:readline";export const HARNESS_VERSION = "0.10";export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "k3" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | (string & {});-export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "imagegen";+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "imagegen";export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kimi" | "moonshot" | "xai" | "zai" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";/** Events streamed by `harness --json` (one JSON object per stdout line), each@@ -432,4 +432,4 @@ export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<Event> {}export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-build", "k3", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mlx-community/Qwen3.6-27B-OptiQ-4bit"];-export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "imagegen"];+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "imagegen"];diff --git a/sdk/ts/remote.ts b/sdk/ts/remote.tsindex e2a20552..12afe344 100644--- a/sdk/ts/remote.ts+++ b/sdk/ts/remote.ts@@ -10,7 +10,7 @@export const HARNESS_VERSION = "0.10";export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "k3" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | (string & {});-export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "imagegen";+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "imagegen";export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kimi" | "moonshot" | "xai" | "zai" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";/** Events streamed by the bridge (same `--json` contract as the stdio SDK).@@ -323,4 +323,4 @@ export async function* runAgentRemote(opts: RunAgentRemoteOptions): AsyncGenerat}export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-build", "k3", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mlx-community/Qwen3.6-27B-OptiQ-4bit"];-export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "imagegen"];+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "imagegen"];diff --git a/src/agent_tools.zig b/src/agent_tools.zigindex aa7f07a0..292376f9 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -49,6 +49,7 @@ const execTool = exec.execTool;const brief_diversity = @import("brief_diversity.zig"); // #382: N sibling spawns in one batch are a fleetconst playbook_glue = @import("playbook_glue.zig"); // #381: the note_constraint meta arm+const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: the load_tool_schemas meta armconst util = @import("util.zig"); // #225: unixMs, for the clock_sleep interrupted-elapsed measurementconst protocol_seq = @import("protocol_seq.zig"); // #330: monotonic `seq` on every --json event@@ -368,6 +369,7 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {return .{ .text = try clockSleepSuccessText(self.arena, parsed.ms, parsed.clamped), .is_error = false };}if (std.mem.eql(u8, call.name, "note_constraint")) return playbook_glue.noteConstraint(self, call.input); // #381: append-only, and it re-composes the root's own prompt+ if (std.mem.eql(u8, call.name, mcp_schema_gate.tool_name)) return mcp_schema_gate.handleLoad(self, call.input); // #416: inline, so the loaded-schema set has exactly one writerif (std.mem.eql(u8, call.name, "ask_user")) return self.askUser(call);// todo_readreturn .{ .text = self.renderTodos(goal_state.currentEpoch(self.goal)), .is_error = false };diff --git a/src/commands_misc.zig b/src/commands_misc.zigindex 06db0ab1..930d0534 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -31,6 +31,7 @@ const style = &ansi.style;const goal_state = @import("goal_state.zig");const goal_flow = @import("goal_flow.zig");const jobs = @import("jobs.zig");+const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: which listed MCP tools are still schema-deferredconst subagent = @import("subagent.zig"); // #276 P0-3: g_agent_jobs, for /jobsconst pricing = @import("pricing.zig");@@ -326,7 +327,9 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,const probe_note = if (srv.probe_fallback) |reason| reason.note() else "";try out.print(" {s}{s}{s} (mcp {s}, {d} tool(s)){s}{s}{s}\n", .{ style.accent, srv.name, style.reset, srv.protocol_version, reg.toolCount(i), style.dim, probe_note, style.reset });}- for (reg.tools) |t| try out.print(" {s}{s}{s}\n", .{ style.dim, t.qualified_name, style.reset });+ // #416: a deferred tool is registered but carries no schema yet, so+ // say so — otherwise the difference is invisible from here.+ 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");}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 });diff --git a/src/exec.zig b/src/exec.zigindex 2e59fabb..8fc3e61a 100644--- a/src/exec.zig+++ b/src/exec.zig@@ -58,6 +58,7 @@ const jobKill = jobs.jobKill;const shellArgv = jobs.shellArgv;const skills = @import("skills.zig");const skill_docs = @import("skill_docs.zig");+const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: refuse an MCP tool whose schema was never loadedconst read_file = @import("read_file.zig");// #337: edit_file's verified write path, plus the file-tool helpers that moved// out with it (this file is at the 600-line ceiling).@@ -186,6 +187,13 @@ 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 };const r = try reg.call(gpa, call.name, call.input);return .{ .text = r.text, .is_error = r.is_error };}diff --git a/src/mcp_schema_gate.zig b/src/mcp_schema_gate.zignew file mode 100644index 00000000..12d34012--- /dev/null+++ b/src/mcp_schema_gate.zig@@ -0,0 +1,426 @@+//! #416: two-phase MCP tool exposure — names and a one-line description up+//! front, the full JSON Schema on demand.+//!+//! mcp.zig used to put every tool's whole `inputSchema` into the root catalog+//! at connect time, so a session paid for every schema of every configured+//! server on every request. With #345 (a user-level `~/.codegraff/mcp.json`+//! whose servers follow you into every checkout) that is a standing tax: one+//! companion server measured at +2,568 input tokens per call, whether or not+//! the model ever touched it. Measured against the bundled 13-tool Smolify+//! manifest (tool_schema_tests.zig): the catalog served for that one server+//! drops from 10,505 to 3,696 bytes, ~1,700 tokens off EVERY request.+//!+//! The deferred half of the catalog therefore carries `name` + a shortened+//! description + a placeholder schema, and `load_tool_schemas` hands back the+//! real schemas and ENABLES those tools for the rest of the session. A call to+//! a tool whose schema was never loaded is refused with instructions rather+//! than run (exec.zig, layer 2 — see `blocked`).+//!+//! Two invariants this module must never break:+//!+//! - **Consent is untouched.** Deferral is about context cost, not permission.+//! Nothing here reads or writes approvals, and the layer-2 refusal lives+//! INSIDE execToolInner, i.e. downstream of agent_tool_gate.gateTool: the+//! consent prompt is reached in exactly the cases it was reached before, in+//! the same order, and deferral can only ever subtract a call that consent+//! already allowed — never add one it did not.+//! - **Small servers behave exactly as they do today.** The default is+//! size-based: a server whose tools cost at most `default_budget` bytes of+//! description + schema stays EAGER, because the load round trip re-emits+//! those same bytes and would be a wash. Only servers above the threshold+//! are deferred, plus whatever the user pins either way.+//!+//! Session state (which schemas have been loaded) is a lock-free append-only+//! list: the only writer is the orchestrator thread — `load_tool_schemas` is a+//! meta tool, handled inline — and pool threads only ever read it, always+//! after the spawn that publishes the write.++const std = @import("std");+const Io = std.Io;+const Value = std.json.Value;+const Allocator = std.mem.Allocator;++const mcp = @import("mcp.zig");+const mcp_config = @import("mcp_config.zig");+const tools_mod = @import("tools.zig");+const util = @import("util.zig");++const ExecResult = tools_mod.ExecResult;++/// Per-server budget, in bytes of description + serialized schema, under which+/// a server is served eagerly. 4 KiB is roughly 1,000 tokens: below that the+/// `load_tool_schemas` round trip (a tool call plus a result that re-emits the+/// very schemas it saved) costs about what deferral saves, so the indirection+/// only pays above it. It also means every small server keeps working byte for+/// byte as it did before #416.+pub const default_budget: usize = 4096;++/// How much of an MCP tool's description survives into the deferred listing.+/// Enough for a model to tell tools apart and decide what to load; a real MCP+/// description runs to paragraphs (codedbpro's `read` is over 400 bytes).+pub const desc_cap: usize = 180;++/// What a deferred tool advertises as its schema. Valid, permissive, and+/// self-describing, so a model that ignores the tool description still gets+/// told what to do — and `serde.defaultRootObjectType` has nothing to fix up.+/// Kept terse on purpose: it is repeated once per deferred tool, so every byte+/// here is paid N times against the savings it exists to buy. The full+/// protocol lives once, in `tool_desc`.+pub const placeholder_schema =+ \\{"type": "object", "description": "Deferred - load_tool_schemas first."}+;++pub const env_enabled = "GRAFF_MCP_LAZY_SCHEMAS"; // "0" turns deferral off entirely+pub const env_budget = "GRAFF_MCP_SCHEMA_BUDGET"; // per-server byte threshold; 0 defers everything+pub const env_eager = "GRAFF_MCP_EAGER"; // comma-separated server names; "*" pins them all++/// The `load_tool_schemas` tool's name/description/schema, kept here as plain+/// strings (the skill_docs.zig pattern) so schema.zig's catalog needs one+/// 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 MCP tools and enable them for the rest of this session. MCP servers with large schemas 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 qualified names (mcp__server__tool), or pass server to load every deferred tool on one 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_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"}}}+;++/// How this session decides eager vs deferred. Set once by `configure`.+pub const Policy = struct {+ enabled: bool = true,+ budget: usize = default_budget,+ /// Server names always served eagerly. A single "*" entry pins every+ /// server, which is the escape hatch back to pre-#416 behavior.+ eager: []const []const u8 = &.{},+};++pub var g_policy: Policy = .{};++// --- session state: which schemas have been loaded -------------------------++const Node = struct {+ name: []const u8,+ /// The rendered `{"name":…,"description":…,"input_schema":…}` block, kept+ /// so a repeated load is a pointer copy rather than a re-serialization.+ /// This is the per-session schema cache the issue asks for.+ rendered: []const u8,+ next: ?*Node,+};++var g_head: std.atomic.Value(?*Node) = .init(null);+/// Test seam: how many schemas this session has actually serialized. A second+/// `load_tool_schemas` for the same tool must not move it.+var g_renders: usize = 0;++/// Drop every loaded schema. A new session, and every test that touches the+/// gate.+pub fn reset() void {+ g_head.store(null, .release);+ g_renders = 0;+}++pub fn rendersForTest() usize {+ return g_renders;+}++fn find(name: []const u8) ?*Node {+ var cur = g_head.load(.acquire);+ while (cur) |node| : (cur = node.next) {+ if (std.mem.eql(u8, node.name, name)) return node;+ }+ return null;+}++pub fn isLoaded(name: []const u8) bool {+ return find(name) != null;+}++/// Publish one loaded schema. Single-writer (the orchestrator thread); the+/// release store is what makes the new node visible to a pool thread that+/// later acquires the head.+fn publish(arena: Allocator, name: []const u8, rendered: []const u8) !*Node {+ const node = try arena.create(Node);+ // The name is COPIED, not aliased: `tool.qualified_name` belongs to the+ // registry's arena, and this list has to outlive any registry rebuild.+ node.* = .{ .name = try arena.dupe(u8, name), .rendered = rendered, .next = g_head.load(.acquire) };+ g_head.store(node, .release);+ return node;+}++// --- policy ----------------------------------------------------------------++/// Resolve the session policy from the environment and the merged MCP config.+/// A server object may carry `"eager": true` to pin itself; unknown keys are+/// ignored by `mcp.Registry.startServer`, so the flag costs that path nothing.+/// Best-effort: an unparseable knob falls back to the default rather than+/// failing a session over a typo.+pub fn configure(arena: Allocator, merged: mcp_config.Merged, environ_map: anytype) void {+ var policy: Policy = .{};+ if (environ_map.get(env_enabled)) |v| policy.enabled = !std.mem.eql(u8, std.mem.trim(u8, v, " \t"), "0");+ if (environ_map.get(env_budget)) |v| {+ policy.budget = std.fmt.parseInt(usize, std.mem.trim(u8, v, " \t"), 10) catch default_budget;+ }+ var eager: std.ArrayList([]const u8) = .empty;+ if (environ_map.get(env_eager)) |v| {+ var it = std.mem.tokenizeScalar(u8, v, ',');+ while (it.next()) |raw| {+ const name = std.mem.trim(u8, raw, " \t");+ if (name.len > 0) eager.append(arena, arena.dupe(u8, name) catch continue) catch {};+ }+ }+ var it = merged.servers.iterator();+ while (it.next()) |entry| {+ if (entry.value_ptr.* != .object) continue;+ const flag = entry.value_ptr.object.get("eager") orelse continue;+ if (flag != .bool or !flag.bool) continue;+ eager.append(arena, arena.dupe(u8, entry.key_ptr.*) catch continue) catch {};+ }+ policy.eager = eager.items;+ g_policy = policy;+}++/// The server half of `mcp__<server>__<tool>`; "" for a name that is not one.+pub fn serverOf(qualified: []const u8) []const u8 {+ const prefix = "mcp__";+ if (!std.mem.startsWith(u8, qualified, prefix)) return "";+ const rest = qualified[prefix.len..];+ const sep = std.mem.indexOf(u8, rest, "__") orelse return rest;+ return rest[0..sep];+}++pub fn pinnedEager(server: []const u8) bool {+ for (g_policy.eager) |p| {+ if (std.mem.eql(u8, p, "*")) return true;+ if (std.mem.eql(u8, p, server)) return true;+ }+ return false;+}++/// What one server costs the catalog: every one of its tools' descriptions+/// plus its serialized schema. Descriptions count because they are half the+/// bill on a verbose server, and deferral shortens them too.+pub fn serverCost(all: []const mcp.Tool, server: []const u8) usize {+ var total: usize = 0;+ for (all) |t| {+ if (!std.mem.eql(u8, serverOf(t.qualified_name), server)) continue;+ total += t.description.len + jsonBytes(t.input_schema, 0);+ }+ return total;+}++/// Whether this tool is advertised with a placeholder schema instead of its+/// own. Pure: the same inputs always give the same answer, and nothing here+/// consults approvals.+pub fn isDeferred(all: []const mcp.Tool, tool: mcp.Tool) bool {+ if (!g_policy.enabled) return false;+ if (isLoaded(tool.qualified_name)) return false;+ const server = serverOf(tool.qualified_name);+ if (pinnedEager(server)) return false;+ return serverCost(all, server) > g_policy.budget;+}++pub fn anyDeferred(all: []const mcp.Tool) bool {+ for (all) |t| if (isDeferred(all, t)) return true;+ return false;+}++/// Whether a built-in spec should be dropped from the rendered root catalog.+/// `load_tool_schemas` is only useful while something is deferred, so a+/// session with no MCP (or with everything eager) is never charged for it —+/// the same "advertise only what can be used" rule #330/#352 apply.+pub fn hiddenSpec(name: []const u8, all: []const mcp.Tool) bool {+ return std.mem.eql(u8, name, tool_name) and !anyDeferred(all);+}++/// The description a deferred tool advertises: the first line (or paragraph)+/// of the real one, capped on a codepoint boundary.+pub fn shortDesc(desc: []const u8) []const u8 {+ var line = desc;+ if (std.mem.indexOfScalar(u8, line, '\n')) |nl| line = line[0..nl];+ line = std.mem.trim(u8, line, " \t\r");+ return util.utf8Prefix(line, desc_cap);+}++// --- layer 2: refuse a call whose schema was never loaded -------------------++/// 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).+pub fn blocked(all: []const mcp.Tool, qualified: []const u8) bool {+ for (all) |t| {+ if (!std.mem.eql(u8, t.qualified_name, qualified)) continue;+ return isDeferred(all, t);+ }+ 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 {+ text: []const u8,+ is_error: bool = false,+ /// How many tools this call newly enabled (0 for a listing or an error).+ loaded: usize = 0,+};++/// Serialize one tool as `{"name":…,"description":…,"input_schema":…}`.+fn renderEntry(arena: Allocator, tool: mcp.Tool) ![]const u8 {+ var aw: Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.beginObject();+ try s.objectField("name");+ try s.write(tool.qualified_name);+ try s.objectField("description");+ try s.write(tool.description);+ try s.objectField("input_schema");+ try s.write(tool.input_schema);+ try s.endObject();+ g_renders += 1;+ return aw.writer.buffered();+}++/// Render, or reuse this session's cached render, and mark the tool enabled.+fn enable(arena: Allocator, tool: mcp.Tool) ![]const u8 {+ if (find(tool.qualified_name)) |node| return node.rendered;+ const rendered = try renderEntry(arena, tool);+ const node = try publish(arena, tool.qualified_name, rendered);+ return node.rendered;+}++/// The pure core of the `load_tool_schemas` tool: everything except touching+/// the Agent. `input` is the model-supplied argument object.+pub fn loadInto(arena: Allocator, all: []const mcp.Tool, input: Value) !Loaded {+ var wanted: std.ArrayList(usize) = .empty;+ var missing: std.ArrayList([]const u8) = .empty;++ const server = tools_mod.strField(input, "server");+ if (server) |want| {+ for (all, 0..) |t, i| if (std.mem.eql(u8, serverOf(t.qualified_name), want)) try wanted.append(arena, i);+ if (wanted.items.len == 0) try missing.append(arena, want);+ }+ if (input == .object) if (input.object.get("tools")) |list| if (list == .array) {+ for (list.array.items) |item| {+ if (item != .string) continue;+ const found = for (all, 0..) |t, i| {+ if (std.mem.eql(u8, t.qualified_name, item.string)) break i;+ } else null;+ if (found) |i| try wanted.append(arena, i) else try missing.append(arena, item.string);+ }+ };++ 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 };++ var aw: Io.Writer.Allocating = .init(arena);+ var emitted: usize = 0;+ var fresh: usize = 0;+ for (wanted.items, 0..) |i, k| {+ // Named twice in one call (`server` plus its own name, say), or loaded+ // by an earlier call: neither is an error, both are the cache working.+ if (std.mem.indexOfScalar(usize, wanted.items[0..k], i) != null) continue;+ const first_time = !isLoaded(all[i].qualified_name);+ try aw.writer.print("{s}\n", .{try enable(arena, all[i])});+ emitted += 1;+ if (first_time) fresh += 1;+ }+ var head: Io.Writer.Allocating = .init(arena);+ try head.writer.print(+ "{d} tool schema(s) below are now loaded and callable for the rest of this session ({d} newly enabled). " +++ "Call them with arguments matching input_schema.\n",+ .{ emitted, fresh },+ );+ try head.writer.writeAll(aw.writer.buffered());+ return .{ .text = head.writer.buffered(), .loaded = fresh };+}++/// 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 {+ var aw: Io.Writer.Allocating = .init(arena);+ for (unknown) |name| try aw.writer.print("no deferred MCP tool or server named '{s}'. ", .{name});+ var n: usize = 0;+ for (all) |t| if (isDeferred(all, t)) {+ n += 1;+ };+ if (n == 0) {+ try aw.writer.writeAll("No MCP tool schemas are deferred: every connected tool is already callable with its full schema in your tool list.");+ return aw.writer.buffered();+ }+ try aw.writer.print("{d} MCP tool(s) are deferred — pass their names to {s} to load and enable them:\n", .{ n, tool_name });+ for (all) |t| if (isDeferred(all, t)) {+ try aw.writer.print(" {s}: {s}\n", .{ t.qualified_name, shortDesc(t.description) });+ };+ return aw.writer.buffered();+}++/// The `load_tool_schemas` meta-tool arm (agent_tools.handleMeta). Meta, not+/// external, for two reasons: it mutates the agent's OWN tool catalog, and+/// running inline on the orchestrator thread is what makes the session state+/// above single-writer.+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 };+ const r = loadInto(agent.arena, reg.tools, input) catch+ return .{ .text = "load_tool_schemas failed to render the requested schemas", .is_error = true };+ // Re-render the catalog so the provider sees the real schema too, not just+ // the copy in this tool result.+ if (r.loaded > 0) {+ agent.invalidateRootTools();+ agent.ensureRootTools(agent.provider.kind) catch {};+ }+ return .{ .text = r.text, .is_error = r.is_error };+}++// --- size accounting -------------------------------------------------------++const max_depth = 32;++/// Serialized byte count of a JSON value, near enough for a budget decision+/// (escapes and float formatting are approximated). Depth-capped: the value+/// comes from an MCP server, so it is untrusted input.+pub fn jsonBytes(v: Value, depth: u8) usize {+ if (depth >= max_depth) return 0;+ return switch (v) {+ .null => 4,+ .bool => |b| if (b) @as(usize, 4) else 5,+ .integer => |i| blk: {+ var buf: [24]u8 = undefined;+ const printed = std.fmt.bufPrint(&buf, "{d}", .{i}) catch break :blk 1;+ break :blk printed.len;+ },+ .float => 8,+ .number_string => |s| s.len,+ .string => |s| s.len + 2,+ .array => |a| blk: {+ var n: usize = 2;+ for (a.items, 0..) |item, i| n += jsonBytes(item, depth + 1) + @intFromBool(i > 0);+ break :blk n;+ },+ .object => |o| blk: {+ var n: usize = 2;+ var it = o.iterator();+ var first = true;+ while (it.next()) |e| {+ n += e.key_ptr.len + 3 + jsonBytes(e.value_ptr.*, depth + 1);+ if (!first) n += 1;+ first = false;+ }+ break :blk n;+ },+ };+}+// Tests live in mcp_schema_gate_tests.zig (both files answer to the 600-line+// ceiling); the catalog-level half is in tool_schema_tests.zig, next to+// renderRootTools.diff --git a/src/mcp_schema_gate_tests.zig b/src/mcp_schema_gate_tests.zignew file mode 100644index 00000000..17cdd652--- /dev/null+++ b/src/mcp_schema_gate_tests.zig@@ -0,0 +1,312 @@+//! #416 coverage for the two-phase MCP tool exposure in mcp_schema_gate.zig,+//! split out of it to keep both files inside the 600-line ceiling. The+//! catalog-level half — what a provider actually receives, and the token+//! saving it buys — lives in tool_schema_tests.zig, next to renderRootTools.++const std = @import("std");+const Io = std.Io;+const Value = std.json.Value;+const Allocator = std.mem.Allocator;++const mcp = @import("mcp.zig");+const mcp_config = @import("mcp_config.zig");+const gate = @import("mcp_schema_gate.zig");++const testing = std.testing;++/// A fixture server: `count` tools whose schemas carry `padding` bytes of+/// property description each, so a test can put a server either side of the+/// budget on purpose.+pub fn fixture(arena: Allocator, server: []const u8, count: usize, padding: usize) ![]mcp.Tool {+ const out = try arena.alloc(mcp.Tool, count);+ for (out, 0..) |*t, i| {+ const filler = try arena.alloc(u8, padding);+ @memset(filler, 'x');+ var inner: std.json.ObjectMap = .empty;+ try inner.put(arena, "type", .{ .string = "string" });+ try inner.put(arena, "description", .{ .string = filler });+ var props: std.json.ObjectMap = .empty;+ try props.put(arena, "q", .{ .object = inner });+ var schema: std.json.ObjectMap = .empty;+ try schema.put(arena, "type", .{ .string = "object" });+ try schema.put(arena, "properties", .{ .object = props });+ t.* = .{+ .server_index = 0,+ .original_name = try std.fmt.allocPrint(arena, "t{d}", .{i}),+ .qualified_name = try std.fmt.allocPrint(arena, "mcp__{s}__t{d}", .{ server, i }),+ .description = "first line of the description\nsecond line nobody needs up front",+ .input_schema = .{ .object = schema },+ };+ }+ return out;+}++/// Every test here mutates module state; none may leak into the next.+pub fn withDefaults() void {+ gate.reset();+ gate.g_policy = .{};+}++test "serverOf splits the qualified name, and tolerates one that is not qualified" {+ try testing.expectEqualStrings("deepwiki", gate.serverOf("mcp__deepwiki__ask_question"));+ try testing.expectEqualStrings("s", gate.serverOf("mcp__s__t"));+ try testing.expectEqualStrings("", gate.serverOf("bash"));+ try testing.expectEqualStrings("lonely", gate.serverOf("mcp__lonely"));+}++test "jsonBytes tracks the real serialized size closely enough to budget with" {+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const src = "{\"type\":\"object\",\"properties\":{\"a\":{\"type\":\"string\"}},\"required\":[\"a\"],\"n\":12,\"ok\":true}";+ const v = try std.json.parseFromSliceLeaky(Value, arena, src, .{ .allocate = .alloc_always });+ var aw: Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.write(v);+ const actual = aw.writer.buffered().len;+ const estimate = gate.jsonBytes(v, 0);+ // Within 10% of the bytes std.json actually emits, in both directions.+ try testing.expect(estimate + actual / 10 >= actual);+ try testing.expect(estimate <= actual + actual / 10);+}++test "a small server stays eager, an expensive one is deferred (#416 default)" {+ withDefaults();+ defer withDefaults();+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ const small = try fixture(arena, "small", 2, 40);+ try testing.expect(gate.serverCost(small, "small") <= gate.default_budget);+ for (small) |t| try testing.expect(!gate.isDeferred(small, t));+ try testing.expect(!gate.anyDeferred(small));++ const fat = try fixture(arena, "fat", 8, 2000);+ try testing.expect(gate.serverCost(fat, "fat") > gate.default_budget);+ for (fat) |t| try testing.expect(gate.isDeferred(fat, t));+ try testing.expect(gate.anyDeferred(fat));+}++test "the eager pin and the off switch both bypass deferral entirely" {+ 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", 8, 2000);+ const other = try fixture(arena, "other", 8, 2000);++ gate.g_policy.eager = &.{"fat"};+ for (fat) |t| try testing.expect(!gate.isDeferred(fat, t));+ // A pin names ONE server; a sibling over the budget is still deferred.+ try testing.expect(gate.isDeferred(other, other[0]));++ gate.g_policy.eager = &.{"*"};+ for (fat) |t| try testing.expect(!gate.isDeferred(fat, t));+ try testing.expect(!gate.isDeferred(other, other[0]));++ gate.g_policy = .{ .enabled = false };+ for (fat) |t| try testing.expect(!gate.isDeferred(fat, t));++ // A budget of 0 is the opposite extreme: defer everything.+ gate.g_policy = .{ .budget = 0 };+ const small = try fixture(arena, "small", 1, 4);+ try testing.expect(gate.isDeferred(small, small[0]));+}++const Env = struct {+ vals: []const [2][]const u8,+ pub fn get(self: @This(), key: []const u8) ?[]const u8 {+ for (self.vals) |kv| if (std.mem.eql(u8, kv[0], key)) return kv[1];+ return null;+ }+};++test "configure reads the env knobs and the per-server eager flag" {+ withDefaults();+ defer withDefaults();+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ const cfg = try std.json.parseFromSliceLeaky(Value, arena,+ \\{"pinned":{"command":"./a","eager":true},"lazy":{"command":"./b"},"off":{"command":"./c","eager":false}}+ , .{ .allocate = .alloc_always });+ const merged: mcp_config.Merged = .{ .servers = cfg.object };++ gate.configure(arena, merged, Env{ .vals = &.{+ .{ gate.env_budget, "1234" },+ .{ gate.env_eager, "one, two ,,three" },+ } });+ try testing.expect(gate.g_policy.enabled);+ try testing.expectEqual(@as(usize, 1234), gate.g_policy.budget);+ // Three names from the env plus the one config entry that opted in.+ try testing.expectEqual(@as(usize, 4), gate.g_policy.eager.len);+ try testing.expect(gate.pinnedEager("three"));+ try testing.expect(gate.pinnedEager("pinned"));+ try testing.expect(!gate.pinnedEager("lazy"));+ try testing.expect(!gate.pinnedEager("off"));++ gate.configure(arena, .{}, Env{ .vals = &.{.{ gate.env_enabled, "0" }} });+ try testing.expect(!gate.g_policy.enabled);+ try testing.expectEqual(gate.default_budget, gate.g_policy.budget);++ // A junk budget falls back rather than failing the session over a typo.+ gate.configure(arena, .{}, Env{ .vals = &.{.{ gate.env_budget, "soon" }} });+ try testing.expectEqual(gate.default_budget, gate.g_policy.budget);+}++test "shortDesc keeps one capped line and never splits a codepoint" {+ try testing.expectEqualStrings("one line", gate.shortDesc("one line\nand more\nand more"));+ // Built with a comptime loop rather than `**`, which the CI compiler+ // rejects however it is spaced: 600 bytes of "é", so a naive cap would+ // land mid-codepoint.+ const long_arr = comptime blk: {+ var buf: [600]u8 = undefined;+ var i: usize = 0;+ while (i < buf.len) : (i += 2) {+ buf[i] = 0xC3;+ buf[i + 1] = 0xA9;+ }+ break :blk buf;+ };+ const short = gate.shortDesc(&long_arr);+ try testing.expect(short.len <= gate.desc_cap);+ try testing.expect(std.unicode.utf8ValidateSlice(short));+}++test "load_tool_schemas returns the full schemas and enables the tools" {+ 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", 4, 2000);++ // Before: every tool blocked, with an actionable refusal.+ 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);+ try testing.expect(!r.is_error);+ try testing.expectEqual(@as(usize, 1), r.loaded);+ try testing.expect(std.mem.indexOf(u8, r.text, "\"input_schema\":{\"type\":\"object\",\"properties\"") != null);+ try testing.expect(std.mem.indexOf(u8, r.text, "second line nobody needs up front") != null); // the FULL description++ // After: that tool is callable, and only that one.+ try testing.expect(gate.isLoaded("mcp__fat__t0"));+ try testing.expect(!gate.blocked(fat, "mcp__fat__t0"));+ try testing.expect(!gate.isDeferred(fat, fat[0]));+ try testing.expect(gate.blocked(fat, "mcp__fat__t1"));+}++test "schemas are cached per session: a repeat load re-serializes nothing" {+ 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", 4, 2000);+ const req = try std.json.parseFromSliceLeaky(Value, arena, "{\"server\":\"fat\"}", .{ .allocate = .alloc_always });++ const first = try gate.loadInto(arena, fat, req);+ try testing.expectEqual(@as(usize, 4), first.loaded);+ try testing.expectEqual(@as(usize, 4), gate.rendersForTest());++ const second = try gate.loadInto(arena, fat, req);+ try testing.expectEqual(@as(usize, 0), second.loaded); // already enabled+ try testing.expectEqual(@as(usize, 4), gate.rendersForTest()); // and nothing re-serialized+ const body = struct {+ fn of(t: []const u8) []const u8 {+ return t[std.mem.indexOfScalar(u8, t, '\n').?..];+ }+ }.of;+ try testing.expectEqualStrings(body(first.text), body(second.text));+}++test "one tool named twice in a call is emitted once, not duplicated" {+ 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", 2, 2000);+ // `server` selects both tools, then `tools` names one of them again.+ const req = try std.json.parseFromSliceLeaky(Value, arena,+ \\{"server":"fat","tools":["mcp__fat__t0"]}+ , .{ .allocate = .alloc_always });+ const r = try gate.loadInto(arena, fat, req);+ try testing.expect(!r.is_error);+ try testing.expectEqual(@as(usize, 2), r.loaded);+ try testing.expect(std.mem.startsWith(u8, r.text, "2 tool schema(s) below"));+ // Exactly one entry per tool, and only two entries in total.+ try testing.expectEqual(@as(usize, 2), std.mem.count(u8, r.text, "\"name\":\"mcp__fat__t"));+ try testing.expectEqual(@as(usize, 1), std.mem.count(u8, r.text, "\"name\":\"mcp__fat__t0\""));+ try testing.expectEqual(@as(usize, 2), gate.rendersForTest());+}++test "an unknown name errors and lists what is actually deferred; no args just lists" {+ 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 bad = try std.json.parseFromSliceLeaky(Value, arena, "{\"tools\":[\"mcp__fat__nope\"]}", .{ .allocate = .alloc_always });+ const err = try gate.loadInto(arena, fat, bad);+ try testing.expect(err.is_error);+ try testing.expectEqual(@as(usize, 0), err.loaded);+ try testing.expect(std.mem.startsWith(u8, err.text, "no deferred MCP tool or server named 'mcp__fat__nope'."));+ try testing.expect(std.mem.indexOf(u8, err.text, "mcp__fat__t0: first line of the description\n") != null);++ const none = try std.json.parseFromSliceLeaky(Value, arena, "{}", .{ .allocate = .alloc_always });+ const list = try gate.loadInto(arena, fat, none);+ try testing.expect(!list.is_error);+ try testing.expect(std.mem.startsWith(u8, list.text, "3 MCP tool(s) are deferred"));+ // A listing must not smuggle the schemas back in — that is the whole point.+ try testing.expect(std.mem.indexOf(u8, list.text, "input_schema") == null);+ try testing.expect(std.mem.indexOf(u8, list.text, "second line nobody needs up front") == null);++ // Nothing deferred at all: say so rather than printing an empty list.+ const small = try fixture(arena, "small", 1, 4);+ const quiet = try gate.loadInto(arena, small, none);+ try testing.expect(!quiet.is_error);+ try testing.expect(std.mem.startsWith(u8, quiet.text, "No MCP tool schemas are deferred"));+}++test "an eager tool is never blocked, and the load tool is advertised only when needed" {+ withDefaults();+ defer withDefaults();+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const small = try fixture(arena, "small", 2, 40);+ try testing.expect(!gate.blocked(small, "mcp__small__t0"));+ try testing.expect(!gate.hiddenSpec("bash", small)); // only the load tool is ever hidden+ try testing.expect(gate.hiddenSpec(gate.tool_name, small)); // nothing deferred -> not advertised++ const fat = try fixture(arena, "fat", 8, 2000);+ try testing.expect(!gate.hiddenSpec(gate.tool_name, fat));+ // A name no server advertises stays mcp.Registry.call's problem, not ours.+ try testing.expect(!gate.blocked(fat, "mcp__fat__ghost"));+}++test "tool_desc stays JSON-escape-free (it is spliced into a raw schema string)" {+ for (gate.tool_desc) |c| try testing.expect(c != '"' and c != '\\' and c >= 0x20);+ try testing.expect(std.mem.indexOf(u8, gate.tool_desc, "CANNOT be called") != null);+ try testing.expect(std.mem.indexOf(u8, gate.tool_desc, "mcp__server__tool") != null);+ var parsed = try std.json.parseFromSlice(Value, testing.allocator, gate.tool_schema, .{});+ defer parsed.deinit();+ try testing.expect(parsed.value.object.get("properties").?.object.get("tools") != null);+ var ph = try std.json.parseFromSlice(Value, testing.allocator, gate.placeholder_schema, .{});+ defer ph.deinit();+ try testing.expectEqualStrings("object", ph.value.object.get("type").?.string);+}diff --git a/src/schema.zig b/src/schema.zigindex 4218e76a..98948b42 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -17,6 +17,7 @@ const skill_docs = @import("skill_docs.zig"); // SKILL.md playbooks: the `skill`const no_local_tools = @import("no_local_tools.zig"); // #330: the hard --no-local-tools gate (layer 1 lives here, layer 2 in exec.zig)const tool_gates = @import("tool_gates.zig"); // #352: the additive twin — optional tools that only exist when startup found their backing capabilityconst imagegen = @import("imagegen.zig"); // #352: name/desc/schema as plain strings, like skill_docs, so this catalog needs one entry and no import cycle+const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: which MCP tools are served schema-first vs description-only, and the `load_tool_schemas` stringsconst render = @import("schema_render.zig"); // the comptime provider-tool renderers moved out when #352's optional-tool catalogs doubled the number held here (600-line ceiling)const anthropicToolsJson = render.anthropicToolsJson;const openaiToolsJson = render.openaiToolsJson;@@ -151,6 +152,11 @@ const meta_specs = [_]ToolSpec{\\{"type": "object", "properties": {"result": {"type": "string", "description": "Final answer to present to the user"}}, "required": ["result"]},},+ // #416, the MCP half of progressive disclosure: an expensive server is+ // registered by name + one line per tool, and this loads the real schemas+ // (and enables those tools) on demand. Meta because it mutates the root's+ // own tool catalog; renderRootTools drops it while nothing is deferred.+ .{ .name = mcp_schema_gate.tool_name, .desc = mcp_schema_gate.tool_desc, .schema = mcp_schema_gate.tool_schema },.{.name = "clock_sleep",.desc = "Pause the current turn for up to 12 hours of wall-clock time; interruptible by user input, and reported as a normal (non-error) result either way. For autonomous /loop runs that need to wait before re-checking something (e.g. a long external job). Root-only; off unless --clock-sleep/GRAFF_CLOCK_SLEEP=1 is set.",@@ -217,7 +223,7 @@ const root_specs_without_clock = rootSpecsWithout(&.{"clock_sleep"});const root_specs_without_learning = rootSpecsWithout(&.{"learn_candidate"});const root_specs_without_optional = rootSpecsWithout(&.{ "clock_sleep", "learn_candidate" });-pub const meta_names = [_][]const u8{ "todo_write", "todo_read", "ask_user", "eval", "attempt_completion", "clock_sleep", "note_constraint" };+pub const meta_names = [_][]const u8{ "todo_write", "todo_read", "ask_user", "eval", "attempt_completion", "clock_sleep", "note_constraint", mcp_schema_gate.tool_name };pub fn isMetaName(name: []const u8) bool {for (meta_names) |m| if (std.mem.eql(u8, name, m)) return true;@@ -289,8 +295,18 @@ pub fn renderRootTools(errdefer aw.deinit();var s: std.json.Stringify = .{ .writer = &aw.writer };try s.beginArray();- for (specs) |t| try writeToolEntry(&s, kind, t.name, t.desc, .{ .raw = t.schema });- for (mcp_tools) |m| try writeToolEntry(&s, kind, m.qualified_name, m.description, .{ .value = m.input_schema });+ for (specs) |t| {+ if (mcp_schema_gate.hiddenSpec(t.name, mcp_tools)) continue; // #416: load_tool_schemas is pointless with nothing deferred+ try 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+ try writeToolEntry(&s, kind, m.qualified_name, m.description, .{ .value = m.input_schema });try s.endArray();return aw.toOwnedSlice();}diff --git a/src/session_start.zig b/src/session_start.zigindex 4e207b4c..fbb5b6c1 100644--- a/src/session_start.zig+++ b/src/session_start.zig@@ -37,6 +37,7 @@ const anim = @import("anim.zig");const mcp = @import("mcp.zig");const mcp_cli = @import("mcp_cli.zig");const mcp_config = @import("mcp_config.zig");+const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: the eager-vs-deferred policy for MCP tool schemasconst jobs = @import("jobs.zig");const tool_spill = @import("tool_spill.zig"); // #409: where an over-cap tool output's full bytes goconst trace = @import("trace.zig");@@ -371,6 +372,9 @@ pub fn initRegistryConsent(io: Io, gpa: Allocator, arena: Allocator, out: *Io.Wr// so an unguarded line here would corrupt the head of every --json run.const quiet = json_mode or flags.oneshot_prompt != null;const merged = mcp_config.load(io, arena, Io.Dir.cwd(), mcp_config_path, global_path);+ // #416: resolve eager-vs-deferred BEFORE anything connects, so the first+ // catalog render already knows which servers pay their schemas up front.+ mcp_schema_gate.configure(arena, merged, environ_map);if (!quiet) {// Reported here rather than in `Registry.init`, which never runs when// consent is declined — a config that does not parse must be nameddiff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 033f8746..75042686 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -91,6 +91,11 @@ const playbook_reflect = @import("playbook_reflect.zig");// that staying true.const mcp_config = @import("mcp_config.zig");+// #416: two-phase MCP tool exposure. schema.zig/exec.zig reach the gate, but+// its tests live in a sibling file that nothing in production imports.+const mcp_schema_gate = @import("mcp_schema_gate.zig");+const mcp_schema_gate_tests = @import("mcp_schema_gate_tests.zig");+// The ultracode escalation ladder and the machinery it decides with. The// production graph reaches escalation.zig/phase_budget.zig through// workflow.zig, but only through a CALL — nothing references their decls at@@ -171,6 +176,8 @@ test {_ = scoring_slot_test;_ = session_tests;_ = mcp_config;+ _ = mcp_schema_gate;+ _ = mcp_schema_gate_tests;_ = acp;_ = agent_eval_control_tests;_ = playbook_glue;diff --git a/src/tool_schema_tests.zig b/src/tool_schema_tests.zigindex 8decadc1..f96daee8 100644--- a/src/tool_schema_tests.zig+++ b/src/tool_schema_tests.zig@@ -29,6 +29,8 @@ const mcp_protocol = @import("mcp_protocol.zig");const imagegen = @import("imagegen.zig");const no_local_tools = @import("no_local_tools.zig");const Provider = @import("provider.zig").Provider;+const gate = @import("mcp_schema_gate.zig"); // #416+const smolify_manifest = @import("smolify_manifest.zig"); // a REAL 13-tool MCP manifest to measure #416 againstconst testing = std.testing;@@ -193,6 +195,101 @@ test "the discovery path itself flattens, so nothing reaches a provider unlowere}}+/// #416's catalog half, measured against a REAL MCP manifest rather than a+/// made-up one: the bundled Smolify server (13 tools, ~9.5 KB of description ++/// schema — the same order as the companion server that provoked the issue at+/// +2,568 input tokens per call).+fn realServerTools(arena: Allocator) ![]const mcp.Tool {+ var list: std.ArrayList(mcp.Tool) = .empty;+ _ = try smolify_manifest.appendTools(mcp.Tool, arena, &list, 0, true);+ return list.items;+}++test "#416: deferring a real MCP server's schemas cuts the served catalog in half" {+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ gate.reset();+ gate.g_policy = .{};+ defer {+ gate.reset();+ gate.g_policy = .{};+ }+ const tools = try realServerTools(arena);+ try testing.expectEqual(@as(usize, 13), tools.len);++ // Pre-#416 behavior, still reachable with the escape-hatch pin.+ gate.g_policy = .{ .eager = &.{"*"} };+ const eager = try schema.renderRootTools(arena, .anthropic, &.{}, tools);++ // The default: this server is 2.3x over the 4 KiB budget, so it defers.+ gate.g_policy = .{};+ try testing.expect(gate.serverCost(tools, "smolify") > gate.default_budget);+ const deferred = try schema.renderRootTools(arena, .anthropic, &.{}, 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+ // else. Measured on this manifest: 10,505 -> 3,696 bytes, a 64.8% cut, or+ // roughly 1,700 input tokens at 4 bytes/token — per request, for the whole+ // session, from ONE server. Asserted at a conservative 50% so a schema+ // 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.+ 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);+ }+ // ...and the tool that undoes it rides along — but only while it is needed,+ // so a session whose servers are all eager is never charged for it.+ const with_specs = try schema.renderRootTools(arena, .anthropic, &schema.root_specs, tools);+ try testing.expect(std.mem.indexOf(u8, with_specs, gate.tool_name) != null);+ gate.g_policy = .{ .eager = &.{"*"} };+ const eager_specs = try schema.renderRootTools(arena, .anthropic, &schema.root_specs, tools);+ try testing.expect(std.mem.indexOf(u8, eager_specs, gate.tool_name) == null);+ gate.g_policy = .{};++ // Loading one tool restores that tool's schema to the catalog and nothing+ // else's: enabling is per tool, not per server.+ const req = try std.json.parseFromSliceLeaky(Value, arena, "{\"tools\":[\"mcp__smolify__read_public_source\"]}", .{ .allocate = .alloc_always });+ const 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);+ try testing.expect(std.mem.indexOf(u8, after, "lineCount") != null); // read_public_source's own schema is back+ try testing.expect(std.mem.indexOf(u8, after, "pathHints") == null); // build_docs_context's is not+ try testing.expect(after.len > deferred.len and after.len < eager.len);+}++test "#416: every provider wire format defers identically, and stays valid JSON" {+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ gate.reset();+ gate.g_policy = .{};+ defer {+ gate.reset();+ gate.g_policy = .{};+ }+ const tools = try realServerTools(arena);+ for ([_]Provider.Kind{ .anthropic, .openai, .responses }) |kind| {+ const catalog = try schema.renderRootTools(arena, kind, &.{}, tools);+ // A placeholder must be as wire-legal as a real schema: parseable,+ // combinator-free, and a JSON Schema object like every other entry.+ try forEachServedSchema(arena, catalog, struct {+ fn check(name: []const u8, sch: Value) anyerror!void {+ _ = name;+ try testing.expectEqualStrings("object", sch.object.get("type").?.string);+ try testing.expect(mcp_protocol.topLevelCombinator(sch) == null);+ }+ }.check);+ }+}+// The two below live here rather than in schema.zig, which is at the// 600-line ceiling.