Skip to content

[Bug]: TypeScript Compiler OOM / "Type instantiation is excessively deep" when using registerTool with Zod schemas #1423

@fanggz2017

Description

@fanggz2017

Describe the bug

I am encountering a critical TypeScript compilation issue (JavaScript heap out of memory) when using server.registerTool with a standard Zod schema.
The TypeScript compiler attempts to recursively infer the types from the Zod schema passed to inputSchema, leading to an infinite recursion or excessive memory usage that crashes the build process.

Reproduction

Here is the code structure that causes the OOM. The schema uses .describe() and .optional(), which seems to trigger the deep instantiation issue in the SDK's type definitions.

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";

// 1. The Schema
const AuditInputSchema = z.object({
  projectPath: z.string().describe("Root path of the project"),
  sizeLimitMb: z.number().default(5).describe("File size limit in MB"),
  allowlist: z.array(z.string()).optional().describe("Allowlist patterns"),
});

// 2. The Implementation
export function registerAuditTool(server: McpServer) {
  // 💥 THIS CAUSES OOM DURING BUILD 💥
  server.registerTool(
    "audit_staged_files",
    {
      description: "Audit staged files",
      inputSchema: AuditInputSchema
    },
    async (args: any) => {
       return { content: [{ type: "text", text: "done" }] };
    }
  );
}


<--- Last few GCs --->
[5560:0000020577775000]    95921 ms: Mark-Compact ... allocation failure; scavenge might not succeed

<--- JS stacktrace --->
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
...
TS2589: Type instantiation is excessively deep and possibly infinite.

I have to cast the schema to any to stop the compiler from crashing, which defeats the purpose of TypeScript safety.

inputSchema: AuditInputSchema as any

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions