Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

feat(mcp): implement tool discovery and enhance MCP server

Amruth Pillai70399d7792b5
diff --git a/apps/server/src/http/app.ts b/apps/server/src/http/app.ts
index b36b15968..b0fdc904e 100644
--- a/apps/server/src/http/app.ts
+++ b/apps/server/src/http/app.ts
@@ -8,6 +8,7 @@ import { bodyLimit } from "hono/body-limit";
import { compress } from "hono/compress";
import { prepareStagedBody, withStagedBody } from "@reactive-resume/api/features/storage/transport";
import { env } from "@reactive-resume/env/server";
+import { prepareMcpDiscovery } from "@reactive-resume/mcp";
import { handleMcp } from "../mcp/handler";
import { handleOpenApi } from "../openapi/handler";
import {
@@ -57,6 +58,7 @@ type AppOptions = {
};
export function createApp(options: AppOptions = {}) {
+ prepareMcpDiscovery();
const app = new Hono<ServerEnvironment>();
const proxies = new BlockList();
for (const range of env.TRUSTED_PROXIES) {
diff --git a/apps/server/src/mcp/discovery.test.ts b/apps/server/src/mcp/discovery.test.ts
new file mode 100644
index 000000000..926d02824
--- /dev/null
+++ b/apps/server/src/mcp/discovery.test.ts
@@ -0,0 +1,256 @@
+import type { RequestAuthentication } from "@reactive-resume/api/context";
+import { once } from "node:events";
+import { Socket } from "node:net";
+import { setImmediate } from "node:timers/promises";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { serve } from "@hono/node-server";
+import { Pool } from "pg";
+import z from "zod";
+
+const mocks = vi.hoisted(() => ({
+ authentication: vi.fn(),
+ limit: vi.fn(),
+ call: vi.fn(),
+ execute: vi.fn(),
+ healthcheck: vi.fn(),
+}));
+vi.mock("@reactive-resume/db/client", async (original) => {
+ const actual = await original<typeof import("@reactive-resume/db/client")>();
+ return {
+ ...actual,
+ db: new Proxy(actual.db, {
+ get: (target, property) => (property === "execute" ? mocks.execute : Reflect.get(target, property)),
+ }),
+ };
+});
+vi.mock("@reactive-resume/db/redis", async (original) => ({
+ ...(await original<typeof import("@reactive-resume/db/redis")>()),
+ getRedis: () => null,
+}));
+vi.mock("@reactive-resume/api/features/storage", async (original) => ({
+ ...(await original<typeof import("@reactive-resume/api/features/storage")>()),
+ getStorageService: () => ({ healthcheck: mocks.healthcheck }),
+}));
+vi.mock("@reactive-resume/api/context", async (original) => ({
+ ...(await original<typeof import("@reactive-resume/api/context")>()),
+ resolveAuthenticationFromRequestHeaders: mocks.authentication,
+}));
+vi.mock("@reactive-resume/api/features/mcp/transport", () => ({
+ consumeMcpRequestLimit: mocks.limit,
+ consumeMcpUserLimit: mocks.limit,
+}));
+vi.mock("@orpc/server", async (original) => ({
+ ...(await original<typeof import("@orpc/server")>()),
+ createRouterClient: (_router: unknown, options: { context: () => unknown }) => ({
+ resume: {
+ listVersions: (input: unknown) => mocks.call("listVersions", input, options.context()),
+ deleteVersion: (input: unknown) => mocks.call("deleteVersion", input, options.context()),
+ },
+ }),
+}));
+
+function authentication(id: string, permissions: RequestAuthentication["permissions"]): RequestAuthentication {
+ return {
+ user: {
+ id,
+ name: id,
+ email: `${id}@example.test`,
+ emailVerified: true,
+ createdAt: new Date(0),
+ updatedAt: new Date(0),
+ },
+ method: "bearer",
+ permissions,
+ };
+}
+
+function request(method = "tools/list", token = "reader", params: object = {}) {
+ return new Request("http://localhost:3000/mcp", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Accept: "application/json, text/event-stream",
+ Authorization: `Bearer ${token}`,
+ Cookie: `session=${token}; locale=en-US`,
+ },
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
+ });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.execute.mockImplementation(async () => {
+ await setImmediate();
+ return [];
+ });
+ mocks.healthcheck.mockImplementation(async () => {
+ await setImmediate();
+ return { status: "healthy" };
+ });
+ mocks.authentication.mockImplementation((headers: Headers) => {
+ const token = headers.get("authorization")?.slice(7);
+ return token === "reader"
+ ? authentication("reader", ["read"])
+ : token === "writer"
+ ? authentication("writer", ["read", "write", "delete"])
+ : null;
+ });
+ mocks.call.mockImplementation(
+ (
+ method: string,
+ _input: unknown,
+ context: {
+ authentication: RequestAuthentication;
+ resHeaders: Headers;
+ },
+ ) => {
+ context.resHeaders.set("X-MCP-User", context.authentication.user.id);
+ return method === "listVersions"
+ ? [{ id: context.authentication.user.id, kind: "named", name: "Saved", createdAt: new Date(0) }]
+ : undefined;
+ },
+ );
+});
+afterEach(() => vi.restoreAllMocks());
+
+it("precomputes discovery before the first request without user queries or network calls", async () => {
+ const query = vi.spyOn(Pool.prototype, "query").mockImplementation(() => {
+ throw new Error("Unexpected database query");
+ });
+ const connect = vi.spyOn(Pool.prototype, "connect").mockImplementation(() => {
+ throw new Error("Unexpected database connection");
+ });
+ const socket = vi.spyOn(Socket.prototype, "connect").mockImplementation(() => {
+ throw new Error("Unexpected network connection");
+ });
+ const fetch = vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("Unexpected network call"));
+ // Import under the guards: parity contracts are also built during module initialization.
+ const { createApp } = await import("../http/app");
+ createApp({ serveStatic: false });
+ expect(query.mock.calls.length).toBe(0);
+ expect(connect.mock.calls.length).toBe(0);
+ expect(socket.mock.calls.length).toBe(0);
+ expect(fetch.mock.calls.length).toBe(0);
+ for (const mock of [mocks.authentication, mocks.call, mocks.execute, mocks.healthcheck, mocks.limit]) {
+ expect(mock.mock.calls.length).toBe(0);
+ }
+ const conversions = vi.spyOn(z.globalRegistry, "get");
+ const { handleMcp } = await import("./handler");
+ const response = await handleMcp(request());
+ expect(response.status).toBe(200);
+ expect((await response.json()).result.tools.length).toBeGreaterThan(70);
+ expect(conversions.mock.calls.length).toBe(0);
+}, 30_000);
+
+it("reuses static schema conversions across separate authenticated discovery requests", async () => {
+ const { handleMcp } = await import("./handler");
+ // Warm-up models startup. Conversion metadata lookups expose both Zod and SDK conversion work.
+ await handleMcp(request());
+ const conversions = vi.spyOn(z.globalRegistry, "get");
+ const durations: number[] = [];
+ for (const token of ["reader", "writer", "reader"]) {
+ const started = performance.now();
+ const response = await handleMcp(request("tools/list", token));
+ expect(response.status).toBe(200);
+ expect((await response.json()).result.tools.length).toBeGreaterThan(70);
+ durations.push(performance.now() - started);
+ }
+ console.info("MCP tools/list milliseconds", durations.map(Math.round));
+ expect(mocks.authentication).toHaveBeenCalledTimes(4);
+ expect(conversions.mock.calls.length).toBe(0);
+}, 30_000);
+
+it("keeps concurrent HTTP health checks responsive during repeated MCP discovery", async () => {
+ const { createApp } = await import("../http/app");
+ const app = createApp({ serveStatic: false, trustedClient: () => "127.0.0.1" });
+ const server = serve({ fetch: app.fetch, port: 0 });
+ try {
+ if (!server.listening) await once(server, "listening");
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("Missing HTTP address");
+ const url = `http://127.0.0.1:${address.port}`;
+ const input = request();
+ const body = await input.text();
+ const started = performance.now();
+ const discovery = Promise.all(
+ Array.from({ length: 20 }, async () => {
+ const response = await fetch(`${url}/mcp`, { method: "POST", headers: input.headers, body });
+ expect(response.status).toBe(200);
+ expect((await response.json()).result.tools.length).toBeGreaterThan(70);
+ }),
+ );
+ const health = Promise.all(
+ Array.from({ length: 3 }, async () => {
+ await setImmediate();
+ const response = await fetch(`${url}/api/health`);
+ expect(response.status).toBe(200);
+ expect((await response.json()).status).toBe("healthy");
+ return performance.now() - started;
+ }),
+ );
+ const [, healthDurations] = await Promise.all([discovery, health]);
+ console.info("20 concurrent MCP discoveries milliseconds", Math.round(performance.now() - started));
+ console.info("Concurrent HTTP health milliseconds", healthDurations.map(Math.round));
+ expect(Math.max(...healthDurations)).toBeLessThan(1_000);
+ expect(mocks.execute).toHaveBeenCalledTimes(3);
+ expect(mocks.healthcheck).toHaveBeenCalledTimes(3);
+ } finally {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ }
+}, 30_000);
+
+it("keeps credentials, permissions, headers and callbacks isolated between requests", async () => {
+ const { handleMcp } = await import("./handler");
+ for (const token of ["reader", "writer", "reader"]) {
+ const response = await handleMcp(
+ request("tools/call", token, {
+ name: "api_resume_list_versions",
+ arguments: { resumeId: "resume-1" },
+ }),
+ );
+ expect(response.headers.get("x-mcp-user")).toBe(token);
+ expect((await response.json()).result.structuredContent.items[0].id).toBe(token);
+ }
+ const params = { name: "api_resume_delete_version", arguments: { resumeId: "resume-1", versionId: "version-1" } };
+ for (const token of ["reader", "writer", "reader"]) {
+ const response = await handleMcp(request("tools/call", token, params));
+ const result = (await response.json()).result;
+ expect(result.isError === true).toBe(token === "reader");
+ }
+ expect(mocks.call.mock.calls.filter(([method]) => method === "deleteVersion")).toHaveLength(1);
+ const contexts = mocks.call.mock.calls.map(
+ ([, , context]) =>
+ context as {
+ reqHeaders: Headers;
+ resHeaders: Headers;
+ authentication: RequestAuthentication;
+ },
+ );
+ expect(new Set(contexts.map((context) => context.resHeaders)).size).toBe(contexts.length);
+ for (const context of contexts) {
+ expect(context.reqHeaders.has("cookie")).toBe(false);
+ expect(context.reqHeaders.get("authorization")).toBe(`Bearer ${context.authentication.user.id}`);
+ }
+ expect((await handleMcp(request("tools/list", "invalid"))).status).toBe(401);
+ expect(mocks.authentication.mock.calls.every(([headers]) => !(headers as Headers).has("cookie"))).toBe(true);
+ const beforeInvalidInput = mocks.call.mock.calls.length;
+ const invalid = await handleMcp(
+ request("tools/call", "reader", {
+ name: "api_resume_list_versions",
+ arguments: { resumeId: 123 },
+ }),
+ );
+ expect((await invalid.json()).result.isError).toBe(true);
+ expect(mocks.call.mock.calls.length).toBe(beforeInvalidInput);
+ mocks.call.mockResolvedValueOnce([{ createdAt: "not-a-date" }]);
+ const invalidOutput = await handleMcp(
+ request("tools/call", "reader", {
+ name: "api_resume_list_versions",
+ arguments: { resumeId: "resume-1" },
+ }),
+ );
+ expect((await invalidOutput.json()).result).toMatchObject({
+ isError: true,
+ content: [{ type: "text", text: expect.stringContaining("Output validation error") }],
+ });
+}, 30_000);
diff --git a/apps/server/src/mcp/server.ts b/apps/server/src/mcp/server.ts
index 467e0d7a3..182617f29 100644
--- a/apps/server/src/mcp/server.ts
+++ b/apps/server/src/mcp/server.ts
@@ -11,6 +11,7 @@ import {
registerPrompts,
registerResources,
registerTools,
+ registerToolDiscovery,
} from "@reactive-resume/mcp";
import { appVersion } from "../app-version";
import { getRequestLocale } from "../rpc/locale";
@@ -79,6 +80,7 @@ export function createMcpServer(
signal: request.signal,
});
registerPrompts(server, client);
+ registerToolDiscovery(server);
return server;
}
diff --git a/apps/server/src/static/web.ts b/apps/server/src/static/web.ts
index 45a2757af..f18a272e5 100644
--- a/apps/server/src/static/web.ts
+++ b/apps/server/src/static/web.ts
@@ -263,7 +263,8 @@ export const serveWebDistStatic = env.CLOUDFLARE
: serveStatic({
root: staticRoot,
onFound: (_path, context) => {
- if (/^\/videos\/.*-v\d+\.(?:mp4|webp)$/.test(context.req.path)) {
+ // Vite fingerprints everything under /assets, so a file there never changes.
+ if (context.req.path.startsWith("/assets/") || /^\/videos\/.*-v\d+\.(?:mp4|webp)$/.test(context.req.path)) {
context.header("Cache-Control", "public, max-age=31536000, immutable");
}
},
diff --git a/apps/web/public/fonts/ibm-plex-mono-500.ttf b/apps/web/public/fonts/ibm-plex-mono-500.ttf
deleted file mode 100644
index 8253c5fba..000000000
Binary files a/apps/web/public/fonts/ibm-plex-mono-500.ttf and /dev/null differ
diff --git a/apps/web/public/fonts/ibm-plex-mono-500.woff2 b/apps/web/public/fonts/ibm-plex-mono-500.woff2
new file mode 100644
index 000000000..aa287d33a
Binary files /dev/null and b/apps/web/public/fonts/ibm-plex-mono-500.woff2 differ
diff --git a/apps/web/public/fonts/ibm-plex-mono-700.ttf b/apps/web/public/fonts/ibm-plex-mono-700.ttf
deleted file mode 100644
index 247979cae..000000000
Binary files a/apps/web/public/fonts/ibm-plex-mono-700.ttf and /dev/null differ
diff --git a/apps/web/public/fonts/ibm-plex-mono-700.woff2 b/apps/web/public/fonts/ibm-plex-mono-700.woff2
new file mode 100644
index 000000000..57aedce78
Binary files /dev/null and b/apps/web/public/fonts/ibm-plex-mono-700.woff2 differ
diff --git a/apps/web/src/components/ui/donation-toast.test.tsx b/apps/web/src/components/ui/donation-toast.test.tsx
new file mode 100644
index 000000000..53dff61ed
--- /dev/null
+++ b/apps/web/src/components/ui/donation-toast.test.tsx
@@ -0,0 +1,66 @@
+// @vitest-environment happy-dom
+// @vitest-environment-options {"url":"https://localhost:3000"}
+
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { i18n } from "@lingui/core";
+import Cookies from "js-cookie";
+import { Toaster } from "@reactive-resume/ui/components/toast";
+import { DonationToast } from "./donation-toast";
+
+const LAUNCH_START = Date.parse("2026-10-05T07:01:00Z");
+const LAUNCH_END = LAUNCH_START + 24 * 60 * 60 * 1000;
+const FIVE_MINUTES = 5 * 60 * 1000;
+const DISMISSED_COOKIE = "donation-toast-dismissed";
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "requestAnimationFrame", "cancelAnimationFrame"] });
+ i18n.loadAndActivate({ locale: "en-US", messages: {} });
+ Cookies.remove(DISMISSED_COOKIE);
+});
+
+afterEach(() => {
+ Cookies.remove(DISMISSED_COOKIE);
+ vi.useRealTimers();
+});
+
+it("hides an existing donation toast when launch starts without recording a dismissal", async () => {
+ vi.setSystemTime(LAUNCH_START - FIVE_MINUTES - 60_000);
+ render(
+ <>
+ <DonationToast />
+ <Toaster />
+ </>,
+ );
+
+ await act(() => vi.advanceTimersByTimeAsync(FIVE_MINUTES));
+ expect(screen.getByText("Please support the project")).toBeVisible();
+
+ await act(() => vi.advanceTimersByTimeAsync(60_000));
+ await act(() => vi.advanceTimersByTimeAsync(20));
+ expect(screen.queryByText("Please support the project")).not.toBeInTheDocument();
+ expect(Cookies.get(DISMISSED_COOKIE)).toBeUndefined();
+
+ await act(() => vi.advanceTimersByTimeAsync(FIVE_MINUTES));
+ expect(screen.queryByText("Please support the project")).not.toBeInTheDocument();
+});
+
+it("pauses donation prompts during launch and resumes five minutes after it ends", async () => {
+ vi.setSystemTime(LAUNCH_END - FIVE_MINUTES - 60_000);
+ render(
+ <>
+ <DonationToast />
+ <Toaster />
+ </>,
+ );
+
+ await act(() => vi.advanceTimersByTimeAsync(FIVE_MINUTES));
+ expect(screen.queryByText("Please support the project")).not.toBeInTheDocument();
+ await act(() => vi.advanceTimersByTimeAsync(60_000));
+ expect(screen.queryByText("Please support the project")).not.toBeInTheDocument();
+ await act(() => vi.advanceTimersByTimeAsync(FIVE_MINUTES));
+ expect(screen.getByText("Please support the project")).toBeVisible();
+
+ fireEvent.click(screen.getByLabelText("Close"));
+ expect(Cookies.get(DISMISSED_COOKIE)).toBe("true");
+});
diff --git a/apps/web/src/components/ui/donation-toast.tsx b/apps/web/src/components/ui/donation-toast.tsx
index acdc86e16..3497a973f 100644
--- a/apps/web/src/components/ui/donation-toast.tsx
+++ b/apps/web/src/components/ui/donation-toast.tsx
@@ -1,9 +1,9 @@
import { t } from "@lingui/core/macro";
import Cookies from "js-cookie";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { useTimeout } from "usehooks-ts";
import { toast } from "@reactive-resume/ui/components/toast";
-import { isProductHuntLaunchLive } from "./product-hunt-banner";
+import { isProductHuntLaunchLive, useLaunchClock } from "./product-hunt-banner";
const TOAST_ID = "donation-toast";
const SHOW_TOAST_DELAY_MS = 5 * 60 * 1000; // 5 minutes
@@ -13,9 +13,15 @@ const DISMISSED_COOKIE_EXPIRES_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
const getDismissedCookieExpiresAt = () => new Date(Date.now() + DISMISSED_COOKIE_EXPIRES_MS);
export function DonationToast() {
+ const now = useLaunchClock();
+ const launchLive = isProductHuntLaunchLive(now);
// ponytail: inlined from @reactive-resume/ui/hooks/use-cookie — only consumer, one read + one set-with-expiry
const [dismissed, setDismissedState] = useState<string | null>(() => Cookies.get(DISMISSED_COOKIE_NAME) ?? null);
+ useEffect(() => {
+ if (launchLive) toast.close(TOAST_ID);
+ }, [launchLive]);
+
const setDismissed = (value: string, options?: { expires?: Date }) => {
// Attributes match the former useCookie DEFAULT_COOKIE_ATTRIBUTES; options (expiry) override.
Cookies.set(DISMISSED_COOKIE_NAME, value, { path: "/", secure: true, sameSite: "lax", ...options });
@@ -40,12 +46,14 @@ export function DonationToast() {
},
},
onClose: () => {
+ // Launch suppression isn't a user dismissal; allow the donation toast to return afterward.
+ if (isProductHuntLaunchLive()) return;
setDismissed("true", { expires: getDismissedCookieExpiresAt() });
},
});
};
- useTimeout(showToast, SHOW_TOAST_DELAY_MS);
+ useTimeout(showToast, launchLive ? null : SHOW_TOAST_DELAY_MS);
return null;
}
diff --git a/apps/web/src/components/ui/product-hunt-banner.tsx b/apps/web/src/components/ui/product-hunt-banner.tsx
index 345628b19..a5842a794 100644
--- a/apps/web/src/components/ui/product-hunt-banner.tsx
+++ b/apps/web/src/components/ui/product-hunt-banner.tsx
@@ -24,7 +24,7 @@ const SHOWN_ON = /^\/(?:$|ats-checker|templates|dashboard)/;
export const isProductHuntLaunchLive = (now = Date.now()) => now >= LAUNCH_START && now < LAUNCH_END;
/** The current time, refreshed when the launch starts, on every minute while it runs, and once when it ends. */
-function useLaunchClock() {
+export function useLaunchClock() {
const [now, setNow] = useState(Date.now);
useEffect(() => {
diff --git a/apps/web/src/dialogs/manager.tsx b/apps/web/src/dialogs/manager.tsx
index 6d9da3e81..dcd3e14d0 100644
--- a/apps/web/src/dialogs/manager.tsx
+++ b/apps/web/src/dialogs/manager.tsx
@@ -1,16 +1,26 @@
-import { Fragment } from "react";
+import type { DialogSchema } from "./schemas";
+import { Fragment, lazy, Suspense } from "react";
import { Dialog } from "@reactive-resume/ui/components/dialog";
-import { renderDialog } from "./renderers";
import { useDialogStore } from "./store";
+// The dialogs pull in forms, importers and editors; load them on first open so they stay out of every page's bundle.
+const DialogContent = lazy(async () => {
+ const { renderDialog } = await import("./renderers");
+ return { default: ({ dialog }: { dialog: DialogSchema }) => renderDialog(dialog) };
+});
+
export function DialogManager() {
const { open, activeDialog, openCount, onOpenChange } = useDialogStore();
- const DialogContent = renderDialog(activeDialog);
-
return (
<Dialog open={open} onOpenChange={onOpenChange}>
- <Fragment key={openCount}>{DialogContent}</Fragment>
+ <Fragment key={openCount}>
+ {activeDialog && (
+ <Suspense>
+ <DialogContent dialog={activeDialog} />
+ </Suspense>
+ )}
+ </Fragment>
</Dialog>
);
}
diff --git a/apps/web/src/features/homepage/landing.css b/apps/web/src/features/homepage/landing.css
index 4a7619c9a..7c5231525 100644
--- a/apps/web/src/features/homepage/landing.css
+++ b/apps/web/src/features/homepage/landing.css
@@ -11,7 +11,7 @@
font-style: normal;
font-weight: 500;
font-display: swap;
- src: url("/fonts/ibm-plex-mono-500.ttf") format("truetype");
+ src: url("/fonts/ibm-plex-mono-500.woff2") format("woff2");
}
@font-face {
@@ -19,7 +19,7 @@
font-style: normal;
font-weight: 700;
font-display: swap;
- src: url("/fonts/ibm-plex-mono-700.ttf") format("truetype");
+ src: url("/fonts/ibm-plex-mono-700.woff2") format("woff2");
}
@theme {
diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts
index d9f1a032f..2aaa3e72f 100644
--- a/apps/web/vite.config.ts
+++ b/apps/web/vite.config.ts
@@ -49,7 +49,10 @@ async function prerenderPages() {
/<meta\s+name="description"[^>]*>/,
() => `<meta name="description" content="${escapeHtml(page.description)}">`,
)
- .replace('<div id="app"></div>', () => `<div id="app">${page.html}</div>`);
+ .replace('<div id="app"></div>', () => `<div id="app">${page.html}</div>`)
+ // The page is readable before any script runs, so the stylesheet, fonts and images go first.
+ .replaceAll('<link rel="modulepreload" ', '<link rel="modulepreload" fetchpriority="low" ')
+ .replace('<script type="module" ', '<script type="module" fetchpriority="low" ');
await writeFile(`${prerenderOutDir}/${name}/${locale}.html`, html);
}
}
@@ -109,6 +112,9 @@ export default defineConfig({
chunkSizeWarningLimit: 10 * 1024, // 10 MB
rolldownOptions: {
external: ["bcryptjs", "sharp", "@aws-sdk/client-s3", "ioredis", "linkedom"],
+ // Every page loads the libraries the entry imports statically; one file instead of ~100 tiny ones saves
+ // a round trip each on slow connections. App modules stay split to keep their execution order.
+ output: { codeSplitting: { groups: [{ name: "vendor", test: /node_modules/, tags: ["$initial"] }] } },
},
},
diff --git a/packages/mcp/src/contracts.ts b/packages/mcp/src/contracts.ts
index 5ba1bc62c..750b38b13 100644
--- a/packages/mcp/src/contracts.ts
+++ b/packages/mcp/src/contracts.ts
@@ -1,7 +1,26 @@
+import { toJsonSchemaCompat } from "@modelcontextprotocol/sdk/server/zod-json-schema-compat.js";
import z from "zod";
import { createResumeDataJsonSchema } from "@reactive-resume/schema/resume/json-schema";
import { writableResumeDataSchema } from "@reactive-resume/schema/resume/write";
+type DiscoveryOptions = NonNullable<Parameters<typeof toJsonSchemaCompat>[1]>;
+const discoverySchemas = new WeakMap<z.ZodObject, Map<string, ReturnType<typeof toJsonSchemaCompat>>>();
+
+/** Static discovery only; validation continues to use the original Zod schemas. */
+export function discoveryJsonSchema(schema: z.ZodObject, options: DiscoveryOptions) {
+ const key = JSON.stringify([options.strictUnions ?? true, options.pipeStrategy ?? "input", options.target ?? null]);
+ let schemas = discoverySchemas.get(schema);
+ const cached = schemas?.get(key);
+ if (cached) return cached;
+ const converted = toJsonSchemaCompat(schema, options);
+ if (!schemas) {
+ schemas = new Map();
+ discoverySchemas.set(schema, schemas);
+ }
+ schemas.set(key, converted);
+ return converted;
+}
+
export const fileInputSchema = z.union([
z.object({
name: z.string().min(1).max(255),
diff --git a/packages/mcp/src/discovery.test.ts b/packages/mcp/src/discovery.test.ts
new file mode 100644
index 000000000..253e2304c
--- /dev/null
+++ b/packages/mcp/src/discovery.test.ts
@@ -0,0 +1,85 @@
+import type { RouterClient } from "@orpc/server";
+import type { RequestAuthentication } from "@reactive-resume/api/context";
+import { expect, it } from "vitest";
+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
+import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+import { toJsonSchemaCompat } from "@modelcontextprotocol/sdk/server/zod-json-schema-compat.js";
+import z from "zod";
+import { discoveryJsonSchema } from "./contracts";
+import { registerToolDiscovery } from "./discovery";
+import { buildMcpServerCard } from "./mcp-server-card";
+import { MCP_ROUTER, parityToolContract, registerParityTools } from "./parity";
+import { registerTools } from "./tools";
+
+it("matches the complete unmodified SDK tools/list response and server-card schemas", async () => {
+ const server = new McpServer({ name: "discovery-test", version: "1.0.0" });
+ const apiClient = {} as RouterClient<typeof MCP_ROUTER>;
+ const authentication: RequestAuthentication = {
+ user: {
+ id: "owner",
+ name: "Owner",
+ email: "[email protected]",
+ emailVerified: true,
+ createdAt: new Date(0),
+ updatedAt: new Date(0),
+ },
+ method: "bearer",
+ permissions: ["read", "write", "delete"],
+ };
+ registerTools(server, apiClient, new Headers(), authentication);
+ registerParityTools(server, apiClient, new Headers(), {
+ authentication,
+ resHeaders: new Headers(),
+ locale: "en-US",
+ trustedClient: "127.0.0.1",
+ });
+ const client = new Client({ name: "discovery-client", version: "1.0.0" });
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ try {
+ await server.connect(serverTransport);
+ await client.connect(clientTransport);
+ const baseline = JSON.parse(JSON.stringify(await client.listTools()));
+ registerToolDiscovery(server);
+ const optimized = JSON.parse(JSON.stringify(await client.listTools()));
+ expect(optimized).toEqual(baseline);
+ expect(buildMcpServerCard("1.0.0").tools).toEqual(
+ (await client.listTools()).tools.map(({ execution: _execution, _meta, ...tool }) => tool),
+ );
+ } finally {
+ await client.close();
+ await server.close();
+ }
+}, 30_000);
+
+it("keys JSON Schema reuse by schema identity and all SDK conversion options", () => {
+ const schema = z.object({ value: z.string().default("default") });
+ const options = [
+ { strictUnions: true, pipeStrategy: "input" as const },
+ { strictUnions: true, pipeStrategy: "output" as const },
+ { strictUnions: false, pipeStrategy: "input" as const },
+ { strictUnions: true, pipeStrategy: "input" as const, target: "draft-2020-12" as const },
+ ] as const;
+ const converted = options.map((option) => discoveryJsonSchema(schema, option));
+ for (const [index, option] of options.entries()) {
+ expect(converted[index]).toEqual(toJsonSchemaCompat(schema, option));
+ expect(discoveryJsonSchema(schema, { ...option })).toBe(converted[index]);
+ }
+ expect(converted[0]?.required).toBeUndefined();
+ expect(converted[1]?.required).toEqual(["value"]);
+ expect(new Set(converted).size).toBe(options.length);
+ const other = z.object({ value: z.number() });
+ expect(discoveryJsonSchema(other, options[0])).toEqual(toJsonSchemaCompat(other, options[0]));
+});
+
+it("keeps procedure aliases and different procedures' contracts distinct", () => {
+ const procedure = MCP_ROUTER.resume.verifyPassword;
+ const ordinary = parityToolContract("ordinary", procedure);
+ const special = parityToolContract("resume.verifyPassword", procedure);
+ expect(ordinary.outputSchema.shape).not.toHaveProperty("resourceCookie");
+ expect(special.outputSchema.shape).toHaveProperty("resourceCookie");
+ expect(parityToolContract("resume.verifyPassword", procedure)).toBe(special);
+ const different = parityToolContract("ordinary", MCP_ROUTER.resume.checkSlug);
+ expect(different.inputSchema.shape).not.toHaveProperty("password");
+ expect(ordinary.inputSchema.shape).toHaveProperty("password");
+});
diff --git a/packages/mcp/src/discovery.ts b/packages/mcp/src/discovery.ts
new file mode 100644
index 000000000..9a852a1be
--- /dev/null
+++ b/packages/mcp/src/discovery.ts
@@ -0,0 +1,40 @@
+import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+import type { Tool } from "@modelcontextprotocol/sdk/types.js";
+import { ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
+import { discoveryJsonSchema } from "./contracts";
+import { PARITY_TOOL_META } from "./parity";
+import { TOOL_META } from "./tool-meta";
+
+function buildToolDefinitions() {
+ return Object.entries({ ...TOOL_META, ...PARITY_TOOL_META }).map(
+ ([name, { title, description, inputSchema, outputSchema, annotations }]) => ({
+ name,
+ title,
+ description,
+ inputSchema: discoveryJsonSchema(inputSchema, {
+ strictUnions: true,
+ pipeStrategy: "input",
+ }) as Tool["inputSchema"],
+ outputSchema: discoveryJsonSchema(outputSchema, { strictUnions: true, pipeStrategy: "output" }) as NonNullable<
+ Tool["outputSchema"]
+ >,
+ annotations,
+ // SDK registerTool declares ordinary callbacks as non-task tools.
+ execution: { taskSupport: "forbidden" as const },
+ }),
+ );
+}
+
+let discovery: { tools: ReturnType<typeof buildToolDefinitions> } | undefined;
+
+/** Run before accepting HTTP traffic. Reads only static metadata; creates no clients or callbacks. */
+export function prepareMcpDiscovery() {
+ return (discovery ??= { tools: buildToolDefinitions() });
+}
+
+/** Install after tool registration so SDK tools/call validation and callbacks remain intact. */
+export function registerToolDiscovery(server: McpServer) {
+ const metadata = prepareMcpDiscovery();
+ // The public low-level handler API avoids SDK tools/list reconverting every schema per request.
+ server.server.setRequestHandler(ListToolsRequestSchema, () => metadata);
+}
diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts
index 9fa0216b4..1bd6a1e23 100644
--- a/packages/mcp/src/index.ts
+++ b/packages/mcp/src/index.ts
@@ -1,4 +1,5 @@
export { buildMcpServerInfo } from "./mcp-server-card";
+export { prepareMcpDiscovery, registerToolDiscovery } from "./discovery";
export { MCP_TOOL_NAME } from "./mcp-tool-names";
export { registerPrompts } from "./prompts";
export { registerResources } from "./resources";
diff --git a/packages/mcp/src/mcp-server-card.ts b/packages/mcp/src/mcp-server-card.ts
index 4d5b23252..db8d46d3a 100644
--- a/packages/mcp/src/mcp-server-card.ts
+++ b/packages/mcp/src/mcp-server-card.ts
@@ -1,8 +1,6 @@
-import { toJsonSchemaCompat } from "@modelcontextprotocol/sdk/server/zod-json-schema-compat.js";
+import { prepareMcpDiscovery } from "./discovery";
import { MCP_TOOL_NAME as T } from "./mcp-tool-names";
-import { PARITY_TOOL_META } from "./parity";
import { PROMPT_META } from "./prompts";
-import { TOOL_META } from "./tool-meta";
const RESUME_ID_ARGUMENT = [{ name: "id", description: "Resume ID.", required: true }] as const;
@@ -30,17 +28,7 @@ export function buildMcpServerInfo(version: string) {
* The parameterized resume URI is therefore duplicated here so discovery matches the live template.
*/
export function buildMcpServerCard(appVersion: string) {
- // ponytail: derived from TOOL_META; title/description/inputSchema/annotations declared once
- const tools = Object.entries({ ...TOOL_META, ...PARITY_TOOL_META }).map(
- ([name, { title, description, inputSchema, outputSchema, annotations }]) => ({
- name,
- title,
- description,
- inputSchema: toJsonSchemaCompat(inputSchema, { strictUnions: true, pipeStrategy: "input" }),
- outputSchema: toJsonSchemaCompat(outputSchema, { strictUnions: true, pipeStrategy: "output" }),
- annotations,
- }),
- );
+ const tools = prepareMcpDiscovery().tools.map(({ execution: _execution, ...tool }) => tool);
const prompts = Object.entries(PROMPT_META).map(([name, meta]) => ({
name,
diff --git a/packages/mcp/src/parity.ts b/packages/mcp/src/parity.ts
index c607866c2..181388fc2 100644
--- a/packages/mcp/src/parity.ts
+++ b/packages/mcp/src/parity.ts
@@ -143,8 +143,18 @@ const accountToolMeta = {
annotations: handoffAnnotations,
};
-/** The live server and server card derive the same contracts from the API DTOs. */
-export function parityToolContract(path: string, procedure: AnyProcedure) {
+type ParityToolContract = {
+ inputJson: ReturnType<typeof wireJsonSchema>;
+ inputSchema: z.ZodObject;
+ outputSchema: z.ZodObject;
+};
+const parityContracts = new WeakMap<AnyProcedure, Map<string, ParityToolContract>>();
+
+/** The live server and server card share static contracts, never request context or callbacks. */
+export function parityToolContract(path: string, procedure: AnyProcedure): ParityToolContract {
+ let contracts = parityContracts.get(procedure);
+ const cached = contracts?.get(path);
+ if (cached) return cached;
const definition = procedure["~orpc"];
const inputJson = definition.inputSchema
? wireJsonSchema(requireZod(definition.inputSchema), "input")
@@ -184,7 +194,13 @@ export function parityToolContract(path: string, procedure: AnyProcedure) {
: path === "resume.updates.subscribe"
? toWireObjectSchema(requireZod(router.resume.getById["~orpc"].outputSchema))
: toWireObjectSchema(requireZod(definition.outputSchema));
- return { inputJson, inputSchema: boundedInput, outputSchema };
+ const contract = { inputJson, inputSchema: boundedInput, outputSchema };
+ if (!contracts) {
+ contracts = new Map();
+ parityContracts.set(procedure, contracts);
+ }
+ contracts.set(path, contract);
+ return contract;
}
export const PARITY_TOOL_META: Record<