From 20946d58b26b688ea9985b083c5fd04bf2c390c1 Mon Sep 17 00:00:00 2001 From: mdbase release automation Date: Sun, 29 Nov 2026 01:16:32 +1100 Subject: [PATCH] Reduce MCP query view allocations and tighten feedback validation --- changelog.d/mcp-pages-feedback-validation.md | 4 +++ services/feedback/src/index.test.ts | 34 ++++++++++++++++++++ services/feedback/src/index.ts | 25 +++++++------- services/mcp/bench/concurrent.mjs | 33 +++++++++++++++---- services/mcp/src/app.test.ts | 9 ++++++ services/mcp/src/app.ts | 5 ++- services/mcp/src/next-gateway.test.ts | 22 +++++++++++++ services/mcp/src/next-gateway.ts | 8 +++-- services/mcp/view/model.test.ts | 12 +++++++ services/mcp/view/model.ts | 27 +++++++++------- 10 files changed, 145 insertions(+), 34 deletions(-) create mode 100644 changelog.d/mcp-pages-feedback-validation.md diff --git a/changelog.d/mcp-pages-feedback-validation.md b/changelog.d/mcp-pages-feedback-validation.md new file mode 100644 index 000000000..1ab6f8176 --- /dev/null +++ b/changelog.d/mcp-pages-feedback-validation.md @@ -0,0 +1,4 @@ +## Fixed + +- Reduce allocations when preparing paginated MCP query results for the collection view. Rediscover routes after replacing a connection and close replica sessions on gateway shutdown. +- Reject incorrectly typed legacy feedback diagnostics and reduce temporary memory used to decode screenshots. diff --git a/services/feedback/src/index.test.ts b/services/feedback/src/index.test.ts index 35819ce1b..4218dfafb 100644 --- a/services/feedback/src/index.test.ts +++ b/services/feedback/src/index.test.ts @@ -207,6 +207,40 @@ describe("feedback Worker", () => { expect(await oversized.json()).toMatchObject({ error: { code: "invalid_screenshot" } }); }); + it("delivers a screenshot at the three MiB limit and rejects one extra byte", async () => { + const jpeg = atob(ONE_PIXEL_JPEG_BASE64); + const provider = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => Response.json({ id: "email" })); + const worker = createFeedbackWorker(provider); + for (const extra of [0, 1]) { + // JPEG permits fill bytes before a marker. The empty comment is stripped on delivery. + const comment = "\xff".repeat(3 * 1024 * 1024 + extra - jpeg.length - 3) + "\xfe\x00\x02"; + const content = btoa(jpeg.slice(0, 2) + comment + jpeg.slice(2)); + const response = await worker.fetch(request(submission({ + screenshot: { media_type: "image/jpeg", filename: "screenshot.jpg", content_base64: content } + })), env); + expect(response.status).toBe(extra === 0 ? 202 : 400); + if (extra) expect(await response.json()).toMatchObject({ error: { code: "invalid_screenshot" } }); + } + expect(provider).toHaveBeenCalledOnce(); + const email = JSON.parse(String(provider.mock.calls[0][1]?.body)); + expect(email.attachments[0].content).toBe(ONE_PIXEL_JPEG_BASE64); + }); + + it.each([ + { source_view: ["applications"] }, + { build_revision: 123 }, + { environment: ["production"] }, + { viewport: ["wide"] }, + { events: [{ ...submission().diagnostics.events[0], code: ["http_error"] }] } + ])("rejects non-string legacy diagnostic fields before delivery (%j)", async (fields) => { + const provider = vi.fn(); + const diagnostics = { ...submission().diagnostics, ...fields }; + const response = await createFeedbackWorker(provider).fetch(request(submission({ diagnostics })), env); + expect(response.status).toBe(400); + expect(await response.json()).toMatchObject({ error: { code: "invalid_diagnostics" } }); + expect(provider).not.toHaveBeenCalled(); + }); + it("does not expose provider response details", async () => { const provider = vi.fn(async () => new Response("mailbox and provider details", { status: 500 })); const response = await createFeedbackWorker(provider).fetch(request(), env); diff --git a/services/feedback/src/index.ts b/services/feedback/src/index.ts index 4b9638381..b87571e8d 100644 --- a/services/feedback/src/index.ts +++ b/services/feedback/src/index.ts @@ -18,7 +18,6 @@ interface FeedbackScreenshot { media_type: "image/png" | "image/jpeg"; filename: "screenshot.png" | "screenshot.jpg"; content_base64: string; - bytes: Uint8Array; } interface FeedbackApplication { @@ -189,18 +188,18 @@ function validateDiagnostics(value: unknown): Record { if (input.schema_version !== 1 || input.product !== "mdbase editor" || input.surface !== "connect") { throw new RequestError(400, "invalid_diagnostics", "The diagnostic format is invalid."); } - if (!["overview", "storage", "access", "collections", "applications", "computers", "account", "feedback"].includes(String(input.source_view))) { + if (typeof input.source_view !== "string" || !["overview", "storage", "access", "collections", "applications", "computers", "account", "feedback"].includes(input.source_view)) { throw new RequestError(400, "invalid_diagnostics", "The diagnostic source is invalid."); } - if (input.build_revision !== null && input.build_revision !== undefined && !/^[a-zA-Z0-9._-]{1,64}$/u.test(String(input.build_revision))) { + if (input.build_revision !== null && input.build_revision !== undefined && (typeof input.build_revision !== "string" || !/^[a-zA-Z0-9._-]{1,64}$/u.test(input.build_revision))) { throw new RequestError(400, "invalid_diagnostics", "The diagnostic revision is invalid."); } - if (!["production", "staging", "development"].includes(String(input.environment))) throw new RequestError(400, "invalid_diagnostics", "The diagnostic environment is invalid."); + if (typeof input.environment !== "string" || !["production", "staging", "development"].includes(input.environment)) throw new RequestError(400, "invalid_diagnostics", "The diagnostic environment is invalid."); const browser = text(input.browser, "browser", 40); const operatingSystem = text(input.operating_system, "operating_system", 20); if (!/^(?:Edge|Firefox|Chrome|Safari) (?:\d+|unknown)$|^Other$/u.test(browser)) throw new RequestError(400, "invalid_diagnostics", "The diagnostic browser is invalid."); if (!["Windows", "macOS", "Android", "iOS", "Linux", "Other"].includes(operatingSystem)) throw new RequestError(400, "invalid_diagnostics", "The diagnostic operating system is invalid."); - if (!["compact", "medium", "wide"].includes(String(input.viewport))) throw new RequestError(400, "invalid_diagnostics", "The diagnostic viewport is invalid."); + if (typeof input.viewport !== "string" || !["compact", "medium", "wide"].includes(input.viewport)) throw new RequestError(400, "invalid_diagnostics", "The diagnostic viewport is invalid."); if (!Array.isArray(input.events) || input.events.length > MAX_DIAGNOSTIC_EVENTS) throw new RequestError(400, "invalid_diagnostics", "The diagnostic events are invalid."); const events = input.events.map(validateDiagnosticEvent); return { ...input, browser, operating_system: operatingSystem, events }; @@ -212,7 +211,7 @@ function validateDiagnosticEvent(value: unknown): Record { const at = text(event.at, "diagnostic event time", 40); if (!Number.isFinite(Date.parse(at))) throw new RequestError(400, "invalid_diagnostics", "A diagnostic event time is invalid."); if (event.event !== "management_request_failed" && event.event !== "management_refresh_failed") throw new RequestError(400, "invalid_diagnostics", "A diagnostic event name is invalid."); - if (!["cancelled", "http_error", "invalid_response", "outcome_unknown", "partial_failure", "timeout", "network_error", "unknown_error"].includes(String(event.code))) { + if (typeof event.code !== "string" || !["cancelled", "http_error", "invalid_response", "outcome_unknown", "partial_failure", "timeout", "network_error", "unknown_error"].includes(event.code)) { throw new RequestError(400, "invalid_diagnostics", "A diagnostic event code is invalid."); } if (event.status !== undefined && (!Number.isInteger(event.status) || Number(event.status) < 0 || Number(event.status) > 599)) { @@ -228,20 +227,20 @@ function validateScreenshot(value: unknown): FeedbackScreenshot { const expectedFilename = input.media_type === "image/png" ? "screenshot.png" : "screenshot.jpg"; if (input.filename !== expectedFilename) throw new RequestError(400, "invalid_screenshot", "The screenshot filename is invalid."); if (typeof input.content_base64 !== "string") throw new RequestError(400, "invalid_screenshot", "The screenshot encoding is invalid."); - if (input.content_base64.length > 4_200_000) throw new RequestError(400, "invalid_screenshot", "The screenshot is invalid or too large."); + if (input.content_base64.length > 4 * Math.ceil(MAX_SCREENSHOT_BYTES / 3)) throw new RequestError(400, "invalid_screenshot", "The screenshot is invalid or too large."); const content = input.content_base64; if (!/^[a-zA-Z0-9+/]*={0,2}$/u.test(content)) throw new RequestError(400, "invalid_screenshot", "The screenshot encoding is invalid."); - let bytes: Uint8Array; - try { bytes = Uint8Array.from(atob(content), (character) => character.charCodeAt(0)); } catch { throw new RequestError(400, "invalid_screenshot", "The screenshot encoding is invalid."); } - if (bytes.byteLength > MAX_SCREENSHOT_BYTES) { - throw new RequestError(400, "invalid_screenshot", "The screenshot is invalid or too large."); - } + let binary: string; + try { binary = atob(content); } catch { throw new RequestError(400, "invalid_screenshot", "The screenshot encoding is invalid."); } + if (binary.length > MAX_SCREENSHOT_BYTES) throw new RequestError(400, "invalid_screenshot", "The screenshot is invalid or too large."); + const bytes = new Uint8Array(binary.length); + for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index); const sanitized = sanitizeRaster(bytes, input.media_type); if (!sanitized) { throw new RequestError(400, "invalid_screenshot", "The screenshot is invalid or too large."); } const contentBase64 = sanitized === bytes ? content : bytesToBase64(sanitized); - return { media_type: input.media_type, filename: expectedFilename, content_base64: contentBase64, bytes: sanitized }; + return { media_type: input.media_type, filename: expectedFilename, content_base64: contentBase64 }; } async function verifyTurnstile(fetchImpl: typeof fetch, secret: string, token: string | undefined, origin: string): Promise { diff --git a/services/mcp/bench/concurrent.mjs b/services/mcp/bench/concurrent.mjs index bead1d4d6..bc8c6e045 100644 --- a/services/mcp/bench/concurrent.mjs +++ b/services/mcp/bench/concurrent.mjs @@ -7,6 +7,11 @@ import { createDatabase } from "../src/db.ts"; import { SecretBox, tokenHash } from "../src/security.ts"; import { PostgresGrantKeyStore } from "../src/key-store.ts"; +// --view-sample measures the host consuming the query result as well as the gateway. +import { shownResult, typeOfResults } from "../view/model.ts"; +const viewSample = process.argv.includes("--view-sample"); +let viewMs = 0; + const db = await createDatabase("memory"); const masterKey = new SecretBox(Buffer.alloc(32, 7)); const resource = "https://mcp.example/mcp"; @@ -35,7 +40,7 @@ globalThis.fetch = async (url, options) => { const { input, request_id, protocol_version } = JSON.parse(options.body); let result; if (path.endsWith("/query")) { - result = { results: queryRows.slice(input.offset, input.offset + input.limit) }; + result = { results: queryRows.slice(input.offset, input.offset + input.limit), ...(viewSample ? { meta: { total_count: queryRows.length } } : {}) }; } else if (path.endsWith("/create")) { assert.ok(!records.has(input.path)); result = { path: input.path, frontmatter: input.frontmatter }; @@ -92,7 +97,18 @@ async function call(client, name, args, { status = 200, errorCode } = {}) { return; } assert.ok(rpc.result && !rpc.result.isError, response.body.slice(0, 200)); - if (name === "query_records") assert.equal(rpc.result.structuredContent.results.length, Math.min(args.limit, queryRows.length - args.offset)); + if (name === "query_records") { + assert.equal(rpc.result.structuredContent.results.length, Math.min(args.limit, queryRows.length - args.offset)); + if (viewSample) { + const start = performance.now(); + const shown = shownResult(rpc.result, args); + const type = typeOfResults(args, shown.rows); + viewMs += performance.now() - start; + assert.equal(type, "note"); + assert.equal(shown.rows.length, rpc.result.structuredContent.results.length); + assert.equal(shown.columns.length, 6); + } + } } async function mixed() { @@ -132,7 +148,9 @@ try { for (const size of [32, 10_000]) { queryRows = Array.from({ length: size }, (_, i) => ({ path: `notes/${i}.md`, revision: `rev-${i}`, types: ["note"], - frontmatter: { title: `Sample note ${i}`, tags: ["work", "benchmark"] }, body: "Collection record. ".repeat(8) + frontmatter: { title: `Sample note ${i}`, tags: ["work", "benchmark"], ...(viewSample ? { + status: "open", priority: 2, owner: "team", project: "notes", category: "work", order: i + } : {}) }, body: "Collection record. ".repeat(8) })); records.clear(); for (const row of queryRows) records.set(row.path, row); @@ -140,13 +158,16 @@ try { for (let i = 0; i < 3; i++) await run(); const times = []; const allocations = []; - for (let i = 0; i < 21; i++) { + let timedViewMs; + for (let i = 0; i < (viewSample ? 1 : 21); i++) { + viewMs = 0; const start = performance.now(); await run(); times.push(performance.now() - start); + timedViewMs = viewMs; } - for (let i = 0; i < 11; i++) allocations.push(await sampleAllocation(run)); - console.log(JSON.stringify({ size, workload: run.name, batchMs: summary(times), sampledMiB: summary(allocations) })); + for (let i = 0; i < (viewSample ? 1 : 11); i++) allocations.push(await sampleAllocation(run)); + console.log(JSON.stringify({ size, workload: run.name, batchMs: summary(times), sampledMiB: summary(allocations), ...(viewSample ? { viewMs: timedViewMs } : {}) })); } } await db.query("UPDATE mcp_access_tokens SET revoked_at = now() WHERE token_hash = $1", [tokenHash(clients[0].bearer)]); diff --git a/services/mcp/src/app.test.ts b/services/mcp/src/app.test.ts index a493c25d5..76d0b8430 100644 --- a/services/mcp/src/app.test.ts +++ b/services/mcp/src/app.test.ts @@ -35,6 +35,15 @@ const secondGrantId = "30000000-0000-4000-8000-000000000002"; afterEach(() => vi.restoreAllMocks()); describe("mdbase MCP gateway", () => { + it("closes replica sessions when the app shuts down", async () => { + const db = await createDatabase("memory"); + const { app, gateway } = await buildApp({ db, config: testConfig(), view: TEST_VIEW }); + const close = vi.spyOn(gateway.next, "close"); + await app.close(); + expect(close).toHaveBeenCalledOnce(); + await db.end(); + }); + it("publishes OAuth metadata and challenges unauthenticated MCP requests", async () => { const db = await createDatabase("memory"); const { app } = await buildApp({ db, config: testConfig(), view: TEST_VIEW }); diff --git a/services/mcp/src/app.ts b/services/mcp/src/app.ts index 2a98a19f7..5ad062840 100644 --- a/services/mcp/src/app.ts +++ b/services/mcp/src/app.ts @@ -68,7 +68,10 @@ export async function buildApp(options: BuildOptions) { oauth.pruneExpiredState().catch((error) => app.log.error({ err: error }, "MCP OAuth state pruning failed")); }, 5 * 60_000); pruning.unref(); - app.addHook("onClose", async () => clearInterval(pruning)); + app.addHook("onClose", async () => { + clearInterval(pruning); + gateway.next.close(); + }); const resourceMetadataUrl = `${config.publicUrl}/.well-known/oauth-protected-resource/mcp`; const view = { html: viewPage(options.view, config.publicUrl), origin: config.publicUrl }; diff --git a/services/mcp/src/next-gateway.test.ts b/services/mcp/src/next-gateway.test.ts index b9125ec37..271962033 100644 --- a/services/mcp/src/next-gateway.test.ts +++ b/services/mcp/src/next-gateway.test.ts @@ -53,6 +53,28 @@ describe("NextGateway", () => { expect(setup.open).not.toHaveBeenCalled(); }); + it("discovers a replacement connection immediately after dropping its legacy route", async () => { + const setup = await fixture([{ status: 404, body: {} }, routed], 200, true); + expect(await setup.gateway.run(connection, "access", "query", {}, "first")).toBe(LEGACY); + setup.gateway.drop(connection.id); + await expect(setup.gateway.run(connection, "renewed", "query", {}, "second")) + .resolves.toEqual({ results: [], meta: { has_more: false } }); + expect(setup.open).toHaveBeenCalledOnce(); + setup.gateway.close(); + }); + + it("ignores a legacy lookup that completed after a key replacement", async () => { + const setup = await fixture([{ status: 404, body: {} }, routed], 200, true); + const old = setup.gateway.run(connection, "access", "query", {}, "first"); + setup.gateway.drop(connection.id); + expect(await old).toBe(LEGACY); + const renewed = { ...connection, key_handle: "gk-2" }; + await expect(setup.gateway.run(renewed, "renewed", "query", {}, "second")) + .resolves.toEqual({ results: [], meta: { has_more: false } }); + expect(setup.calls).toHaveLength(2); + setup.gateway.close(); + }); + it("ignores cached legacy routing for a native connection", async () => { const setup = await fixture([{ status: 404, body: {} }, { status: 200, body: { collection: "col-1", grant: grantId, targets: [] } }]); expect(await setup.gateway.run(connection, "access", "query", {}, "req-1")).toBe(LEGACY); diff --git a/services/mcp/src/next-gateway.ts b/services/mcp/src/next-gateway.ts index e83f2b26d..647da5a05 100644 --- a/services/mcp/src/next-gateway.ts +++ b/services/mcp/src/next-gateway.ts @@ -70,7 +70,7 @@ export class NextGateway { private readonly sessions = new Map>(); /** Opens that were dropped before they finished: their sessions are not handed out. */ private readonly dropped = new WeakSet>(); - private readonly legacy = new Map(); + private readonly legacy = new Map(); /** Connections whose last hosted open used up its grace without opening. */ private readonly hostedSpent = new Set(); /** By connection and mutation ID; in insertion order, so the oldest entry comes first. */ @@ -93,7 +93,8 @@ export class NextGateway { /** Run one tool operation on next, or return LEGACY. */ async run(connection: NextConnection, accessToken: string, operation: string, input: Record, requestId: string, signal?: AbortSignal): Promise { - if (!connection.native && (this.legacy.get(connection.id) ?? 0) > this.now()) return LEGACY; + const cached = this.legacy.get(connection.id); + if (!connection.native && cached && cached.keyHandle === connection.key_handle && cached.expires > this.now()) return LEGACY; const started = this.now(); const memo = operation === "create" || operation === "rename" ? this.memo(`${connection.id}:${requestId}`) : NO_MEMO; for (let retry = 0; ; retry++) { @@ -150,7 +151,7 @@ export class NextGateway { } const route = await this.route(connection, accessToken, true, signal); if (route === LEGACY) { - this.legacy.set(connection.id, this.now() + LEGACY_TTL_MS); + this.legacy.set(connection.id, { keyHandle: connection.key_handle, expires: this.now() + LEGACY_TTL_MS }); return LEGACY; } // Another call may have opened one while Connect answered. @@ -294,6 +295,7 @@ export class NextGateway { /** Close whatever session the connection has. */ drop(id: string): void { + this.legacy.delete(id); const session = this.sessions.get(id); if (!session) return; this.sessions.delete(id); diff --git a/services/mcp/view/model.test.ts b/services/mcp/view/model.test.ts index 8c02b70ea..871be4400 100644 --- a/services/mcp/view/model.test.ts +++ b/services/mcp/view/model.test.ts @@ -41,6 +41,18 @@ describe("what a tool result shows", () => { expect((shown as Records).rows.map((row) => [row.name, row.cells.status])).toEqual([["renew-passport", "open"], ["b", "done"]]); }); + it("keeps the first six distinct implicit fields across valid rows", () => { + const rows = [ + null, { frontmatter: { ignored: true } }, + { path: "one.md", frontmatter: { title: "One", a: 1, b: 2 } }, + { path: "two.md", frontmatter: { b: 3, c: 4, d: 5, e: 6, f: 7, g: 8 } }, + { path: "three.md", frontmatter: { h: 9 } } + ]; + const shown = shownResult({ structuredContent: { results: rows, meta: {} } }) as Records; + expect(shown.rows.map(row => row.path)).toEqual(["one.md", "two.md", "three.md"]); + expect(shown.columns.map(column => column.key)).toEqual(["a", "b", "c", "d", "e", "f"]); + }); + it("takes selected columns' values from the query's values, labelled as the query labels them", () => { const shown = shownResult({ structuredContent: { diff --git a/services/mcp/view/model.ts b/services/mcp/view/model.ts index 5766f87e0..51be2cc51 100644 --- a/services/mcp/view/model.ts +++ b/services/mcp/view/model.ts @@ -158,8 +158,8 @@ export function rowOf(record: RecordDocument, columns: readonly Column[]): Row { export function typeOfResults(args: Json, rows: readonly Row[]): string | undefined { const asked = stringList(args.types); if (asked.length) return asked.length === 1 ? asked[0] : undefined; - const held = unique(rows.flatMap((row) => row.types)); - return held.length === 1 && rows.every((row) => row.types.length === 1) ? held[0] : undefined; + const first = rows[0]?.types[0]; + return rows.every((row) => row.types.length === 1 && row.types[0] === first) ? first : undefined; } /** A task line's text, without its bullet and box. */ @@ -184,23 +184,28 @@ function queryResult(results: unknown[], meta: Json, args: Json): Records | Grou const keys = unique(groups.flatMap((group) => [...Object.keys(group.values), ...Object.keys(group.summaries)])); return { kind: "groups", groups, columns: keys.map((key) => ({ key, label: key, field: false })) }; } - const rows = results.filter(isObject).flatMap((result): Row[] => { - if (typeof result.path !== "string") return []; + const rows: Row[] = []; + const implicit = new Set(); + for (const result of results) { + if (!isObject(result) || typeof result.path !== "string") continue; const frontmatter = isObject(result.frontmatter) ? result.frontmatter : {}; const values = isObject(result.values) ? result.values : {}; - return [{ + if (!selected && implicit.size < IMPLICIT_COLUMNS) { + for (const key of Object.keys(frontmatter)) { + if (key !== "title") implicit.add(key); + if (implicit.size === IMPLICIT_COLUMNS) break; + } + } + rows.push({ path: result.path, revision: typeof result.revision === "string" ? result.revision : undefined, name: fileName(result), types: stringList(result.types), frontmatter, cells: selected ? Object.fromEntries(selected.map((column) => [column.key, values[column.key] ?? frontmatter[column.key]])) : frontmatter, - }]; - }); - const columns = selected ?? unique(rows.flatMap((row) => Object.keys(row.frontmatter))) - .filter((key) => key !== "title") - .slice(0, IMPLICIT_COLUMNS) - .map((key) => ({ key, label: key, field: true })); + }); + } + const columns = selected ?? Array.from(implicit, (key) => ({ key, label: key, field: true })); return { kind: "records", rows,