Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🧰 fix: Scope MCP Registry Initialization To Config Fingerprints (#13115)

Danny Avila9e8b8c37059c
diff --git a/packages/api/src/mcp/registry/MCPServersInitializer.ts b/packages/api/src/mcp/registry/MCPServersInitializer.ts
index a8b8e3ca8a..56c6ef486b 100644
--- a/packages/api/src/mcp/registry/MCPServersInitializer.ts
+++ b/packages/api/src/mcp/registry/MCPServersInitializer.ts
@@ -1,3 +1,4 @@
+import { createHash } from 'crypto';
import { logger } from '@librechat/data-schemas';
import type * as t from '~/mcp/types';
import { registryStatusCache as statusCache } from './cache/RegistryStatusCache';
@@ -6,8 +7,30 @@ import { sanitizeUrlForLogging } from '~/mcp/utils';
import { withTimeout } from '~/utils';
import { isLeader } from '~/cluster';
-const MCP_INIT_TIMEOUT_MS =
- process.env.MCP_INIT_TIMEOUT_MS != null ? parseInt(process.env.MCP_INIT_TIMEOUT_MS) : 30_000;
+const DEFAULT_MCP_INIT_TIMEOUT_MS = 30_000;
+const DEFAULT_FOLLOWER_RETRY_MS = 3000;
+
+const parseDurationMs = (
+ value: string | undefined,
+ fallback: number,
+ allowZero = false,
+): number => {
+ if (value == null) {
+ return fallback;
+ }
+ const parsed = Number(value);
+ if (!Number.isFinite(parsed)) {
+ return fallback;
+ }
+ if (allowZero) {
+ return parsed >= 0 ? parsed : fallback;
+ }
+ return parsed > 0 ? parsed : fallback;
+};
+
+type InitializeRegistryOptions = {
+ skipStatusLeaderCheck?: boolean;
+};
/**
* Handles initialization of MCP servers at application startup with distributed coordination.
@@ -37,37 +60,72 @@ export class MCPServersInitializer {
}
public static async initialize(rawConfigs: t.MCPServers): Promise<void> {
+ const configHash = MCPServersInitializer.configHash(rawConfigs);
// On first call in this process, always reset and re-initialize
// This ensures we don't use stale Redis data from previous runs
- const isFirstCallThisProcess = !MCPServersInitializer.hasInitializedThisProcess;
- // Set flag immediately so recursive calls (from followers) use Redis cache for coordination
+ let isFirstAttemptThisProcess = !MCPServersInitializer.hasInitializedThisProcess;
+ // Set flag immediately so follower retries use Redis cache for coordination
MCPServersInitializer.hasInitializedThisProcess = true;
+ const followerWaitStartedAt = performance.now();
+
+ while (true) {
+ if (!isFirstAttemptThisProcess && (await statusCache.isInitializedFor(configHash))) {
+ return;
+ }
- if (!isFirstCallThisProcess && (await statusCache.isInitialized())) return;
-
- if (await isLeader()) {
- // Leader performs initialization - always reset on first call
- await statusCache.reset();
- await MCPServersRegistry.getInstance().reset();
- const serverNames = Object.keys(rawConfigs);
- await Promise.allSettled(
- serverNames.map((serverName) =>
- withTimeout(
- MCPServersInitializer.initializeServer(serverName, rawConfigs[serverName]),
- MCP_INIT_TIMEOUT_MS,
- `${MCPServersInitializer.prefix(serverName)} Server initialization timed out`,
- logger.error,
- ),
+ if (await isLeader()) {
+ await MCPServersInitializer.initializeRegistry(rawConfigs, configHash);
+ return;
+ }
+
+ const followerWaitMs = performance.now() - followerWaitStartedAt;
+ const followerMaxWaitMs = MCPServersInitializer.followerMaxWaitMs();
+ if (followerWaitMs >= followerMaxWaitMs) {
+ logger.warn(
+ '[MCP] Timed out waiting for leader to initialize registry for current config fingerprint; initializing on this instance',
+ );
+ await MCPServersInitializer.initializeRegistry(rawConfigs, configHash, {
+ skipStatusLeaderCheck: true,
+ });
+ return;
+ }
+
+ logger.debug(
+ '[MCP] Waiting for leader to initialize registry for current config fingerprint',
+ );
+ isFirstAttemptThisProcess = false;
+ await new Promise((resolve) =>
+ setTimeout(
+ resolve,
+ Math.min(MCPServersInitializer.followerRetryMs(), followerMaxWaitMs - followerWaitMs),
),
);
- await statusCache.setInitialized(true);
- } else {
- // Followers try again after a delay if not initialized
- await new Promise((resolve) => setTimeout(resolve, 3000));
- await this.initialize(rawConfigs);
}
}
+ private static async initializeRegistry(
+ rawConfigs: t.MCPServers,
+ configHash: string,
+ options?: InitializeRegistryOptions,
+ ): Promise<void> {
+ await statusCache.reset();
+ await MCPServersRegistry.getInstance().reset();
+ const serverNames = Object.keys(rawConfigs);
+ await Promise.allSettled(
+ serverNames.map((serverName) =>
+ withTimeout(
+ MCPServersInitializer.initializeServer(serverName, rawConfigs[serverName]),
+ MCPServersInitializer.initTimeoutMs(),
+ `${MCPServersInitializer.prefix(serverName)} Server initialization timed out`,
+ logger.error,
+ ),
+ ),
+ );
+ await statusCache.setInitialized(true, configHash, {
+ skipLeaderCheck: options?.skipStatusLeaderCheck,
+ });
+ }
+
/** Initializes a single server with all its metadata and adds it to appropriate collections */
public static async initializeServer(serverName: string, rawConfig: t.MCPOptions): Promise<void> {
try {
@@ -110,4 +168,46 @@ export class MCPServersInitializer {
private static prefix(serverName: string): string {
return `[MCP][${serverName}]`;
}
+
+ private static configHash(rawConfigs: t.MCPServers): string {
+ const registry = MCPServersRegistry.getInstance();
+ const fingerprint = {
+ rawConfigs,
+ allowedDomains: registry.getAllowedDomains() ?? null,
+ allowedAddresses: registry.getAllowedAddresses() ?? null,
+ };
+ return createHash('sha256')
+ .update(JSON.stringify(MCPServersInitializer.sortForHash(fingerprint)))
+ .digest('hex');
+ }
+
+ private static followerRetryMs(): number {
+ return parseDurationMs(process.env.MCP_INIT_FOLLOWER_RETRY_MS, DEFAULT_FOLLOWER_RETRY_MS);
+ }
+
+ private static followerMaxWaitMs(): number {
+ return parseDurationMs(
+ process.env.MCP_INIT_FOLLOWER_MAX_WAIT_MS,
+ MCPServersInitializer.initTimeoutMs() + MCPServersInitializer.followerRetryMs(),
+ true,
+ );
+ }
+
+ private static initTimeoutMs(): number {
+ return parseDurationMs(process.env.MCP_INIT_TIMEOUT_MS, DEFAULT_MCP_INIT_TIMEOUT_MS);
+ }
+
+ private static sortForHash(value: unknown): unknown {
+ if (Array.isArray(value)) {
+ return value.map((item) => MCPServersInitializer.sortForHash(item));
+ }
+ if (value !== null && typeof value === 'object') {
+ return Object.fromEntries(
+ Object.entries(value as Record<string, unknown>)
+ .sort(([left], [right]) => left.localeCompare(right))
+ .map(([key, item]) => [key, MCPServersInitializer.sortForHash(item)]),
+ );
+ }
+ return value;
+ }
}
diff --git a/packages/api/src/mcp/registry/__tests__/MCPServersInitializer.test.ts b/packages/api/src/mcp/registry/__tests__/MCPServersInitializer.test.ts
index dd372744e0..03cfa948fc 100644
--- a/packages/api/src/mcp/registry/__tests__/MCPServersInitializer.test.ts
+++ b/packages/api/src/mcp/registry/__tests__/MCPServersInitializer.test.ts
@@ -1,5 +1,6 @@
import { logger } from '@librechat/data-schemas';
import * as t from '~/mcp/types';
+import { isLeader } from '~/cluster';
import { registryStatusCache } from '~/mcp/registry/cache/RegistryStatusCache';
import { MCPServersInitializer } from '~/mcp/registry/MCPServersInitializer';
import { MCPServerInspector } from '~/mcp/registry/MCPServerInspector';
@@ -47,6 +48,33 @@ const mockInspect = MCPServerInspector.inspect as jest.MockedFunction<
typeof MCPServerInspector.inspect
>;
+const withFollowerWaitEnv = async (
+ retryMs: string,
+ maxWaitMs: string,
+ callback: () => Promise<void>,
+): Promise<void> => {
+ const originalRetryMs = process.env.MCP_INIT_FOLLOWER_RETRY_MS;
+ const originalMaxWaitMs = process.env.MCP_INIT_FOLLOWER_MAX_WAIT_MS;
+ process.env.MCP_INIT_FOLLOWER_RETRY_MS = retryMs;
+ process.env.MCP_INIT_FOLLOWER_MAX_WAIT_MS = maxWaitMs;
+
+ try {
+ await callback();
+ } finally {
+ if (originalRetryMs == null) {
+ delete process.env.MCP_INIT_FOLLOWER_RETRY_MS;
+ } else {
+ process.env.MCP_INIT_FOLLOWER_RETRY_MS = originalRetryMs;
+ }
+
+ if (originalMaxWaitMs == null) {
+ delete process.env.MCP_INIT_FOLLOWER_MAX_WAIT_MS;
+ } else {
+ process.env.MCP_INIT_FOLLOWER_MAX_WAIT_MS = originalMaxWaitMs;
+ }
+ }
+};
+
describe('MCPServersInitializer', () => {
let mockConnection: jest.Mocked<MCPConnection>;
let registry: MCPServersRegistry;
@@ -184,6 +212,7 @@ describe('MCPServersInitializer', () => {
await registry.reset();
MCPServersInitializer.resetProcessFlag();
jest.clearAllMocks();
+ (isLeader as jest.MockedFunction<typeof isLeader>).mockResolvedValue(true);
});
afterEach(() => {
@@ -221,6 +250,115 @@ describe('MCPServersInitializer', () => {
expect(mockInspect).not.toHaveBeenCalled();
});
+ it('should re-initialize when the shared initialized status belongs to a different config', async () => {
+ await MCPServersInitializer.initialize(testConfigs);
+ expect(await registryStatusCache.isInitialized()).toBe(true);
+ const firstConfigHash = await registryStatusCache.getInitializedConfigHash();
+
+ const updatedConfigs: t.MCPServers = {
+ ...testConfigs,
+ new_server: {
+ type: 'stdio',
+ command: 'node',
+ args: ['new-server.js'],
+ },
+ };
+
+ jest.clearAllMocks();
+
+ await MCPServersInitializer.initialize(updatedConfigs);
+
+ expect(mockInspect).toHaveBeenCalledTimes(6);
+ expect(await registry.getServerConfig('new_server')).toBeDefined();
+ expect(await registryStatusCache.getInitializedConfigHash()).not.toBe(firstConfigHash);
+ });
+
+ it('should not let a follower accept stale initialized status from another config', async () => {
+ await MCPServersInitializer.initialize(testConfigs);
+
+ const updatedConfigs: t.MCPServers = {
+ ...testConfigs,
+ new_server: {
+ type: 'stdio',
+ command: 'node',
+ args: ['new-server.js'],
+ },
+ };
+ const mockIsLeader = isLeader as jest.MockedFunction<typeof isLeader>;
+ mockIsLeader.mockResolvedValueOnce(false).mockResolvedValueOnce(true);
+
+ jest.clearAllMocks();
+
+ await withFollowerWaitEnv('1', '50', async () => {
+ await MCPServersInitializer.initialize(updatedConfigs);
+ });
+
+ expect(mockInspect).toHaveBeenCalledTimes(6);
+ expect(mockIsLeader.mock.calls.length).toBeGreaterThanOrEqual(2);
+ expect(await registry.getServerConfig('new_server')).toBeDefined();
+ });
+
+ it('should initialize locally when a stale follower wait is exhausted', async () => {
+ await MCPServersInitializer.initialize(testConfigs);
+
+ const updatedConfigs: t.MCPServers = {
+ ...testConfigs,
+ new_server: {
+ type: 'stdio',
+ command: 'node',
+ args: ['new-server.js'],
+ },
+ };
+ const mockIsLeader = isLeader as jest.MockedFunction<typeof isLeader>;
+ mockIsLeader.mockResolvedValue(false);
+
+ jest.clearAllMocks();
+
+ await withFollowerWaitEnv('1', '1', async () => {
+ await MCPServersInitializer.initialize(updatedConfigs);
+ });
+
+ expect(mockInspect).toHaveBeenCalledTimes(6);
+ expect(mockIsLeader).toHaveBeenCalled();
+ expect(mockLogger.warn).toHaveBeenCalledWith(expect.stringContaining('Timed out waiting'));
+ expect(await registry.getServerConfig('new_server')).toBeDefined();
+ });
+
+ it('should ignore invalid follower max wait env values', async () => {
+ await MCPServersInitializer.initialize(testConfigs);
+
+ const updatedConfigs: t.MCPServers = {
+ ...testConfigs,
+ new_server: {
+ type: 'stdio',
+ command: 'node',
+ args: ['new-server.js'],
+ },
+ };
+ const mockIsLeader = isLeader as jest.MockedFunction<typeof isLeader>;
+ mockIsLeader.mockResolvedValue(false);
+ const originalInitTimeoutMs = process.env.MCP_INIT_TIMEOUT_MS;
+ process.env.MCP_INIT_TIMEOUT_MS = '1';
+
+ jest.clearAllMocks();
+
+ try {
+ await withFollowerWaitEnv('1', 'not-a-number', async () => {
+ await MCPServersInitializer.initialize(updatedConfigs);
+ });
+ } finally {
+ if (originalInitTimeoutMs == null) {
+ delete process.env.MCP_INIT_TIMEOUT_MS;
+ } else {
+ process.env.MCP_INIT_TIMEOUT_MS = originalInitTimeoutMs;
+ }
+ }
+
+ expect(mockInspect).toHaveBeenCalledTimes(6);
+ expect(mockLogger.warn).toHaveBeenCalledWith(expect.stringContaining('Timed out waiting'));
+ expect(await registry.getServerConfig('new_server')).toBeDefined();
+ });
+
it('should process all server configs through inspector', async () => {
await MCPServersInitializer.initialize(testConfigs);
diff --git a/packages/api/src/mcp/registry/cache/RegistryStatusCache.ts b/packages/api/src/mcp/registry/cache/RegistryStatusCache.ts
index 5fbd18ffdf..41e35ae99e 100644
--- a/packages/api/src/mcp/registry/cache/RegistryStatusCache.ts
+++ b/packages/api/src/mcp/registry/cache/RegistryStatusCache.ts
@@ -3,6 +3,11 @@ import { BaseRegistryCache } from './BaseRegistryCache';
// Status keys
const INITIALIZED = 'INITIALIZED';
+const INITIALIZED_CONFIG_HASH = 'INITIALIZED_CONFIG_HASH';
+
+type StatusSetOptions = {
+ skipLeaderCheck?: boolean;
+};
/**
* Cache for tracking MCP Servers Registry global metadata and status across distributed instances.
@@ -20,16 +25,41 @@ class RegistryStatusCache extends BaseRegistryCache {
return (await this.get(INITIALIZED)) === true;
}
- public async setInitialized(value: boolean): Promise<void> {
- await this.set(INITIALIZED, value);
+ public async isInitializedFor(configHash: string): Promise<boolean> {
+ if (!(await this.isInitialized())) {
+ return false;
+ }
+ return (await this.getInitializedConfigHash()) === configHash;
+ }
+
+ public async getInitializedConfigHash(): Promise<string | undefined> {
+ return this.get<string>(INITIALIZED_CONFIG_HASH);
+ }
+
+ public async setInitialized(
+ value: boolean,
+ configHash?: string,
+ options?: StatusSetOptions,
+ ): Promise<void> {
+ if (configHash != null) {
+ await this.set(INITIALIZED_CONFIG_HASH, configHash, undefined, options);
+ }
+ await this.set(INITIALIZED, value, undefined, options);
}
private async get<T = unknown>(key: string): Promise<T | undefined> {
return this.cache.get(key);
}
- private async set(key: string, value: string | number | boolean, ttl?: number): Promise<void> {
- await this.leaderCheck('set MCP Servers Registry status');
+ private async set(
+ key: string,
+ value: string | number | boolean,
+ ttl?: number,
+ options?: StatusSetOptions,
+ ): Promise<void> {
+ if (!options?.skipLeaderCheck) {
+ await this.leaderCheck('set MCP Servers Registry status');
+ }
const success = await this.cache.set(key, value, ttl);
this.successCheck(`set status key "${key}"`, success);
}