{"record":{"id":"84b7f210445eb0b9","repo":"mastra-ai/mastra","slug":"mcpclient-was-initialized-multiple-times-with-the","errorCode":null,"errorMessage":"MCPClient was initialized multiple times with the same configuration options.\n\nThis error is intended to prevent memory leaks.\n\nTo fix this you have three different options:\n1. If you need multiple MCPClient class instances with identical server configurations, set an id when configuring: new MCPClient({ id: \"my-unique-id\" })\n2. Call \"await client.disconnect()\" after you're done using the client and before you recreate another instance with the same options. If the identical MCPClient instance is already closed at the time\n3. If you only need one instance of MCPClient in your app, refactor your code so it's only created one time (ex. move it out of a loop into a higher scope code block)","messagePattern":"MCPClient was initialized multiple times with the same configuration options\\.\n\nThis error is intended to prevent memory leaks\\.\n\nTo fix this you have three different options:\n1\\. If you need multiple MCPClient class instances with identical server configurations, set an id when configuring: new MCPClient\\(\\{ id: \"my-unique-id\" \\}\\)\n2\\. Call \"await client\\.disconnect\\(\\)\" after you're done using the client and before you recreate another instance with the same options\\. If the identical MCPClient instance is already closed at the time\n3\\. If you only need one instance of MCPClient in your app, refactor your code so it's only created one time \\(ex\\. move it out of a loop into a higher scope code block\\)","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/mcp/src/client/configuration.ts","lineNumber":175,"sourceCode":"      this.id = args.id;\n      const cached = mcpClientInstances.get(this.id);\n\n      if (cached && !equal(cached.serverConfigs, args.servers)) {\n        const existingInstance = mcpClientInstances.get(this.id);\n        if (existingInstance) {\n          void existingInstance.disconnect();\n          mcpClientInstances.delete(this.id);\n        }\n      }\n    } else {\n      this.id = this.makeId();\n    }\n\n    // to prevent memory leaks return the same MCP server instance when configured the same way multiple times\n    const existingInstance = mcpClientInstances.get(this.id);\n    if (existingInstance) {\n      if (!args.id) {\n        throw new Error(`MCPClient was initialized multiple times with the same configuration options.\n\nThis error is intended to prevent memory leaks.\n\nTo fix this you have three different options:\n1. If you need multiple MCPClient class instances with identical server configurations, set an id when configuring: new MCPClient({ id: \"my-unique-id\" })\n2. Call \"await client.disconnect()\" after you're done using the client and before you recreate another instance with the same options. If the identical MCPClient instance is already closed at the time of re-creating it, you will not see this error.\n3. If you only need one instance of MCPClient in your app, refactor your code so it's only created one time (ex. move it out of a loop into a higher scope code block)\n`);\n      }\n      return existingInstance;\n    }\n\n    mcpClientInstances.set(this.id, this);\n    this.addToInstanceCache();\n    return this;\n  }\n\n  /**","sourceCodeStart":157,"sourceCodeEnd":193,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/mcp/src/client/configuration.ts#L157-L193","documentation":"MCPClient keeps a registry (mcpClientInstances) keyed by an id derived from its configuration. Constructing a second MCPClient with identical options and no explicit id would leak the first instance's connections, so the constructor throws this plain Error with the three documented remedies. It is a guard against duplicate long-lived clients (duplicated transports, toolsets, and event handlers).","triggerScenarios":"Calling new MCPClient({...same servers/options...}) twice (or more) while the first instance is still connected and no explicit id was supplied — commonly inside loops, React render/effect bodies, serverless cold-start handlers, or module-level accidental double-imports.","commonSituations":"Creating the client inside a request handler or component render; dev-mode double evaluation (HMR) of a module that constructs the client at top level; serverless functions constructing per invocation without disconnect; copy-pasting client setup in two files both executed.","solutions":["Add a stable explicit id: new MCPClient({ id: 'my-unique-id', ... }) so identical configurations reuse the same registered instance.","Call await client.disconnect() when done, before creating another instance with the same options.","Refactor to a singleton: create the client once at a higher scope (module level / app init) instead of per request, loop iteration, or render.","In dev/HMR, guard construction with a global singleton (e.g. globalThis.__mcpClient ??= new MCPClient(...))."],"exampleFix":"// before: per-request construction duplicates the client\nasync function handler() {\n  const mcp = new MCPClient({ servers: { filesystem: { command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem', '/data'] } } });\n  return mcp.getTools();\n}\n// after: ided singleton\nconst mcp = new MCPClient({ id: 'fs-tools', servers: { filesystem: { command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem', '/data'] } } });\nasync function handler() {\n  return mcp.getTools();\n}","handlingStrategy":"validation","validationCode":"// Check whether an identical instance is already registered before constructing\nconst id = 'fs-tools';\n// MCPClient dedupes instances by explicit id, so always pass one:\nconst mcp = globalThis.__mcpClient ?? (globalThis.__mcpClient = new MCPClient({ id, servers: {...} }));","typeGuard":"function hasExplicitId(opts: ConstructorParameters<typeof MCPClient>[0]): boolean {\n  return typeof (opts as { id?: string }).id === 'string' && (opts as { id?: string }).id!.length > 0;\n}","tryCatchPattern":"let mcp: MCPClient;\ntry {\n  mcp = new MCPClient({ servers: {...} });\n} catch (e) {\n  if (e instanceof Error && e.message.includes('initialized multiple times')) {\n    mcp = MCPClient.getInstance?.() ?? new MCPClient({ id: 'shared-client', servers: {...} });\n  } else throw e;\n}","preventionTips":["Always pass an explicit id when constructing MCPClient.","Create the client once at module/app scope; never inside request handlers, loops, or render bodies.","Always await client.disconnect() during shutdown or before re-creating with the same options.","Use a globalThis singleton guard to survive HMR/double module evaluation in dev."],"tags":["mcp","memory-leak","duplicate-instance","lifecycle"],"backgroundTag":"duplicate-client-initialization","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}