Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<id> missed_event=<id>` warning when one channel's
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -2804,7 +2804,7 @@ async function doctorCmd(argv: string[]): Promise<boolean> {
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(
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,11 @@ const ServerName = z
(name) => !name.includes("__"),
"a doubled underscore separates server from tool in `mcp__<server>__<tool>`, 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__<server>__<tool>` and can " +
"collide with another server's tools — end the server name with a letter, number, or `-`",
);

export const McpServerSchema = z
Expand Down
24 changes: 19 additions & 5 deletions packages/core/src/mcp-broker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ export interface McpBrokerOptions {
export class McpBroker {
private connections = new Map<string, { server: McpServerConfig; conn: McpConnection }>();
private pinnedSchemas = new Map<string, string>();
private qualifiedServers = new Map<string, string>();
private nextId = 0;

constructor(private opts: McpBrokerOptions) {}
Expand Down Expand Up @@ -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__<server>__<tool>`. 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<string, unknown> } | 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 ?? {};

Expand All @@ -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}`);
Expand Down Expand Up @@ -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<string>();
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");
Expand Down
11 changes: 7 additions & 4 deletions packages/core/src/mcp-http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> },
{
tool: qualifyTool(identity.server, identity.tool),
args: (msg.params?.arguments ?? {}) as Record<string, unknown>,
},
async () => { throw new ToolRefused(verdict.reason); },
);
}
Expand All @@ -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;
Expand Down
77 changes: 48 additions & 29 deletions packages/core/src/tool-policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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__<server>__<tool>`. 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}`;
Expand All @@ -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__<server>`, with nothing after the server segment.
*
* Only a bare one expands to a prefix. A qualified `mcp__<server>__<tool>` 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];
Expand Down Expand Up @@ -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` };
}
}

Expand All @@ -196,7 +204,8 @@ export class ToolPolicy {
*
* - `mcp__<server>` covers every tool that server provides;
* - `mcp__<server>__<tool>` 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
Expand All @@ -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__<server>` 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);
}
Expand Down
5 changes: 3 additions & 2 deletions packages/core/test/manifest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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` +
Expand All @@ -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` +
Expand Down
58 changes: 57 additions & 1 deletion packages/core/test/mcp-broker.test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down
32 changes: 32 additions & 0 deletions packages/core/test/mcp-http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
Loading