Skip to content

Open source alternative to Semrush and Ahrefs

Convert MCP tool schemas to JSON Schema once per isolate instead of per request (#1039)

Ben Senescu4a4de76ae20c
diff --git a/src/server/mcp/json-schema-memo.test.ts b/src/server/mcp/json-schema-memo.test.ts
new file mode 100644
index 00000000..ae974d81
--- /dev/null
+++ b/src/server/mcp/json-schema-memo.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from "vitest";
+import { z } from "zod";
+import { memoizeJsonSchema } from "./json-schema-memo";
+
+const schema = z.object({
+ projectId: z.string(),
+ limit: z.number().optional(),
+});
+const options = { target: "draft-2020-12" } as const;
+
+describe("memoizeJsonSchema", () => {
+ it("converts to JSON Schema once and returns zod's own result", () => {
+ const memo = memoizeJsonSchema(schema);
+ const first = memo["~standard"].jsonSchema.input(options);
+ expect(memo["~standard"].jsonSchema.input(options)).toBe(first);
+ expect(first).toEqual(schema["~standard"].jsonSchema.input(options));
+ });
+});
diff --git a/src/server/mcp/json-schema-memo.ts b/src/server/mcp/json-schema-memo.ts
new file mode 100644
index 00000000..384f6767
--- /dev/null
+++ b/src/server/mcp/json-schema-memo.ts
@@ -0,0 +1,35 @@
+import type { StandardSchemaWithJSON } from "@modelcontextprotocol/server";
+import type { z } from "zod";
+
+/**
+ * A Standard Schema view of a zod schema whose JSON Schema conversion runs
+ * once per direction. Validation still goes through zod.
+ *
+ * The MCP SDK converts every tool's schema to JSON Schema on registerTool and
+ * again on tools/list, and the server is built per request (transport.ts).
+ * On the hosted app worker that conversion was ~70% of all allocations under
+ * MCP load (heap profile, 2026-10-20), and every exceededMemory outcome that
+ * day was on /mcp.
+ *
+ * The cached JSON reaches every per-request server by reference: the SDK
+ * shallow-copies the input root before stamping `type` on it and emits the
+ * output root as is, so nested objects are always shared. It only reads them;
+ * anything that wrote to them would leak into every later request.
+ */
+export function memoizeJsonSchema(schema: z.ZodType): StandardSchemaWithJSON {
+ const std = schema["~standard"];
+ // The SDK always asks for the same target (JSON Schema draft 2020-12), so
+ // one result per direction is enough.
+ const cache: Partial<Record<"input" | "output", Record<string, unknown>>> =
+ {};
+ const convert =
+ (io: "input" | "output") =>
+ (options: Parameters<typeof std.jsonSchema.input>[0]) =>
+ (cache[io] ??= std.jsonSchema[io](options));
+ return {
+ "~standard": {
+ ...std,
+ jsonSchema: { input: convert("input"), output: convert("output") },
+ },
+ };
+}
diff --git a/src/server/mcp/server.ts b/src/server/mcp/server.ts
index 04733ca3..653fc36a 100644
--- a/src/server/mcp/server.ts
+++ b/src/server/mcp/server.ts
@@ -17,6 +17,7 @@ import {
import {
type CallToolResult,
McpServer,
+ type StandardSchemaWithJSON,
type ToolAnnotations,
} from "@modelcontextprotocol/server";
import { z } from "zod";
@@ -26,6 +27,7 @@ import {
type ToolContext,
} from "@/server/mcp/context";
import { objectSchema } from "@/server/mcp/output-schemas";
+import { memoizeJsonSchema } from "@/server/mcp/json-schema-memo";
import { instrumentMcpToolHandler } from "@/server/mcp/instrumentation";
import { submitIndexNowUrlsTool } from "@/server/mcp/tools/submit-indexnow-urls";
import { getBacklinksOverviewTool } from "@/server/mcp/tools/get-backlinks-overview";
@@ -151,32 +153,69 @@ type OpenSeoToolDefinition<Input extends ToolSchema> = {
) => CallToolResult | Promise<CallToolResult>;
};
+const widgetToolName = z.enum(WidgetTool);
+
+type ToolSchemas = {
+ // Handed to the SDK, which converts them to JSON Schema for tools/list.
+ inputSchema: StandardSchemaWithJSON;
+ outputSchema: StandardSchemaWithJSON | undefined;
+ // The same output schema as zod, for the handler instrumentation.
+ outputZod: z.ZodType | undefined;
+};
+
+// Built once per isolate and shared by every per-request server (see
+// transport.ts) so the SDK's JSON Schema conversion is paid once per tool, not
+// once per request. The widget-source tools get a second entry for clients
+// without MCP Apps support, which see an output schema without resultId.
+const toolSchemaCache = new Map<string, ToolSchemas>();
+
+function toolSchemas(
+ tool: {
+ name: string;
+ config: { inputSchema: ToolSchema; outputSchema?: ToolSchema };
+ },
+ omitResultId: boolean,
+): ToolSchemas {
+ const key = omitResultId ? `${tool.name}/no-result-id` : tool.name;
+ let schemas = toolSchemaCache.get(key);
+ if (!schemas) {
+ // Output objects must allow added fields, including nested objects. The
+ // tools/list contract test checks every registered tool for cached-client
+ // compatibility; input schemas keep their existing validation rules.
+ const schema = objectSchema(tool.config.outputSchema);
+ const outputZod =
+ omitResultId && schema instanceof z.ZodObject
+ ? schema.omit({ resultId: true })
+ : schema;
+ schemas = {
+ inputSchema: memoizeJsonSchema(objectSchema(tool.config.inputSchema)),
+ outputSchema: outputZod && memoizeJsonSchema(outputZod),
+ outputZod,
+ };
+ toolSchemaCache.set(key, schemas);
+ }
+ return schemas;
+}
+
function registerOpenSeoTool<Input extends ToolSchema>(
server: McpServer,
tool: OpenSeoToolDefinition<Input>,
authProps: McpProps,
supportsApps: boolean,
) {
- // Output objects must allow added fields, including nested objects. The
- // tools/list contract test checks every registered tool for cached-client
- // compatibility; input schemas keep their existing validation rules.
- const widgetSource = z.enum(WidgetTool).safeParse(tool.name);
- const schema = objectSchema(tool.config.outputSchema);
- const outputSchema =
- !supportsApps && widgetSource.success && schema instanceof z.ZodObject
- ? schema.omit({ resultId: true })
- : schema;
+ const widgetSource = widgetToolName.safeParse(tool.name);
+ const schemas = toolSchemas(tool, !supportsApps && widgetSource.success);
const handler = instrumentMcpToolHandler(
tool.name,
- outputSchema,
+ schemas.outputZod,
tool.handler,
);
server.registerTool(
tool.name,
{
...tool.config,
- inputSchema: objectSchema(tool.config.inputSchema),
- outputSchema,
+ inputSchema: schemas.inputSchema,
+ outputSchema: schemas.outputSchema,
},
async (args, context) => {
const toolContext = createMcpToolContext(context, authProps);