Public: anyone can read this; the crew can change it.

The MCP manifest names the caller's role and lists only the tools that role may call #13477

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/13461-the-mcp-manifest-names-the-caller-s-role → main 4 commits fork 1 thread · 1 unresolved

  • Merged. mason/13461-the-mcp-manifest-names-the-caller-s-role was merged into main as 23122eb.

Review

Sign in to review this change.
4 files changed +92 −6
docs/MCP.md +2
@@ -716,3 +716,5 @@ Every 401, 403, 404, 409 and 422 JSON answer from `/api/v1` is `{ error, message
716716 ## "Next:" on a refused tool call (#12421)
717717
718718 Every refused `tools/call` text ends in `Next: …`, one step: which argument to fix, which sign-in to use, which tool to call first. A tool that has its own `Next:` keeps it; otherwise `withNextStep` (`src/http/mcp/hints.ts`) adds one from the error code and the tool's own schema, so a new tool is covered without editing. It never echoes arguments, tokens or another person's data. `test/mcp-refusal-hints.test.ts` calls every tool in `tools/list` (`all: true`, paged) with empty and bad arguments, as a member and as an admin, and the stranger's 401 and `report`/`start`.
719
720 A guest token (a person who is neither member nor admin) is listed only `report` and `offer` by default; `all: true` still pages every tool. Its `tools/list` and `initialize` name the role; the role is read on every request, so a promotion shows at once. Every other tool still answers by name, and `find_tool` shows its schema.
outdated

False against the code: a guest who sends all: true still gets every tool listed. Reword to match, or change the code.

src/http/mcp.ts +27 −6
@@ -47,7 +47,8 @@ import { type Args, alreadyDone, notAdminTool, visible, plansOnly, str, REPO_ARG
4747 import { CONVERSATION_BRIEF } from "../crew/conversation_brief.ts";
4848 import { TOOLS } from "./mcp/tools.ts";
4949 import { NO_TOOL_HINT, READ_ONLY_REFUSAL, hintOf, hintOfText, noToolNamed, withNextStep } from "./mcp/hints.ts";
50 import { DEFAULT_TOOLS, wantsAll } from "./mcp/catalog.ts";
50 import { DEFAULT_TOOLS, GUEST_TOOLS, wantsAll } from "./mcp/catalog.ts";
51 import { roleOf, type Role } from "../core/roles.ts";
5152 import { OFFER_TOOL, offerAnswer } from "./mcp/offer.ts";
5253 import { OFFER_REQUEST_MAX } from "../actions/offer.ts";
5354
@@ -80,9 +81,22 @@ export const entriesFor = (ctx: Ctx, user: User) => toolEntries(TOOLS.filter((t)
8081 // names the rest, so adding a tool never busts one response.
8182 export const TOOLS_PAGE_BYTES = 20_000;
8283
84 /**
85 * The caller's role, read from the database on every request, never kept: a promotion or a
86 * demotion shows in the next answer. Only a person is a guest; a crew agent is listed as a member.
87 */
88 export const roleHere = (ctx: Ctx, user: User): Role =>
89 user.kind === "user" ? roleOf(ctx.app.db, user) : "member";
90
8391 /** Who answers: the forge, at the version its build stamped. */
8492 const server = () => ({ name: "forge", version: running().version });
8593
94 /** The role a token acts as, and for a guest what is listed and how to reach the rest. */
95 const roleNote = (role: Role): string =>
96 role === "guest"
97 ? " This token is a guest: tools/list shows `report` and `offer`, the two doors open to a guest; `find_tool` reaches the rest."
98 : ` This token is ${role === "admin" ? "an" : "a"} ${role}.`;
99
86100 /**
87101 * Said to an MCP client whose token belongs to a site admin (#596): it acts
88102 * as admin, and the person's everyday account is where daily work belongs.
@@ -152,7 +166,7 @@ function rpcOne(
152166 : PROTOCOLS[0],
153167 capabilities: { tools: {}, resources: {} },
154168 serverInfo: server(),
155 instructions: `This is a person's forge: their apps, and the crew that builds them. \`tell\` and \`say\` are how they direct it. Keep what you relay short — three sentences and the real options. This door runs the forge (crew, apps, forges). With a shell, clone and push for repo work; \`read_file\` and \`write_file\` are for agents with none. A tool with \`dryRun\` plans unless it is \`false\`.${adminNote(ctx, user)}${hidden === "" ? "" : ` ${hidden}`}${
169 instructions: `This is a person's forge: their apps, and the crew that builds them. \`tell\` and \`say\` are how they direct it. Keep what you relay short — three sentences and the real options. This door runs the forge (crew, apps, forges). With a shell, clone and push for repo work; \`read_file\` and \`write_file\` are for agents with none. A tool with \`dryRun\` plans unless it is \`false\`.${adminNote(ctx, user)}${roleNote(roleHere(ctx, user))}${hidden === "" ? "" : ` ${hidden}`}${
156170 ctx.auth.through === undefined ? "" : ` ${CONVERSATION_BRIEF}`
157171 }`,
158172 });
@@ -163,9 +177,13 @@ function rpcOne(
163177 // By default a short list (docs/MCP.md, "Ask for less"); `all: true` is every tool, paged.
164178 const everything = wantsAll(params);
165179 const listed = entriesFor(ctx, user);
166 const all = everything
167 ? listed
168 : listed.filter((t) => DEFAULT_TOOLS.includes(t.name));
180 const role = roleHere(ctx, user);
181 const all =
182 everything
183 ? listed
184 : role === "guest"
185 ? listed.filter((t) => GUEST_TOOLS.includes(t.name))
186 : listed.filter((t) => DEFAULT_TOOLS.includes(t.name));
169187 // The cursor is the name of the last tool of the page before, so a tool
170188 // added between two requests moves nothing.
171189 const cursor = params["cursor"];
@@ -184,10 +202,13 @@ function rpcOne(
184202 end++;
185203 }
186204 const hidden = from === 0 ? hiddenAdminNote(ctx, user) : "";
205 const meta: Record<string, string> = {};
206 if (role === "guest") meta["role"] = role;
207 if (hidden !== "") meta["hidden"] = hidden;
187208 return reply({
188209 tools: all.slice(from, end),
189210 ...(end < all.length ? { nextCursor: all[end - 1]!.name } : {}),
190 ...(hidden === "" ? {} : { _meta: { hidden } }),
211 ...(Object.keys(meta).length === 0 ? {} : { _meta: meta }),
191212 });
192213 }
193214 case "resources/list":
src/http/mcp/catalog.ts +7
@@ -17,6 +17,13 @@ export const DEFAULT_TOOLS: readonly string[] = [
1717 "usage", "apps", "app_deploy", "forges", "find_tool", "report", "start",
1818 ];
1919
20 /**
21 * What a guest's manifest lists (#13461): the two doors an outsider is given, a report and an
22 * offer. Every other tool still answers by name (`find_tool` shows its schema); it is not listed to
23 * someone who could only be refused.
24 */
25 export const GUEST_TOOLS: readonly string[] = ["report", "offer"];
26
2027 export interface ToolEntry {
2128 name: string;
2229 description: string;
test/mcp-size.test.ts +56
@@ -16,6 +16,7 @@ import { join } from "node:path";
1616 import { createApp, type App } from "../src/app.ts";
1717 import { createToken } from "../src/core/tokens.ts";
1818 import { createUser } from "../src/core/users.ts";
19 import { setMember } from "../src/core/roles.ts";
1920 import { FIND_MAX, matching, WORDS_MAX } from "../src/http/mcp/catalog.ts";
2021 import { costliestTools } from "./mcp-size-rank.ts";
2122 import { serve, type Servers } from "../src/http/server.ts";
@@ -300,3 +301,58 @@ test("find_tool never returns a tool its caller cannot see; find_tool's `more` c
300301 expect(broad.tools.length).toBe(FIND_MAX);
301302 expect(broad.more).toBeGreaterThan(0);
302303 });
304
305 test("a guest's manifest names the role and lists only report and offer: a strict subset, and smaller; a promotion shows at once", async () => {
306 const made = await createUser(app.db, {
307 origin: "seed",
308 trusted: true,
309 username: "gus",
310 email: "[email protected]",
311 password: "a-good-passphrase",
312 });
313 if (!made.ok) throw new Error(made.error);
314 const gus = createToken(app.db, made.value.id, "rw", "rw").token;
315 const list = async (tok: string, all: boolean) => {
316 const res = await fetch(`${servers.url}/mcp`, {
317 method: "POST",
318 headers: { "content-type": "application/json", accept: "application/json", authorization: `Bearer ${tok}` },
319 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: all ? { all: true } : {} }),
320 });
321 const text = await res.text();
322 return { bytes: Buffer.byteLength(text), result: JSON.parse(text).result };
323 };
324 const init = async (tok: string): Promise<string> =>
325 ((
326 await (
327 await fetch(`${servers.url}/mcp`, {
328 method: "POST",
329 headers: { "content-type": "application/json", accept: "application/json", authorization: `Bearer ${tok}` },
330 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} }),
331 })
332 ).json()
333 ) as any).result.instructions;
334
335 const owner = await list(token, false);
336 const guest = await list(gus, false);
337 const names = guest.result.tools.map((t: any) => t.name).sort();
338 expect(names).toEqual(["offer", "report"]);
339 expect(guest.result.nextCursor).toBeUndefined();
340 expect(guest.result._meta.role).toBe("guest");
341 // `all: true` is not trimmed for a guest: it still pages every tool (docs/MCP.md).
342 const guestAll = await list(gus, true);
343 expect(guestAll.result.tools.length).toBeGreaterThan(2);
344 expect(guestAll.result._meta.role).toBe("guest");
345 expect(owner.result._meta?.role).toBeUndefined(); // the owner's answer stays as it was
346 const ownerAll = (await walk()).tools.map((t: any) => t.name);
347 expect(ownerAll.length).toBeGreaterThan(names.length);
348 for (const n of names) expect(ownerAll).toContain(n);
349 expect(guest.bytes).toBeLessThan(owner.bytes);
350 expect(await init(gus)).toContain("This token is a guest");
351 expect(await init(token)).toContain("This token is an admin");
352
353 // Computed per request: promoted, the next answer lists the member's tools.
354 setMember(app.db, made.value.id, true, aliceId, new Date());
355 const member = await list(gus, false);
356 expect(member.result._meta?.role).toBeUndefined();
357 expect(member.result.tools.map((t: any) => t.name)).toContain("tell");
358 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs