Skip to content

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

Python

fix: encode MCP tool names and preserve raw routing

justrachd932d53d17f1
diff --git a/docs/adr/0112-mcp-wire-names-preserve-raw-routing.md b/docs/adr/0112-mcp-wire-names-preserve-raw-routing.md
new file mode 100644
index 00000000..b5d1d9ab
--- /dev/null
+++ b/docs/adr/0112-mcp-wire-names-preserve-raw-routing.md
@@ -0,0 +1,28 @@
+# 0112. MCP wire names preserve raw routing
+
+Status: accepted 2026-09-14
+
+## Context
+
+MCP configuration keys and tool names can contain characters rejected in
+function declarations. Deferred loading delays the rejection until a later
+request. Replacing punctuation with underscores alone can alias distinct tools.
+
+## Decision
+
+Encode unsafe UTF-8 bytes as `_xHH`, and escape literal escape markers and
+server delimiters. Preserve ordinary short identifiers. Reserve `_h` for
+empty or oversized components, represented by 96 bits of a SHA-256 digest.
+Bound the complete qualified name to 64 ASCII characters. Names depend only
+on raw identity, so concurrent discovery and restarts produce the same names.
+
+Store the raw server name on each tool. Use it for eager policy, grouping,
+and server-based selection; use the original tool name for MCP dispatch.
+Only model-visible identifiers use the encoded name.
+
+## Consequences
+
+Deferred and eager catalogs share the same safe identifiers. Loading remains
+subject to existing consent and deferral checks. Previously invalid or oversized
+names change, so their saved schema selections must be loaded again. Hashes
+have a finite collision probability; ordinary escaped names remain reversible.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 8cb1e80b..b2177c81 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -121,6 +121,7 @@ record only when you need the evidence or the edge cases.
| [0108](0108-browser-events-outrank-pending-snapshots.md) | Browser page-info events invalidate older pending IPC snapshots; a loaded page must not revert to loading. |
| [0109](0109-resume-retains-catalog-and-layout-snapshots.md) | Resume restores loaded tool selections and the same-workspace layout snapshot, without freezing current instructions or granting permissions. |
| [0110](0110-project-mcp-listing-opts-in-optional-servers.md) | Project MCP entries opt in optional servers; inherited extras still require opt-in, and startup consent applies to both. |
+| [0112](0112-mcp-wire-names-preserve-raw-routing.md) | MCP wire names are escaped and bounded; raw server/tool identities control policy and dispatch. |
## When to write one
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonl
index 4181d9dd..def84f33 100644
--- a/evals/harness_behavior.jsonl
+++ b/evals/harness_behavior.jsonl
@@ -82,3 +82,4 @@
{"id": "publication-unresolved-command-refused", "why": "#847: a non-literal publication command cannot bypass head/body inspection by chaining checks before creation. No GitHub write or lookup should execute.", "args": ["--old"], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Exercise the scripted prepublication refusal.", "script": [{"tool": "bash", "arguments": {"command": "gh pr checks --watch && gh pr create --title fixture --body '## Verification: local passed'"}}, {"text": "The publication was blocked."}], "assert": [{"event": {"type": "tool_result", "name": "bash", "is_error": true}}, {"request_contains": {"text": "separate literal gh pr command"}}, {"final_text_contains": "The publication was blocked."}]}
{"id": "render-html-hands-back-an-opaque-view", "why": "The model's own drawing surface must be advertised, dispatch to the snapshot writer, and put only the opaque path into the transcript - a page the model drew must never come back to it as a second copy of the markup.", "args": [], "prompt": "draw the retry flow as a page", "script": [{"tool": "render_html", "arguments": {"html": "<h1 id=\"flow\">Retry flow</h1><p>the second attempt is declined</p>"}}, {"text": "drawn above"}], "assert": [{"request_contains": {"index": 0, "text": "render_html"}}, {"events_at_least": {"match": {"type": "tool_call", "name": "render_html"}, "count": 1}}, {"event": {"type": "tool_result"}}, {"request_contains": {"index": -1, "text": "[Rendered view]"}}, {"request_contains": {"index": -1, "text": "/.graff/views/"}}, {"final_text_contains": "drawn above"}]}
{"id": "bundled-mcp-skill-loads", "why": "The bundled invocation skill must be discoverable and load its connection instructions after adding an MCP server.", "prompt": "Load the bundled mcp skill before adding a server.", "script": [{"tool": "skill", "arguments": {"name": "mcp"}}, {"text": "MCP instructions loaded."}], "assert": [{"event": {"type": "tool_call", "name": "skill"}}, {"request_contains": {"index": -1, "text": "graff mcp add"}}, {"request_contains": {"index": -1, "text": "/mcp trust"}}, {"final_text_contains": "MCP instructions loaded."}]}
+{"id": "mcp-wire-name-normalization", "why": "#930: loading a tool with spaces in its server name and punctuation in its tool name must emit an API-safe definition and retain original MCP dispatch.", "env": {"GRAFF_MCP_SCHEMA_BUDGET": "0", "GRAFF_MCP_PROBE": "0", "GRAFF_LEARN_AUTO": "off"}, "workspace_seed": {".mcp.json": "{\"mcpServers\": {\"docs server\": {\"command\": \"python3\", \"args\": [\"mock_mcp.py\"]}}}", "mock_mcp.py": "import json, sys\nfor line in sys.stdin:\n r = json.loads(line)\n if 'id' not in r: continue\n method = r.get('method')\n if method == 'initialize':\n result = {'protocolVersion':'2025-06-18','capabilities':{'tools':{}},'serverInfo':{'name':'fixture','version':'1'}}\n elif method == 'tools/list':\n result = {'tools':[{'name':'room.for_branch','description':'Find a room','inputSchema':{'type':'object','properties':{}}}]}\n elif method == 'tools/call':\n result = {'content':[{'type':'text','text':'original name routed' if r['params']['name'] == 'room.for_branch' else 'WRONG NAME'}]}\n else: result = {}\n print(json.dumps({'jsonrpc':'2.0','id':r['id'],'result':result}),flush=True)\n"}, "prompt": "Load the docs server tool, call it and report completion.", "script": [{"tool": "load_tool_schemas", "arguments": {"server": "docs server"}}, {"tool": "mcp__docs_x20server__room_x2efor_branch", "arguments": {}}, {"text": "routing complete"}], "assert": [{"request_contains": {"index": 1, "text": "mcp__docs_x20server__room_x2efor_branch"}}, {"request_lacks": {"index": 1, "text": "mcp__docs server__room.for_branch"}}, {"request_contains": {"index": -1, "text": "original name routed"}}, {"final_text_contains": "routing complete"}]}
diff --git a/src/main.zig b/src/main.zig
index a95fede8..4cdddc39 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -361,7 +361,6 @@ pub fn main(init: std.process.Init) !void {
telem.flush();
telem.deinit();
}
-
// MCP servers from .mcp.json. SECURITY: a workspace .mcp.json launches arbitrary local commands, so opening an untrusted repo could run them —
// auto-connect only with --yolo (trusted) or explicit per-session consent; otherwise start with an empty (but live) registry so `/mcp add`
// still works.
@@ -597,4 +596,5 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu
_ = @import("subagent_recovery.zig");
_ = @import("acp_agent_activity.zig");
_ = @import("read_image.zig");
+ _ = @import("mcp_names.zig");
}
diff --git a/src/mcp.zig b/src/mcp.zig
index eeb11603..61731e2b 100644
--- a/src/mcp.zig
+++ b/src/mcp.zig
@@ -40,12 +40,16 @@ const initializeServer = mcp_rpc.initializeServer;
const request = mcp_rpc.request;
pub const Tool = struct {
+ server_name: ?[]const u8 = null, // raw configuration identity; null for legacy fixtures
ui_resource_uri: ?[]const u8 = null,
server_index: usize,
original_name: []const u8, // name as the server knows it
qualified_name: []const u8, // "mcp__<server>__<tool>" shown to the model
description: []const u8,
input_schema: Value, // arena-owned parsed JSON Schema
+ pub fn serverName(tool: Tool) []const u8 {
+ return tool.server_name orelse @import("mcp_names.zig").serverOf(tool.qualified_name);
+ }
};
pub const Registry = struct {
@@ -414,7 +418,7 @@ pub const Registry = struct {
const name_v = t.object.get("name") orelse continue;
if (name_v != .string) continue;
const orig = try a.dupe(u8, name_v.string);
- const qualified = try std.fmt.allocPrint(a, "mcp__{s}__{s}", .{ name, orig });
+ const qualified = try @import("mcp_names.zig").qualify(a, name, orig);
// Prefer description; fall back to the 2025-06-18+ human-readable
// title so a metadata-only tool isn't blank to the model.
const desc = if (t.object.get("description")) |d| (if (d == .string) d.string else "") else if (t.object.get("title")) |ti| (if (ti == .string) ti.string else "") else "";
@@ -426,6 +430,7 @@ pub const Registry = struct {
try mcp_protocol.flattenTopLevel(a, &schema);
try tools.append(a, .{
.server_index = server_index,
+ .server_name = server.name,
.original_name = orig,
.qualified_name = qualified,
.description = try a.dupe(u8, desc),
diff --git a/src/mcp_names.zig b/src/mcp_names.zig
new file mode 100644
index 00000000..3af3949c
--- /dev/null
+++ b/src/mcp_names.zig
@@ -0,0 +1,118 @@
+//! Stable wire names, independent of server discovery order. Raw identities
+//! stay on Tool/Server for configuration and MCP tools/call routing.
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+
+pub fn serverOf(qualified: []const u8) []const u8 {
+ if (!std.mem.startsWith(u8, qualified, "mcp__")) return "";
+ const rest = qualified[5..];
+ return rest[0 .. std.mem.indexOf(u8, rest, "__") orelse rest.len];
+}
+
+fn allowed(c: u8) bool {
+ return std.ascii.isAlphanumeric(c) or c == '_' or c == '-';
+}
+
+// Escape unsafe UTF-8 bytes, literal escape markers and server delimiters.
+// Unlike replacing punctuation with underscores, this keeps short names
+// distinct without depending on which server finishes its handshake first.
+fn component(a: Allocator, raw: []const u8, limit: usize, server: bool) ![]const u8 {
+ var out: std.Io.Writer.Allocating = .init(a);
+ defer out.deinit();
+ for (raw, 0..) |c, i| {
+ const next: ?u8 = if (i + 1 < raw.len) raw[i + 1] else null;
+ const reserved = c == '_' and if (next) |n|
+ n == 'x' or (i == 0 and n == 'h') or (server and (n == '_' or !allowed(n)))
+ else
+ server;
+ if (!allowed(c) or reserved) {
+ try out.writer.print("_x{x:0>2}", .{c});
+ } else try out.writer.writeByte(c);
+ }
+ const encoded = out.writer.buffered();
+ if (encoded.len > 0 and encoded.len <= limit) return a.dupe(u8, encoded);
+ // Reserve _h for bounded identities (literal _h prefixes are escaped).
+ // 96 hash bits fit even when both server and tool names are oversized.
+ var digest: [32]u8 = undefined;
+ std.crypto.hash.sha2.Sha256.hash(raw, &digest, .{});
+ return std.fmt.allocPrint(a, "_h{s}", .{std.fmt.bytesToHex(digest[0..12], .lower)});
+}
+
+pub fn qualify(a: Allocator, server: []const u8, tool: []const u8) ![]const u8 {
+ const sv = try component(a, server, 26, true);
+ defer a.free(sv);
+ const name = try component(a, tool, 57 - sv.len, false);
+ defer a.free(name);
+ return std.fmt.allocPrint(a, "mcp__{s}__{s}", .{ sv, name });
+}
+
+test "#930 wire names escape punctuation and preserve ordinary names" {
+ const a = std.testing.allocator;
+ const cases = [_][3][]const u8{
+ .{ "wiki", "read_file", "mcp__wiki__read_file" },
+ .{ "docs server", "room.for_branch", "mcp__docs_x20server__room_x2efor_branch" },
+ .{ "docs_server", "read-file", "mcp__docs_server__read-file" },
+ .{ "a__b", "read", "mcp__a_x5f_b__read" },
+ .{ "a_ b", "read", "mcp__a_x5f_x20b__read" },
+ .{ "a_", "read", "mcp__a_x5f__read" },
+ .{ "docs_x20server", "read", "mcp__docs_x5fx20server__read" },
+ };
+ for (cases) |c| {
+ const name = try qualify(a, c[0], c[1]);
+ defer a.free(name);
+ try std.testing.expectEqualStrings(c[2], name);
+ }
+}
+
+test "#930 raw server identity controls eager policy search and schema loading" {
+ const gate = @import("mcp_schema_gate.zig");
+ const select = @import("mcp_select.zig");
+ const mcp = @import("mcp.zig");
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const saved = gate.g_policy;
+ defer gate.g_policy = saved;
+ gate.reset();
+ defer gate.reset();
+ gate.g_policy = .{ .budget = 0 };
+ const tools = [_]mcp.Tool{.{
+ .server_index = 0,
+ .server_name = "docs server",
+ .original_name = "room.for_branch",
+ .qualified_name = try qualify(a, "docs server", "room.for_branch"),
+ .description = "Find a room",
+ .input_schema = .{ .object = .empty },
+ }};
+ try std.testing.expect(gate.isDeferred(&tools, tools[0]));
+ gate.g_policy.eager = &.{"docs server"};
+ try std.testing.expect(!gate.isDeferred(&tools, tools[0]));
+ gate.g_policy.eager = &.{};
+ const input = try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"server\":\"docs server\",\"query\":\"room\"}", .{});
+ const found = try select.searchInto(a, &tools, input);
+ try std.testing.expect(!found.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, found.text, tools[0].qualified_name) != null);
+ const loaded = try gate.loadInto(a, &tools, input);
+ try std.testing.expectEqual(@as(usize, 1), loaded.loaded);
+ try std.testing.expect(gate.isLoaded(tools[0].qualified_name));
+ try std.testing.expectEqualStrings("room.for_branch", tools[0].original_name);
+}
+
+test "#930 names remain distinct for escaping Unicode empty and oversized identities" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const long: [200]u8 = @splat('z');
+ var other = long;
+ other[199] = 'y';
+ const inputs = [_][]const u8{ "a b", "a.b", "a_b", "a_x20b", "_h", "", "日本語", &long, &other, "a__b" };
+ var names: std.StringHashMap(void) = .init(a);
+ for (inputs) |server| for (inputs) |tool| {
+ const name = try qualify(a, server, tool);
+ try std.testing.expect(name.len <= 64);
+ for (name) |c| try std.testing.expect(allowed(c));
+ try std.testing.expect(!(try names.getOrPut(name)).found_existing);
+ try std.testing.expectEqualStrings(name, try qualify(a, server, tool));
+ try std.testing.expect(serverOf(name).len > 0);
+ };
+}
diff --git a/src/mcp_schema_gate.zig b/src/mcp_schema_gate.zig
index 035f68b7..d47ce67d 100644
--- a/src/mcp_schema_gate.zig
+++ b/src/mcp_schema_gate.zig
@@ -114,7 +114,7 @@ pub var g_stable_catalog = true;
/// and (in stable mode) the listing, which must not change as tools load.
pub fn policyDeferred(all: []const mcp.Tool, tool: mcp.Tool) bool {
if (!g_policy.enabled) return false;
- const server = serverOf(tool.qualified_name);
+ const server = tool.serverName();
if (pinnedEager(server)) return false;
return serverCost(all, server) > g_policy.budget;
}
@@ -244,13 +244,7 @@ pub fn deferAllRuntime() void {
}
/// 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 const serverOf = @import("mcp_names.zig").serverOf;
pub fn pinnedEager(server: []const u8) bool {
for (g_policy.eager) |p| {
@@ -266,7 +260,7 @@ pub fn pinnedEager(server: []const u8) bool {
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;
+ if (!std.mem.eql(u8, t.serverName(), server)) continue;
total += t.description.len + jsonBytes(t.input_schema, 0);
}
return total;
@@ -278,7 +272,7 @@ pub fn serverCost(all: []const mcp.Tool, server: []const u8) usize {
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);
+ const server = tool.serverName();
if (pinnedEager(server)) return false;
return serverCost(all, server) > g_policy.budget;
}
@@ -381,7 +375,7 @@ pub fn loadInto(arena: Allocator, all: []const mcp.Tool, input: Value) !Loaded {
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);
+ for (all, 0..) |t, i| if (std.mem.eql(u8, t.serverName(), 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) {
@@ -522,7 +516,7 @@ pub fn descWithListing(arena: Allocator, all: []const mcp.Tool) ![]const u8 {
for (all) |t| {
if (omitMcp(t.qualified_name)) continue;
if (!deferredRule(all, t)) continue;
- const sv = serverOf(t.qualified_name);
+ const sv = t.serverName();
const seen = for (servers.items) |s| {
if (std.mem.eql(u8, s, sv)) break true;
} else false;
@@ -542,7 +536,7 @@ pub fn descWithListing(arena: Allocator, all: []const mcp.Tool) ![]const u8 {
for (all) |t| {
if (omitMcp(t.qualified_name)) continue;
if (!deferredRule(all, t)) continue;
- if (!std.mem.eql(u8, serverOf(t.qualified_name), sv)) continue;
+ if (!std.mem.eql(u8, t.serverName(), sv)) continue;
if (!first) try aw.writer.writeAll(", ");
try aw.writer.writeAll(shortName(t.qualified_name));
first = false;
diff --git a/src/mcp_select.zig b/src/mcp_select.zig
index 26eb5eb5..bd11c7e3 100644
--- a/src/mcp_select.zig
+++ b/src/mcp_select.zig
@@ -51,7 +51,7 @@ pub fn searchInto(arena: Allocator, all: []const mcp.Tool, input: Value) !mcp_sc
for (all, 0..) |t, i| {
if (!mcp_schema_gate.isDeferred(all, t)) continue;
if (server) |sv| {
- if (!std.mem.eql(u8, mcp_schema_gate.serverOf(t.qualified_name), sv)) continue;
+ if (!std.mem.eql(u8, t.serverName(), sv)) continue;
}
const score = scoreTool(t, query);
if (score == 0) continue;