Files
Alan WizemannandClaude Fable 5 f3157c55fc feat(mcp): hosts can mount the MCP server per tenant with a tool allowlist
handleMcp gains an optional fourth argument, McpOptions, whose allowTools
narrows the tool set for that request. A filtered-out tool is absent from
tools/list and answers tools/call exactly as an unknown tool does (-32602,
same message) — so an allowlist leaks no evidence that the tool exists.
Omitting the option is byte-for-byte today's behavior, and the Worker's own
single-tenant mount is unchanged.

Each tool now carries an `access` class, published as MCP_TOOLS with
READ_ONLY_TOOLS / WRITE_TOOLS derived from it (all frozen). A host builds its
grant from that table instead of hard-coding names, so a release that adds a
tool cannot silently widen a grant already handed out. handleMcp and the
table are re-exported from the library entry point.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-10 20:38:00 -04:00

168 lines
7.4 KiB
TypeScript

import { describe, it, expect } from 'vitest';
import { handleMcp, MCP_TOOLS, READ_ONLY_TOOLS, WRITE_TOOLS } from '../src/mcp';
import type { McpOptions } from '../src/mcp';
import type { AgentDeps } from '../src/deps';
// A deps object that fails loudly the moment a handler touches a binding: any
// tool that actually RUNS shows up as an isError result, so "blocked" (a
// JSON-RPC error, no execution) and "dispatched" are never confusable.
const tripwire = () => {
const calls: string[] = [];
const boom = (what: string) => () => {
calls.push(what);
throw new Error(`handler ran: ${what}`);
};
const deps = {
db: { prepare: boom('db') },
overrides: { get: boom('kv'), list: boom('kv') },
draftQueue: { send: boom('queue') },
ai: { run: boom('ai') },
config: {},
secrets: {},
} as unknown as AgentDeps;
return { deps, calls };
};
const ctx = { waitUntil: () => {}, passThroughOnException: () => {} } as unknown as ExecutionContext;
async function rpc(body: unknown, options?: McpOptions) {
const { deps, calls } = tripwire();
const res = await handleMcp(
new Request('https://agent.example.com/mcp', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
}),
deps,
ctx,
options,
);
return { res, body: (await res.json()) as any, calls };
}
const listTools = async (options?: McpOptions) =>
(await rpc({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, options)).body.result.tools as { name: string }[];
// --- the metadata table hosts read instead of hard-coding names ---------------
describe('MCP_TOOLS classification', () => {
it('classifies every tool, and the two lists partition the table', () => {
expect(MCP_TOOLS.length).toBeGreaterThan(0);
expect(MCP_TOOLS.every((t) => t.access === 'read' || t.access === 'write')).toBe(true);
expect(READ_ONLY_TOOLS.length + WRITE_TOOLS.length).toBe(MCP_TOOLS.length);
expect(READ_ONLY_TOOLS.filter((n) => WRITE_TOOLS.includes(n))).toEqual([]);
});
it('keeps the site-mutating tools out of the read-only set', () => {
for (const name of ['run_pipeline', 'approve_proposal', 'reject_proposal', 'create_proposal', 'revert_change', 'dismiss_finding', 'restore_finding', 'run_citation_check']) {
expect(WRITE_TOOLS).toContain(name);
}
expect(READ_ONLY_TOOLS).toContain('seo_status');
expect(READ_ONLY_TOOLS).toContain('list_findings');
});
it('names match what tools/list advertises by default', async () => {
const advertised = (await listTools()).map((t) => t.name);
expect(advertised).toEqual(MCP_TOOLS.map((t) => t.name));
});
});
// --- default behavior: the single-tenant mount must not shift ----------------
describe('handleMcp without options', () => {
it('advertises every tool with its schema', async () => {
const tools = (await listTools()) as any[];
expect(tools.length).toBe(MCP_TOOLS.length);
expect(tools.every((t) => t.inputSchema?.type === 'object' && typeof t.description === 'string')).toBe(true);
});
it('initialize reports the tools capability and no tool names', async () => {
const { body } = await rpc({ jsonrpc: '2.0', id: 2, method: 'initialize', params: { protocolVersion: '2025-06-18' } });
expect(body.result.protocolVersion).toBe('2025-06-18');
expect(body.result.capabilities).toEqual({ tools: { listChanged: false } });
expect(JSON.stringify(body.result)).not.toContain('seo_status');
});
it('dispatches a known tool (handler runs; its failure is an isError result, not a protocol error)', async () => {
const { body, calls } = await rpc({ jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'seo_status', arguments: {} } });
expect(calls.length).toBeGreaterThan(0);
expect(body.error).toBeUndefined();
expect(body.result.isError).toBe(true);
});
it('rejects an unknown tool with -32602', async () => {
const { body } = await rpc({ jsonrpc: '2.0', id: 4, method: 'tools/call', params: { name: 'nope' } });
expect(body.error.code).toBe(-32602);
expect(body.error.message).toContain('nope');
});
it('rejects an unknown method with -32601', async () => {
const { body } = await rpc({ jsonrpc: '2.0', id: 5, method: 'resources/list' });
expect(body.error.code).toBe(-32601);
});
});
// --- the host-facing allowlist ----------------------------------------------
describe('handleMcp with allowTools', () => {
it('tools/list advertises only the allowed tools', async () => {
const names = (await listTools({ allowTools: ['seo_status', 'list_findings'] })).map((t) => t.name);
expect(names).toEqual(['seo_status', 'list_findings']);
});
it('READ_ONLY_TOOLS as an allowlist hides every write tool', async () => {
const names = (await listTools({ allowTools: READ_ONLY_TOOLS })).map((t) => t.name);
expect(names).toEqual([...READ_ONLY_TOOLS]);
for (const w of WRITE_TOOLS) expect(names).not.toContain(w);
});
it('an empty allowlist is honored — no tools at all, not "unrestricted"', async () => {
expect(await listTools({ allowTools: [] })).toEqual([]);
const { body } = await rpc({ jsonrpc: '2.0', id: 6, method: 'tools/call', params: { name: 'seo_status' } }, { allowTools: [] });
expect(body.error.code).toBe(-32602);
});
it('a disallowed tool cannot be called and its handler never runs', async () => {
const { body, calls } = await rpc(
{ jsonrpc: '2.0', id: 7, method: 'tools/call', params: { name: 'approve_proposal', arguments: { id: 1 } } },
{ allowTools: READ_ONLY_TOOLS },
);
expect(calls).toEqual([]);
expect(body.result).toBeUndefined();
expect(body.error.code).toBe(-32602);
// Indistinguishable from a tool that never existed — no existence leak.
const unknown = await rpc({ jsonrpc: '2.0', id: 7, method: 'tools/call', params: { name: 'approve_proposal' } }, { allowTools: [] });
expect(body.error.message).toBe(unknown.body.error.message);
});
it('an allowed tool still dispatches', async () => {
const { body, calls } = await rpc(
{ jsonrpc: '2.0', id: 8, method: 'tools/call', params: { name: 'seo_status', arguments: {} } },
{ allowTools: ['seo_status'] },
);
expect(calls.length).toBeGreaterThan(0);
expect(body.result.isError).toBe(true);
});
it('advertising order comes from the tool table, not the allowlist', async () => {
const names = (await listTools({ allowTools: ['list_findings', 'seo_status'] })).map((t) => t.name);
expect(names).toEqual(['seo_status', 'list_findings']);
});
it('the exported grant lists are frozen — a host cannot widen them in place', () => {
expect(Object.isFrozen(READ_ONLY_TOOLS)).toBe(true);
expect(Object.isFrozen(WRITE_TOOLS)).toBe(true);
expect(Object.isFrozen(MCP_TOOLS)).toBe(true);
expect(MCP_TOOLS.every((t) => Object.isFrozen(t))).toBe(true);
});
it('unknown names in the allowlist are ignored, not invented', async () => {
const names = (await listTools({ allowTools: ['seo_status', 'not_a_tool'] })).map((t) => t.name);
expect(names).toEqual(['seo_status']);
});
it('does not change initialize, ping, or transport-level behavior', async () => {
const init = await rpc({ jsonrpc: '2.0', id: 9, method: 'initialize', params: {} }, { allowTools: [] });
expect(init.body.result.capabilities).toEqual({ tools: { listChanged: false } });
const ping = await rpc({ jsonrpc: '2.0', id: 10, method: 'ping' }, { allowTools: [] });
expect(ping.body.result).toEqual({});
});
});