diff --git a/CHANGELOG.md b/CHANGELOG.md index 013d0ff..b86bce2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Security + +- MCP tool grants now match the actual server and bare tool separately, preventing a + grant for `docs` from authorizing `docs_`. MCP server names ending in `_` are rejected; + rename them and update their policy rules. Discovery also rejects duplicate qualified + tool identities. + ### Added - Buzz: a `subscription_stalled channel= missed_event=` warning when one channel's diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 0b39dce..8c63eae 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -532,7 +532,7 @@ export async function buildBrain( })), // A granted reader is the only use for a synced ledger, and a first sync is not cheap. syncLedgers: ["team_sessions", "team_recent"].some( - (tool) => policy?.allowsTool(qualifyTool(cfg.name, tool)).ok === true, + (tool) => policy?.allowsTool({ server: cfg.name, tool }).ok === true, ), // Resolved here, in the gateway, and per lookup rather than once: file-first, so a // mounted secret beats an env var, and a mount rewritten under this process is what @@ -2804,7 +2804,7 @@ async function doctorCmd(argv: string[]): Promise { continue; } const allowed = tools.filter( - (t) => policy.allowsTool(`mcp__${server.name}__${t.name}`).ok, + (t) => policy.allowsTool({ server: server.name, tool: t.name }).ok, ); if (!allowed.length) { problems.push( diff --git a/packages/core/src/manifest.ts b/packages/core/src/manifest.ts index ecfb96a..bd56122 100644 --- a/packages/core/src/manifest.ts +++ b/packages/core/src/manifest.ts @@ -380,6 +380,11 @@ const ServerName = z (name) => !name.includes("__"), "a doubled underscore separates server from tool in `mcp____`, so a " + "server name carrying one makes a whole-server rule ambiguous — use a single `_` or `-`", + ) + .refine( + (name) => !name.endsWith("_"), + "a trailing underscore overlaps the separator in `mcp____` and can " + + "collide with another server's tools — end the server name with a letter, number, or `-`", ); export const McpServerSchema = z diff --git a/packages/core/src/mcp-broker.ts b/packages/core/src/mcp-broker.ts index 236102a..d2fea97 100644 --- a/packages/core/src/mcp-broker.ts +++ b/packages/core/src/mcp-broker.ts @@ -198,6 +198,7 @@ export interface McpBrokerOptions { export class McpBroker { private connections = new Map(); private pinnedSchemas = new Map(); + private qualifiedServers = new Map(); private nextId = 0; constructor(private opts: McpBrokerOptions) {} @@ -234,11 +235,11 @@ export class McpBroker { return method === "tools/list" ? this.pinTools(result, entry.server.name) : result; } - // A server knows its tools by their bare names; the policy — like the brain's own - // permission requests — names them `mcp____`. Qualifying here is what - // makes one policy line govern both the brain asking and the broker relaying. + // Keep the connection's server separate from the requested bare tool for policy; + // qualification is only an audit label, not an unambiguous authorization identity. const call = params as { name?: string; arguments?: Record } | undefined; - const tool = qualifyTool(entry.server.name, call?.name ?? ""); + const identity = { server: entry.server.name, tool: call?.name ?? "" }; + const tool = qualifyTool(identity.server, identity.tool); const args = call?.arguments; const scope = entry.server.scope ?? {}; @@ -259,7 +260,7 @@ export class McpBroker { .map(([name]) => name); return auditToolCall({ tool, args, declared }, async () => { - const verdict = this.opts.policy.allowsTool(tool); + const verdict = this.opts.policy.allowsTool(identity); // Thrown as a refusal rather than a plain failure so the audit can tell the two // apart: a call the policy stopped is the line an operator goes looking for. if (!verdict.ok) throw new ToolRefused(`MCP call refused: ${verdict.reason}`); @@ -315,6 +316,19 @@ export class McpBroker { const tools = (result as { tools?: Array<{ name: string }> } | undefined)?.tools; if (!Array.isArray(tools)) return result; + // Discovery must not hand the brain two identities with the same policy spelling, + // even when a caller constructs broker config without going through the manifest. + const seen = new Set(); + for (const tool of tools) { + const qualified = qualifyTool(server, tool.name); + const owner = this.qualifiedServers.get(qualified); + if (seen.has(qualified) || (owner !== undefined && owner !== server)) { + throw new Error(`ambiguous MCP tool identity ${qualified}`); + } + seen.add(qualified); + this.qualifiedServers.set(qualified, server); + } + const kept = tools.filter((tool) => { const key = `${server}:${tool.name}`; const hash = createHash("sha256").update(JSON.stringify(tool)).digest("hex"); diff --git a/packages/core/src/mcp-http.ts b/packages/core/src/mcp-http.ts index deaf2cd..0cefde5 100644 --- a/packages/core/src/mcp-http.ts +++ b/packages/core/src/mcp-http.ts @@ -103,11 +103,14 @@ export async function serveMcp(handle: McpHandler, opts: ServeOptions = {}): Pro const guarded: McpHandler = async (msg) => { const gate = opts.toolPolicy; if (gate && msg.method === "tools/call") { - const tool = qualifyTool(gate.server, String(msg.params?.name ?? "")); - const verdict = gate.policy.allowsTool(tool); + const identity = { server: gate.server, tool: String(msg.params?.name ?? "") }; + const verdict = gate.policy.allowsTool(identity); if (!verdict.ok) { return auditToolCall( - { tool, args: (msg.params?.arguments ?? {}) as Record }, + { + tool: qualifyTool(identity.server, identity.tool), + args: (msg.params?.arguments ?? {}) as Record, + }, async () => { throw new ToolRefused(verdict.reason); }, ); } @@ -117,7 +120,7 @@ export async function serveMcp(handle: McpHandler, opts: ServeOptions = {}): Pro return { ...result, tools: result.tools.filter((tool: { name: string }) => - gate.policy.allowsTool(qualifyTool(gate.server, tool.name)).ok), + gate.policy.allowsTool({ server: gate.server, tool: tool.name }).ok), }; } return result; diff --git a/packages/core/src/tool-policy.ts b/packages/core/src/tool-policy.ts index 55460b9..bd7bb12 100644 --- a/packages/core/src/tool-policy.ts +++ b/packages/core/src/tool-policy.ts @@ -42,14 +42,16 @@ const SettingsSchema = z export type ToolVerdict = { ok: true } | { ok: false; reason: string }; +/** The server comes from trusted gateway wiring, not from a flattened tool name. */ +export type McpToolIdentity = { server: string; tool: string }; + /** * The name a tool is known by outside its own server, and the only place that spelling is * built. * - * It lives beside the matcher because it is the same language: a server knows its tools by - * their bare names, while the policy — like the brain's own permission requests — names them - * `mcp____`. Both `tools/call` chokepoints qualify through this, so one policy - * line governs the brain asking, the broker relaying, and the gateway hosting. + * Used for policy text and audit labels. Authorization at a gateway chokepoint must pass + * the server and bare tool separately: `docs_` / `read` and `docs` / `_read` have the same + * spelling here, but must never share a grant. */ export function qualifyTool(server: string, tool: string): string { return `mcp__${server}__${tool}`; @@ -72,23 +74,22 @@ const MCP = "mcp__"; */ const ANCHORED_ALLOW_GLOB = /^mcp__[^*]+__/; +type McpToolRule = { server: string; toolPattern?: string }; + /** - * A rule naming a whole server: `mcp__`, with nothing after the server segment. - * - * Only a bare one expands to a prefix. A qualified `mcp____` rule names that - * tool and stops there — expanding it too would turn `mcp__github__pr_list` into a grant - * for any tool whose name extends it, `pr_list__admin` included, and MCP tool names may - * contain the separator. One tool is what the operator wrote and one tool is what it has - * to mean. Both spellings begin `mcp__`, so the discriminator is what follows the server. - * - * That discriminator is only sound because a server name cannot contain `__`, which - * `manifest.ts`'s `ServerName` enforces where the name is chosen. Relax it there and - * `mcp__my__server` becomes ambiguous here, with a whole-server deny silently ceasing to - * apply — the ambiguity is not resolvable from the rule text, which is why it is refused - * at the source rather than guessed at in this function. + * Split at the first separator only: a bare tool may start with `_` or contain `__`. + * Manifest server names cannot contain `__` or end in `_`, so policy text and the brain's + * qualified permission requests have one interpretation. Gateway calls retain the actual + * identity instead of round-tripping it through this parser. */ -const isServerRule = (rule: string): boolean => - rule.startsWith(MCP) && !rule.slice(MCP.length).includes("__"); +function parseMcpRule(rule: string): McpToolRule | undefined { + if (!rule.startsWith(MCP)) return undefined; + const rest = rule.slice(MCP.length); + const separator = rest.indexOf("__"); + return separator === -1 + ? { server: rest } + : { server: rest.slice(0, separator), toolPattern: rest.slice(separator + 2) }; +} /** The tool-name position: everything before an argument list, if there is one. */ const toolNameOf = (rule: string): string => rule.split("(")[0]; @@ -181,13 +182,20 @@ export class ToolPolicy { * The brain reads untrusted text, so a side-effecting tool is an exfiltration and * write vector. Read-only is the low-risk default; anything else gets named on purpose. */ - allowsTool(name: string): ToolVerdict { + allowsTool(name: string | McpToolIdentity): ToolVerdict { + if (typeof name === "string") { + const parsed = parseMcpRule(name); + if (parsed?.toolPattern !== undefined) { + name = { server: parsed.server, tool: parsed.toolPattern }; + } + } + const label = typeof name === "string" ? name : qualifyTool(name.server, name.tool); if (this.deny.some((rule) => matches(rule, name, "deny"))) - return { ok: false, reason: `tool ${name} is denied by policy` }; + return { ok: false, reason: `tool ${label} is denied by policy` }; if (this.allow.some((rule) => matches(rule, name, "allow"))) return { ok: true }; - return { ok: false, reason: `tool ${name} is not allowlisted` }; + return { ok: false, reason: `tool ${label} is not allowlisted` }; } } @@ -196,7 +204,8 @@ export class ToolPolicy { * * - `mcp__` covers every tool that server provides; * - `mcp____` is that one tool; - * - a `*` is a glob over the whole tool name — but only a **deny** may be unanchored. + * - an anchored `*` globs the bare tool name on one exact server; + * - only a **deny** may glob across server boundaries. * * It is Claude Code's language rather than one of our own because `settings.json` is read * by both matchers: Claude Code decides whether the brain may call a tool, and this @@ -210,13 +219,23 @@ export class ToolPolicy { * a redundancy. `test/policy-cases` adjudicates what these rules actually reach; change * this function and read the verdicts that flip. */ -function matches(rule: string, name: string, direction: Direction): boolean { - if (rule === name) return true; - - // A bare `mcp__` is the whole server. Written without a glob, so it is checked - // before one — and `${rule}__` keeps `mcp__github` off `mcp__github_actions__run`. - if (!rule.includes("*")) return isServerRule(rule) && name.startsWith(`${rule}__`); +function matches(rule: string, name: string | McpToolIdentity, direction: Direction): boolean { + if (typeof name !== "string") { + const parsed = parseMcpRule(rule); + if (parsed && !parsed.server.includes("*")) { + return parsed.server === name.server && + (parsed.toolPattern === undefined || parsed.toolPattern === name.tool || + (parsed.toolPattern.includes("*") && globToRegExp(parsed.toolPattern).test(name.tool))); + } + + // Only broad denies retain full-name glob semantics, e.g. `*` or `mcp__*__delete`. + // Falling back to flattened matching for a grant would lose the server boundary. + if (direction === "allow") return false; + name = qualifyTool(name.server, name.tool); + } + if (rule === name) return true; + if (!rule.includes("*")) return false; if (direction === "allow" && grantsNothing(rule)) return false; return globToRegExp(rule).test(name); } diff --git a/packages/core/test/manifest.test.ts b/packages/core/test/manifest.test.ts index b2928e0..13e0213 100644 --- a/packages/core/test/manifest.test.ts +++ b/packages/core/test/manifest.test.ts @@ -87,7 +87,8 @@ surfaces: // silently stops applying at the one layer the brain cannot skip. The second case is // the same ambiguity arriving by sanitization: anything outside `[A-Za-z0-9_-]` in a // server name becomes `_`, so `my..server` would show up as `my__server`. - for (const name of ["my__server", "my..server"]) { + // A trailing `_` overlaps the separator too: `docs_` / `read` and `docs` / `_read`. + for (const name of ["my__server", "my..server", "docs_", "my_server_"]) { expect(() => loadManifest( `name: x\nbrain: {provider: mock}\nrespondTo: anyone\nsurfaces: [{kind: console}]\n` + @@ -99,7 +100,7 @@ surfaces: }); it("keeps the server names the toolkit itself generates", () => { - for (const name of ["brain", "team-brain", "brain-shared-0", "github", "surface-egress"]) { + for (const name of ["brain", "team-brain", "brain-shared-0", "github", "surface-egress", "my_server"]) { expect(() => loadManifest( `name: x\nbrain: {provider: mock}\nrespondTo: anyone\nsurfaces: [{kind: console}]\n` + diff --git a/packages/core/test/mcp-broker.test.ts b/packages/core/test/mcp-broker.test.ts index c8e5d27..e7f1e54 100644 --- a/packages/core/test/mcp-broker.test.ts +++ b/packages/core/test/mcp-broker.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, vi } from "vitest"; import type { InboundEvent } from "../src/events.ts"; import { McpBroker, TURN_META_KEY, type McpTransport } from "../src/mcp-broker.ts"; -import { loadToolPolicy, qualifyTool } from "../src/tool-policy.ts"; +import { loadToolPolicy, qualifyTool, ToolPolicy } from "../src/tool-policy.ts"; import { loadManifest } from "../src/manifest.ts"; import { SurfaceEgress } from "../src/surface-egress.ts"; import { Gateway } from "../src/gateway.ts"; @@ -111,6 +111,32 @@ describe("McpBroker policy chokepoint", () => { ); }); + it.each(["mcp__docs", "mcp__docs__*", "mcp__docs___read"])( + "does not relay a docs_ call under %s, even without manifest validation", + async (rule) => { + const f = fakeServer(); + const b = new McpBroker({ + servers: ["docs", "docs_"].map((name) => ({ + name, command: "x", args: [], secrets: {}, scope: { repo: ["acme/docs"] }, + })), + policy: new ToolPolicy([rule], []), + transport: f.transport, + }); + const docs = await b.connect("docs"); + const other = await b.connect("docs_"); + const args = { repo: "acme/docs" }; + for (const name of ["read", "_read", "__read"]) { + await expect(b.message(other, "tools/call", { name, arguments: args })) + .rejects.toThrow(/not allowlisted/); + } + expect(f.received).toHaveLength(0); + await expect(b.message(docs, "tools/call", { name: "_read", arguments: args })) + .resolves.toMatchObject({ ok: true }); + expect(f.received).toHaveLength(1); + await b.stop(); + }, + ); + it("passes non-tool methods straight through", async () => { const f = fakeServer(); const b = broker(f); @@ -398,6 +424,36 @@ describe("McpBroker live-turn stamp", () => { }); describe("McpBroker schema pinning (trust on first use)", () => { + it.each([ + [{ server: "docs", tool: "_read" }, { server: "docs_", tool: "read" }], + [{ server: "docs_", tool: "read" }, { server: "docs", tool: "_read" }], + ])("rejects colliding qualified identities discovered on %j and %j", async (first, second) => { + const f = fakeServer([{ name: first.tool }]); + const b = new McpBroker({ + servers: [first, second].map(({ server: name }) => ({ + name, command: "x", args: [], secrets: {}, + })), + policy, + transport: f.transport, + }); + const one = await b.connect(first.server); + const two = await b.connect(second.server); + await expect(b.message(one, "tools/list")).resolves.toEqual({ tools: [{ name: first.tool }] }); + // Seeing the same identity again is not a collision. + await expect(b.message(one, "tools/list")).resolves.toEqual({ tools: [{ name: first.tool }] }); + f.setTools([{ name: second.tool }]); + await expect(b.message(two, "tools/list")).rejects.toThrow(/ambiguous MCP tool identity/); + await b.stop(); + }); + + it("rejects duplicate identities in one tool list", async () => { + const f = fakeServer([{ name: "read_file" }, { name: "read_file" }]); + const b = broker(f); + const id = await b.connect("github"); + await expect(b.message(id, "tools/list")).rejects.toThrow(/ambiguous MCP tool identity/); + await b.stop(); + }); + it("passes tools through unchanged on first sight", async () => { const f = fakeServer([{ name: "mcp__github__read_file", inputSchema: { path: "string" } }]); const b = broker(f); diff --git a/packages/core/test/mcp-http.test.ts b/packages/core/test/mcp-http.test.ts index 90098ff..b58ec62 100644 --- a/packages/core/test/mcp-http.test.ts +++ b/packages/core/test/mcp-http.test.ts @@ -8,6 +8,38 @@ afterEach(async () => { }); describe("gateway MCP tool permissions", () => { + it.each(["mcp__docs", "mcp__docs__*", "mcp__docs___read"])( + "does not list or execute docs_ tools under %s", + async (rule) => { + const call = vi.fn(async () => "done"); + hosted = await serveMcp(mcpToolServer({ + name: "docs_", + tools: () => ["read", "_read", "__read"].map((name) => ({ + name, inputSchema: { type: "object" }, + })), + call, + }), { + toolPolicy: { server: "docs_", policy: new ToolPolicy([rule], []) }, + }); + const request = async (method: string, name?: string) => { + const response = await fetch(hosted!.url, { + method: "POST", + headers: { authorization: `Bearer ${hosted!.token}`, "content-type": "application/json" }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params: { name, arguments: {} } }), + }); + return response.json() as Promise<{ + result?: { tools?: { name: string }[] }; + error?: { message: string }; + }>; + }; + expect((await request("tools/list")).result?.tools).toEqual([]); + for (const name of ["read", "_read", "__read"]) { + expect((await request("tools/call", name)).error?.message).toMatch(/not allowlisted/); + } + expect(call).not.toHaveBeenCalled(); + }, + ); + it("lists only allowed tools and refuses direct calls before executing them", async () => { const call = vi.fn(async () => "done"); hosted = await serveMcp(mcpToolServer({ diff --git a/packages/core/test/tool-policy.test.ts b/packages/core/test/tool-policy.test.ts index 2954192..a676ef3 100644 --- a/packages/core/test/tool-policy.test.ts +++ b/packages/core/test/tool-policy.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from "vitest"; import { DEFAULT_SECRETS_DIR } from "../src/secrets.ts"; -import { loadToolPolicy, ToolPolicy } from "../src/tool-policy.ts"; +import { loadToolPolicy, qualifyTool, ToolPolicy } from "../src/tool-policy.ts"; const ok = { permissions: { @@ -203,6 +203,40 @@ describe("the rule language, which is Claude Code's", () => { ).toBe(false); }); + it.each(["mcp__docs", "mcp__docs__*", "mcp__docs___read"])( + "keeps %s on its actual server, even when qualified names collide", + (rule) => { + const p = policy([rule]); + expect(qualifyTool("docs", "_read")).toBe(qualifyTool("docs_", "read")); + expect(p.allowsTool({ server: "docs", tool: "_read" }).ok).toBe(true); + for (const tool of ["read", "_read", "__read"]) { + expect(p.allowsTool({ server: "docs_", tool }).ok).toBe(false); + } + }, + ); + + it.each(["mcp__docs", "mcp__docs__*", "mcp__docs___read"])( + "keeps an anchored deny %s on its actual server too", + (rule) => { + const p = policy(["mcp__docs", "mcp__docs_"], [rule]); + expect(p.allowsTool({ server: "docs", tool: "_read" }).ok).toBe(false); + expect(p.allowsTool({ server: "docs_", tool: "read" }).ok).toBe(true); + expect(policy(["mcp__docs"], ["mcp__docs_"]) + .allowsTool({ server: "docs", tool: "_read" }).ok).toBe(true); + }, + ); + + it("agrees on brain-facing and structured identities for unambiguous server names", () => { + for (const rule of ["mcp__my_server", "mcp__my_server__*", "mcp__my_server___read"]) { + const p = policy([rule], ["mcp__*__delete", "mcp__my_server__read__admin"]); + for (const server of ["my_server", "other"]) { + for (const tool of ["read", "_read", "__read", "read__admin", "delete"]) { + expect(p.allowsTool({ server, tool })).toEqual(p.allowsTool(qualifyTool(server, tool))); + } + } + } + }); + it("keeps a qualified tool rule exact, so it cannot expand into a suffixed name", () => { // Only a BARE server rule expands to a prefix. `mcp__github__pr_list` names one tool, // and MCP tool names may themselves contain the separator — so expanding it would