Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions changelog.d/mcp-pages-feedback-validation.md
Original file line number Diff line number Diff line change
@@ -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.
34 changes: 34 additions & 0 deletions services/feedback/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
25 changes: 12 additions & 13 deletions services/feedback/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ interface FeedbackScreenshot {
media_type: "image/png" | "image/jpeg";
filename: "screenshot.png" | "screenshot.jpg";
content_base64: string;
bytes: Uint8Array;
}

interface FeedbackApplication {
Expand Down Expand Up @@ -189,18 +188,18 @@ function validateDiagnostics(value: unknown): Record<string, unknown> {
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 };
Expand All @@ -212,7 +211,7 @@ function validateDiagnosticEvent(value: unknown): Record<string, unknown> {
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)) {
Expand All @@ -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<void> {
Expand Down
33 changes: 27 additions & 6 deletions services/mcp/bench/concurrent.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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 };
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -132,21 +148,26 @@ 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);
for (const run of [mixed, pages]) {
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)]);
Expand Down
9 changes: 9 additions & 0 deletions services/mcp/src/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand Down
5 changes: 4 additions & 1 deletion services/mcp/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };

Expand Down
22 changes: 22 additions & 0 deletions services/mcp/src/next-gateway.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
8 changes: 5 additions & 3 deletions services/mcp/src/next-gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export class NextGateway {
private readonly sessions = new Map<string, Promise<Session>>();
/** Opens that were dropped before they finished: their sessions are not handed out. */
private readonly dropped = new WeakSet<Promise<Session>>();
private readonly legacy = new Map<string, number>();
private readonly legacy = new Map<string, { keyHandle: string | null; expires: number }>();
/** Connections whose last hosted open used up its grace without opening. */
private readonly hostedSpent = new Set<string>();
/** By connection and mutation ID; in insertion order, so the oldest entry comes first. */
Expand All @@ -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<string, unknown>, requestId: string, signal?: AbortSignal): Promise<unknown> {
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++) {
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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);
Expand Down
12 changes: 12 additions & 0 deletions services/mcp/view/model.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
Loading