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

An MCP client with no token can initialize and list tools, and sees the five token-free ones #13899

Merged opened this

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

Merged

scout/forge:scout/13882-an-mcp-client-with-no-token-can-initiali → main 4 commits fork 1 thread · 1 unresolved

  • Merged. scout/13882-an-mcp-client-with-no-token-can-initiali was merged into main as 0fe1331.

Review

Sign in to review this change.
7 files changed +142 −6
src/http/mcp.ts +36
@@ -527,6 +527,40 @@ async function startAnswer(ctx: Ctx, id: unknown, args: Args): Promise<unknown>
527527 );
528528 }
529529
530 /**
531 * The session start a stranger may make: initialize, ping and tools/list (the token-free tools
532 * only, with their schemas), and any notification (202). Undefined for every other message, which
533 * keeps the sign-in refusal.
534 */
535 function openSession(message: unknown): Response | undefined {
536 if (typeof message !== "object" || message === null) return undefined;
537 const m = message as Record<string, unknown>;
538 if (m["jsonrpc"] !== "2.0" || typeof m["method"] !== "string") return undefined;
539 const method = m["method"];
540 if (m["id"] === undefined)
541 return method.startsWith("notifications/") ? new Response(null, { status: 202 }) : undefined;
542 const id = m["id"];
543 if (typeof id !== "string" && typeof id !== "number") return undefined;
544 const reply = (result: unknown) => json({ jsonrpc: "2.0", id, result });
545 const params =
546 typeof m["params"] === "object" && m["params"] !== null ? (m["params"] as Record<string, unknown>) : {};
547 if (method === "ping") return reply({});
548 if (method === "initialize") {
549 const asked = str(params["protocolVersion"]);
550 return reply({
551 protocolVersion: (PROTOCOLS as readonly string[]).includes(asked) ? asked : PROTOCOLS[0],
552 capabilities: { tools: {} },
553 serverInfo: server(),
554 instructions: `Without a token only ${TOKEN_FREE_TOOLS.map((n) => `\`${n}\``).join(", ")} answer; sign in and send \`Authorization: Bearer <token>\` for the rest.`,
555 });
556 }
557 if (method === "tools/list")
558 return reply({
559 tools: toolEntries(TOOLS.filter((t) => TOKEN_FREE_TOOLS.includes(t.name))),
outdated

The list is filtered by TOKEN_FREE_TOOLS twice: once on TOOLS before toEntries and again on the result. Keep one.

560 });
561 return undefined;
562 }
563
530564 const ANON_HINT = "Sign in, make a token, and send it as `Authorization: Bearer <token>`.";
531565
532566 const NOT_HERE = (allow: string): Response =>
@@ -587,6 +621,8 @@ export function mcpRoutes(router: Router<Handler>): void {
587621 const message = parsed;
588622 const reported = openToolCall(ctx, message, false);
589623 if (reported !== undefined) return json(await reported);
624 const session = ctx.request.headers.has("authorization") ? undefined : openSession(message);
625 if (session !== undefined) return session;
590626 // The refusal keeps the OAuth challenge a client starts from, and names
591627 // the one thing a stranger can do without signing in.
592628 // The same body is a JSON-RPC error: a code, one plain sentence, the sign-in URL.
test/mcp-anonymous-session.test.ts added +82
@@ -0,0 +1,82 @@
1 /**
2 * A client with no token can start an MCP session (#13882): the token-free tools and nothing more.
3 */
4 import { afterAll, beforeAll, expect, test } from "bun:test";
5 import { mkdtemp, rm } from "node:fs/promises";
6 import { tmpdir } from "node:os";
7 import { join } from "node:path";
8 import { createApp, type App } from "../src/app.ts";
9 import { serve, type Servers } from "../src/http/server.ts";
10 import { TOKEN_FREE_TOOLS } from "../src/core/mcp_card.ts";
11 import { quietLogs } from "./helpers/globals.ts";
12
13 quietLogs();
14 let dir: string, app: App, servers: Servers;
15 beforeAll(async () => {
16 dir = await mkdtemp(join(tmpdir(), "forge-mcp-anon-session-"));
17 app = createApp({ dataDir: dir, port: 0 });
18 servers = await serve(app);
19 });
20 afterAll(async () => {
21 await servers.stop();
22 await rm(dir, { recursive: true, force: true });
23 });
24
25 const post = (body: unknown) =>
26 fetch(`${servers.url}/mcp`, {
27 method: "POST",
28 headers: { "content-type": "application/json", accept: "application/json" },
29 body: JSON.stringify(body),
30 });
31
32 test("initialize, initialized, tools/list, tools/call explore, with no token", async () => {
33 const init = await post({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } });
34 expect(init.status).toBe(200);
35 const initBody = await init.json() as any;
36 expect(initBody.result.protocolVersion).toBe("2025-06-18");
37 expect(initBody.result.serverInfo.name).toBe("forge");
38
39 const note = await post({ jsonrpc: "2.0", method: "notifications/initialized" });
40 expect(note.status).toBe(202);
41
42 expect(((await (await post({ jsonrpc: "2.0", id: 2, method: "ping" })).json()) as any).result).toEqual({});
43
44 const list = (await (await post({ jsonrpc: "2.0", id: 3, method: "tools/list" })).json()) as any;
45 const names = list.result.tools.map((t: { name: string }) => t.name).sort();
46 expect(names).toEqual([...TOKEN_FREE_TOOLS].sort());
47 for (const t of list.result.tools) expect(t.inputSchema.type).toBe("object");
48
49 const call = await (
50 await post({ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "explore", arguments: {} } })
51 ).json() as any;
52 expect(call.error).toBeUndefined();
53 expect(call.result.content[0].type).toBe("text");
54 });
55
56 test("a tool that is not token-free, and any other method, still ask for sign-in", async () => {
57 for (const body of [
58 { jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "tell", arguments: {} } },
59 { jsonrpc: "2.0", id: 6, method: "resources/list" },
60 { jsonrpc: "2.0", id: 7, method: "prompts/list" },
61 ]) {
62 const res = await post(body);
63 expect(res.status).toBe(401);
64 expect(((await res.json()) as any).error.code).toBe(-32001);
65 }
66 });
67
68 test("a token that was sent and is not good is invalid_token, never the free list", async () => {
69 for (const method of ["initialize", "ping", "tools/list"]) {
70 const res = await fetch(`${servers.url}/mcp`, {
71 method: "POST",
72 headers: {
73 "content-type": "application/json",
74 accept: "application/json",
75 authorization: "Bearer forge_nonsense",
76 },
77 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method }),
78 });
79 expect(res.status).toBe(401);
80 expect(res.headers.get("www-authenticate")).toContain('error="invalid_token"');
81 }
82 });
test/mcp-discovery-walk.test.ts +1 −1
@@ -55,7 +55,7 @@ describe("an MCP client walks from nothing to a tool list", () => {
5555 accept: "application/json, text/event-stream",
5656 ...(token ? { authorization: `Bearer ${token}` } : {}),
5757 },
58 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }),
58 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: token ? "tools/list" : "resources/list" }),
5959 });
6060 const json = async (url: string, init?: RequestInit) => {
6161 const res = await fetch(url, init);
test/mcp.test.ts +20 −2
@@ -4,6 +4,7 @@
44 * action the pages call — so what a person may not do on a page they may
55 * not do here.
66 */
7 import { TOKEN_FREE_TOOLS } from "../src/core/mcp_card.ts";
78 import { READ_ONLY_REFUSAL } from "../src/http/mcp/hints.ts";
89 import { seatAs } from "./helpers/seat.ts";
910 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
@@ -143,7 +144,7 @@ describe("the forge over MCP", () => {
143144 });
144145
145146 test("a token is the only way in, and a stream is never offered", async () => {
146 const anon = await call(null, "tools/list");
147 const anon = await call(null, "resources/list");
147148 expect(anon.res.status).toBe(401);
148149 expect(anon.res.headers.get("www-authenticate")).toContain("Bearer");
149150 const get = await fetch(`${base}/mcp`, {
@@ -1117,10 +1118,27 @@ describe("the forge over MCP", () => {
11171118 const res = await fetch(`${base}/mcp`, {
11181119 method: "POST",
11191120 headers: { "content-type": "application/json", cookie, origin: base },
1120 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }),
1121 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "resources/list" }),
11211122 });
11221123 expect(res.status).toBe(401);
11231124 });
1125 test("a signed-in cookie caller is a stranger: the five token-free tools, never the full list", async () => {
1126 const signin = await fetch(`${base}/signin`, {
1127 method: "POST",
1128 redirect: "manual",
1129 headers: { "content-type": "application/x-www-form-urlencoded", origin: base },
1130 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
1131 });
1132 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
1133 const res = await fetch(`${base}/mcp`, {
1134 method: "POST",
1135 headers: { "content-type": "application/json", cookie, origin: base },
1136 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }),
1137 });
1138 expect(res.status).toBe(200);
1139 const names = ((await res.json()) as any).result.tools.map((t: { name: string }) => t.name).sort();
1140 expect(names).toEqual([...TOKEN_FREE_TOOLS].sort());
1141 });
11241142 test("limits: admins only, dry by default, an admin-scope token to change", async () => {
11251143 const key = "front.pinned_max";
11261144 const admin = createToken(app.db, alice.id, "admin", "admin").token;
test/oauth-challenge.test.ts +1 −1
@@ -46,7 +46,7 @@ describe("the bearer challenge", () => {
4646 fetch(`${servers.url}/mcp`, {
4747 method: "POST",
4848 headers: { "content-type": "application/json", ...(authorization ? { authorization } : {}) },
49 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }),
49 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "resources/list" }),
5050 });
5151 const api = (authorization?: string) =>
5252 fetch(`${servers.url}/api/v1/repos`, {
test/report-discovery.test.ts +1 −1
@@ -160,7 +160,7 @@ describe("an outside agent finds the report path unaided", () => {
160160 const refused = await rpc({
161161 jsonrpc: "2.0",
162162 id: 1,
163 method: "initialize",
163 method: "resources/list",
164164 params: { protocolVersion: "2025-06-18", capabilities: {} },
165165 });
166166 expect(refused.status).toBe(401);
test/tesla-journey.test.ts +1 −1
@@ -110,7 +110,7 @@ describe("the Tesla test: any MCP client connects with OAuth and steers", () =>
110110 });
111111
112112 test("a bare call is answered 401 pointing at the protected-resource document", async () => {
113 const res = await rpc("initialize", {});
113 const res = await rpc("resources/list", {});
114114 expect(res.status).toBe(401);
115115 const challenge = res.headers.get("www-authenticate") ?? "";
116116 expect(challenge).toMatch(/^Bearer /);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs