mirror of
https://github.com/danny-avila/LibreChat.git
synced 2025-12-17 08:50:15 +01:00
* Feature: Dynamic MCP Server with Full UI Management * 🚦 feat: Add MCP Connection Status icons to MCPBuilder panel (#10805) * feature: Add MCP server connection status icons to MCPBuilder panel * refactor: Simplify MCPConfigDialog rendering in MCPBuilderPanel --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Danny Avila <danny@librechat.ai> * fix: address code review feedback for MCP server management - Fix OAuth secret preservation to avoid mutating input parameter by creating a merged config copy in ServerConfigsDB.update() - Improve error handling in getResourcePermissionsMap to propagate critical errors instead of silently returning empty Map - Extract duplicated MCP server filter logic by exposing selectableServers from useMCPServerManager hook and using it in MCPSelect component * test: Update PermissionService tests to throw errors on invalid resource types - Changed the test for handling invalid resource types to ensure it throws an error instead of returning an empty permissions map. - Updated the expectation to check for the specific error message when an invalid resource type is provided. * feat: Implement retry logic for MCP server creation to handle race conditions - Enhanced the createMCPServer method to include retry logic with exponential backoff for handling duplicate key errors during concurrent server creation. - Updated tests to verify that all concurrent requests succeed and that unique server names are generated. - Added a helper function to identify MongoDB duplicate key errors, improving error handling during server creation. * refactor: StatusIcon to use CircleCheck for connected status - Replaced the PlugZap icon with CircleCheck in the ConnectedStatusIcon component to better represent the connected state. - Ensured consistent icon usage across the component for improved visual clarity. * test: Update AccessControlService tests to throw errors on invalid resource types - Modified the test for invalid resource types to ensure it throws an error with a specific message instead of returning an empty permissions map. - This change enhances error handling and improves test coverage for the AccessControlService. * fix: Update error message for missing server name in MCP server retrieval - Changed the error message returned when the server name is not provided from 'MCP ID is required' to 'Server name is required' for better clarity and accuracy in the API response. --------- Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com> Co-authored-by: Danny Avila <danny@librechat.ai>
90 lines
4.1 KiB
TypeScript
90 lines
4.1 KiB
TypeScript
import { registryStatusCache as statusCache } from './cache/RegistryStatusCache';
|
|
import { isLeader } from '~/cluster';
|
|
import { withTimeout } from '~/utils';
|
|
import { logger } from '@librechat/data-schemas';
|
|
import { ParsedServerConfig } from '~/mcp/types';
|
|
import { sanitizeUrlForLogging } from '~/mcp/utils';
|
|
import type * as t from '~/mcp/types';
|
|
import { MCPServersRegistry } from './MCPServersRegistry';
|
|
|
|
const MCP_INIT_TIMEOUT_MS =
|
|
process.env.MCP_INIT_TIMEOUT_MS != null ? parseInt(process.env.MCP_INIT_TIMEOUT_MS) : 30_000;
|
|
|
|
/**
|
|
* Handles initialization of MCP servers at application startup with distributed coordination.
|
|
* In cluster environments, ensures only the leader node performs initialization while followers wait.
|
|
* Connects to each configured MCP server, inspects capabilities and tools, then caches the results.
|
|
* Categorizes servers as either shared app servers (auto-started) or shared user servers (OAuth/on-demand).
|
|
* Uses a timeout mechanism to prevent hanging on unresponsive servers during initialization.
|
|
*/
|
|
export class MCPServersInitializer {
|
|
/**
|
|
* Initializes MCP servers with distributed leader-follower coordination.
|
|
*
|
|
* Design rationale:
|
|
* - Handles leader crash scenarios: If the leader crashes during initialization, all followers
|
|
* will independently attempt initialization after a 3-second delay. The first to become leader
|
|
* will complete the initialization.
|
|
* - Only the leader performs the actual initialization work (reset caches, inspect servers).
|
|
* When complete, the leader signals completion via `statusCache`, allowing followers to proceed.
|
|
* - Followers wait and poll `statusCache` until the leader finishes, ensuring only one node
|
|
* performs the expensive initialization operations.
|
|
*/
|
|
public static async initialize(rawConfigs: t.MCPServers): Promise<void> {
|
|
if (await statusCache.isInitialized()) return;
|
|
|
|
if (await isLeader()) {
|
|
// Leader performs initialization
|
|
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,
|
|
),
|
|
),
|
|
);
|
|
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);
|
|
}
|
|
}
|
|
|
|
/** 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 {
|
|
const result = await MCPServersRegistry.getInstance().addServer(
|
|
serverName,
|
|
rawConfig,
|
|
'CACHE',
|
|
);
|
|
MCPServersInitializer.logParsedConfig(serverName, result.config);
|
|
} catch (error) {
|
|
logger.error(`${MCPServersInitializer.prefix(serverName)} Failed to initialize:`, error);
|
|
}
|
|
}
|
|
|
|
// Logs server configuration summary after initialization
|
|
private static logParsedConfig(serverName: string, config: ParsedServerConfig): void {
|
|
const prefix = MCPServersInitializer.prefix(serverName);
|
|
logger.info(`${prefix} -------------------------------------------------┐`);
|
|
logger.info(`${prefix} URL: ${config.url ? sanitizeUrlForLogging(config.url) : 'N/A'}`);
|
|
logger.info(`${prefix} OAuth Required: ${config.requiresOAuth}`);
|
|
logger.info(`${prefix} Capabilities: ${config.capabilities}`);
|
|
logger.info(`${prefix} Tools: ${config.tools}`);
|
|
logger.info(`${prefix} Server Instructions: ${config.serverInstructions}`);
|
|
logger.info(`${prefix} Initialized in: ${config.initDuration ?? 'N/A'}ms`);
|
|
logger.info(`${prefix} -------------------------------------------------┘`);
|
|
}
|
|
|
|
// Returns formatted log prefix for server messages
|
|
private static prefix(serverName: string): string {
|
|
return `[MCP][${serverName}]`;
|
|
}
|
|
}
|