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

The MCP endpoint answers JSON-RPC's own errors before asking anyone to sign in: a body that is not JSON is -32700, an unknown method is -32601 #14375

Merged opened this

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

Merged

scout/forge:scout/14364-the-mcp-endpoint-answers-json-rpc-s-own → main 4 commits fork 1 thread · 1 unresolved

  • Merged. scout/14364-the-mcp-endpoint-answers-json-rpc-s-own was merged into main as 398ecca.

Review

Sign in to review this change.
3 files changed +194 −11
src/http/mcp.ts +74 −9
@@ -25,8 +25,8 @@ import type { User } from "../core/users.ts";
2525 import type { Ctx, Handler } from "./context.ts";
2626 import { running } from "../kernel/version.ts";
2727 import { bearerChallenge } from "./oauth.ts";
28 import { body, json } from "./respond.ts";
29 import { readBounded } from "./limits.ts";
28 import { BodyTooLarge, json } from "./respond.ts";
29 import { bodyCapFor, readBounded } from "./limits.ts";
3030 import { page, signInHref } from "../web/layout.ts";
3131 import { html } from "../web/html.ts";
3232 import type { Router } from "./router.ts";
@@ -580,16 +580,66 @@ export const toolRegistry = () =>
580580 plansOnly: (args: Args) => plansOnly(t, args),
581581 }));
582582
583 /** Bytes as a JSON object, or `{}` for anything else. */
584 function parseObject(bytes: Uint8Array): Record<string, unknown> {
583 /** The methods `rpcOne` answers; a test holds this to its switch. */
584 export const RPC_METHODS: readonly string[] = [
585 "initialize",
586 "ping",
587 "tools/list",
588 "resources/list",
589 "resources/templates/list",
590 "resources/read",
591 "tools/call",
592 ];
593
594 const NOT_JSON = Symbol("not json");
595
596 /** The bytes parsed once: the value, or `NOT_JSON`. */
597 function parseRpc(bytes: Uint8Array): unknown {
585598 try {
586 const value: unknown = JSON.parse(new TextDecoder().decode(bytes));
587 return typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
599 return JSON.parse(new TextDecoder().decode(bytes));
588600 } catch {
589 return {};
601 return NOT_JSON;
590602 }
591603 }
592604
605 /**
606 * JSON-RPC's own errors, said to every caller before any sign-in is asked of a stranger: a body
607 * that is not JSON (-32700), not a 2.0 request object (-32600), a method this server lacks
608 * (-32601), and, for a stranger only, a tool it lacks (-32602; the issue does not name it, but a
609 * call to a tool that does not exist cannot be helped by signing in). With a `challenge` the
610 * -32700 and -32600 answer 401 and carry it; without, they answer 200 to a caller already let in.
611 * Undefined when the message is well formed and names something that exists.
612 */
613 function rpcFault(value: unknown, challenge: Record<string, string> | undefined): Response | undefined {
614 const fail = (code: number, message: string, id: unknown, status: number) =>
615 json(
616 { jsonrpc: "2.0", id: typeof id === "string" || typeof id === "number" ? id : null, error: { code, message } },
617 challenge === undefined ? 200 : status,
618 challenge !== undefined && status === 401 ? challenge : {},
619 );
620 if (value === NOT_JSON) return fail(-32700, "Parse error: the body is not JSON", null, 401);
621 if (typeof value !== "object" || value === null || Array.isArray(value))
622 return fail(-32600, "Invalid Request: send one JSON-RPC 2.0 object", null, 401);
623 const m = value as Record<string, unknown>;
624 if (m["jsonrpc"] !== "2.0" || typeof m["method"] !== "string")
625 return fail(-32600, "Invalid Request: not a JSON-RPC 2.0 request", m["id"], 401);
626 if (m["id"] === undefined) return undefined;
627 const method = m["method"];
628 if (!RPC_METHODS.includes(method) && !method.startsWith("notifications/"))
629 return fail(-32601, `Method not found: no method ${method}`, m["id"], 200);
630 if (challenge !== undefined && method === "tools/call") {
631 const params = m["params"];
632 const name = typeof params === "object" && params !== null ? (params as Record<string, unknown>)["name"] : undefined;
633 if (typeof name !== "string" || !toolNames().includes(name))
634 return fail(-32602, `Invalid params: no tool ${typeof name === "string" ? name : "named"}`, m["id"], 200);
635 }
636 return undefined;
637 }
638
639 /** A parsed value as a JSON object, or `{}` for anything else. */
640 const asRpcObject = (value: unknown): Record<string, unknown> =>
641 typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
642
593643 export function mcpRoutes(router: Router<Handler>): void {
594644 router.add("POST", "/mcp", async (ctx) => {
595645 const user = ctx.auth.user;
@@ -598,7 +648,13 @@ export function mcpRoutes(router: Router<Handler>): void {
598648 user !== undefined &&
599649 (ctx.auth.via === "token" || ctx.auth.via === "password")
600650 ) {
601 const message: unknown = await body(ctx.request);
651 const cap = bodyCapFor(ctx.request);
652 const raw = await readBounded(ctx.request, cap);
653 if (raw === "too_large") throw new BodyTooLarge(cap);
654 const value = parseRpc(raw);
655 const fault = rpcFault(value, undefined);
656 if (fault !== undefined) return fault;
657 const message = asRpcObject(value);
602658 const reported = openToolCall(ctx, message, true);
603659 if (reported !== undefined) return json(await reported);
604660 const answer = await rpcOne(ctx, user, message);
@@ -609,7 +665,8 @@ export function mcpRoutes(router: Router<Handler>): void {
609665 // to a hard byte limit and no further.
610666 // An offer carries a patch, so it may be larger; every other call keeps the small limit.
611667 const bytes = await readBounded(ctx.request, OFFER_REQUEST_MAX);
612 const parsed = bytes === "too_large" ? {} : parseObject(bytes);
668 const value = bytes === "too_large" ? {} : parseRpc(bytes);
669 const parsed = asRpcObject(value);
613670 const params = parsed["params"];
outdated

Skipping rpcFault when authorization is present means the errors are not said "for anyone" (boxes 1 and 3). Run it for every caller, and keep invalid_token for a bad token on a real method. Test the signed-in cases.

614671 const offering =
615672 typeof params === "object" && params !== null && (params as Record<string, unknown>)["name"] === "offer";
@@ -620,6 +677,14 @@ export function mcpRoutes(router: Router<Handler>): void {
620677 413,
621678 );
622679 const message = parsed;
680 // Only a call to something that exists is told to sign in.
681 // A request that is not one keeps the 401 and the OAuth challenge a client starts from;
682 // when a token was sent the challenge says `invalid_token` (it did not get the caller in).
683 const fault = rpcFault(value, {
684 "www-authenticate": bearerChallenge(ctx.url.origin, ctx.request),
685 link: `<${ctx.url.origin}/llms.txt>; rel="service-doc"; type="text/markdown"`,
686 });
687 if (fault !== undefined) return fault;
623688 const reported = openToolCall(ctx, message, false);
624689 if (reported !== undefined) return json(await reported);
625690 const session = ctx.request.headers.has("authorization") ? undefined : openSession(message);
test/mcp-anonymous-session.test.ts +6 −2
@@ -53,11 +53,10 @@ test("initialize, initialized, tools/list, tools/call explore, with no token", a
5353 expect(call.result.content[0].type).toBe("text");
5454 });
5555
56 test("a tool that is not token-free, and any other method, still ask for sign-in", async () => {
56 test("a tool that is not token-free, and a method that needs it, still ask for sign-in", async () => {
5757 for (const body of [
5858 { jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "tell", arguments: {} } },
5959 { jsonrpc: "2.0", id: 6, method: "resources/list" },
60 { jsonrpc: "2.0", id: 7, method: "prompts/list" },
6160 ]) {
6261 const res = await post(body);
6362 expect(res.status).toBe(401);
@@ -65,6 +64,11 @@ test("a tool that is not token-free, and any other method, still ask for sign-in
6564 }
6665 });
6766
67 test("a method the server does not have is -32601, not a sign-in", async () => {
68 const res = await post({ jsonrpc: "2.0", id: 7, method: "prompts/list" });
69 expect(((await res.json()) as any).error.code).toBe(-32601);
70 });
71
6872 test("a token that was sent and is not good is invalid_token, never the free list", async () => {
6973 for (const method of ["initialize", "ping", "tools/list"]) {
7074 const res = await fetch(`${servers.url}/mcp`, {
test/mcp-rpc-errors.test.ts added +114
@@ -0,0 +1,114 @@
1 /**
2 * An anonymous POST /mcp hears JSON-RPC's own errors, not "sign in", for a request that cannot work
3 * (#14364).
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { serve, type Servers } from "../src/http/server.ts";
11 import { createToken } from "../src/core/tokens.ts";
12 import { createUser } from "../src/core/users.ts";
13 import { RPC_METHODS } from "../src/http/mcp.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15
16 quietLogs();
17 let dir: string, app: App, servers: Servers, user: string;
18 beforeAll(async () => {
19 dir = await mkdtemp(join(tmpdir(), "forge-mcp-rpc-"));
20 app = createApp({ dataDir: dir, port: 0 });
21 servers = await serve(app);
22 const u = await createUser(app.db, {
23 origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true,
24 });
25 if (!u.ok) throw new Error(u.error);
26 user = u.value.id;
27 });
28 afterAll(async () => {
29 await servers.stop();
30 await rm(dir, { recursive: true, force: true });
31 });
32
33 const post = async (body: string) => {
34 const res = await fetch(`${servers.url}/mcp`, { method: "POST", headers: { "content-type": "application/json" }, body });
35 return { res, json: JSON.parse(await res.text()) };
36 };
37
38 test("a body that is not JSON is -32700 with id null", async () => {
39 for (const body of ["not json", "", "{"]) {
40 const { res, json } = await post(body);
41 expect(json.error.code, body).toBe(-32700);
42 expect(json.id).toBeNull();
43 expect(res.headers.get("www-authenticate"), body).toContain("resource_metadata");
44 }
45 });
46
47 test("a body that is not a JSON-RPC 2.0 object is -32600", async () => {
48 for (const body of ["[]", "7", "null", '{"method":"ping"}', '{"jsonrpc":"2.0","id":1}', '{"jsonrpc":"2.0","id":1,"method":5}']) {
49 const { json } = await post(body);
50 expect(json.error.code, body).toBe(-32600);
51 }
52 });
53
54 test("an unknown method is -32601 naming it", async () => {
55 const { json } = await post('{"jsonrpc":"2.0","id":3,"method":"nope"}');
56 expect(json.error.code).toBe(-32601);
57 expect(json.error.message).toContain("nope");
58 expect(json.id).toBe(3);
59 });
60
61 test("an unknown tool is -32602; a real one that needs sign-in still says -32001", async () => {
62 const unknown = await post('{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"nothing_here"}}');
63 expect(unknown.json.error.code).toBe(-32602);
64 const real = await post('{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"tell","arguments":{}}}');
65 expect(real.res.status).toBe(401);
66 expect(real.json.error.code).toBe(-32001);
67 });
68
69 const signed = async (body: string, token: string) => {
70 const res = await fetch(`${servers.url}/mcp`, {
71 method: "POST",
72 headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
73 body,
74 });
75 return { res, json: JSON.parse(await res.text()) };
76 };
77
78 test("a stranger's -32700 and -32600 are 401 with the challenge", async () => {
79 for (const body of ["not json", "[]"]) {
80 const { res } = await post(body);
81 expect(res.status, body).toBe(401);
82 expect(res.headers.get("www-authenticate"), body).toContain("Bearer");
83 }
84 });
85
86 test("a good token hears the same JSON-RPC errors, with no challenge", async () => {
87 const mine = createToken(app.db, user, "rpc", "admin").token;
88 const bad = await signed("not json", mine);
89 expect(bad.json.error.code).toBe(-32700);
90 expect(bad.json.id).toBeNull();
91 expect(bad.res.headers.get("www-authenticate")).toBeNull();
92 expect((await signed("[]", mine)).json.error.code).toBe(-32600);
93 const unknown = await signed('{"jsonrpc":"2.0","id":8,"method":"nope"}', mine);
94 expect(unknown.json.error.code).toBe(-32601);
95 expect(unknown.json.id).toBe(8);
96 expect((await signed('{"jsonrpc":"2.0","id":9,"method":"ping"}', mine)).json.result).toEqual({});
97 });
98
99 test("a bad token hears them too, and a real method still gets invalid_token", async () => {
100 const bad = await signed("not json", "forge_nope");
101 expect(bad.json.error.code).toBe(-32700);
102 expect((await signed('{"jsonrpc":"2.0","id":8,"method":"nope"}', "forge_nope")).json.error.code).toBe(-32601);
103 const real = await signed('{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"tell","arguments":{}}}', "forge_nope");
104 expect(real.res.status).toBe(401);
105 expect(real.res.headers.get("www-authenticate")).toContain("invalid_token");
106 });
107
108 test("every method in RPC_METHODS is one the signed-in server answers", async () => {
109 const mine = createToken(app.db, user, "rpc2", "admin").token;
110 for (const method of RPC_METHODS) {
111 const { json } = await signed(JSON.stringify({ jsonrpc: "2.0", id: 1, method, params: {} }), mine);
112 expect(json.error?.code, method).not.toBe(-32601);
113 }
114 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs