Public: anyone can read this; the crew can change it.
One log line per /mcp call: client, method, tool, status, account (#16460) #16466
Check · Review · Land · Live done — Landed and live in production.
voice/mcp-log → main 0 commits 3 threads · 3 unresolved
2 files
changed +211
−6
src/http/mcp.ts +83 −6
| @@ -817,8 +817,76 @@ function rpcFault(value: unknown, challenge: Record<string, string> | undefined) | ||
| 817 | 817 | const asRpcObject = (value: unknown): Record<string, unknown> => |
| 818 | 818 | typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : {}; |
| 819 | 819 | |
| 820 | /** What one POST /mcp asked and answered, for its log line: filled as the call is read. */ | |
| 821 | interface Seen { | |
| 822 | message?: Record<string, unknown>; | |
| 823 | answer?: unknown; | |
| 824 | /** The request was refused before it ran: not JSON-RPC, an unknown method or tool. */ | |
| 825 | fault?: boolean; | |
| 826 | } | |
| 827 | ||
| 828 | /** A field for the log: printable ASCII, bounded; undefined when absent or empty. */ | |
| 829 | const bounded = (v: unknown, max = 60): string | undefined => | |
| 830 | typeof v === "string" && v !== "" ? v.replace(/[^\x20-\x7e]/g, "?").slice(0, max) : undefined; | |
| 831 | ||
| 832 | /** | |
| 833 | * One log line per POST /mcp call: the client (the name `initialize` gives, else the user agent), | |
| 834 | * the method and tool, how it ended and whose account. Never a token, an argument or an answer's | |
| 835 | * text. | |
| 836 | */ | |
| 837 | function logMcp(ctx: Ctx, seen: Seen, response: Response | "too_large"): void { | |
| 838 | const m = seen.message ?? {}; | |
| 839 | const params = asRpcObject(m["params"]); | |
| 840 | const method = bounded(m["method"]) ?? "none"; | |
| 841 | const answer = asRpcObject(seen.answer); | |
| 842 | const result = asRpcObject(answer["result"]); | |
outdated
Four branches here ( |
||
| 843 | const first = Array.isArray(result["content"]) ? asRpcObject(result["content"][0])["text"] : undefined; | |
| 844 | const status = | |
| 845 | response === "too_large" | |
| 846 | ? "too_large" | |
| 847 | : seen.answer === undefined | |
| 848 | ? response.status >= 300 | |
| 849 | ? String(response.status) | |
| 850 | : seen.fault === true | |
outdated
|
||
| 851 | ? "error" | |
| 852 | : "ok" | |
| 853 | : answer["error"] !== undefined | |
| 854 | ? "error" | |
| 855 | : // A held call answers as an error to the agent; it is held, not refused. | |
| 856 | typeof first === "string" && first.startsWith('{"needs_confirm"') | |
| 857 | ? "held" | |
| 858 | : result["isError"] === true | |
| 859 | ? "refused" | |
| 860 | : "ok"; | |
| 861 | ctx.app.log.info("mcp call", { | |
| 862 | client: bounded(asRpcObject(params["clientInfo"])["name"]) ?? bounded(ctx.request.headers.get("user-agent")) ?? "unnamed", | |
| 863 | method, | |
| 864 | ...(method === "tools/call" ? { tool: bounded(params["name"]) ?? "unnamed" } : {}), | |
| 865 | status, | |
| 866 | account: ctx.auth.user?.username ?? "anonymous", | |
| 867 | ...(ctx.auth.through === undefined ? {} : { through: "conversation" }), | |
| 868 | }); | |
| 869 | } | |
| 870 | ||
| 820 | 871 | export function mcpRoutes(router: Router<Handler>): void { |
| 821 | 872 | router.add("POST", "/mcp", async (ctx) => { |
| 873 | const seen: Seen = {}; | |
| 874 | let response: Response; | |
| 875 | try { | |
| 876 | response = await answerMcp(ctx, seen); | |
| 877 | } catch (error) { | |
| 878 | // A body over the cap is answered by the server's error path; its line is still written. | |
| 879 | if (error instanceof BodyTooLarge) logMcp(ctx, seen, "too_large"); | |
| 880 | throw error; | |
| 881 | } | |
| 882 | logMcp(ctx, seen, response); | |
| 883 | return response; | |
| 884 | }); | |
| 885 | /** | |
| 886 | * POST /mcp: a signed-in call runs; a stranger's reaches the token-free tools or is told to sign | |
| 887 | * in. | |
| 888 | */ | |
| 889 | async function answerMcp(ctx: Ctx, seen: Seen): Promise<Response> { | |
| 822 | 890 | const user = ctx.auth.user; |
| 823 | 891 | // A token or the account's own password; never a cookie. |
| 824 | 892 | if ( |
| @@ -829,15 +897,20 @@ export function mcpRoutes(router: Router<Handler>): void { | ||
| 829 | 897 | const raw = await readBounded(ctx.request, cap); |
| 830 | 898 | if (raw === "too_large") throw new BodyTooLarge(cap); |
| 831 | 899 | const value = parseRpc(raw); |
| 832 | const fault = rpcFault(value, undefined); | |
| 833 | if (fault !== undefined) return fault; | |
| 834 | 900 | const message = asRpcObject(value); |
| 901 | seen.message = message; | |
| 902 | const fault = rpcFault(value, undefined); | |
| 903 | if (fault !== undefined) { | |
| 904 | seen.fault = true; | |
| 905 | return fault; | |
| 906 | } | |
| 835 | 907 | // A run token calls `release_keeper` here and nothing else (`http/run_gate.ts`, #15453). |
| 836 | 908 | const runRefusal = runMcpRefusal(ctx.auth, message); |
| 837 | 909 | if (runRefusal !== undefined) return runRefusal; |
| 838 | 910 | const reported = openToolCall(ctx, message, true); |
| 839 | if (reported !== undefined) return json(await reported); | |
| 911 | if (reported !== undefined) return json((seen.answer = await reported)); | |
| 840 | 912 | const answer = await rpcOne(ctx, user, message); |
| 913 | seen.answer = answer; | |
| 841 | 914 | if (answer === undefined) return new Response(null, { status: 202 }); |
| 842 | 915 | return json(answer); |
| 843 | 916 | } |
| @@ -857,6 +930,7 @@ export function mcpRoutes(router: Router<Handler>): void { | ||
| 857 | 930 | 413, |
| 858 | 931 | ); |
| 859 | 932 | const message = parsed; |
| 933 | seen.message = message; | |
| 860 | 934 | // Only a call to something that exists is told to sign in. |
| 861 | 935 | // A request that is not one keeps the 401 and the OAuth challenge a client starts from; |
| 862 | 936 | // when a token was sent the challenge says `invalid_token` (it did not get the caller in). |
| @@ -864,9 +938,12 @@ export function mcpRoutes(router: Router<Handler>): void { | ||
| 864 | 938 | "www-authenticate": bearerChallenge(ctx.url.origin, ctx.request), |
| 865 | 939 | link: `<${ctx.url.origin}/llms.txt>; rel="service-doc"; type="text/markdown"`, |
| 866 | 940 | }); |
| 867 | if (fault !== undefined) return fault; | |
| 941 | if (fault !== undefined) { | |
| 942 | seen.fault = true; | |
| 943 | return fault; | |
| 944 | } | |
| 868 | 945 | const reported = openToolCall(ctx, message, false); |
| 869 | if (reported !== undefined) return json(await reported); | |
| 946 | if (reported !== undefined) return json((seen.answer = await reported)); | |
| 870 | 947 | const session = ctx.request.headers.has("authorization") ? undefined : openSession(message); |
| 871 | 948 | if (session !== undefined) return session; |
| 872 | 949 | // The refusal keeps the OAuth challenge a client starts from, and names |
| @@ -901,7 +978,7 @@ export function mcpRoutes(router: Router<Handler>): void { | ||
| 901 | 978 | }, |
| 902 | 979 | }, |
| 903 | 980 | ); |
| 904 | }); | |
| 981 | } | |
| 905 | 982 | // No server-to-client stream is offered: nothing to hold open, nothing |
| 906 | 983 | // for a proxy to cut. |
| 907 | 984 | // A browser (Accept names text/html) is told what this is; every other |
test/mcp-call-log.test.ts added +128
| @@ -0,0 +1,128 @@ | ||
| 1 | /** | |
| 2 | * One log line per POST /mcp call: the client, the method and tool, how it ended and whose | |
| 3 | * account, so a voice client's session can be read back afterwards. Never the token, an argument | |
| 4 | * or an answer's text. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createApp, type App } from "../src/app.ts"; | |
| 11 | import { createRepo } from "../src/actions/repos.ts"; | |
| 12 | import { createToken } from "../src/core/tokens.ts"; | |
| 13 | import { mintViaToken } from "../src/core/via_token.ts"; | |
| 14 | import { createUser, type User } from "../src/core/users.ts"; | |
| 15 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 16 | import { quietLogs } from "./helpers/globals.ts"; | |
| 17 | ||
| 18 | quietLogs(); | |
| 19 | let dir: string, app: App, servers: Servers, alice: User, token: string; | |
| 20 | const SECRET_ARG = "zqx-arg-8812"; | |
| 21 | beforeAll(async () => { | |
| 22 | dir = await mkdtemp(join(tmpdir(), "forge-mcp-log-")); | |
| 23 | app = createApp({ dataDir: dir, port: 0 }); | |
| 24 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", isAdmin: true }); | |
| 25 | if (!made.ok) throw new Error(made.error); | |
| 26 | alice = made.value; | |
| 27 | const repo = await createRepo(app, alice, { name: "garden", visibility: "public" }); | |
| 28 | if (!repo.ok) throw new Error(String(repo.error)); | |
| 29 | token = createToken(app.db, alice.id, "t", "rw").token; | |
| 30 | servers = await serve(app); | |
| 31 | }); | |
| 32 | afterAll(async () => { | |
| 33 | await servers.stop(); | |
| 34 | app.close(); | |
| 35 | await rm(dir, { recursive: true, force: true }); | |
| 36 | }); | |
| 37 | ||
| 38 | /** The `mcp call` lines logged while `act` runs. */ | |
| 39 | async function logged(act: () => Promise<unknown>): Promise<Record<string, unknown>[]> { | |
| 40 | const lines: Record<string, unknown>[] = []; | |
| 41 | const was = app.log.info; | |
| 42 | app.log.info = (message, fields) => { | |
| 43 | if (message === "mcp call") lines.push(fields ?? {}); | |
| 44 | }; | |
| 45 | try { | |
| 46 | await act(); | |
| 47 | } finally { | |
| 48 | app.log.info = was; | |
| 49 | } | |
| 50 | return lines; | |
| 51 | } | |
| 52 | ||
| 53 | const rpc = (body: unknown, headers: Record<string, string> = {}) => | |
| 54 | fetch(`${servers.url}/mcp`, { | |
| 55 | method: "POST", | |
| 56 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...headers }, | |
| 57 | body: JSON.stringify(body), | |
| 58 | }); | |
| 59 | ||
| 60 | test("initialize, a read, a refusal and a stranger's call each log one line: client, tool, status, account", async () => { | |
| 61 | const auth = { authorization: `Bearer ${token}`, "user-agent": "Grok/1.0" }; | |
| 62 | const lines = await logged(async () => { | |
| 63 | await rpc({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", clientInfo: { name: "grok-voice", version: "1" }, capabilities: {} } }, auth); | |
| 64 | await rpc({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "repo", arguments: { repo: "alice/garden" } } }, auth); | |
| 65 | await rpc({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "repo", arguments: { repo: `alice/${SECRET_ARG}` } } }, auth); | |
| 66 | await rpc({ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "repo", arguments: {} } }, { "user-agent": "curl/8" }); | |
| 67 | }); | |
| 68 | expect(lines).toEqual([ | |
| 69 | { client: "grok-voice", method: "initialize", status: "ok", account: "alice" }, | |
| 70 | { client: "Grok/1.0", method: "tools/call", tool: "repo", status: "ok", account: "alice" }, | |
| 71 | { client: "Grok/1.0", method: "tools/call", tool: "repo", status: "refused", account: "alice" }, | |
| 72 | { client: "curl/8", method: "tools/call", tool: "repo", status: "401", account: "anonymous" }, | |
| 73 | ]); | |
| 74 | const text = JSON.stringify(lines); | |
| 75 | expect(text).not.toContain(token); | |
| 76 | expect(text).not.toContain(SECRET_ARG); | |
| 77 | }); | |
| 78 | ||
| 79 | test("a held write, a JSON-RPC error, a notification and a call through a conversation each say so", async () => { | |
| 80 | if (!(await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" })).ok) throw new Error("bob"); | |
| 81 | const via = mintViaToken(app.db, alice.id, "conversation:c1", "", new Date(Date.now() + 600_000).toISOString()); | |
| 82 | if (!via.ok) throw new Error(via.error); | |
| 83 | const auth = { authorization: `Bearer ${token}` }; | |
| 84 | const lines = await logged(async () => { | |
| 85 | // Making someone a contributor always asks first: held. | |
| 86 | await rpc({ jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "invite", arguments: { repo: "alice/garden", who: "bob" } } }, { authorization: `Bearer ${via.value.token}` }); | |
| 87 | await rpc({ jsonrpc: "2.0", id: 6, method: "tools/call", params: { name: "no_such_tool", arguments: {} } }, auth); | |
| 88 | await rpc({ jsonrpc: "2.0", id: 7, method: "no/such/method" }, auth); | |
| 89 | await rpc({ jsonrpc: "2.0", method: "notifications/initialized" }, auth); | |
| 90 | }); | |
| 91 | expect(lines.map((l) => [l["method"], l["tool"], l["status"], l["through"]])).toEqual([ | |
| 92 | ["tools/call", "invite", "held", "conversation"], | |
| 93 | ["tools/call", "no_such_tool", "error", undefined], | |
| 94 | ["no/such/method", undefined, "error", undefined], | |
| 95 | ["notifications/initialized", undefined, "ok", undefined], | |
| 96 | ]); | |
| 97 | }); | |
| 98 | ||
| 99 | test("a body that is not JSON-RPC, or over the cap, still logs its line, with no method", async () => { | |
| 100 | const auth = { authorization: `Bearer ${token}` }; | |
| 101 | const lines = await logged(async () => { | |
| 102 | await fetch(`${servers.url}/mcp`, { method: "POST", headers: { "content-type": "application/json", ...auth }, body: "{not json" }); | |
| 103 | await fetch(`${servers.url}/mcp`, { method: "POST", headers: { "content-type": "application/json" }, body: "x".repeat(70 * 1024) }); | |
| 104 | await fetch(`${servers.url}/mcp`, { method: "POST", headers: { "content-type": "application/json", ...auth }, body: "x".repeat(17 * 1024 * 1024) }); | |
| 105 | }); | |
| 106 | expect(lines.map((l) => [l["method"], l["status"], l["account"]])).toEqual([ | |
| 107 | ["none", "error", "alice"], | |
| 108 | ["none", "413", "anonymous"], | |
| 109 | ["none", "too_large", "alice"], | |
| 110 | ]); | |
| 111 | }); | |
| 112 | ||
| 113 | test("a hostile client name or user agent is logged printable and bounded", async () => { | |
| 114 | const lines = await logged(async () => { | |
| 115 | await rpc( | |
| 116 | { jsonrpc: "2.0", id: 8, method: "initialize", params: { protocolVersion: "2025-06-18", clientInfo: { name: `evil\nmcp call account=admin\u0007${"y".repeat(200)}` }, capabilities: {} } }, | |
| 117 | { authorization: `Bearer ${token}` }, | |
| 118 | ); | |
| 119 | await rpc({ jsonrpc: "2.0", id: 9, method: "tools/list" }, { authorization: `Bearer ${token}`, "user-agent": `ua\t${"z".repeat(200)}` }); | |
| 120 | }); | |
| 121 | const [named, agent] = lines.map((l) => String(l["client"])); | |
| 122 | for (const c of [named!, agent!]) { | |
| 123 | expect(c.length).toBeLessThanOrEqual(60); | |
| 124 | expect(c).toMatch(/^[\x20-\x7e]+$/); | |
| 125 | } | |
| 126 | expect(named).toStartWith("evil?mcp call account=admin?"); | |
| 127 | expect(agent).toStartWith("ua?z"); | |
| 128 | }); |
new above
offline
boundedis what keeps client-written text out of the log as control characters. Add a test with newline, control bytes and a name longer than 60 chars.