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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🔗 fix: Normalize MCP Tool Keys at Every Producer, Resolve Raw Names via Aliases (#14553)
Danny Avila6f45a9e32ebd
diff --git a/api/app/clients/tools/util/handleTools.js b/api/app/clients/tools/util/handleTools.jsindex 99f7d2fedc..5c624962a3 100644--- a/api/app/clients/tools/util/handleTools.js+++ b/api/app/clients/tools/util/handleTools.js@@ -7,6 +7,9 @@ const {mcpToolPattern,loadWebSearchAuth,splitMCPToolKey,+ buildServerNameAliases,+ findShadowedServerNames,+ isNormalizationSensitiveName,buildInlineMemoryTool,getCodeApiAuthHeaders,buildImageToolContext,@@ -47,6 +50,7 @@ const {createMCPTools,createMCPPermissionContext,resolveMcpServerContext,+ resolveCollisionAuditNames,} = require('~/server/services/MCP');const { getMCPRequestContext } = require('~/server/services/MCPRequestContext');const { createFileSearchTool, primeFiles: primeSearchFiles } = require('./fileSearch');@@ -288,12 +292,40 @@ const loadTools = async ({let configServers;/** All configured names, in the normalized form tool keys carry */let mcpServerNames = [];+ /** All configured names in raw config form, for normalized→raw resolution */+ let mcpRawServerNames = [];if (hasMCPTools && canUseMCP) {/** Reuse the caller's context when it already resolved one, so the chat* startup path reads the request app config once. */- ({ configServers, serverNames: mcpServerNames } =- options.mcpServerContext ?? (await resolveMcpServerContext(options.req)));+ ({+ configServers,+ serverNames: mcpServerNames,+ rawServerNames: mcpRawServerNames = [],+ } = options.mcpServerContext ?? (await resolveMcpServerContext(options.req)));}+ /**+ * Collision guards need the FULL accessible set (operator + user DB): a+ * cross-tier collision (DB `foo` vs operator `foo!`) is invisible to the+ * operator-config names alone. The caller's heal may have already fetched+ * it (threaded via `mcpServerContext.accessibleServerNames`); otherwise it+ * is fetched ONLY when a configured name actually needs normalizing. When+ * the full set was needed but unavailable, normalization-sensitive+ * references FAIL CLOSED below rather than auditing operator names alone.+ */+ const collisionAudit = hasMCPTools+ ? await resolveCollisionAuditNames({+ rawServerNames: mcpRawServerNames,+ /** Load-time callers thread the audit inside `mcpServerContext`;+ * deferred execution threads initialization's snapshot as a bare+ * `accessibleMcpServerNames` (it resolves no server context). */+ accessibleServerNames:+ options.mcpServerContext?.accessibleServerNames ?? options.accessibleMcpServerNames,+ userId: user,+ role: options.req?.user?.role,+ })+ : { names: [], complete: true };+ const serverNameAliases = buildServerNameAliases(collisionAudit.names);+ const shadowedServers = findShadowedServerNames(collisionAudit.names);for (const tool of tools) {if (tool === Tools.execute_code) {@@ -402,14 +434,54 @@ const loadTools = async ({continue;}- const [toolName, serverName] = splitMCPToolKey(tool, mcpServerNames);+ /** Keys carry the normalized server name (raw in pre-normalization data),+ * so both spellings resolve the boundary; everything downstream — the+ * registry, config maps, cache, and auth rows — is keyed by the RAW name. */+ const [toolName, parsedServerName] = splitMCPToolKey(tool, [+ ...mcpServerNames,+ ...serverNameAliases.values(),+ ]);if (toolName === Constants.mcp_server) {/** Placeholder used for UI purposes */continue;}- const serverConfig = serverName+ /** DIRECT-FIRST: a server resolving under the parsed name as-is wins+ * (a user-DB server may be named exactly like an operator server's+ * normalized form); only when nothing resolves is the parsed name+ * treated as a normalized spelling of a raw config name. */+ let serverName = parsedServerName;+ let serverConfig = serverName? await getMCPServersRegistry().getServerConfig(serverName, user, configServers): null;+ if (!serverConfig && serverName != null) {+ const aliasedName = serverNameAliases.get(serverName);+ if (aliasedName != null && aliasedName !== serverName) {+ serverConfig = await getMCPServersRegistry().getServerConfig(+ aliasedName,+ user,+ configServers,+ );+ if (serverConfig) {+ serverName = aliasedName;+ }+ }+ }+ /** A shadowed server's instances (wildcard-expanded or single) get the+ * SAME normalized names as the winning server's — in-run dispatch+ * could execute either. Fail closed at execution too, since legacy+ * raw keys and `mcp_all` tokens bypass catalog filtering. Under an+ * incomplete audit, any normalization-sensitive reference is+ * potentially shadowed and fails closed the same way. */+ if (+ serverName != null &&+ (shadowedServers.has(serverName) ||+ (!collisionAudit.complete && isNormalizationSensitiveName(serverName, mcpRawServerNames)))+ ) {+ logger.warn(+ `[handleTools] Skipping MCP tool "${tool}": server "${serverName}" is shadowed by a name collision (or the collision audit is unavailable); rename one server or retry.`,+ );+ continue;+ }if (!serverConfig) {logger.warn(`MCP server "${serverName}" for "${toolName}" tool is not configured${agent?.id != null && agent.id ? ` but attached to "${agent.id}"` : ''}`,diff --git a/api/app/clients/tools/util/handleTools.test.js b/api/app/clients/tools/util/handleTools.test.jsindex 6987e61091..ee5f50a512 100644--- a/api/app/clients/tools/util/handleTools.test.js+++ b/api/app/clients/tools/util/handleTools.test.js@@ -10,6 +10,7 @@ const mockGetMCPServerTools = jest.fn();const mockCreateMCPTool = jest.fn();const mockCreateMCPTools = jest.fn();const mockGetServerConfig = jest.fn();+const mockGetAccessibleMcpServerNames = jest.fn(async () => []);jest.mock('~/server/services/PluginService', () => mockPluginService);@@ -43,6 +44,23 @@ jest.mock('~/server/services/MCP', () => ({})),resolveConfigServers: jest.fn().mockResolvedValue({}),resolveMcpServerContext: jest.fn(async () => ({ configServers: {}, serverNames: [] })),+ /** Mirrors the real resolver: threaded set wins, then the accessible fetch+ * (union with raw so operator-only fixtures keep working), incomplete on+ * failure. The pure sensitivity predicate is the REAL @librechat/api one. */+ resolveCollisionAuditNames: jest.fn(async ({ rawServerNames, accessibleServerNames }) => {+ if (accessibleServerNames?.length) {+ return { names: accessibleServerNames, complete: true };+ }+ try {+ const fetched = await mockGetAccessibleMcpServerNames();+ return {+ names: fetched?.length ? fetched : rawServerNames,+ complete: true,+ };+ } catch {+ return { names: rawServerNames, complete: false };+ }+ }),}));jest.mock('~/config', () => ({@@ -358,6 +376,288 @@ describe('Tool Handlers', () => {);});+ it('resolves normalized tool keys back to the raw server for config lookups', async () => {+ /** Model-facing keys embed `normalizeServerName(server)`, while the+ * registry/config/cache are keyed by the raw config name — a+ * special-character server must still resolve its config and receive+ * the normalized key as the toolKey. */+ const rawServerName = 'Connector: Company';+ const normalizedKey = `search${Constants.mcp_delimiter}Connector__Company`;+ const serverConfig = {+ type: 'streamable-http',+ url: 'https://api.example.com/mcp',+ source: 'yaml',+ };++ const { resolveMcpServerContext } = require('~/server/services/MCP');+ resolveMcpServerContext.mockResolvedValueOnce({+ configServers: { [rawServerName]: serverConfig },+ serverNames: ['Connector__Company'],+ rawServerNames: [rawServerName],+ });+ /** Direct-first: the parsed (normalized) name is tried as-is and only+ * the raw alias resolves — mirroring a registry keyed by raw names. */+ mockGetServerConfig.mockImplementation(async (name) =>+ name === rawServerName ? serverConfig : null,+ );+ mockCreateMCPTool.mockResolvedValue({ name: normalizedKey });++ const result = await loadTools({+ user: fakeUser._id.toString(),+ tools: [normalizedKey],+ options: {+ req: {+ user: { id: fakeUser._id.toString(), role: 'USER' },+ body: {},+ },+ },+ });++ expect(result.loadedTools).toEqual([{ name: normalizedKey }]);+ expect(mockGetServerConfig).toHaveBeenCalledWith(+ rawServerName,+ expect.anything(),+ expect.anything(),+ );+ expect(mockCreateMCPTool).toHaveBeenCalledWith(+ expect.objectContaining({+ toolKey: normalizedKey,+ serverName: rawServerName,+ }),+ );+ });++ it('skips tools of a shadowed server (colliding normalized names) at execution', async () => {+ /** Instances of a shadowed server get the SAME normalized names as the+ * winner's, so in-run dispatch could execute either — legacy raw keys+ * and mcp_all tokens bypass catalog filtering, so execution must also+ * fail closed. */+ const serverConfig = {+ type: 'streamable-http',+ url: 'https://x.example/mcp',+ source: 'yaml',+ };+ const { resolveMcpServerContext } = require('~/server/services/MCP');+ resolveMcpServerContext.mockResolvedValueOnce({+ configServers: {},+ serverNames: ['Sales_Force', 'Sales_Force'],+ rawServerNames: ['Sales Force', 'Sales:Force'],+ });+ mockGetServerConfig.mockResolvedValue(serverConfig);+ mockCreateMCPTool.mockResolvedValue({ name: 'never' });++ const result = await loadTools({+ user: fakeUser._id.toString(),+ tools: [`search${Constants.mcp_delimiter}Sales:Force`],+ options: {+ req: {+ user: { id: fakeUser._id.toString(), role: 'USER' },+ body: {},+ },+ },+ });++ expect(result.loadedTools).toEqual([]);+ expect(mockCreateMCPTool).not.toHaveBeenCalled();+ });++ it('detects CROSS-TIER collisions via the accessible-server set at execution', async () => {+ /** A user-DB server `foo` shadowing operator `foo!` is invisible to the+ * operator-config names — the guard must consult the full accessible+ * set so the operator server's legacy raw key fails closed instead of+ * joining the run under the same normalized name as the DB server. */+ const serverConfig = {+ type: 'streamable-http',+ url: 'https://x.example/mcp',+ source: 'yaml',+ };+ const { resolveMcpServerContext } = require('~/server/services/MCP');+ resolveMcpServerContext.mockResolvedValueOnce({+ configServers: {},+ serverNames: ['foo'],+ rawServerNames: ['foo!'],+ });+ mockGetAccessibleMcpServerNames.mockResolvedValueOnce(['foo', 'foo!']);+ mockGetServerConfig.mockResolvedValue(serverConfig);+ mockCreateMCPTool.mockResolvedValue({ name: 'never' });++ const result = await loadTools({+ user: fakeUser._id.toString(),+ tools: [`search${Constants.mcp_delimiter}foo!`],+ options: {+ req: {+ user: { id: fakeUser._id.toString(), role: 'USER' },+ body: {},+ },+ },+ });++ expect(result.loadedTools).toEqual([]);+ expect(mockCreateMCPTool).not.toHaveBeenCalled();+ });++ it('reuses the initialization audit snapshot threaded as bare execution options', async () => {+ /** Deferred execution threads initialization's COMPLETE audit as+ * `options.accessibleMcpServerNames` (no server context is resolved+ * there) — a transient registry failure at execution must not+ * fail-closed a tool the same turn already advertised. */+ const rawServerName = 'Connector: Company';+ const normalizedKey = `search${Constants.mcp_delimiter}Connector__Company`;+ const serverConfig = {+ type: 'streamable-http',+ url: 'https://api.example.com/mcp',+ source: 'yaml',+ };+ const { resolveMcpServerContext } = require('~/server/services/MCP');+ resolveMcpServerContext.mockResolvedValueOnce({+ configServers: { [rawServerName]: serverConfig },+ serverNames: ['Connector__Company'],+ rawServerNames: [rawServerName],+ });+ mockGetAccessibleMcpServerNames.mockImplementation(async () => {+ throw new Error('registry down');+ });+ mockGetServerConfig.mockImplementation(async (name) =>+ name === rawServerName ? serverConfig : null,+ );+ mockCreateMCPTool.mockResolvedValue({ name: normalizedKey });++ try {+ const result = await loadTools({+ user: fakeUser._id.toString(),+ tools: [normalizedKey],+ options: {+ accessibleMcpServerNames: [rawServerName],+ req: {+ user: { id: fakeUser._id.toString(), role: 'USER' },+ body: {},+ },+ },+ });++ expect(result.loadedTools).toEqual([{ name: normalizedKey }]);+ expect(mockGetAccessibleMcpServerNames).not.toHaveBeenCalled();+ } finally {+ mockGetAccessibleMcpServerNames.mockImplementation(async () => []);+ }+ });++ it('detects cross-tier collisions from the execution-threaded audit snapshot', async () => {+ const serverConfig = {+ type: 'streamable-http',+ url: 'https://x.example/mcp',+ source: 'yaml',+ };+ const { resolveMcpServerContext } = require('~/server/services/MCP');+ resolveMcpServerContext.mockResolvedValueOnce({+ configServers: {},+ serverNames: ['foo'],+ rawServerNames: ['foo!'],+ });+ mockGetServerConfig.mockResolvedValue(serverConfig);+ mockCreateMCPTool.mockResolvedValue({ name: 'never' });++ const result = await loadTools({+ user: fakeUser._id.toString(),+ tools: [`search${Constants.mcp_delimiter}foo!`],+ options: {+ accessibleMcpServerNames: ['foo', 'foo!'],+ req: {+ user: { id: fakeUser._id.toString(), role: 'USER' },+ body: {},+ },+ },+ });++ expect(result.loadedTools).toEqual([]);+ expect(mockCreateMCPTool).not.toHaveBeenCalled();+ });++ it('keeps a server resolving under the parsed name as-is (direct identity wins)', async () => {+ /** A user-DB server named exactly like an operator server's normalized+ * form must keep its own identity instead of being rerouted. */+ const dbServerName = 'Connector__Company';+ const toolKey = `search${Constants.mcp_delimiter}${dbServerName}`;+ const serverConfig = {+ type: 'streamable-http',+ url: 'https://db.example.com/mcp',+ source: 'user',+ };++ const { resolveMcpServerContext } = require('~/server/services/MCP');+ resolveMcpServerContext.mockResolvedValueOnce({+ configServers: {},+ serverNames: ['Connector__Company'],+ rawServerNames: ['Connector: Company'],+ });+ mockGetServerConfig.mockImplementation(async (name) =>+ name === dbServerName ? serverConfig : null,+ );+ mockCreateMCPTool.mockResolvedValue({ name: toolKey });++ const result = await loadTools({+ user: fakeUser._id.toString(),+ tools: [toolKey],+ options: {+ req: {+ user: { id: fakeUser._id.toString(), role: 'USER' },+ body: {},+ },+ },+ });++ expect(result.loadedTools).toEqual([{ name: toolKey }]);+ expect(mockCreateMCPTool).toHaveBeenCalledWith(+ expect.objectContaining({+ toolKey,+ serverName: dbServerName,+ }),+ );+ });++ it('still resolves legacy raw-keyed tools for a special-character server', async () => {+ const rawServerName = 'Connector: Company';+ const legacyKey = `search${Constants.mcp_delimiter}${rawServerName}`;+ const serverConfig = {+ type: 'streamable-http',+ url: 'https://api.example.com/mcp',+ source: 'yaml',+ };++ const { resolveMcpServerContext } = require('~/server/services/MCP');+ resolveMcpServerContext.mockResolvedValueOnce({+ configServers: { [rawServerName]: serverConfig },+ serverNames: ['Connector__Company'],+ rawServerNames: [rawServerName],+ });+ mockGetServerConfig.mockResolvedValue(serverConfig);+ mockCreateMCPTool.mockResolvedValue({ name: 'loaded-mcp-tool' });++ const result = await loadTools({+ user: fakeUser._id.toString(),+ tools: [legacyKey],+ options: {+ req: {+ user: { id: fakeUser._id.toString(), role: 'USER' },+ body: {},+ },+ },+ });++ expect(result.loadedTools).toEqual([{ name: 'loaded-mcp-tool' }]);+ expect(mockGetServerConfig).toHaveBeenCalledWith(+ rawServerName,+ expect.anything(),+ expect.anything(),+ );+ expect(mockCreateMCPTool).toHaveBeenCalledWith(+ expect.objectContaining({+ toolKey: legacyKey,+ serverName: rawServerName,+ }),+ );+ });+it('resolves an MCP tool whose raw name itself contains the delimiter substring', async () => {// Regression test for https://github.com/danny-avila/LibreChat/issues/14440:// gateways that prefix aggregated tool names by server (e.g. LiteLLM'sdiff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.jsindex da758b384c..1b8b9d1090 100644--- a/api/server/controllers/agents/client.js+++ b/api/server/controllers/agents/client.js@@ -119,7 +119,7 @@ const {const { filterFilesByAgentAccess } = require('~/server/services/Files/permissions');const { encodeAndFormat } = require('~/server/services/Files/images/encode');const { createContextHandlers } = require('~/app/clients/prompts');-const { resolveConfigServers } = require('~/server/services/MCP');+const { resolveConfigServers, getAccessibleMcpServerNames } = require('~/server/services/MCP');const { getMCPServerTools } = require('~/server/services/Config');const BaseClient = require('~/app/clients/BaseClient');const { getMCPManager } = require('~/config');@@ -1558,6 +1558,7 @@ class AgentClient extends BaseClient {getFiles: db.getFiles,getUserKey: db.getUserKey,getConvoFiles: db.getConvoFiles,+ getAccessibleMcpServerNames,updateFilesUsage: db.updateFilesUsage,getUserKeyValues: db.getUserKeyValues,getToolFilesByIds: db.getToolFilesByIds,diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.jsindex 6c76fa5207..8cafce9ef5 100644--- a/api/server/controllers/agents/openai.js+++ b/api/server/controllers/agents/openai.js@@ -43,7 +43,11 @@ const {createToolEndCallback,agentLogHandlerObj,} = require('~/server/controllers/agents/callbacks');-const { loadAgentTools, loadToolsForExecution } = require('~/server/services/ToolService');+const {+ loadAgentTools,+ loadToolsForExecution,+ getAccessibleMcpServerNames,+} = require('~/server/services/ToolService');const {findAccessibleResources,getEffectivePermissions,@@ -76,6 +80,7 @@ function createToolLoader(signal, definitionsOnly = true) {provider,tool_options,tool_resources,+ accessibleMcpServerNames,}) {const agent = { id: agentId, tools, provider, model, tool_options };try {@@ -86,6 +91,7 @@ function createToolLoader(signal, definitionsOnly = true) {signal,tool_resources,definitionsOnly,+ accessibleMcpServerNames,streamId: null, // No resumable stream for OpenAI compat});} catch (error) {@@ -258,6 +264,7 @@ const OpenAIChatCompletionController = async (req, res) => {getFiles: db.getFiles,getUserKey: db.getUserKey,getMessages: db.getMessages,+ getAccessibleMcpServerNames,updateFilesUsage: db.updateFilesUsage,getUserKeyValues: db.getUserKeyValues,getUserCodeFiles: db.getUserCodeFiles,@@ -512,6 +519,7 @@ const OpenAIChatCompletionController = async (req, res) => {userMCPAuthMap: ctx.userMCPAuthMap,tool_resources: ctx.tool_resources,actionsEnabled: ctx.actionsEnabled,+ accessibleMcpServerNames: ctx.accessibleMcpServerNames,});return enrichLoadedToolsWithAgentContext({result,diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.jsindex 9b15032ab3..ee53e319c5 100644--- a/api/server/controllers/agents/responses.js+++ b/api/server/controllers/agents/responses.js@@ -69,7 +69,7 @@ const {enrichLoadedToolsWithAgentContext,} = require('~/server/services/Endpoints/agents/skillDeps');const { getModelsConfig } = require('~/server/controllers/ModelController');-const { resolveConfigServers } = require('~/server/services/MCP');+const { resolveConfigServers, getAccessibleMcpServerNames } = require('~/server/services/MCP');const { getMCPManager } = require('~/config');const { logViolation } = require('~/cache');const db = require('~/models');@@ -90,6 +90,7 @@ function createToolLoader(signal, definitionsOnly = true) {provider,tool_options,tool_resources,+ accessibleMcpServerNames,}) {const agent = { id: agentId, tools, provider, model, tool_options };try {@@ -100,6 +101,7 @@ function createToolLoader(signal, definitionsOnly = true) {signal,tool_resources,definitionsOnly,+ accessibleMcpServerNames,streamId: null,});} catch (error) {@@ -380,6 +382,7 @@ const createResponse = async (req, res) => {getFiles: db.getFiles,getUserKey: db.getUserKey,getMessages: db.getMessages,+ getAccessibleMcpServerNames,updateFilesUsage: db.updateFilesUsage,getUserKeyValues: db.getUserKeyValues,getUserCodeFiles: db.getUserCodeFiles,@@ -732,6 +735,7 @@ const createResponse = async (req, res) => {userMCPAuthMap: ctx.userMCPAuthMap,tool_resources: ctx.tool_resources,actionsEnabled: ctx.actionsEnabled,+ accessibleMcpServerNames: ctx.accessibleMcpServerNames,});return enrichLoadedToolsWithAgentContext({result,@@ -914,6 +918,7 @@ const createResponse = async (req, res) => {userMCPAuthMap: ctx.userMCPAuthMap,tool_resources: ctx.tool_resources,actionsEnabled: ctx.actionsEnabled,+ accessibleMcpServerNames: ctx.accessibleMcpServerNames,});return enrichLoadedToolsWithAgentContext({result,diff --git a/api/server/controllers/agents/v1.js b/api/server/controllers/agents/v1.jsindex 3fcdf53054..efc36c9940 100644--- a/api/server/controllers/agents/v1.js+++ b/api/server/controllers/agents/v1.js@@ -5,7 +5,8 @@ const { logger } = require('@librechat/data-schemas');const {refreshS3Url,splitMCPToolKey,- normalizeServerName,+ buildServerNameAliases,+ findShadowedServerNames,agentCreateSchema,agentUpdateSchema,refreshListAvatars,@@ -235,6 +236,7 @@ const filterAuthorizedTools = async ({let mcpServerConfigs;/** normalized server name -> the raw key `mcpServerConfigs` is indexed by */let configNamesByNormalized = new Map();+ let shadowedServerNames = new Set();let registryUnavailable = false;const existingToolSet = existingTools?.length ? new Set(existingTools) : null;const hasMCPTools = tools.some((tool) => tool?.includes(Constants.mcp_delimiter));@@ -278,9 +280,12 @@ const filterAuthorizedTools = async ({mcpServerConfigs = {};registryUnavailable = true;}- configNamesByNormalized = new Map(- Object.keys(mcpServerConfigs).map((name) => [normalizeServerName(name), name]),- );+ /** Shared first-wins construction — authorization must resolve a+ * colliding normalized key to the SAME server execution routes to,+ * or a tool could be authorized against one server and executed+ * against another. */+ configNamesByNormalized = buildServerNameAliases(Object.keys(mcpServerConfigs));+ shadowedServerNames = findShadowedServerNames(Object.keys(mcpServerConfigs));}/** Tool keys embed the normalized server name; the config is keyed by the raw name. */@@ -308,6 +313,17 @@ const filterAuthorizedTools = async ({continue;}+ /** A shadowed server's tools (including its `mcp_all` wildcard) produce+ * the SAME normalized function names as the winning server's — in-run+ * dispatch could execute either. Fail closed at authorization; this map+ * is the full accessible set, so DB-vs-config collisions are visible. */+ if (shadowedServerNames.has(serverName)) {+ logger.warn(+ `[filterAuthorizedTools] Rejected MCP tool "${tool}" — server "${serverName}" is shadowed by a name collision; rename one server to use it`,+ );+ continue;+ }+resolvedServerNames?.add(serverName);filteredTools.push(tool);}diff --git a/api/server/controllers/assistants/v1.js b/api/server/controllers/assistants/v1.jsindex 2a835c8f93..460734c01a 100644--- a/api/server/controllers/assistants/v1.js+++ b/api/server/controllers/assistants/v1.js@@ -7,6 +7,7 @@ const validateAuthor = require('~/server/middleware/assistants/validateAuthor');const { getStrategyFunctions } = require('~/server/services/Files/strategies');const { deleteAssistantActions } = require('~/server/services/ActionService');const { getOpenAIClient, fetchAssistants } = require('./helpers');+const { healMcpToolNames } = require('~/server/services/MCP');const { getCachedTools } = require('~/server/services/Config');const { manifestToolMap, isAgentsOnlyTool } = require('~/app/clients/tools');@@ -31,8 +32,9 @@ const createAssistant = async (req, res) => {delete assistantData.append_current_datetime;const toolDefinitions = (await getCachedTools()) ?? {};+ const healedTools = await healMcpToolNames({ req, tools, toolDefinitions });- assistantData.tools = tools+ assistantData.tools = healedTools.map((tool) => {/** Agents-runtime-only tools (e.g. ask_user_question) cannot execute on* the assistants runtime — drop them even when posted directly, since@@ -145,8 +147,9 @@ const patchAssistant = async (req, res) => {} = req.body;const toolDefinitions = (await getCachedTools()) ?? {};+ const healedTools = await healMcpToolNames({ req, tools: updateData.tools, toolDefinitions });- updateData.tools = (updateData.tools ?? [])+ updateData.tools = healedTools.map((tool) => {/** Agents-runtime-only tools (e.g. ask_user_question) cannot execute on* the assistants runtime — drop them even when posted directly, sincediff --git a/api/server/controllers/assistants/v2.js b/api/server/controllers/assistants/v2.jsindex fa05e1286a..221ebc03c1 100644--- a/api/server/controllers/assistants/v2.js+++ b/api/server/controllers/assistants/v2.js@@ -2,6 +2,7 @@ const { logger } = require('@librechat/data-schemas');const { ToolCallTypes } = require('librechat-data-provider');const validateAuthor = require('~/server/middleware/assistants/validateAuthor');const { validateAndUpdateTool } = require('~/server/services/ActionService');+const { healMcpToolNames } = require('~/server/services/MCP');const { getCachedTools } = require('~/server/services/Config');const { manifestToolMap, isAgentsOnlyTool } = require('~/app/clients/tools');const { updateAssistantDoc } = require('~/models');@@ -29,8 +30,9 @@ const createAssistant = async (req, res) => {delete assistantData.append_current_datetime;const toolDefinitions = (await getCachedTools()) ?? {};+ const healedTools = await healMcpToolNames({ req, tools, toolDefinitions });- assistantData.tools = tools+ assistantData.tools = healedTools.map((tool) => {/** Agents-runtime-only tools (e.g. ask_user_question) cannot execute on* the assistants runtime — drop them even when posted directly, since@@ -133,7 +135,9 @@ const updateAssistant = async ({ req, openai, assistant_id, updateData }) => {}let hasFileSearch = false;- for (const tool of updateData.tools ?? []) {+ const toolDefinitions = (await getCachedTools()) ?? {};+ const healedTools = await healMcpToolNames({ req, tools: updateData.tools, toolDefinitions });+ for (const tool of healedTools) {/** Agents-runtime-only tools (e.g. ask_user_question) cannot execute on* the assistants runtime — drop them even when posted directly, since* the tools-dialog scoping doesn't gate REST clients or stale payloads. */@@ -143,7 +147,6 @@ const updateAssistant = async ({ req, openai, assistant_id, updateData }) => {);continue;}- const toolDefinitions = (await getCachedTools()) ?? {};let actualTool = typeof tool === 'string' ? toolDefinitions[tool] : tool;if (!actualTool && manifestToolMap[tool] && manifestToolMap[tool].toolkit === true) {diff --git a/api/server/controllers/mcp.js b/api/server/controllers/mcp.jsindex bc850e08b4..fcd18805cb 100644--- a/api/server/controllers/mcp.js+++ b/api/server/controllers/mcp.js@@ -11,6 +11,8 @@ const {isUserSourced,MCPErrorCodes,splitMCPToolKey,+ normalizeServerName,+ findShadowedServerNames,redactServerSecrets,redactAllServerSecrets,isMCPDomainNotAllowedError,@@ -87,7 +89,21 @@ const getMCPTools = async (req, res) => {}const mcpConfig = await resolveAllMcpConfigs(userId, req.user);- const configuredServers = Object.keys(mcpConfig);+ /**+ * A server whose normalized name is claimed by an earlier server produces+ * IDENTICAL model-facing tool keys — selecting its tools would silently+ * execute against the first server's config (alias resolution is+ * first-wins). Fail closed: never publish a shadowed server's tools.+ */+ const shadowedServers = findShadowedServerNames(Object.keys(mcpConfig));+ for (const shadowedName of shadowedServers) {+ logger.warn(+ `[getMCPTools] Skipping MCP server "${shadowedName}": its normalized name collides with an earlier configured server, making tool keys ambiguous. Rename one server to expose both.`,+ );+ }+ const configuredServers = Object.keys(mcpConfig).filter(+ (serverName) => !shadowedServers.has(serverName),+ );if (!configuredServers.length) {return res.status(200).json({ servers: {} });@@ -178,7 +194,10 @@ const getMCPTools = async (req, res) => {continue;}- const [toolName] = splitMCPToolKey(toolKey, [serverName]);+ const [toolName] = splitMCPToolKey(toolKey, [+ serverName,+ normalizeServerName(serverName),+ ]);server.tools.push({name: toolName,pluginKey: toolKey,@@ -362,7 +381,13 @@ const createMCPServerController = async (req, res) => {.status(403).json({ message: 'Forbidden: Insufficient permissions to configure OBO' });}- const reservedServerNames = await resolveMcpConfigNames(req);+ /** Reserve both spellings: a generated slug must not collide with a raw+ * config name OR the normalized form its tool keys actually carry+ * (deduped — the spellings coincide for safe names). */+ const configNames = await resolveMcpConfigNames(req);+ const reservedServerNames = [+ ...new Set([...configNames, ...configNames.map(normalizeServerName)]),+ ];const result = await getMCPServersRegistry().addServer('temp_server_name',validation.data,diff --git a/api/server/routes/__tests__/mcp.spec.js b/api/server/routes/__tests__/mcp.spec.jsindex 74df9b7b59..afe275b671 100644--- a/api/server/routes/__tests__/mcp.spec.js+++ b/api/server/routes/__tests__/mcp.spec.js@@ -3044,6 +3044,33 @@ describe('MCP Routes', () => {);});+ it('reserves the normalized spelling of special-character config names too', async () => {+ /** Tool keys embed `normalizeServerName(server)`, so a generated slug+ * must not collide with that form either. */+ const validConfig = {+ type: 'sse',+ url: 'https://mcp-server.example.com/sse',+ title: 'Test SSE Server',+ };++ mockResolveMcpConfigNames.mockResolvedValueOnce(['Connector: Company']);+ mockRegistryInstance.addServer.mockResolvedValue({+ serverName: 'test-sse-server',+ config: validConfig,+ });++ const response = await request(app).post('/api/mcp/servers').send({ config: validConfig });++ expect(response.status).toBe(201);+ expect(mockRegistryInstance.addServer).toHaveBeenCalledWith(+ 'temp_server_name',+ expect.anything(),+ 'DB',+ 'test-user-id',+ ['Connector: Company', 'Connector__Company'],+ );+ });+it('should reject stdio config for security reasons', async () => {const stdioConfig = {type: 'stdio',diff --git a/api/server/services/Endpoints/agents/addedConvo.js b/api/server/services/Endpoints/agents/addedConvo.jsindex 8ab4eea9f5..d57c656028 100644--- a/api/server/services/Endpoints/agents/addedConvo.js+++ b/api/server/services/Endpoints/agents/addedConvo.js@@ -10,6 +10,7 @@ const {const { isEphemeralAgentId } = require('librechat-data-provider');const { filterFilesByAgentAccess } = require('~/server/services/Files/permissions');const { getMCPServerTools } = require('~/server/services/Config');+const { getAccessibleMcpServerNames } = require('~/server/services/MCP');const { getSkillDbMethods, canAuthorSkillFiles } = require('./skillDeps');const db = require('~/models');@@ -192,6 +193,7 @@ const processAddedConvo = async ({getUserKey: db.getUserKey,getMessages: db.getMessages,getConvoFiles: db.getConvoFiles,+ getAccessibleMcpServerNames,updateFilesUsage: db.updateFilesUsage,getUserCodeFiles: db.getUserCodeFiles,getUserKeyValues: db.getUserKeyValues,diff --git a/api/server/services/Endpoints/agents/addedConvo.spec.js b/api/server/services/Endpoints/agents/addedConvo.spec.jsindex 89e8b0af0a..de637a4011 100644--- a/api/server/services/Endpoints/agents/addedConvo.spec.js+++ b/api/server/services/Endpoints/agents/addedConvo.spec.js@@ -37,6 +37,10 @@ jest.mock('~/server/services/Config', () => ({getMCPServerTools: (...args) => mockGetMCPServerTools(...args),}));+jest.mock('~/server/services/MCP', () => ({+ getAccessibleMcpServerNames: jest.fn(async () => []),+}));+jest.mock('./skillDeps', () => ({canAuthorSkillFiles: (...args) => mockCanAuthorSkillFiles(...args),getSkillDbMethods: () => mockGetSkillDbMethods(),diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.jsindex e0e5b3024a..20f1a78b2c 100644--- a/api/server/services/Endpoints/agents/initialize.js+++ b/api/server/services/Endpoints/agents/initialize.js@@ -36,7 +36,11 @@ const {createBackgroundCodeResultHandler,getDefaultHandlers,} = require('~/server/controllers/agents/callbacks');-const { loadAgentTools, loadToolsForExecution } = require('~/server/services/ToolService');+const {+ loadAgentTools,+ loadToolsForExecution,+ getAccessibleMcpServerNames,+} = require('~/server/services/ToolService');const { filterFilesByAgentAccess } = require('~/server/services/Files/permissions');const {getSkillToolDeps,@@ -88,6 +92,7 @@ function createToolLoader(signal, streamId = null, definitionsOnly = false, jobCprovider,tool_options,tool_resources,+ accessibleMcpServerNames,}) {const agent = { id: agentId, tools, provider, model, tool_options };try {@@ -100,6 +105,7 @@ function createToolLoader(signal, streamId = null, definitionsOnly = false, jobCjobCreatedAt,tool_resources,definitionsOnly,+ accessibleMcpServerNames,});} catch (error) {logger.error('Error loading tools for agent ' + agentId, error);@@ -287,6 +293,7 @@ const initializeClient = async ({userMCPAuthMap: ctx.userMCPAuthMap,tool_resources: ctx.tool_resources,actionsEnabled: ctx.actionsEnabled,+ accessibleMcpServerNames: ctx.accessibleMcpServerNames,jobCreatedAt,});@@ -477,6 +484,7 @@ const initializeClient = async ({getUserKey: db.getUserKey,getMessages: db.getMessages,getConvoFiles: db.getConvoFiles,+ getAccessibleMcpServerNames,updateFilesUsage: db.updateFilesUsage,getUserKeyValues: db.getUserKeyValues,getUserCodeFiles: db.getUserCodeFiles,@@ -557,6 +565,7 @@ const initializeClient = async ({getUserKey: db.getUserKey,getMessages: db.getMessages,getConvoFiles: db.getConvoFiles,+ getAccessibleMcpServerNames,updateFilesUsage: db.updateFilesUsage,getUserKeyValues: db.getUserKeyValues,getUserCodeFiles: db.getUserCodeFiles,@@ -775,6 +784,7 @@ const initializeClient = async ({getUserKey: db.getUserKey,getMessages: db.getMessages,getConvoFiles: db.getConvoFiles,+ getAccessibleMcpServerNames,updateFilesUsage: db.updateFilesUsage,getUserKeyValues: db.getUserKeyValues,getUserCodeFiles: db.getUserCodeFiles,diff --git a/api/server/services/Endpoints/agents/skillDeps.js b/api/server/services/Endpoints/agents/skillDeps.jsindex d357c2bb0d..d5542ab31d 100644--- a/api/server/services/Endpoints/agents/skillDeps.js+++ b/api/server/services/Endpoints/agents/skillDeps.js@@ -286,6 +286,7 @@ function buildAgentToolContext({ agent, config }) {userMCPAuthMap: config.userMCPAuthMap,tool_resources: config.tool_resources,actionsEnabled: config.actionsEnabled,+ accessibleMcpServerNames: config.accessibleMcpServerNames,accessibleSkillIds: config.accessibleSkillIds,activeSkillNames: config.activeSkillNames,codeEnvAvailable: config.codeEnvAvailable,diff --git a/api/server/services/MCP.js b/api/server/services/MCP.jsindex 9fea5617d8..b2781c9bec 100644--- a/api/server/services/MCP.js+++ b/api/server/services/MCP.js@@ -8,6 +8,9 @@ const {isMCPDomainAllowed,splitMCPToolKey,normalizeServerName,+ normalizeMCPToolKey,+ buildServerNameAliases,+ findShadowedServerNames,resolveMCPServerContext,normalizeJsonSchema,GenerationJobManager,@@ -186,7 +189,7 @@ async function resolveMcpServerContext(req) {'[resolveMcpServerContext] Failed to resolve MCP servers, degrading to empty:',error,);- return { configServers: {}, serverNames: [] };+ return { configServers: {}, serverNames: [], rawServerNames: [] };}}@@ -197,6 +200,141 @@ async function resolveMcpServerContext(req) {* @param {{ id?: string, role?: string }} [user]* @returns {Promise<Record<string, import('@librechat/api').ParsedServerConfig>>}*/+/**+ * Names of every MCP server the user can reach (operator config + user DB),+ * for the legacy-key heal's collision detection in `initializeAgent`. Only+ * consulted when a configured server name needs normalization.+ * @param {string} [userId]+ * @param {string} [role]+ * @returns {Promise<string[]>}+ */+async function getAccessibleMcpServerNames(userId, role) {+ const configs = await resolveAllMcpConfigs(+ userId,+ role != null ? { id: userId, role } : { id: userId },+ );+ return Object.keys(configs ?? {});+}++/**+ * Heals legacy raw-keyed MCP tool names in an assistant payload to the+ * current normalized cache keys. Cached tool definitions are keyed+ * `${toolName}${mcp_delimiter}${normalizeServerName(server)}`, while an+ * assistant saved before that convention resubmits the raw-suffixed string+ * on every edit — the controllers' exact-only lookup would then silently+ * drop the tool from the assistant. SHADOWED raw names (normalized slot+ * claimed by another configured server) stay raw and fail closed, mirroring+ * the runtime heal, with the shadow set built from the FULL accessible+ * audit (cross-tier collisions included) and healing skipped outright when+ * that audit cannot complete. Config names are read only when a+ * delimiter-bearing name actually misses the cache; config-read failures+ * propagate (write path) rather than silently dropping the tool. Healed+ * string entries dedupe order-preserving so a payload carrying both+ * spellings can't submit duplicate function names.+ * @param {object} params+ * @param {ServerRequest} params.req+ * @param {Array<string | object>} [params.tools]+ * @param {Record<string, unknown>} params.toolDefinitions+ * @returns {Promise<Array<string | object>>}+ */+async function healMcpToolNames({ req, tools, toolDefinitions }) {+ const list = tools ?? [];+ const needsHeal = list.some(+ (tool) =>+ typeof tool === 'string' &&+ tool.includes(Constants.mcp_delimiter) &&+ toolDefinitions[tool] == null,+ );+ if (!needsHeal) {+ return list;+ }+ const rawServerNames = await resolveMcpConfigNames(req);+ /** Cross-tier shadowing (DB `foo` vs operator `foo!`) is invisible to+ * operator names alone — the shadow set must come from the FULL+ * accessible audit. Every rewrite candidate here is normalization-+ * sensitive by construction, so an incomplete audit skips healing+ * entirely (the raw key stays raw and fails closed). */+ const audit = await resolveCollisionAuditNames({+ rawServerNames,+ userId: req.user?.id,+ role: req.user?.role,+ });+ if (!audit.complete) {+ return list;+ }+ const shadowed = findShadowedServerNames(audit.names);+ const seen = new Set();+ const healedList = [];+ for (const tool of list) {+ let healedTool = tool;+ if (+ typeof tool === 'string' &&+ tool.includes(Constants.mcp_delimiter) &&+ toolDefinitions[tool] == null+ ) {+ const [, parsedServerName] = splitMCPToolKey(tool, rawServerNames);+ if (+ parsedServerName != null &&+ rawServerNames.includes(parsedServerName) &&+ !shadowed.has(parsedServerName)+ ) {+ const healed = normalizeMCPToolKey(tool, rawServerNames);+ if (toolDefinitions[healed] != null) {+ healedTool = healed;+ }+ }+ }+ /** A payload carrying both spellings collapses to one entry after the+ * heal — duplicate function names make providers reject the save. */+ if (typeof healedTool === 'string') {+ if (seen.has(healedTool)) {+ continue;+ }+ seen.add(healedTool);+ }+ healedList.push(healedTool);+ }+ return healedList;+}++/**+ * Resolves the name set MCP collision guards audit against. Prefers the+ * caller-threaded accessible set; self-fetches only when a configured name+ * needs normalization (safe-name deployments never pay the lookup); reports+ * `complete: false` when the full set was needed but unavailable — callers+ * must then fail closed for normalization-sensitive references instead of+ * auditing against operator names alone.+ * @param {object} params+ * @param {readonly string[]} params.rawServerNames+ * @param {readonly string[]} [params.accessibleServerNames]+ * @param {string} [params.userId]+ * @param {string} [params.role]+ * @returns {Promise<{ names: readonly string[], complete: boolean }>}+ */+async function resolveCollisionAuditNames({ rawServerNames, accessibleServerNames, userId, role }) {+ if (accessibleServerNames?.length) {+ return { names: accessibleServerNames, complete: true };+ }+ const needsFullAudit = rawServerNames.some((name) => normalizeServerName(name) !== name);+ if (!needsFullAudit) {+ return { names: rawServerNames, complete: true };+ }+ try {+ const names = await getAccessibleMcpServerNames(userId, role);+ /** `resolveAllMcpConfigs` tolerates `ensureConfigServers` failures, so+ * the merged read can silently omit config-only servers. The caller's+ * raw config names come from the app-config snapshot (registry-+ * independent), so the union keeps `complete: true` honest. */+ return { names: [...new Set([...names, ...rawServerNames])], complete: true };+ } catch (error) {+ logger.warn(+ '[MCP] Collision audit unavailable; normalization-sensitive references fail closed:',+ error,+ );+ return { names: rawServerNames, complete: false };+ }+}+async function resolveAllMcpConfigs(userId, user) {const registry = getMCPServersRegistry();const appConfig = await getAppConfigForUser(userId, user);@@ -657,7 +795,9 @@ async function createMCPTools({jobCreatedAt,availableTools: result.availableTools,serverName,- toolKey: `${tool.name}${Constants.mcp_delimiter}${serverName}`,+ /** Model-facing key: matches the normalized `availableTools` keys and+ * the instance name `createToolInstance` will assign. */+ toolKey: `${tool.name}${Constants.mcp_delimiter}${normalizeServerName(serverName)}`,requestBody,requestScopedConnections,config: serverConfig,@@ -713,17 +853,37 @@ async function createMCPTool({/** `loadTools` already resolved the server for this key; parsing is the fallback. */const [parsedToolName, parsedServerName] = splitMCPToolKey(toolKey,- /** Tool keys embed the normalized server name, so the candidate list must be- * normalized too or a name needing normalization never matches. */+ /** Current keys embed the NORMALIZED server name, legacy persisted keys+ * the RAW one — the candidate list needs both spellings or a raw name+ * that contains the delimiter mis-splits under the generic fallback. */resolvedServerName- ? [normalizeServerName(resolvedServerName)]- : Object.keys(configServers ?? {}).map(normalizeServerName),+ ? [resolvedServerName, normalizeServerName(resolvedServerName)]+ : Object.keys(configServers ?? {}).flatMap((name) => [name, normalizeServerName(name)]),);- const serverName = resolvedServerName ?? parsedServerName;+ let serverName = resolvedServerName ?? parsedServerName;const toolName = parsedToolName;- const serverConfig =+ let serverConfig =config ?? (await getMCPServersRegistry().getServerConfig(serverName, user?.id, configServers));+ /** DIRECT-FIRST alias fallback: only when the parsed name resolves to no+ * server is it treated as the normalized spelling of a raw config name —+ * a user-DB server named like an operator server's normalized form must+ * keep its own identity. */+ if (!serverConfig && resolvedServerName == null && parsedServerName != null) {+ const aliasedName = buildServerNameAliases(Object.keys(configServers ?? {})).get(+ parsedServerName,+ );+ if (aliasedName != null && aliasedName !== parsedServerName) {+ serverConfig = await getMCPServersRegistry().getServerConfig(+ aliasedName,+ user?.id,+ configServers,+ );+ if (serverConfig) {+ serverName = aliasedName;+ }+ }+ }const requestScopedTools = serverConfig ? requiresEphemeralUserConnection(serverConfig) : false;const useMissingToolCache = !requestScopedTools;@@ -750,8 +910,19 @@ async function createMCPTool({}}+ /** Legacy keys persisted pre-normalization (assistants, direct tool+ * calls) carry the RAW server name, while `availableTools` is keyed by+ * the canonical normalized key — look up both spellings. */+ const canonicalToolKey =+ serverName != null+ ? `${toolName}${Constants.mcp_delimiter}${normalizeServerName(serverName)}`+ : toolKey;+ const findToolDefinition = (tools) =>+ tools?.[toolKey]?.function ??+ (canonicalToolKey !== toolKey ? tools?.[canonicalToolKey]?.function : undefined);+/** @type {LCTool | undefined} */- let toolDefinition = availableTools?.[toolKey]?.function;+ let toolDefinition = findToolDefinition(availableTools);if (!toolDefinition) {const cachedAt = useMissingToolCache ? missingToolCache.get(toolKey) : undefined;if (cachedAt && Date.now() - cachedAt < MISSING_TOOL_TTL_MS) {@@ -781,7 +952,7 @@ async function createMCPTool({if (result?.availableTools) {onAvailableTools?.(result.availableTools);}- toolDefinition = result?.availableTools?.[toolKey]?.function;+ toolDefinition = findToolDefinition(result?.availableTools);if (!toolDefinition && useMissingToolCache) {missingToolCache.set(toolKey, Date.now());@@ -1151,6 +1322,9 @@ module.exports = {resolveConfigServers,resolveMcpServerNames,resolveMcpServerContext,+ getAccessibleMcpServerNames,+ healMcpToolNames,+ resolveCollisionAuditNames,resolveMcpConfigNames,resolveAllMcpConfigs,createOAuthStart,diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.jsindex 89f4f945da..b4a81c7627 100644--- a/api/server/services/ToolService.js+++ b/api/server/services/ToolService.js@@ -29,6 +29,10 @@ const {buildMCPAuthRunStepCompletedEvent,isFileAuthoringToolDefinition,ASK_USER_QUESTION_TOOL_NAME,+ splitMCPToolKey,+ buildServerNameAliases,+ findShadowedServerNames,+ isNormalizationSensitiveName,} = require('@librechat/api');const {Time,@@ -69,7 +73,12 @@ const { primeFiles: primeCodeFiles } = require('~/server/services/Files/Code/proconst { manifestToolMap, toolkits } = require('~/app/clients/tools/manifest');const { createOnSearchResults } = require('~/server/services/Tools/search');const { reinitMCPServer } = require('~/server/services/Tools/mcp');-const { createMCPPermissionContext, resolveMcpServerContext } = require('~/server/services/MCP');+const {+ createMCPPermissionContext,+ resolveMcpServerContext,+ getAccessibleMcpServerNames,+ resolveCollisionAuditNames,+} = require('~/server/services/MCP');const { getMCPRequestContext } = require('~/server/services/MCPRequestContext');const { recordUsage } = require('~/server/services/Threads');const { loadTools } = require('~/app/clients/tools/util');@@ -548,6 +557,7 @@ async function loadToolDefinitionsWrapper({streamId = null,jobCreatedAt,tool_resources,+ accessibleMcpServerNames,}) {if (!agent.tools || agent.tools.length === 0) {return { toolDefinitions: [] };@@ -610,9 +620,64 @@ async function loadToolDefinitionsWrapper({/** Only MCP tool keys need the server context; a purely non-MCP agent should not* pay an app-config lookup on startup. */const hasFilteredMCPTools = filteredTools.some((t) => t.includes(Constants.mcp_delimiter));- const { configServers, serverNames: mcpServerNames } = hasFilteredMCPTools+ const {+ configServers,+ serverNames: mcpServerNames,+ rawServerNames: mcpRawServerNames = [],+ } = hasFilteredMCPTools? await resolveMcpServerContext(req)- : { configServers: {}, serverNames: [] };+ : { configServers: {}, serverNames: [], rawServerNames: [] };++ /**+ * Shadowed servers must not emit definitions: their normalized function+ * names equal the winning server's, and the default execution path later+ * resolves those names directly — selecting a shadowed server's definition+ * could execute another server's action. Audited against the full+ * accessible set (threaded from the caller's heal, or fetched only when a+ * configured name needs normalization); normalization-sensitive references+ * fail closed when the audit is incomplete.+ */+ let defsFilteredTools = filteredTools;+ /** Complete audit names, forwarded to the definitions loader so its alias+ * fallback can tell "server not found" from "server found but currently+ * unavailable" — only the former may fall back to the raw alias. */+ let defsAccessibleServerNames;+ if (hasFilteredMCPTools) {+ const collisionAudit = await resolveCollisionAuditNames({+ rawServerNames: mcpRawServerNames,+ accessibleServerNames: accessibleMcpServerNames,+ userId: req.user.id,+ role: req.user?.role,+ });+ if (collisionAudit.complete) {+ defsAccessibleServerNames = collisionAudit.names;+ }+ const defsShadowedServers = findShadowedServerNames(collisionAudit.names);+ if (defsShadowedServers.size > 0 || !collisionAudit.complete) {+ const defsAliases = buildServerNameAliases(collisionAudit.names);+ const boundaryCandidates = [...collisionAudit.names, ...defsAliases.keys()];+ defsFilteredTools = filteredTools.filter((tool) => {+ if (!tool.includes(Constants.mcp_delimiter)) {+ return true;+ }+ const [, parsed] = splitMCPToolKey(tool, boundaryCandidates);+ const serverName = parsed != null ? (defsAliases.get(parsed) ?? parsed) : parsed;+ if (serverName == null) {+ return true;+ }+ if (+ defsShadowedServers.has(serverName) ||+ (!collisionAudit.complete && isNormalizationSensitiveName(serverName, mcpRawServerNames))+ ) {+ logger.warn(+ `[Tool Definitions] Skipping MCP tool "${tool}": server "${serverName}" is shadowed by a name collision (or the collision audit is unavailable); rename one server or retry.`,+ );+ return false;+ }+ return true;+ });+ }+ }/** @type {Record<string, Record<string, string>>} */let userMCPAuthMap;@@ -620,7 +685,7 @@ async function loadToolDefinitionsWrapper({userMCPAuthMap = await getUserMCPAuthMap({tools: filteredTools,userId: req.user.id,- serverNames: mcpServerNames,+ serverNames: mcpRawServerNames,findPluginAuthsByKeys,});}@@ -738,6 +803,9 @@ async function loadToolDefinitionsWrapper({return cachedOAuthStart;};+ /** Name-preserving: the definitions loader resolves normalized-vs-raw+ * spellings itself (direct identity first, alias fallback), so this+ * closure must look up EXACTLY the name it is given. */const getOrFetchMCPServerTools = async (userId, serverName) => {const addPendingOAuthServer = async () => {const pendingOAuthStart = await getReplayablePendingMCPOAuthStart({@@ -886,13 +954,15 @@ async function loadToolDefinitionsWrapper({{userId: req.user.id,agentId: agent.id,- tools: filteredTools,+ tools: defsFilteredTools,toolOptions: agent.tool_options,deferredToolsEnabled,programmaticToolsEnabled,codeExecutionEnabled,provider: agent.provider,mcpServerNames,+ rawServerNames: mcpRawServerNames,+ accessibleServerNames: defsAccessibleServerNames,},{isBuiltInTool,@@ -901,7 +971,9 @@ async function loadToolDefinitionsWrapper({},);- for (const serverName of getMCPServerNamesFromTools(filteredTools, mcpServerNames)) {+ /** OAuth discovery must not reconnect (or prompt for) a server whose+ * definitions the collision filter deliberately rejected. */+ for (const serverName of getMCPServerNamesFromTools(defsFilteredTools, mcpServerNames)) {if (pendingOAuthServers.has(serverName)) {continue;}@@ -969,13 +1041,15 @@ async function loadToolDefinitionsWrapper({{userId: req.user.id,agentId: agent.id,- tools: filteredTools,+ tools: defsFilteredTools,toolOptions: agent.tool_options,deferredToolsEnabled,programmaticToolsEnabled,codeExecutionEnabled,provider: agent.provider,mcpServerNames,+ rawServerNames: mcpRawServerNames,+ accessibleServerNames: defsAccessibleServerNames,},{isBuiltInTool,@@ -1112,6 +1186,7 @@ async function loadAgentTools({streamId = null,jobCreatedAt,definitionsOnly = true,+ accessibleMcpServerNames,}) {if (definitionsOnly) {return loadToolDefinitionsWrapper({@@ -1121,6 +1196,7 @@ async function loadAgentTools({streamId,jobCreatedAt,tool_resources,+ accessibleMcpServerNames,});}@@ -1190,10 +1266,16 @@ async function loadAgentTools({webSearchCallbacks = createOnSearchResults(res, streamId, jobCreatedAt);}- /** Resolved once and threaded into `loadTools` so the request app config is read once. */- const mcpServerContext = _agentTools?.some((t) => t.includes(Constants.mcp_delimiter))+ /** Resolved once and threaded into `loadTools` so the request app config is+ * read once. The accessible set (operator + user DB), when the caller's+ * heal already fetched it, rides along so execution-side collision guards+ * see cross-tier shadowing without another registry round-trip. */+ let mcpServerContext = _agentTools?.some((t) => t.includes(Constants.mcp_delimiter))? await resolveMcpServerContext(req): undefined;+ if (mcpServerContext && accessibleMcpServerNames?.length) {+ mcpServerContext = { ...mcpServerContext, accessibleServerNames: accessibleMcpServerNames };+ }/** @type {Record<string, Record<string, string>>} */let userMCPAuthMap;@@ -1201,7 +1283,7 @@ async function loadAgentTools({userMCPAuthMap = await getUserMCPAuthMap({tools: _agentTools,userId: req.user.id,- serverNames: mcpServerContext.serverNames,+ serverNames: mcpServerContext.rawServerNames ?? mcpServerContext.serverNames,findPluginAuthsByKeys,});}@@ -1483,6 +1565,7 @@ async function loadAgentTools({* @param {string|null} [params.streamId] - Stream ID for web search callbacks* @param {number} [params.jobCreatedAt] - The generation epoch that owns emitted tool events* @param {boolean} [params.actionsEnabled] - Whether the actions capability is enabled+ * @param {readonly string[]} [params.accessibleMcpServerNames] - COMPLETE accessible-server audit resolved at initialization* @returns {Promise<{ loadedTools: Array, configurable: Object }>}*/async function loadToolsForExecution({@@ -1501,6 +1584,7 @@ async function loadToolsForExecution({streamId = null,jobCreatedAt,actionsEnabled,+ accessibleMcpServerNames,}) {const appConfig = req.config;const allLoadedTools = [];@@ -1681,6 +1765,10 @@ async function loadToolsForExecution({uploadImageBuffer,returnMetadata: true,mcpAvailableTools,+ /** Initialization's COMPLETE audit snapshot — reused so a transient+ * registry failure at execution can't fail-closed a tool the same+ * turn already advertised. */+ accessibleMcpServerNames,requestScopedConnections: mcpRequestScopedConnections,[Tools.web_search]: webSearchCallbacks,},@@ -1872,4 +1960,7 @@ module.exports = {loadToolsForExecution,processRequiredActions,resolveAgentCapabilities,+ /** Re-exported for controllers that already depend on (and mock) this+ * module, avoiding a fresh heavy `services/MCP` require chain there. */+ getAccessibleMcpServerNames,};diff --git a/api/server/services/__tests__/MCP.spec.js b/api/server/services/__tests__/MCP.spec.jsindex 81848ebadb..76df1c321d 100644--- a/api/server/services/__tests__/MCP.spec.js+++ b/api/server/services/__tests__/MCP.spec.js@@ -24,21 +24,28 @@ jest.mock('~/server/services/Config', () => ({}));jest.mock('@librechat/api', () => ({+ /** Pure helpers (normalizeServerName, splitMCPToolKey, schema utils, ...)+ * stay REAL so key-normalization paths are exercised, not mirrored. */+ ...jest.requireActual('@librechat/api'),sendEvent: jest.fn(),MCPOAuthHandler: jest.fn(),isMCPDomainAllowed: jest.fn(),- normalizeServerName: jest.fn((name) => name),- normalizeJsonSchema: jest.fn((schema) => schema),GenerationJobManager: jest.fn(),- resolveJsonSchemaRefs: jest.fn((schema) => schema),buildOAuthToolCallName: jest.fn((name) => name),/** Mirrors the real resolver so these tests still exercise the wrapper's own* plumbing - loading the request config and degrading on failure - rather than- * the resolution logic, which is unit-tested in packages/api. */- resolveMCPServerContext: jest.fn(async ({ mcpConfig, ensureConfigServers }) => ({- configServers: await ensureConfigServers(mcpConfig),- serverNames: Object.keys(mcpConfig),- })),+ * the resolution logic, which is unit-tested in packages/api. Like the real+ * resolver, a lazy-init failure keeps the name lists. */+ resolveMCPServerContext: jest.fn(async ({ mcpConfig, ensureConfigServers }) => {+ const rawServerNames = Object.keys(mcpConfig);+ let configServers = {};+ try {+ configServers = await ensureConfigServers(mcpConfig);+ } catch {+ /* tolerated: name lists derive from the config snapshot alone */+ }+ return { configServers, serverNames: rawServerNames, rawServerNames };+ }),}));jest.mock('~/cache', () => ({ getLogStores: jest.fn() }));@@ -60,12 +67,18 @@ jest.mock('~/server/services/Tools/mcp', () => ({reinitMCPServer: jest.fn(),}));+const { Constants } = require('librechat-data-provider');+const { getAppConfig } = require('~/server/services/Config');+const { reinitMCPServer } = require('~/server/services/Tools/mcp');const {+ createMCPTool,+ healMcpToolNames,resolveConfigServers,resolveMcpConfigNames,resolveAllMcpConfigs,resolveMcpServerContext,+ resolveCollisionAuditNames,} = require('../MCP');describe('resolveConfigServers', () => {@@ -134,16 +147,23 @@ describe('resolveMcpServerContext', () => {const result = await resolveMcpServerContext({ user: { id: 'u1' } });- expect(result).toEqual({ configServers: {}, serverNames: [] });+ expect(result).toEqual({ configServers: {}, serverNames: [], rawServerNames: [] });});- it('degrades to empty when ensureConfigServers throws', async () => {+ it('keeps the name lists when only ensureConfigServers throws', async () => {+ /** The name lists derive from the config snapshot alone; losing them+ * would leave normalized tool keys unresolvable for the whole request —+ * a strictly worse degradation than missing overlay configs. */getAppConfig.mockResolvedValue({ mcpConfig: { srv: {} } });mockRegistry.ensureConfigServers.mockRejectedValue(new Error('inspect failed'));const result = await resolveMcpServerContext({ user: { id: 'u1' } });- expect(result).toEqual({ configServers: {}, serverNames: [] });+ expect(result).toEqual({+ configServers: {},+ serverNames: ['srv'],+ rawServerNames: ['srv'],+ });});});@@ -227,3 +247,229 @@ describe('resolveAllMcpConfigs', () => {await expect(resolveAllMcpConfigs('u1', { id: 'u1' })).rejects.toThrow('mongo down');});});++describe('healMcpToolNames', () => {+ beforeEach(() => jest.clearAllMocks());++ const req = { user: { id: 'u1', role: 'user' } };++ it('heals a legacy raw-keyed assistant tool to the normalized cache key', async () => {+ /** Assistant docs saved pre-normalization resubmit the raw-suffixed+ * string on every edit; the controllers' exact lookup would silently+ * drop the tool. */+ getAppConfig.mockResolvedValue({ mcpConfig: { 'Connector: Company': {} } });+ mockRegistry.ensureConfigServers.mockResolvedValue({});+ mockRegistry.getAllServerConfigs.mockResolvedValue({ 'Connector: Company': {} });+ const canonicalKey = `search${Constants.mcp_delimiter}Connector__Company`;+ const toolDefinitions = { [canonicalKey]: { type: 'function' } };++ const healed = await healMcpToolNames({+ req,+ tools: [`search${Constants.mcp_delimiter}Connector: Company`, 'code_interpreter'],+ toolDefinitions,+ });++ expect(healed).toEqual([canonicalKey, 'code_interpreter']);+ });++ it('leaves a SHADOWED raw name untouched (fail closed like the runtime heal)', async () => {+ /** With `foo` and `foo!` both configured, rewriting `search_mcp_foo!`+ * would land on the WINNER server's key. */+ getAppConfig.mockResolvedValue({ mcpConfig: { foo: {}, 'foo!': {} } });+ mockRegistry.ensureConfigServers.mockResolvedValue({});+ mockRegistry.getAllServerConfigs.mockResolvedValue({ foo: {}, 'foo!': {} });+ const toolDefinitions = { [`search${Constants.mcp_delimiter}foo`]: { type: 'function' } };++ const healed = await healMcpToolNames({+ req,+ tools: [`search${Constants.mcp_delimiter}foo!`],+ toolDefinitions,+ });++ expect(healed).toEqual([`search${Constants.mcp_delimiter}foo!`]);+ });++ it('skips the config read entirely when every delimiter-bearing name resolves', async () => {+ const key = `search${Constants.mcp_delimiter}srv`;+ const healed = await healMcpToolNames({+ req,+ tools: [key, 'web_search'],+ toolDefinitions: { [key]: { type: 'function' } },+ });++ expect(healed).toEqual([key, 'web_search']);+ expect(getAppConfig).not.toHaveBeenCalled();+ });++ it('fails closed on a CROSS-TIER shadow (user-DB server owns the normalized slot)', async () => {+ /** Operator config alone shows `foo!` unshadowed, but a user-DB server+ * named `foo` owns the normalized slot — rewriting would bind the+ * saved assistant to the DB server's tool at execution. */+ getAppConfig.mockResolvedValue({ mcpConfig: { 'foo!': {} } });+ mockRegistry.ensureConfigServers.mockResolvedValue({});+ mockRegistry.getAllServerConfigs.mockResolvedValue({+ foo: { name: 'foo' },+ 'foo!': { name: 'foo!' },+ });+ const toolDefinitions = { [`search${Constants.mcp_delimiter}foo`]: { type: 'function' } };++ const healed = await healMcpToolNames({+ req,+ tools: [`search${Constants.mcp_delimiter}foo!`],+ toolDefinitions,+ });++ expect(healed).toEqual([`search${Constants.mcp_delimiter}foo!`]);+ });++ it('skips healing entirely when the collision audit cannot complete', async () => {+ getAppConfig.mockResolvedValue({ mcpConfig: { 'Connector: Company': {} } });+ mockRegistry.ensureConfigServers.mockResolvedValue({});+ mockRegistry.getAllServerConfigs.mockRejectedValue(new Error('redis down'));+ const canonicalKey = `search${Constants.mcp_delimiter}Connector__Company`;++ const healed = await healMcpToolNames({+ req,+ tools: [`search${Constants.mcp_delimiter}Connector: Company`],+ toolDefinitions: { [canonicalKey]: { type: 'function' } },+ });++ expect(healed).toEqual([`search${Constants.mcp_delimiter}Connector: Company`]);+ });++ it('dedupes when the payload carries both spellings of the same tool', async () => {+ getAppConfig.mockResolvedValue({ mcpConfig: { 'Connector: Company': {} } });+ mockRegistry.ensureConfigServers.mockResolvedValue({});+ mockRegistry.getAllServerConfigs.mockResolvedValue({ 'Connector: Company': {} });+ const canonicalKey = `search${Constants.mcp_delimiter}Connector__Company`;+ const toolDefinitions = { [canonicalKey]: { type: 'function' } };++ const healed = await healMcpToolNames({+ req,+ tools: [+ `search${Constants.mcp_delimiter}Connector: Company`,+ canonicalKey,+ 'code_interpreter',+ ],+ toolDefinitions,+ });++ expect(healed).toEqual([canonicalKey, 'code_interpreter']);+ });+});++describe('resolveCollisionAuditNames', () => {+ beforeEach(() => jest.clearAllMocks());++ it('restores config names the tolerant merged read silently dropped', async () => {+ /** `resolveAllMcpConfigs` swallows `ensureConfigServers` failures, so a+ * transient init error can omit a config-only server from the merged+ * map — the audit would then miss the `foo` / `foo!` collision while+ * still claiming completeness. The snapshot-derived raw names must be+ * unioned back in. */+ getAppConfig.mockResolvedValue({ mcpConfig: { 'foo!': {} } });+ mockRegistry.ensureConfigServers.mockRejectedValue(new Error('init failed'));+ mockRegistry.getAllServerConfigs.mockResolvedValue({ foo: { name: 'foo' } });++ const audit = await resolveCollisionAuditNames({+ rawServerNames: ['foo!'],+ userId: 'u1',+ role: 'user',+ });++ expect(audit.complete).toBe(true);+ expect([...audit.names].sort()).toEqual(['foo', 'foo!']);+ });++ it('reports incomplete when the merged read itself fails', async () => {+ getAppConfig.mockResolvedValue({ mcpConfig: { 'foo!': {} } });+ mockRegistry.ensureConfigServers.mockResolvedValue({});+ mockRegistry.getAllServerConfigs.mockRejectedValue(new Error('redis down'));++ const audit = await resolveCollisionAuditNames({+ rawServerNames: ['foo!'],+ userId: 'u1',+ role: 'user',+ });++ expect(audit.complete).toBe(false);+ expect(audit.names).toEqual(['foo!']);+ });+});++describe('createMCPTool', () => {+ beforeEach(() => jest.clearAllMocks());++ const rawServerName = 'Connector: Company';+ const legacyToolKey = `search${Constants.mcp_delimiter}${rawServerName}`;+ const canonicalToolKey = `search${Constants.mcp_delimiter}Connector__Company`;+ const toolFunction = {+ name: canonicalToolKey,+ description: 'Search the company connector',+ parameters: { type: 'object', properties: { q: { type: 'string' } }, required: ['q'] },+ };++ it('resolves a legacy raw-spelled key against the normalized availableTools index', async () => {+ /** Assistants and direct tool calls persisted pre-normalization bypass+ * the agent-boundary heal and arrive with RAW keys; `availableTools`+ * is keyed canonically, so the lookup must cover both spellings+ * instead of stubbing the tool as unavailable. */+ const toolInstance = await createMCPTool({+ user: { id: 'user-1' },+ toolKey: legacyToolKey,+ serverName: rawServerName,+ availableTools: { [canonicalToolKey]: { type: 'function', function: toolFunction } },+ config: { type: 'stdio', command: 'node' },+ provider: 'openAI',+ });++ expect(toolInstance).toBeDefined();+ expect(toolInstance.name).toBe(canonicalToolKey);+ expect(toolInstance.description).toBe(toolFunction.description);+ expect(reinitMCPServer).not.toHaveBeenCalled();+ });++ it('parses a legacy key whose raw server name contains the delimiter', async () => {+ /** A raw name like `foo_mcp_bar!` defeats the generic last-delimiter+ * split (`toolName` would become `search_mcp_foo`), so the boundary+ * candidates must include the RAW resolved name — not only its+ * normalized form — for the canonical rebuild to hit the index. */+ const delimiterRawName = 'foo_mcp_bar!';+ const legacyKey = `search${Constants.mcp_delimiter}${delimiterRawName}`;+ /** `normalizeServerName` strips the trailing underscore the `!` leaves. */+ const canonicalKey = `search${Constants.mcp_delimiter}foo_mcp_bar`;+ const delimiterToolFunction = {+ name: canonicalKey,+ description: 'Search the delimiter-named server',+ parameters: { type: 'object', properties: {} },+ };++ const toolInstance = await createMCPTool({+ user: { id: 'user-1' },+ toolKey: legacyKey,+ serverName: delimiterRawName,+ availableTools: { [canonicalKey]: { type: 'function', function: delimiterToolFunction } },+ config: { type: 'stdio', command: 'node' },+ provider: 'openAI',+ });++ expect(toolInstance).toBeDefined();+ expect(toolInstance.name).toBe(canonicalKey);+ expect(reinitMCPServer).not.toHaveBeenCalled();+ });++ it('still resolves the canonical key directly', async () => {+ const toolInstance = await createMCPTool({+ user: { id: 'user-1' },+ toolKey: canonicalToolKey,+ serverName: rawServerName,+ availableTools: { [canonicalToolKey]: { type: 'function', function: toolFunction } },+ config: { type: 'stdio', command: 'node' },+ provider: 'openAI',+ });++ expect(toolInstance).toBeDefined();+ expect(toolInstance.name).toBe(canonicalToolKey);+ expect(reinitMCPServer).not.toHaveBeenCalled();+ });+});diff --git a/api/server/services/__tests__/ToolService.spec.js b/api/server/services/__tests__/ToolService.spec.jsindex 3b4a31d1b5..511025802b 100644--- a/api/server/services/__tests__/ToolService.spec.js+++ b/api/server/services/__tests__/ToolService.spec.js@@ -90,8 +90,15 @@ jest.mock('~/server/services/MCP', () => ({resolveMcpServerNames: (...args) => mockResolveMcpServerNames(...args),resolveMcpServerContext: async (...args) => {const configServers = (await mockResolveConfigServers(...args)) ?? {};- return { configServers, serverNames: Object.keys(configServers) };+ const serverNames = Object.keys(configServers);+ return { configServers, serverNames, rawServerNames: serverNames };},+ /** Mirrors the real resolver's shape; these fixtures use safe names, so the+ * raw set is always the complete audit. */+ resolveCollisionAuditNames: jest.fn(async ({ rawServerNames, accessibleServerNames }) => ({+ names: accessibleServerNames?.length ? accessibleServerNames : rawServerNames,+ complete: true,+ })),createMCPPermissionContext: jest.fn((req) => ({canUseServers: (user) => mockUserCanUseMCPServers(user, req),})),diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/McpSection.spec.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/McpSection.spec.tsxindex f5f99d0799..6beee45dd3 100644--- a/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/McpSection.spec.tsx+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/McpSection.spec.tsx@@ -6,6 +6,8 @@ import McpSection from '../sections/McpSection';const mockSetValue = jest.fn();const mockGetValues = jest.fn((): string[] => []);+const mockGetToolOptions = jest.fn((): Record<string, object> | undefined => undefined);+const mockMcpServersMap = jest.fn((): Map<string, object> => new Map());const mockInitializeServer = jest.fn();const mockIsConnectionDeferred = jest.fn((): boolean => false);const mockToggleIntentAll = jest.fn();@@ -19,11 +21,12 @@ const mockCapabilities = {jest.mock('react-hook-form', () => ({useFormContext: () => ({ control: {}, setValue: mockSetValue, getValues: mockGetValues }),- useWatch: () => mockGetValues(),+ useWatch: ({ name }: { name: string }) =>+ name === 'tool_options' ? mockGetToolOptions() : mockGetValues(),}));jest.mock('~/Providers', () => ({- useAgentPanelContext: () => ({ mcpServersMap: new Map() }),+ useAgentPanelContext: () => ({ mcpServersMap: mockMcpServersMap() }),}));jest.mock('~/components/ui', () => ({@@ -155,6 +158,10 @@ describe('McpSection', () => {mockToggleIntentAll.mockClear();mockIsToolProgrammaticOnly.mockReset();mockIsToolProgrammaticOnly.mockReturnValue(false);+ mockGetToolOptions.mockReset();+ mockGetToolOptions.mockReturnValue(undefined);+ mockMcpServersMap.mockReset();+ mockMcpServersMap.mockReturnValue(new Map());mockCapabilities.toolIntentsEnabled = false;});@@ -319,6 +326,142 @@ describe('McpSection', () => {]);});+ test('legacy raw-keyed form ids show as selected for a special-character server', () => {+ /** Tool ids in the catalog now embed the normalized server name; an agent+ * saved before that convention must still show its tools checked. */+ const specialItem: McpItem = {+ ...item,+ id: 'Connector: Company',+ name: 'Connector: Company',+ server: {+ serverName: 'Connector: Company',+ isConfigured: true,+ tools: [{ tool_id: 'search_mcp_Connector__Company', name: 'Search' }],+ metadata: { description: 'desc' },+ } as never,+ toolCount: 1,+ };+ mockGetValues.mockReturnValue(['search_mcp_Connector: Company']);+ render(<McpSection item={specialItem} />);+ expect(screen.getByTestId('tool-search_mcp_Connector__Company')).toHaveAttribute(+ 'aria-pressed',+ 'true',+ );+ });++ test('selection updates REPLACE legacy raw-keyed ids instead of letting them survive', () => {+ const specialItem: McpItem = {+ ...item,+ id: 'Connector: Company',+ name: 'Connector: Company',+ server: {+ serverName: 'Connector: Company',+ isConfigured: true,+ tools: [{ tool_id: 'search_mcp_Connector__Company', name: 'Search' }],+ metadata: { description: 'desc' },+ } as never,+ toolCount: 1,+ };+ mockGetValues.mockReturnValue(['search_mcp_Connector: Company']);+ render(<McpSection item={specialItem} />);+ /** Deselecting the (legacy-selected) tool must drop the raw id rather+ * than leave it behind for the runtime heal to keep active. */+ fireEvent.click(screen.getByTestId('tool-search_mcp_Connector__Company'));+ expect(mockSetValue).toHaveBeenCalledWith(+ 'tools',+ ['sys__server__sys_mcp_Connector: Company'],+ expect.objectContaining({ shouldDirty: true }),+ );+ });++ test('migrates legacy raw-keyed tool_options to the current normalized ids', () => {+ /** Persisted options must be readable and clearable through the toggles,+ * which index by the normalized catalog id; an existing normalized entry+ * wins over the legacy one on collision. */+ const specialItem: McpItem = {+ ...item,+ id: 'Connector: Company',+ name: 'Connector: Company',+ server: {+ serverName: 'Connector: Company',+ isConfigured: true,+ tools: [{ tool_id: 'search_mcp_Connector__Company', name: 'Search' }],+ metadata: { description: 'desc' },+ } as never,+ toolCount: 1,+ };+ mockGetToolOptions.mockReturnValue({+ 'search_mcp_Connector: Company': { run_in_background: true, defer_loading: true },+ search_mcp_Connector__Company: { run_in_background: false },+ other_tool: { describe_intent: true },+ });+ render(<McpSection item={specialItem} />);+ expect(mockSetValue).toHaveBeenCalledWith('tool_options', {+ other_tool: { describe_intent: true },+ search_mcp_Connector__Company: { run_in_background: false, defer_loading: true },+ });+ });++ test('never migrates keys of a SHADOWED server (normalized slot claimed by another)', () => {+ /** With servers `foo` and `foo!`, rewriting `search_mcp_foo!` would land+ * on `search_mcp_foo` — the WINNER server's key — so saving would apply+ * the shadowed server's defer/background/intent settings to the other+ * server's tool. The runtime heal leaves shadowed keys raw; the form+ * migration must fail closed the same way. */+ mockMcpServersMap.mockReturnValue(+ new Map<string, object>([+ ['foo', {}],+ ['foo!', {}],+ ]),+ );+ const shadowedServer: McpItem = {+ ...item,+ id: 'foo!',+ name: 'foo!',+ server: {+ serverName: 'foo!',+ isConfigured: true,+ tools: [{ tool_id: 'search_mcp_foo', name: 'Search' }],+ metadata: { description: 'desc' },+ } as never,+ toolCount: 1,+ };+ mockGetToolOptions.mockReturnValue({+ 'search_mcp_foo!': { run_in_background: true },+ });+ render(<McpSection item={shadowedServer} />);+ expect(mockSetValue).not.toHaveBeenCalledWith('tool_options', expect.anything());+ });++ test('never migrates entries that belong to a LONGER server sharing this suffix', () => {+ /** With servers `!bar` and `foo_mcp_!bar`, the longer server's legacy key+ * also suffix-ends with `_mcp_!bar` — opening the shorter server's dialog+ * must not reassign or corrupt the longer server's persisted settings. */+ mockMcpServersMap.mockReturnValue(+ new Map<string, object>([+ ['!bar', {}],+ ['foo_mcp_!bar', {}],+ ]),+ );+ const shortServer: McpItem = {+ ...item,+ id: '!bar',+ name: '!bar',+ server: {+ serverName: '!bar',+ isConfigured: true,+ tools: [{ tool_id: 'search_mcp_bar', name: 'Search' }],+ metadata: { description: 'desc' },+ } as never,+ toolCount: 1,+ };+ mockGetToolOptions.mockReturnValue({+ 'search_mcp_foo_mcp_!bar': { run_in_background: true },+ });+ render(<McpSection item={shortServer} />);+ expect(mockSetValue).not.toHaveBeenCalledWith('tool_options', expect.anything());+ });+test('shows the runtime-tools hint when attached via the wildcard', () => {mockGetValues.mockReturnValue(['sys__all__sys_mcp_srv']);const empty: McpItem = {diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsxindex 6b56d84dc7..d4e0e5a5d5 100644--- a/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsx+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsx@@ -2,6 +2,12 @@ import { useState, useMemo, useEffect, useCallback } from 'react';import { Clock, Code2, Captions, Zap } from 'lucide-react';import { useFormContext, useWatch } from 'react-hook-form';import { Button, Spinner, Checkbox, Skeleton } from '@librechat/client';+import {+ Constants,+ splitMCPToolKey,+ normalizeServerName,+ buildServerNameAliases,+} from 'librechat-data-provider';import type { MouseEvent } from 'react';import type { TranslationKeys } from '~/hooks/useLocalize';import type { McpItem } from '../../items/types';@@ -118,32 +124,118 @@ export default function McpSection({ item }: Props) {* servers whose tools resolve at chat-turn time and can't be listed here. */const isWildcardAttached = formTools.includes(serverAllToken);+ /**+ * Maps a legacy raw-keyed form entry for THIS server to its current+ * (normalized) catalog id — an agent saved before tool keys embedded the+ * normalized server name would otherwise show its tools unchecked while the+ * runtime heal keeps them active, and per-tool updates could never replace+ * the legacy entry. Tokens and other servers' entries pass through.+ */+ const toCurrentToolId = useCallback(+ (entry: string): string => {+ const normalizedName = normalizeServerName(serverName);+ if (+ normalizedName === serverName ||+ entry === serverToken ||+ entry === serverAllToken ||+ !entry.endsWith(`${Constants.mcp_delimiter}${serverName}`)+ ) {+ return entry;+ }+ /** Boundary-exact: this raw suffix could equally terminate a LONGER+ * configured server name — resolve the entry once against every+ * configured server (both spellings, longest match) and rewrite only+ * when it truly belongs to THIS server, or the migration could+ * reassign another server's persisted settings. */+ /** Include THIS server even when a stale catalog map omits it, so a+ * missing entry doesn't misread as a collision. */+ const allServerNames = Array.from(new Set([...mcpServersMap.keys(), serverName]));+ const aliases = buildServerNameAliases(allServerNames);+ /** A SHADOWED server (its normalized slot claimed by another catalog+ * name) keeps legacy keys raw — the runtime heal fails closed the+ * same way; rewriting here would move this server's persisted+ * options onto the winning server's key. */+ if (aliases.get(normalizedName) !== serverName) {+ return entry;+ }+ const [, parsed] = splitMCPToolKey(entry, [...allServerNames, ...aliases.keys()]);+ if (parsed == null || (aliases.get(parsed) ?? parsed) !== serverName) {+ return entry;+ }+ return `${entry.slice(0, entry.length - serverName.length)}${normalizedName}`;+ },+ [serverName, serverToken, serverAllToken, mcpServersMap],+ );++ /**+ * Migrates legacy raw-keyed `tool_options` for THIS server to the current+ * normalized ids the option toggles (defer / programmatic / background /+ * intent) read and write — otherwise a persisted option shows disabled+ * while the runtime heal keeps honoring it, and toggling the normalized+ * control leaves the raw entry behind. An existing normalized entry wins+ * over the legacy one on collision. Form state only; the user's next real+ * edit persists it.+ */+ const formToolOptions = useWatch({ control, name: 'tool_options' });+ useEffect(() => {+ if (!formToolOptions) {+ return;+ }+ const entries = Object.entries(formToolOptions);+ if (!entries.some(([key]) => toCurrentToolId(key) !== key)) {+ return;+ }+ const migrated: typeof formToolOptions = {};+ for (const [key, options] of entries) {+ if (toCurrentToolId(key) === key) {+ migrated[key] = options;+ }+ }+ for (const [key, options] of entries) {+ const target = toCurrentToolId(key);+ if (target === key) {+ continue;+ }+ migrated[target] = { ...options, ...migrated[target] };+ }+ setValue('tool_options', migrated);+ }, [formToolOptions, toCurrentToolId, setValue]);+/** The `mcp_all` wildcard grants every server tool at runtime, so when the* server's tools ARE enumerable (e.g. it stopped being request-scoped), fold* the wildcard into the display as "all selected" — otherwise the dialog* would show unchecked boxes while runtime grants everything. Any selection* interaction then rewrites the form with concrete tool ids (the wildcard is* stripped by `updateFormTools`), converting the attachment on first touch. */- const getSelectedTools = (): string[] =>- isWildcardAttached- ? tools.map((t) => t.tool_id)- : tools.filter((t) => formTools.includes(t.tool_id)).map((t) => t.tool_id);+ const getSelectedTools = (): string[] => {+ if (isWildcardAttached) {+ return tools.map((t) => t.tool_id);+ }+ const formToolIds = new Set(formTools.map(toCurrentToolId));+ return tools.filter((t) => formToolIds.has(t.tool_id)).map((t) => t.tool_id);+ };/** Replace this server's tool selection while keeping the server attached: the* placeholder token is always rewritten, so deselect-all leaves the server* pinned with zero tools; only an explicit remove detaches it. The `mcp_all`* wildcard is also stripped unless explicitly re-passed in `next`, so a* per-tool selection always supersedes a stale wildcard (e.g. after a server- * stops being request-scoped and its tools become enumerable). */+ * stops being request-scoped and its tools become enumerable). Legacy+ * raw-keyed entries count as this server's (via `toCurrentToolId`), so a+ * selection update REPLACES them instead of letting a deselected legacy+ * tool survive every rewrite. */const updateFormTools = useCallback((next: string[]) => {const current = (getValues('tools') ?? []) as string[];const otherTools = current.filter(- (t) => t !== serverToken && t !== serverAllToken && !tools.some((st) => st.tool_id === t),+ (t) =>+ t !== serverToken &&+ t !== serverAllToken &&+ !tools.some((st) => st.tool_id === toCurrentToolId(t)),);setValue('tools', [...otherTools, serverToken, ...next], { shouldDirty: true });},- [getValues, setValue, serverToken, serverAllToken, tools],+ [getValues, setValue, serverToken, serverAllToken, tools, toCurrentToolId],);const toggleToolSelect = (toolId: string) => {diff --git a/client/src/components/SidePanel/Agents/Tools/ToolsMarketplaceDialog.tsx b/client/src/components/SidePanel/Agents/Tools/ToolsMarketplaceDialog.tsxindex a1427b10f0..2089518637 100644--- a/client/src/components/SidePanel/Agents/Tools/ToolsMarketplaceDialog.tsx+++ b/client/src/components/SidePanel/Agents/Tools/ToolsMarketplaceDialog.tsx@@ -11,7 +11,7 @@ import {} from '@librechat/client';import type { AgentItem, AgentItemKind, ItemFilter } from './items/types';import type { AgentForm } from '~/common';-import { itemKey, mcpServerToken, matchesMcpServer } from './items/selectors';+import { itemKey, mcpServerToken, matchesMcpServer, mcpServerIds } from './items/selectors';import { useAgentItems, useUninstallToolCredentials } from './hooks';import AddMcpServerDialog from './ItemDialog/AddMcpServerDialog';import { computeToggleAction } from './items/mutations';@@ -133,10 +133,11 @@ export default function ToolsMarketplaceDialog({case 'mcp-remove': {if (item.kind !== 'mcp') break;const toolIds = new Set((item.server.tools ?? []).map((t) => t.tool_id));+ const allServerNames = mcpServerIds(catalog);const current = (getValues('tools') ?? []) as string[];setValue('tools',- current.filter((t) => !matchesMcpServer(t, item.id) && !toolIds.has(t)),+ current.filter((t) => !matchesMcpServer(t, item.id, allServerNames) && !toolIds.has(t)),{ shouldDirty: true },);break;@@ -145,7 +146,7 @@ export default function ToolsMarketplaceDialog({break;}},- [getValues, setValue, selectedIds, uninstallToolCredentials],+ [getValues, setValue, selectedIds, uninstallToolCredentials, catalog],);const handleCardClick = useCallback(diff --git a/client/src/components/SidePanel/Agents/Tools/items/__tests__/selectors.spec.ts b/client/src/components/SidePanel/Agents/Tools/items/__tests__/selectors.spec.tsindex 12b904e9af..940aef31b3 100644--- a/client/src/components/SidePanel/Agents/Tools/items/__tests__/selectors.spec.ts+++ b/client/src/components/SidePanel/Agents/Tools/items/__tests__/selectors.spec.ts@@ -223,6 +223,29 @@ describe('matchesMcpServer', () => {expect(matchesMcpServer('mcp_github_extra', 'github_extra')).toBe(true);expect(matchesMcpServer('search_mcp_github_extra', 'github_extra')).toBe(true);});++ test('boundary-exact matching prevents a delimiter-bearing normalized name from double-matching', () => {+ /** Raw `foo mcp bar` normalizes to `foo_mcp_bar`, which suffix-matching+ * would ALSO attribute to a server named `bar` — both cards would show+ * selected and removing `bar` would strip the other server's tool.+ * With the full server list, the token resolves once by longest match. */+ const allServers = ['foo mcp bar', 'bar'];+ expect(matchesMcpServer('search_mcp_foo_mcp_bar', 'foo mcp bar', allServers)).toBe(true);+ expect(matchesMcpServer('search_mcp_foo_mcp_bar', 'bar', allServers)).toBe(false);+ expect(matchesMcpServer('search_mcp_bar', 'bar', allServers)).toBe(true);+ expect(matchesMcpServer('search_mcp_bar', 'foo mcp bar', allServers)).toBe(false);+ });++ test('matches normalized-spelling tool ids for a special-character server', () => {+ /** Model-facing tool ids embed `normalizeServerName(server)`, while the+ * marketplace/server cards are keyed raw — both spellings must count as+ * attached or a selected server renders as an unselected orphan. */+ expect(matchesMcpServer('search_mcp_Connector__Company', 'Connector: Company')).toBe(true);+ expect(matchesMcpServer('search_mcp_Connector: Company', 'Connector: Company')).toBe(true);+ expect(matchesMcpServer('mcp_Connector__Company', 'Connector: Company')).toBe(true);+ expect(matchesMcpServer('search_mcp_Connector__Company', 'Connector__Company')).toBe(true);+ expect(matchesMcpServer('search_mcp_Connector__Other', 'Connector: Company')).toBe(false);+ });});describe('selection — ask_user_question builtin rides agent.tools', () => {diff --git a/client/src/components/SidePanel/Agents/Tools/items/selectors.ts b/client/src/components/SidePanel/Agents/Tools/items/selectors.tsindex c1082f8dd2..5023d8cab4 100644--- a/client/src/components/SidePanel/Agents/Tools/items/selectors.ts+++ b/client/src/components/SidePanel/Agents/Tools/items/selectors.ts@@ -1,4 +1,9 @@-import { Constants } from 'librechat-data-provider';+import {+ Constants,+ splitMCPToolKey,+ normalizeServerName,+ buildServerNameAliases,+} from 'librechat-data-provider';import type { Action } from 'librechat-data-provider';import type { AgentItem, AgentItemKind } from './types';@@ -81,26 +86,61 @@ export function mcpAllToken(serverName: string): string {* Whether a form `tools` token references the given MCP server, across every* format ever persisted: the server placeholder token, the raw server name,* the exact `mcp_<server>` pluginKey form, and delimiter-suffixed per-tool- * ids (`<tool>_mcp_<server>`). All checks are exact or delimiter-bounded —+ * ids (`<tool>_mcp_<server>`) — in both the raw spelling (legacy documents)+ * and the normalized spelling model-facing tool ids carry+ * (`normalizeServerName`). All checks are exact or delimiter-bounded —* server names may contain underscores, so a bare prefix match would claim* `mcp_github_extra` for a server named `github`. Selection and removal must* share this predicate: anything the selection logic counts as attached, an* explicit remove must also strip, or a legacy token leaves the server* permanently selected.*/-export function matchesMcpServer(token: string, serverName: string): boolean {+export function matchesMcpServer(+ token: string,+ serverName: string,+ allServerNames?: readonly string[],+): boolean {const prefixed = `${MCP_PREFIX}${serverName}`;- return (+ const normalized = normalizeServerName(serverName);+ if (token === mcpServerToken(serverName) ||token === serverName ||token === prefixed ||- token.endsWith(`_${prefixed}`)- );+ (normalized !== serverName && token === `${MCP_PREFIX}${normalized}`)+ ) {+ return true;+ }+ if (allServerNames?.length) {+ /** Boundary-exact: resolve the token ONCE against every configured+ * server (longest match, both spellings) — a normalized name that+ * itself contains the delimiter (`foo mcp bar` → `foo_mcp_bar`) must+ * not ALSO suffix-match a server named `bar`, or both cards select+ * together and removing one strips the other's tool. */+ const aliases = buildServerNameAliases(allServerNames);+ const [, parsed] = splitMCPToolKey(token, [...allServerNames, ...aliases.keys()]);+ if (parsed == null) {+ return false;+ }+ return (aliases.get(parsed) ?? parsed) === serverName;+ }+ if (token.endsWith(`_${prefixed}`)) {+ return true;+ }+ return normalized !== serverName && token.endsWith(`_${MCP_PREFIX}${normalized}`);}-function isMcpSelected(item: AgentItem, form: FormSelection): boolean {+/** All configured MCP server ids in a catalog, for boundary-exact matching. */+export function mcpServerIds(catalog: AgentItem[]): string[] {+ return catalog.filter((item) => item.kind === 'mcp').map((item) => item.id);+}++function isMcpSelected(+ item: AgentItem,+ form: FormSelection,+ allServerNames: readonly string[],+): boolean {if (item.kind !== 'mcp') return false;- return form.tools.some((t) => matchesMcpServer(t, item.id));+ return form.tools.some((t) => matchesMcpServer(t, item.id, allServerNames));}function isSkillSelected(item: AgentItem, form: FormSelection): boolean {@@ -118,10 +158,11 @@ export function deriveSelectedItems(catalog: AgentItem[],agentActions: Action[],): AgentItem[] {+ const allServerNames = mcpServerIds(catalog);const selected = catalog.filter((item) => {if (item.kind === 'builtin') return isBuiltinSelected(item, form);if (item.kind === 'tool') return isToolSelected(item, form);- if (item.kind === 'mcp') return isMcpSelected(item, form);+ if (item.kind === 'mcp') return isMcpSelected(item, form, allServerNames);if (item.kind === 'skill') return isSkillSelected(item, form);if (item.kind === 'action') return isActionSelected(item, agentActions);return false;diff --git a/client/src/hooks/MCP/__tests__/useVisibleTools.test.ts b/client/src/hooks/MCP/__tests__/useVisibleTools.test.tsindex 724b3980b5..17e99f6b70 100644--- a/client/src/hooks/MCP/__tests__/useVisibleTools.test.ts+++ b/client/src/hooks/MCP/__tests__/useVisibleTools.test.ts@@ -33,6 +33,29 @@ describe('useVisibleTools', () => {expect(result.current.mcpServerNames).toEqual(['gitlab']);});+ it('resolves normalized-spelling ids back to the raw server key of the servers map', () => {+ /** Tool ids embed `normalizeServerName(server)` while the servers map is+ * keyed raw — a special-character server must resolve to its raw map key+ * instead of surfacing the normalized segment as an unknown orphan. */+ const specialMap = new Map<string, MCPServerInfo>([+ ['Connector: Company', {} as MCPServerInfo],+ ]);+ const { result } = renderHook(() =>+ useVisibleTools([`search${d}Connector__Company`], regularTools, specialMap),+ );+ expect(result.current.mcpServerNames).toEqual(['Connector: Company']);+ });++ it('still resolves legacy raw-spelling ids for a special-character server', () => {+ const specialMap = new Map<string, MCPServerInfo>([+ ['Connector: Company', {} as MCPServerInfo],+ ]);+ const { result } = renderHook(() =>+ useVisibleTools([`search${d}Connector: Company`], regularTools, specialMap),+ );+ expect(result.current.mcpServerNames).toEqual(['Connector: Company']);+ });+it('keeps regular (non-MCP) tools separate from MCP server names', () => {const { result } = renderHook(() =>useVisibleTools(['web_search'], regularTools, mcpServersMap),diff --git a/client/src/hooks/MCP/useVisibleTools.ts b/client/src/hooks/MCP/useVisibleTools.tsindex 015248d112..95998948cb 100644--- a/client/src/hooks/MCP/useVisibleTools.ts+++ b/client/src/hooks/MCP/useVisibleTools.ts@@ -1,5 +1,5 @@import { useMemo } from 'react';-import { Constants, splitMCPToolKey } from 'librechat-data-provider';+import { Constants, splitMCPToolKey, buildServerNameAliases } from 'librechat-data-provider';import type { TPlugin } from 'librechat-data-provider';import type { MCPServerInfo } from '~/common';@@ -24,15 +24,21 @@ export function useVisibleTools(): VisibleToolsResult {return useMemo(() => {const knownServerNames = Array.from(mcpServersMap.keys());+ /** Tool ids embed the normalized server name while the servers map is+ * keyed by the raw config name — resolve either spelling back to raw so+ * an attached special-character server is not misread as an unknown+ * orphan (legacy documents may still carry raw-keyed ids). */+ const aliases = buildServerNameAliases(knownServerNames);+ const candidates = [...knownServerNames, ...aliases.keys()];const mcpServers = new Set<string>();const regularToolIds: string[] = [];for (const toolId of selectedToolIds ?? []) {// MCP tools/serversif (toolId.includes(Constants.mcp_delimiter)) {- const [, serverName] = splitMCPToolKey(toolId, knownServerNames);+ const [, serverName] = splitMCPToolKey(toolId, candidates);if (serverName) {- mcpServers.add(serverName);+ mcpServers.add(aliases.get(serverName) ?? serverName);}}// Legacy MCP server check (just server name)diff --git a/packages/api/src/agents/__tests__/initialize.test.ts b/packages/api/src/agents/__tests__/initialize.test.tsindex 61e1a8afb2..27bbe3789c 100644--- a/packages/api/src/agents/__tests__/initialize.test.ts+++ b/packages/api/src/agents/__tests__/initialize.test.ts@@ -33,7 +33,7 @@ jest.mock('@librechat/agents', () => ({}));import { Providers } from '@librechat/agents';-import { EModelEndpoint, EToolResources, Tools } from 'librechat-data-provider';+import { Constants, EModelEndpoint, EToolResources, Tools } from 'librechat-data-provider';import type { IMongoFile } from '@librechat/data-schemas';import type { Agent } from 'librechat-data-provider';import type { ServerRequest, InitializeResultBase, EndpointTokenConfig } from '~/types';@@ -2222,4 +2222,65 @@ describe('initializeAgent — run-scoped MCP tool definitions', () => {expect(result.mcpAvailableTools).toEqual(mcpAvailableTools);});++ it('retains the resolved collision audit on the initialized agent', async () => {+ /** Deferred/event-driven execution reuses this snapshot instead of+ * repeating the merged-registry read — a transient failure there+ * would fail-closed a tool the turn already advertised. */+ const { agent, req, res, loadTools, db } = createMocks();+ const rawServerName = 'Connector: Company';+ const accessibleNames = [rawServerName, 'plain_server'];+ (req as { config: { mcpConfig?: Record<string, unknown> } }).config = {+ mcpConfig: { [rawServerName]: {} },+ };+ agent.tools = [`search${Constants.mcp_delimiter}${rawServerName}`];+ const getAccessibleMcpServerNames = jest.fn(async () => accessibleNames);++ const result = await initializeAgent(+ {+ req,+ res,+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set([Providers.OPENAI]),+ isInitialAgent: true,+ },+ { ...db, getAccessibleMcpServerNames },+ );++ expect(result.accessibleMcpServerNames).toEqual(accessibleNames);+ expect(loadTools).toHaveBeenCalledWith(+ expect.objectContaining({ accessibleMcpServerNames: accessibleNames }),+ );+ });++ it('unions snapshot config names into the audit when the merged read omits them', async () => {+ /** The registry's merged read tolerates config-server init failures and+ * can silently drop config-only servers — the heal audit must restore+ * them from the request's config snapshot or a collision goes unseen+ * while the audit still claims completeness. */+ const { agent, req, res, loadTools, db } = createMocks();+ const rawServerName = 'Connector: Company';+ (req as { config: { mcpConfig?: Record<string, unknown> } }).config = {+ mcpConfig: { [rawServerName]: {} },+ };+ agent.tools = [`search${Constants.mcp_delimiter}${rawServerName}`];+ const getAccessibleMcpServerNames = jest.fn(async () => ['db_only_server']);++ const result = await initializeAgent(+ {+ req,+ res,+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set([Providers.OPENAI]),+ isInitialAgent: true,+ },+ { ...db, getAccessibleMcpServerNames },+ );++ expect(result.accessibleMcpServerNames).toEqual(['db_only_server', rawServerName]);+ });});diff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.tsindex e98cbea041..2ed2740d15 100644--- a/packages/api/src/agents/initialize.ts+++ b/packages/api/src/agents/initialize.ts@@ -40,6 +40,12 @@ import {unionPrimeAllowedTools,MAX_PRIMED_SKILLS_PER_TURN,} from './skills';+import {+ normalizeServerName,+ requiresEphemeralUserConnection,+ splitMCPToolKey,+ normalizeAgentToolKeys,+} from '~/mcp/utils';import {optionalChainWithEmptyCheck,extractLibreChatParams,@@ -51,7 +57,6 @@ import {registerFileAuthoringTools,isFileAuthoringToolDefinition,} from './tools';-import { normalizeServerName, requiresEphemeralUserConnection, splitMCPToolKey } from '~/mcp/utils';import { registerMemoryTools, memoryToolUsageGuard } from './memory';import { applyIntentLabels, sanitizeIntentLabels } from './intent';import { applyBackgroundToolCalls } from './background';@@ -284,6 +289,14 @@ export type InitializedAgent = Agent & {memoryToolsRegistered?: boolean;/** Whether the actions capability is enabled (resolved during tool loading) */actionsEnabled?: boolean;+ /**+ * The COMPLETE accessible-server audit this initialization resolved (via+ * the agent-key or skill-prime heal). Retained so deferred/event-driven+ * execution reuses the same snapshot instead of repeating the merged+ * registry read — a transient failure there would fail-closed a tool the+ * turn already advertised from the successful first audit.+ */+ accessibleMcpServerNames?: readonly string[];/** Maximum characters allowed in a single tool result before truncation. */maxToolResultChars?: number;/** Response field to read model reasoning from for custom OpenAI-compatible endpoints. */@@ -391,6 +404,10 @@ export interface InitializeAgentParams {model: string | null;tool_options: AgentToolOptions | undefined;tool_resources: AgentToolResources | undefined;+ /** Full accessible MCP server names (operator + user DB) when the heal+ * already fetched them — lets execution-side collision guards see+ * cross-tier shadowing without another registry round-trip. */+ accessibleMcpServerNames?: readonly string[];}) => Promise<{/** Full tool instances (only present when definitionsOnly=false) */tools?: GenericTool[];@@ -465,6 +482,15 @@ export interface InitializeAgentParams {* getConvoFiles not yet in data-schemas but included here for consistency*/export interface InitializeAgentDbMethods extends EndpointDbMethods {+ /**+ * Names of every MCP server the user can reach (operator config + user DB).+ * Consulted by the legacy-key heal ONLY when a configured name needs+ * normalization: collision detection must see user-DB servers, or healing a+ * raw key could produce a key that direct-first resolution routes to a+ * different (DB) server. Optional — without it the heal falls back to the+ * operator-config names.+ */+ getAccessibleMcpServerNames?: (userId?: string, role?: string) => Promise<string[]>;/** Update usage tracking for multiple files */updateFilesUsage: (files: Array<{ file_id: string }>,@@ -637,6 +663,78 @@ export async function initializeAgent(throw new Error('initializeAgent requires db methods to be passed');}+ /**+ * Heal legacy MCP tool keys ONCE, before anything reads them: model-facing+ * keys embed the normalized server name (cache keys, definition names,+ * runtime instance names), so an agent document persisted with raw-named+ * keys would neither load those tools nor have any of its per-tool+ * `tool_options` honored. Every downstream consumer — the tool loader, the+ * defer/programmatic classification, the background and intent passes —+ * reads `agent.tools` / `agent.tool_options` after this point.+ */+ const configRawServerNames = Object.keys(req.config?.mcpConfig ?? {});+ const configNeedsNormalization = configRawServerNames.some(+ (name) => normalizeServerName(name) !== name,+ );+ /**+ * Rewriting legacy keys requires a COMPLETE collision audit: the normalized+ * form of an operator name may belong to a user-DB server, and healing into+ * that key would route the tool to the wrong server. The audit therefore+ * uses the full accessible set — fetched lazily, once, and ONLY when a+ * configured name actually needs normalization AND the caller has+ * delimiter-bearing keys to heal (a non-MCP agent never pays the lookup).+ * When the audit cannot complete (no dep, or a transient failure), healing+ * is SKIPPED entirely: un-healed raw keys still resolve through the+ * direct-first candidates, so skipping is safe while rewriting is not.+ */+ let healNamesPromise: Promise<readonly string[] | null> | undefined;+ const resolveHealNames = (): Promise<readonly string[] | null> => {+ if (!configNeedsNormalization) {+ return Promise.resolve(configRawServerNames);+ }+ if (db.getAccessibleMcpServerNames == null) {+ return Promise.resolve(null);+ }+ healNamesPromise ??= db+ .getAccessibleMcpServerNames(req.user?.id, req.user?.role)+ /** The merged registry read tolerates config-server init failures and+ * can silently omit config-only servers; the snapshot-derived config+ * names restore them so the audit stays genuinely complete. */+ .then((names): readonly string[] => [...new Set([...names, ...configRawServerNames])])+ .catch((error): null => {+ logger.warn(+ '[initializeAgent] Failed to resolve accessible MCP server names; skipping legacy-key healing (collision audit unavailable):',+ error,+ );+ return null;+ });+ return healNamesPromise;+ };+ const hasMCPKeyCandidates =+ (agent.tools ?? []).some(+ (tool) => typeof tool === 'string' && tool.includes(Constants.mcp_delimiter),+ ) || Object.keys(agent.tool_options ?? {}).some((key) => key.includes(Constants.mcp_delimiter));+ /**+ * The COMPLETE audit set actually resolved this initialization — from the+ * agent-key heal or the skill-prime heal — threaded to the tool loader so+ * its collision guards neither repeat the lookup nor mistake the+ * operator-only list for a complete audit.+ */+ let resolvedAuditNames: readonly string[] | undefined;+ if (hasMCPKeyCandidates) {+ const mcpHealNames = await resolveHealNames();+ if (mcpHealNames != null) {+ resolvedAuditNames = mcpHealNames;+ const healedKeys = normalizeAgentToolKeys({+ tools: agent.tools ?? undefined,+ toolOptions: agent.tool_options,+ rawServerNames: mcpHealNames,+ });+ agent.tools = healedKeys.tools;+ agent.tool_options = healedKeys.toolOptions;+ }+ }+if (isAgentsEndpoint(endpointOption?.endpoint) &&allowedProviders.size > 0 &&@@ -910,7 +1008,34 @@ export async function initializeAgent(alwaysApplySkillPrimes = alwaysApplySkillPrimes.slice(0, budgetForAlwaysApply);}- const primesForUnion = [...(manualSkillPrimes ?? []), ...(alwaysApplySkillPrimes ?? [])];+ /** Skill `allowed-tools` are legacy-heal candidates too: a raw MCP key+ * declared before the normalized-key convention would neither dedupe+ * against the healed agent tools nor match the normalized-keyed tool+ * map, silently dropping the skill-contributed tool. Same lazy audit+ * and skip-on-unavailable semantics as the agent-key heal. */+ const combinedPrimes = [...(manualSkillPrimes ?? []), ...(alwaysApplySkillPrimes ?? [])];+ const primesNeedHeal = combinedPrimes.some((prime) =>+ prime.allowedTools?.some((name) => name.includes(Constants.mcp_delimiter)),+ );+ const primeHealNames = primesNeedHeal ? await resolveHealNames() : null;+ if (primeHealNames != null) {+ resolvedAuditNames = primeHealNames;+ }+ const primesForUnion =+ primeHealNames != null+ ? combinedPrimes.map((prime) =>+ prime.allowedTools?.length+ ? {+ ...prime,+ allowedTools: normalizeAgentToolKeys({+ tools: prime.allowedTools,+ toolOptions: undefined,+ rawServerNames: primeHealNames,+ }).tools,+ }+ : prime,+ )+ : combinedPrimes;if (primesForUnion.length > 0) {const union = unionPrimeAllowedTools({primes: primesForUnion,@@ -952,6 +1077,7 @@ export async function initializeAgent(model: agent.model,tool_options: agent.tool_options,tool_resources,+ accessibleMcpServerNames: resolvedAuditNames,});let loadToolsResult;@@ -1453,6 +1579,7 @@ export async function initializeAgent(backgroundToolNames,intentToolNames,actionsEnabled,+ accessibleMcpServerNames: resolvedAuditNames,baseContextTokens,memoryToolsRegistered: inlineMemoryRegistered,codeEnvAvailable: effectiveCodeEnvAvailable,diff --git a/packages/api/src/mcp/__tests__/auth.test.ts b/packages/api/src/mcp/__tests__/auth.test.tsindex c5b59a5a41..7bad722730 100644--- a/packages/api/src/mcp/__tests__/auth.test.ts+++ b/packages/api/src/mcp/__tests__/auth.test.ts@@ -99,6 +99,27 @@ describe('getUserMCPAuthMap', () => {expect.objectContaining({ pluginKeys: ['mcp_Google_mcp_Workspace'] }),);});++ it('fetches auth under both spellings for normalized keys, raw-only for legacy keys', async () => {+ /** Plugin auth rows are stored under the raw config name, but a+ * normalized match could equally belong to a user-DB server named+ * exactly like it — fetch the superset and let consumers read by+ * their own server name. Legacy raw keys resolve directly. */+ mockGetPluginAuthMap.mockResolvedValue({});++ await getUserMCPAuthMap({+ userId: 'user123',+ tools: ['search_mcp_Connector__Company', 'lookup_mcp_Connector: Company'],+ serverNames: ['Connector: Company'],+ findPluginAuthsByKeys: mockFindPluginAuthsByKeys,+ });++ expect(mockGetPluginAuthMap).toHaveBeenCalledWith(+ expect.objectContaining({+ pluginKeys: expect.arrayContaining(['mcp_Connector__Company', 'mcp_Connector: Company']),+ }),+ );+ });});describe('Edge Cases', () => {diff --git a/packages/api/src/mcp/__tests__/utils.test.ts b/packages/api/src/mcp/__tests__/utils.test.tsindex 1da821fc1c..b0ff7bbf89 100644--- a/packages/api/src/mcp/__tests__/utils.test.ts+++ b/packages/api/src/mcp/__tests__/utils.test.ts@@ -2,6 +2,8 @@ import type { ParsedServerConfig } from '~/mcp/types';import {buildOAuthToolCallName,normalizeServerName,+ normalizeAgentToolKeys,+ findShadowedServerNames,splitMCPToolKey,redactAllServerSecrets,redactServerSecrets,@@ -75,6 +77,138 @@ describe('splitMCPToolKey', () => {});});+describe('findShadowedServerNames', () => {+ it('flags later names whose normalized form an earlier different name claimed', () => {+ const shadowed = findShadowedServerNames(['Sales Force', 'Sales:Force', 'other']);+ expect(shadowed).toEqual(new Set(['Sales:Force']));+ });++ it('does not flag exact duplicates or safe distinct names', () => {+ expect(findShadowedServerNames(['srv', 'srv', 'other']).size).toBe(0);+ expect(findShadowedServerNames(['Sales Force', 'Sales_Force2']).size).toBe(0);+ });++ it('an identity name always wins over a colliding raw name, in either order', () => {+ /** A server literally named `Sales_Force` owns that key segment; the+ * special-character `Sales Force` is the shadowed one regardless of+ * configuration order — mirroring `buildServerNameAliases` routing. */+ expect(findShadowedServerNames(['Sales_Force', 'Sales Force'])).toEqual(+ new Set(['Sales Force']),+ );+ expect(findShadowedServerNames(['Sales Force', 'Sales_Force'])).toEqual(+ new Set(['Sales Force']),+ );+ });+});++describe('normalizeAgentToolKeys', () => {+ const rawServerNames = ['plain', 'Connector: Company'];++ it('rewrites legacy raw-keyed tools and tool_options to the normalized form', () => {+ const { tools, toolOptions } = normalizeAgentToolKeys({+ tools: ['web_search', 'search_mcp_plain', 'search_mcp_Connector: Company'],+ toolOptions: {+ 'search_mcp_Connector: Company': { run_in_background: true, describe_intent: true },+ search_mcp_plain: { defer_loading: true },+ },+ rawServerNames,+ });+ expect(tools).toEqual(['web_search', 'search_mcp_plain', 'search_mcp_Connector__Company']);+ expect(toolOptions).toEqual({+ search_mcp_Connector__Company: { run_in_background: true, describe_intent: true },+ search_mcp_plain: { defer_loading: true },+ });+ });++ it('returns the same references when no configured name needs rewriting (fast path)', () => {+ const tools = ['search_mcp_plain'];+ const toolOptions = { search_mcp_plain: { defer_loading: true } };+ const result = normalizeAgentToolKeys({+ tools,+ toolOptions,+ rawServerNames: ['plain', 'safe-name.v2'],+ });+ expect(result.tools).toBe(tools);+ expect(result.toolOptions).toBe(toolOptions);+ });++ it('returns the same references when keys are already normalized', () => {+ const tools = ['search_mcp_Connector__Company'];+ const toolOptions = { search_mcp_Connector__Company: { describe_intent: true } };+ const result = normalizeAgentToolKeys({ tools, toolOptions, rawServerNames });+ expect(result.tools).toBe(tools);+ expect(result.toolOptions).toBe(toolOptions);+ });++ it('leaves placeholder and server-pin tokens untouched (config-identity references)', () => {+ const tools = [+ 'sys__all__sys_mcp_Connector: Company',+ 'sys__server__sys_mcp_Connector: Company',+ 'search_mcp_Connector: Company',+ ];+ const result = normalizeAgentToolKeys({ tools, toolOptions: undefined, rawServerNames });+ expect(result.tools).toEqual([+ 'sys__all__sys_mcp_Connector: Company',+ 'sys__server__sys_mcp_Connector: Company',+ 'search_mcp_Connector__Company',+ ]);+ });++ it('handles undefined tools and options', () => {+ const result = normalizeAgentToolKeys({+ tools: undefined,+ toolOptions: undefined,+ rawServerNames,+ });+ expect(result.tools).toBeUndefined();+ expect(result.toolOptions).toBeUndefined();+ });++ it('the CURRENT (normalized) entry wins when both spellings carry options', () => {+ /** A client can write the new spelling before cleaning up the legacy+ * entry; object insertion order must not let stale legacy settings+ * clobber it. */+ const rawLater = normalizeAgentToolKeys({+ tools: undefined,+ toolOptions: {+ search_mcp_Connector__Company: { run_in_background: false },+ 'search_mcp_Connector: Company': { run_in_background: true, defer_loading: true },+ },+ rawServerNames: ['Connector: Company'],+ });+ expect(rawLater.toolOptions).toEqual({+ search_mcp_Connector__Company: { run_in_background: false, defer_loading: true },+ });++ const rawFirst = normalizeAgentToolKeys({+ tools: undefined,+ toolOptions: {+ 'search_mcp_Connector: Company': { run_in_background: true, defer_loading: true },+ search_mcp_Connector__Company: { run_in_background: false },+ },+ rawServerNames: ['Connector: Company'],+ });+ expect(rawFirst.toolOptions).toEqual({+ search_mcp_Connector__Company: { run_in_background: false, defer_loading: true },+ });+ });++ it('never heals a SHADOWED server key into the first server’s key', () => {+ /** Rewriting `search__Sales:Force` would produce exactly the key of the+ * earlier `Sales Force` server — the persisted tool would silently+ * execute the wrong server's action. Left raw, it fails visibly. */+ const result = normalizeAgentToolKeys({+ tools: ['search_mcp_Sales:Force', 'search_mcp_Connector: Company'],+ toolOptions: { 'search_mcp_Sales:Force': { run_in_background: true } },+ rawServerNames: ['Sales Force', 'Sales:Force', 'Connector: Company'],+ });+ expect(result.tools).toEqual(['search_mcp_Sales:Force', 'search_mcp_Connector__Company']);+ expect(result.toolOptions).toEqual({+ 'search_mcp_Sales:Force': { run_in_background: true },+ });+ });+});+describe('buildOAuthToolCallName', () => {it('should prefix a simple server name with oauth_mcp_', () => {expect(buildOAuthToolCallName('my-server')).toBe('oauth_mcp_my-server');diff --git a/packages/api/src/mcp/auth.ts b/packages/api/src/mcp/auth.tsindex 6c7b3b72a7..c374f75019 100644--- a/packages/api/src/mcp/auth.ts+++ b/packages/api/src/mcp/auth.ts@@ -1,5 +1,5 @@import { logger } from '@librechat/data-schemas';-import { Constants } from 'librechat-data-provider';+import { Constants, buildServerNameAliases } from 'librechat-data-provider';import type { PluginAuthMethods } from '@librechat/data-schemas';import type { GenericTool } from '@librechat/agents';import { getPluginAuthMap } from '~/agents/auth';@@ -25,7 +25,12 @@ export async function getUserMCPAuthMap({tools?: (string | undefined)[];servers?: (string | undefined)[];toolInstances?: (GenericTool | null)[];- /** Configured server names, used to resolve the tool-key boundary exactly */+ /**+ * Configured server names in their RAW config form. Tool keys embed the+ * normalized form, so the boundary is resolved against both spellings and+ * the auth-map key is always built from the raw name — the form plugin-auth+ * rows are stored under and every reader passes.+ */serverNames?: readonly string[];findPluginAuthsByKeys: PluginAuthMethods['findPluginAuthsByKeys'];}): Promise<Record<string, Record<string, string>>> {@@ -42,13 +47,24 @@ export async function getUserMCPAuthMap({uniqueMcpServers.add(`${Constants.mcp_prefix}${serverName}`);}} else if (tools != null && tools.length) {+ const aliases = buildServerNameAliases(serverNames ?? []);+ /** Keys may carry either spelling (normalized going forward, raw in+ * legacy agent documents), so both forms resolve the boundary. */+ const candidates = [...(serverNames ?? []), ...aliases.keys()];for (const toolName of tools) {if (!toolName) {continue;}- const [, mcpServer] = splitMCPToolKey(toolName, serverNames);+ const [, mcpServer] = splitMCPToolKey(toolName, candidates);if (!mcpServer) continue;uniqueMcpServers.add(`${Constants.mcp_prefix}${mcpServer}`);+ /** A normalized match could equally belong to a user-DB server named+ * exactly like it, so fetch auth under BOTH spellings — consumers+ * read by their own server name and pick theirs. */+ const aliasedRaw = aliases.get(mcpServer);+ if (aliasedRaw != null && aliasedRaw !== mcpServer) {+ uniqueMcpServers.add(`${Constants.mcp_prefix}${aliasedRaw}`);+ }}} else if (toolInstances != null && toolInstances.length) {for (const tool of toolInstances) {diff --git a/packages/api/src/mcp/context.ts b/packages/api/src/mcp/context.tsindex 8abecc2be6..42c05147aa 100644--- a/packages/api/src/mcp/context.ts+++ b/packages/api/src/mcp/context.ts@@ -1,4 +1,5 @@-import { normalizeServerName } from 'librechat-data-provider';+import { logger } from '@librechat/data-schemas';+import { normalizeServerName, buildServerNameAliases } from 'librechat-data-provider';import type { MCPOptions } from 'librechat-data-provider';import type { ParsedServerConfig } from '~/mcp/types';@@ -7,6 +8,11 @@ export interface MCPServerContext {configServers: Record<string, ParsedServerConfig>;/** Every configured server, in the normalized form tool keys are built from. */serverNames: string[];+ /** Every configured server under its raw config name — the form the+ * registry, config maps, tool cache, and plugin-auth rows are keyed by.+ * Consumers that parse a (normalized) server out of a tool key resolve+ * back to these via `buildServerNameAliases`. */+ rawServerNames: string[];}export interface ResolveMCPServerContextParams {@@ -28,8 +34,58 @@ export async function resolveMCPServerContext({mcpConfig,ensureConfigServers,}: ResolveMCPServerContextParams): Promise<MCPServerContext> {+ const rawServerNames = Object.keys(mcpConfig);+ warnOnNormalizedNameCollisions(rawServerNames);+ /**+ * The name lists derive from the config snapshot alone and must survive a+ * transient lazy-init failure: without them, normalized tool keys cannot+ * resolve back to raw config names and every MCP tool silently drops for+ * the request — a strictly worse degradation than missing overlay configs.+ */+ let configServers: Record<string, ParsedServerConfig> = {};+ try {+ configServers = await ensureConfigServers(mcpConfig);+ } catch (error) {+ logger.warn(+ '[resolveMCPServerContext] Config server initialization failed; continuing with name lists only:',+ error,+ );+ }return {- configServers: await ensureConfigServers(mcpConfig),- serverNames: Object.keys(mcpConfig).map(normalizeServerName),+ configServers,+ serverNames: rawServerNames.map(normalizeServerName),+ rawServerNames,};}++const warnedCollisions = new Set<string>();++/**+ * Two configured names that normalize to the same value produce IDENTICAL+ * model-facing tool keys, so tool selection and config resolution cannot tell+ * the servers apart — `buildServerNameAliases` deterministically routes to the+ * first configured name. Surfaced once per colliding pair per process so the+ * operator can rename one server; silently last-wins routing could execute a+ * different server's tool than the one the agent selected.+ */+function warnOnNormalizedNameCollisions(rawServerNames: readonly string[]): void {+ const aliases = buildServerNameAliases(rawServerNames);+ for (const raw of rawServerNames) {+ if (!raw) {+ continue;+ }+ const normalized = normalizeServerName(raw);+ const winner = aliases.get(normalized);+ if (winner == null || winner === raw) {+ continue;+ }+ const signature = `${winner}::${raw}`;+ if (warnedCollisions.has(signature)) {+ continue;+ }+ warnedCollisions.add(signature);+ logger.warn(+ `[MCP] Server names "${winner}" and "${raw}" normalize to the same tool-key segment "${normalized}"; their tool keys are ambiguous and lookups resolve to "${winner}". Rename one server to disambiguate.`,+ );+ }+}diff --git a/packages/api/src/mcp/registry/MCPServerInspector.ts b/packages/api/src/mcp/registry/MCPServerInspector.tsindex 4feefccefd..06281eb0e8 100644--- a/packages/api/src/mcp/registry/MCPServerInspector.ts+++ b/packages/api/src/mcp/registry/MCPServerInspector.ts@@ -1,5 +1,5 @@import { logger } from '@librechat/data-schemas';-import { Constants } from 'librechat-data-provider';+import { Constants, normalizeServerName } from 'librechat-data-provider';import type { JsonSchemaType } from '@librechat/data-schemas';import type { MCPConnection } from '~/mcp/connection';import type * as t from '~/mcp/types';@@ -181,8 +181,11 @@ export class MCPServerInspector {const tools = await connection.fetchTools();const toolFunctions: t.LCAvailableTools = {};+ /** Model-facing key: must match the runtime instance name, which embeds+ * the normalized server name (see `createToolInstance` in MCP.js). */+ const keyServerName = normalizeServerName(serverName);tools.forEach((tool) => {- const name = `${tool.name}${Constants.mcp_delimiter}${serverName}`;+ const name = `${tool.name}${Constants.mcp_delimiter}${keyServerName}`;toolFunctions[name] = {type: 'function',['function']: {diff --git a/packages/api/src/mcp/registry/__tests__/MCPServerInspector.test.ts b/packages/api/src/mcp/registry/__tests__/MCPServerInspector.test.tsindex b61ccf0c79..a20261bfb5 100644--- a/packages/api/src/mcp/registry/__tests__/MCPServerInspector.test.ts+++ b/packages/api/src/mcp/registry/__tests__/MCPServerInspector.test.ts@@ -555,5 +555,21 @@ describe('MCPServerInspector', () => {expect(result).toEqual({});});++ it('builds keys with the normalized server name (model-facing contract)', async () => {+ mockConnection.fetchTools = jest.fn().mockResolvedValue([+ {+ name: 'file_read',+ description: 'Read a file',+ inputSchema: { type: 'object', properties: {} },+ },+ ]);++ const result = await MCPServerInspector.getToolFunctions('My Server', mockConnection);++ const key = 'file_read_mcp_My_Server';+ expect(Object.keys(result)).toEqual([key]);+ expect(result[key]['function'].name).toBe(key);+ });});});diff --git a/packages/api/src/mcp/tools.spec.ts b/packages/api/src/mcp/tools.spec.tsindex f1a630487a..fac1859262 100644--- a/packages/api/src/mcp/tools.spec.ts+++ b/packages/api/src/mcp/tools.spec.ts@@ -46,6 +46,31 @@ describe('createMCPToolCacheService', () => {expect(deps.setCachedTools).not.toHaveBeenCalled();});+ it('builds MODEL-FACING keys with the normalized server name, store keyed raw', async () => {+ /** Tool keys become builder tool ids, agent.tools entries, tool_options+ * keys, and definition names, and must equal the runtime instance name,+ * which embeds `normalizeServerName(serverName)`. */+ const deps = createMockDeps();+ const { updateMCPServerTools } = createMCPToolCacheService(deps);+ const tools: MCPToolInput[] = [+ { name: 'search', description: 'Search', inputSchema: { type: 'object', properties: {} } },+ ];++ const result = await updateMCPServerTools({+ userId: 'u1',+ serverName: 'Connector: Company',+ tools,+ });++ const expectedKey = `search${Constants.mcp_delimiter}Connector__Company`;+ expect(result[expectedKey]).toBeDefined();+ expect(result[expectedKey]['function'].name).toBe(expectedKey);+ expect(deps.setCachedTools).toHaveBeenCalledWith(result, {+ userId: 'u1',+ serverName: 'Connector: Company',+ });+ });+it('constructs tool names with mcp_delimiter and caches them', async () => {const deps = createMockDeps();const { updateMCPServerTools } = createMCPToolCacheService(deps);@@ -301,6 +326,46 @@ describe('createMCPToolCacheService', () => {expect(deps.getCachedTools).toHaveBeenCalledWith({ userId: 'u1', serverName: 'brave' });});+ it('heals stale raw-keyed cache entries to the normalized key format at read time', async () => {+ /** Entries written before keys embedded the normalized server name would+ * otherwise make the server's tools vanish for up to the cache TTL —+ * the definitions-only loader treats this map as authoritative and+ * never reconnects on a per-key miss. */+ const staleTools: LCAvailableTools = {+ [`search${Constants.mcp_delimiter}Connector: Company`]: {+ type: 'function',+ ['function']: {+ name: `search${Constants.mcp_delimiter}Connector: Company`,+ description: 'Search',+ parameters: { type: 'object', properties: {} },+ },+ },+ };+ const deps = createMockDeps({+ getCachedTools: jest.fn().mockResolvedValue(staleTools),+ getServerConfig: jest.fn().mockResolvedValue(cacheableConfig),+ });+ const { getMCPServerTools } = createMCPToolCacheService(deps);++ const result = await getMCPServerTools('u1', 'Connector: Company');++ const healedKey = `search${Constants.mcp_delimiter}Connector__Company`;+ expect(Object.keys(result ?? {})).toEqual([healedKey]);+ expect(result?.[healedKey]['function'].name).toBe(healedKey);+ });++ it('returns the same reference for safe server names (no heal pass)', async () => {+ const deps = createMockDeps({+ getCachedTools: jest.fn().mockResolvedValue(cachedTools),+ getServerConfig: jest.fn().mockResolvedValue(cacheableConfig),+ });+ const { getMCPServerTools } = createMCPToolCacheService(deps);++ const result = await getMCPServerTools('u1', 'brave');++ expect(result).toBe(cachedTools);+ });+it('returns null for request-scoped servers without reading the cache', async () => {const deps = createMockDeps({getCachedTools: jest.fn().mockResolvedValue(cachedTools),diff --git a/packages/api/src/mcp/tools.ts b/packages/api/src/mcp/tools.tsindex 1326bb99f3..10f779df44 100644--- a/packages/api/src/mcp/tools.ts+++ b/packages/api/src/mcp/tools.ts@@ -1,5 +1,5 @@import { logger } from '@librechat/data-schemas';-import { Constants } from 'librechat-data-provider';+import { Constants, normalizeServerName } from 'librechat-data-provider';import type { JsonSchemaType } from '@librechat/agents';import type { LCAvailableTools, LCFunctionTool, ParsedServerConfig } from './types';import { requiresEphemeralUserConnection } from './utils';@@ -88,8 +88,14 @@ export function createMCPToolCacheService(deps: MCPToolCacheDeps): MCPToolCacheSreturn serverTools;}+ /** Cache keys are MODEL-FACING: they become builder tool ids, agent.tools+ * entries, tool_options keys, and definition names, and must equal the+ * runtime instance name (`createToolInstance` in MCP.js), which embeds+ * `normalizeServerName(serverName)`. The cache STORE itself stays keyed+ * by the raw config name. */+ const keyServerName = normalizeServerName(serverName);for (const tool of tools) {- const name = `${tool.name}${mcpDelimiter}${serverName}`;+ const name = `${tool.name}${mcpDelimiter}${keyServerName}`;const entry: LCFunctionTool = {type: 'function',['function']: {@@ -164,6 +170,44 @@ export function createMCPToolCacheService(deps: MCPToolCacheDeps): MCPToolCacheS}}+ /**+ * Heals cache entries written before keys embedded the normalized server+ * name. The definitions-only loader treats the returned map as+ * authoritative — a per-key miss does NOT trigger a reconnect the way the+ * instance path does — so a stale raw-keyed entry would make the server's+ * tools vanish for up to the cache TTL after rollout. Rewriting at read+ * time covers every consumer without a coordinated invalidation; safe+ * server names (the common case) return the map untouched.+ */+ function normalizeCachedToolKeys(+ tools: LCAvailableTools | null,+ serverName: string,+ ): LCAvailableTools | null {+ if (!tools) {+ return tools;+ }+ const normalized = normalizeServerName(serverName);+ if (normalized === serverName) {+ return tools;+ }+ const legacySuffix = `${Constants.mcp_delimiter}${serverName}`;+ let changed = false;+ const next: LCAvailableTools = {};+ for (const [key, entry] of Object.entries(tools)) {+ if (!key.endsWith(legacySuffix)) {+ next[key] = entry;+ continue;+ }+ const rebuiltKey = `${key.slice(0, key.length - serverName.length)}${normalized}`;+ next[rebuiltKey] = {+ ...entry,+ ['function']: { ...entry['function'], name: rebuiltKey },+ };+ changed = true;+ }+ return changed ? next : tools;+ }+async function getMCPServerTools(userId: string,serverName: string,@@ -173,7 +217,8 @@ export function createMCPToolCacheService(deps: MCPToolCacheDeps): MCPToolCacheSreturn null;}try {- return (await getCachedTools({ userId, serverName })) ?? null;+ const cached = (await getCachedTools({ userId, serverName })) ?? null;+ return normalizeCachedToolKeys(cached, serverName);} catch (error) {logger.error(`[getMCPServerTools] Error fetching cached tools for ${serverName}:`, error);return null;diff --git a/packages/api/src/mcp/utils.ts b/packages/api/src/mcp/utils.tsindex 24ab69a5cc..d56194a63a 100644--- a/packages/api/src/mcp/utils.ts+++ b/packages/api/src/mcp/utils.ts@@ -1,4 +1,10 @@-import { Constants, normalizeServerName } from 'librechat-data-provider';+import {+ Constants,+ normalizeServerName,+ normalizeMCPToolKey,+ buildServerNameAliases,+} from 'librechat-data-provider';+import type { AgentToolOptions } from 'librechat-data-provider';import type { ParsedServerConfig } from '~/mcp/types';import type { RequestBody } from '~/types';@@ -21,6 +27,144 @@ export function isMCPAllPlaceholder(toolName: string): boolean {return toolName.startsWith(MCP_ALL_PLACEHOLDER_PREFIX);}+/** Server-pin token (`sys__server__sys<delim><server>`) that keeps a server+ * attached to an agent independent of its tool selection. */+const MCP_SERVER_TOKEN_PREFIX: string = `${Constants.mcp_server}${Constants.mcp_delimiter}`;++/**+ * Later-configured server names whose normalized form is already claimed by an+ * earlier different name. Such a pair produces IDENTICAL model-facing tool+ * keys, so tool selection and execution cannot tell the servers apart —+ * `buildServerNameAliases` deterministically routes to the first name, and+ * the shadowed later server must be EXCLUDED from tool exposure entirely:+ * offering its tools would let a user select a tool that silently executes+ * against the first server's configuration.+ */+/**+ * Whether a resolved server name is normalization-sensitive — its own name+ * needs normalizing, or it EQUALS the normalized form of some configured+ * special-character name. Under an incomplete collision audit these are the+ * references whose routing cannot be proven unambiguous, so they fail closed.+ */+export function isNormalizationSensitiveName(+ serverName: string,+ rawServerNames: readonly string[],+): boolean {+ if (normalizeServerName(serverName) !== serverName) {+ return true;+ }+ return rawServerNames.some(+ (raw) => raw !== serverName && normalizeServerName(raw) === serverName,+ );+}++export function findShadowedServerNames(rawServerNames: readonly string[]): Set<string> {+ /** Derived from `buildServerNameAliases` so shadow detection can never+ * diverge from the tie-break routing actually uses (identity entries+ * first, then configuration order). */+ const aliases = buildServerNameAliases(rawServerNames);+ const shadowed = new Set<string>();+ for (const raw of rawServerNames) {+ if (raw && aliases.get(normalizeServerName(raw)) !== raw) {+ shadowed.add(raw);+ }+ }+ return shadowed;+}++/**+ * Heals legacy persisted agent data whose MCP tool keys embed a RAW server+ * name: model-facing keys carry `normalizeServerName(server)` (matching cache+ * keys, definition names, and runtime instance names), so an agent document+ * saved before that convention — or through the old raw-keyed cache — would+ * neither load its tools nor have its `tool_options` (defer / programmatic /+ * background / intent) honored for a server whose name needs normalizing.+ *+ * Placeholder and server-pin tokens are left untouched: they are+ * config-identity references consumed against raw config names (the client's+ * selectors, the definitions loader's expansion), never model-facing names.+ * Returns the same references when nothing needs rewriting, so the common+ * path (every server name already normalized) allocates nothing.+ */+export function normalizeAgentToolKeys(params: {+ tools: string[] | undefined;+ toolOptions: AgentToolOptions | undefined;+ rawServerNames: readonly string[];+}): { tools: string[] | undefined; toolOptions: AgentToolOptions | undefined } {+ const { tools, toolOptions, rawServerNames } = params;+ /**+ * A SHADOWED server (its normalized form claimed by an earlier different+ * name) must NOT be healed: rewriting its raw key would produce the first+ * server's key exactly, silently executing the wrong server's action. Left+ * raw, the key fails to match the (normalized-keyed) tool map and the tool+ * errors visibly — broken beats misrouted.+ */+ const shadowed = findShadowedServerNames(rawServerNames);+ const rewritableNames = rawServerNames.filter(+ (name) => normalizeServerName(name) !== name && !shadowed.has(name),+ );+ if (rewritableNames.length === 0) {+ return { tools, toolOptions };+ }++ const rewriteKey = (key: string): string => {+ if (+ !key.includes(Constants.mcp_delimiter) ||+ isMCPAllPlaceholder(key) ||+ key.startsWith(MCP_SERVER_TOKEN_PREFIX)+ ) {+ return key;+ }+ return normalizeMCPToolKey(key, rewritableNames);+ };++ let toolsChanged = false;+ let nextTools = tools?.map((key) => {+ const rewritten = rewriteKey(key);+ if (rewritten !== key) {+ toolsChanged = true;+ }+ return rewritten;+ });+ /** A document carrying BOTH spellings converges on one key after healing —+ * collapse duplicates (order-preserving) so the loaders never build two+ * instances with the same function name. */+ if (toolsChanged && nextTools) {+ const seen = new Set<string>();+ nextTools = nextTools.filter((key) => {+ if (seen.has(key)) {+ return false;+ }+ seen.add(key);+ return true;+ });+ }++ let optionsChanged = false;+ let nextOptions: AgentToolOptions | undefined;+ if (toolOptions) {+ nextOptions = {};+ for (const [key, options] of Object.entries(toolOptions)) {+ const rewritten = rewriteKey(key);+ if (rewritten !== key) {+ optionsChanged = true;+ }+ /** When both spellings carry options, the CURRENT (normalized) entry+ * wins regardless of object insertion order — a legacy entry must not+ * clobber settings a client already wrote under the new spelling. */+ nextOptions[rewritten] =+ rewritten !== key+ ? { ...options, ...nextOptions[rewritten] }+ : { ...nextOptions[key], ...options };+ }+ }++ return {+ tools: toolsChanged ? nextTools : tools,+ toolOptions: optionsChanged ? nextOptions : toolOptions,+ };+}+const RUNTIME_CONTEXT_PLACEHOLDER_PATTERN = /\{\{LIBRECHAT_(?:USER|OPENID|GRAPH|BODY)_[^}]+\}\}/;const RUNTIME_BODY_PLACEHOLDER_PATTERN = /\{\{LIBRECHAT_BODY_[^}]+\}\}/;const RUNTIME_BODY_PLACEHOLDER_CAPTURE_PATTERN = /\{\{LIBRECHAT_BODY_([^}]+)\}\}/g;@@ -426,4 +570,9 @@ export function generateServerNameFromTitle(title: string): string {return slug || 'mcp-server'; // Fallback if empty}-export { splitMCPToolKey, normalizeServerName } from 'librechat-data-provider';+export {+ splitMCPToolKey,+ normalizeServerName,+ normalizeMCPToolKey,+ buildServerNameAliases,+} from 'librechat-data-provider';diff --git a/packages/api/src/tools/definitions.spec.ts b/packages/api/src/tools/definitions.spec.tsindex 0291ea789c..8366d86447 100644--- a/packages/api/src/tools/definitions.spec.ts+++ b/packages/api/src/tools/definitions.spec.ts@@ -632,6 +632,112 @@ describe('definitions.ts', () => {expect((toolDef as { serverName?: string }).serverName).toBe('my-server');});+ it('resolves normalized keys to the RAW server for lookups and definition metadata', async () => {+ /** Config lookups and `serverName` metadata (server instructions are+ * keyed by raw config names) must carry the raw name even though the+ * key embeds the normalized form. Resolution is direct-first, so the+ * raw alias is consulted only after the parsed name yields nothing. */+ const mockServerTools = {+ search_mcp_Connector__Company: {+ function: {+ name: 'search_mcp_Connector__Company',+ description: 'Search',+ parameters: { type: 'object', properties: {} },+ },+ },+ };++ mockGetOrFetchMCPServerTools.mockImplementation(async (_userId: string, name: string) =>+ name === 'Connector: Company' ? mockServerTools : null,+ );++ const params: LoadToolDefinitionsParams = {+ userId: 'user-123',+ agentId: 'agent-123',+ tools: ['search_mcp_Connector__Company'],+ mcpServerNames: ['Connector__Company'],+ rawServerNames: ['Connector: Company'],+ };++ const deps: LoadToolDefinitionsDeps = {+ getOrFetchMCPServerTools: mockGetOrFetchMCPServerTools,+ isBuiltInTool: mockIsBuiltInTool,+ };++ const result = await loadToolDefinitions(params, deps);++ expect(mockGetOrFetchMCPServerTools).toHaveBeenCalledWith('user-123', 'Connector: Company');+ expect(result.toolDefinitions).toHaveLength(1);+ const toolDef = result.toolDefinitions[0];+ expect(toolDef.name).toBe('search_mcp_Connector__Company');+ expect((toolDef as { serverName?: string }).serverName).toBe('Connector: Company');+ });++ it('does not alias-fallback when the parsed name IS a known accessible server', async () => {+ /** A null fetch for a KNOWN server means it is temporarily+ * unavailable (OAuth pending, missing vars) — rerouting to the raw+ * alias would emit the other server's definitions under its names. */+ mockGetOrFetchMCPServerTools.mockResolvedValue(null);++ const params: LoadToolDefinitionsParams = {+ userId: 'user-123',+ agentId: 'agent-123',+ tools: ['search_mcp_Connector__Company'],+ mcpServerNames: ['Connector__Company'],+ rawServerNames: ['Connector: Company'],+ accessibleServerNames: ['Connector__Company', 'Connector: Company'],+ };++ const deps: LoadToolDefinitionsDeps = {+ getOrFetchMCPServerTools: mockGetOrFetchMCPServerTools,+ isBuiltInTool: mockIsBuiltInTool,+ };++ const result = await loadToolDefinitions(params, deps);++ expect(mockGetOrFetchMCPServerTools).toHaveBeenCalledTimes(1);+ expect(mockGetOrFetchMCPServerTools).toHaveBeenCalledWith('user-123', 'Connector__Company');+ expect(result.toolDefinitions).toHaveLength(0);+ });++ it('prefers a server resolving under the parsed name as-is over the raw alias', async () => {+ /** A user-DB server may be named exactly like an operator server's+ * normalized form; its tools must keep its own identity instead of+ * being rerouted to the operator server. */+ const dbServerTools = {+ search_mcp_Connector__Company: {+ function: {+ name: 'search_mcp_Connector__Company',+ description: 'DB server tool',+ parameters: { type: 'object', properties: {} },+ },+ },+ };++ mockGetOrFetchMCPServerTools.mockImplementation(async (_userId: string, name: string) =>+ name === 'Connector__Company' ? dbServerTools : null,+ );++ const params: LoadToolDefinitionsParams = {+ userId: 'user-123',+ agentId: 'agent-123',+ tools: ['search_mcp_Connector__Company'],+ mcpServerNames: ['Connector__Company'],+ rawServerNames: ['Connector: Company'],+ };++ const deps: LoadToolDefinitionsDeps = {+ getOrFetchMCPServerTools: mockGetOrFetchMCPServerTools,+ isBuiltInTool: mockIsBuiltInTool,+ };++ const result = await loadToolDefinitions(params, deps);++ expect(mockGetOrFetchMCPServerTools).toHaveBeenCalledWith('user-123', 'Connector__Company');+ const toolDef = result.toolDefinitions[0];+ expect((toolDef as { serverName?: string }).serverName).toBe('Connector__Company');+ });+it('should convert empty MCP tool descriptions to undefined', async () => {const mockServerTools = {no_desc_tool_mcp_asana: {diff --git a/packages/api/src/tools/definitions.ts b/packages/api/src/tools/definitions.tsindex de31b08dc3..f77be71ead 100644--- a/packages/api/src/tools/definitions.ts+++ b/packages/api/src/tools/definitions.ts@@ -6,7 +6,7 @@*/import { Providers } from '@librechat/agents';-import { isActionTool, splitMCPToolKey } from 'librechat-data-provider';+import { isActionTool, splitMCPToolKey, buildServerNameAliases } from 'librechat-data-provider';import type { LCToolRegistry, JsonSchemaType, LCTool, GenericTool } from '@librechat/agents';import type { AgentToolOptions } from 'librechat-data-provider';import type { ToolDefinition } from './classification';@@ -45,6 +45,22 @@ export interface LoadToolDefinitionsParams {provider?: Providers;/** Configured server names, used to resolve the tool-key boundary exactly */mcpServerNames?: readonly string[];+ /**+ * Configured server names in raw config form. A parsed (normalized) server+ * name resolves back to its raw name for config lookups AND for the+ * `serverName`/`mcpRawServerName` metadata stored on definitions — server+ * instructions and other config-keyed consumers read that field raw.+ */+ rawServerNames?: readonly string[];+ /**+ * Every server the user can reach (operator + user DB), from a COMPLETE+ * collision audit. When a parsed name appears here, it IS a real server —+ * a null tool fetch then means "currently unavailable" (OAuth pending,+ * missing user variables, disconnected) and must NOT fall back to the raw+ * alias, or the aliased server's definitions would be emitted under the+ * unavailable server's names.+ */+ accessibleServerNames?: readonly string[];}export interface ActionToolDefinition {@@ -91,8 +107,11 @@ export async function loadToolDefinitions(codeExecutionEnabled = false,provider,mcpServerNames,+ rawServerNames,+ accessibleServerNames,} = params;const { getOrFetchMCPServerTools, isBuiltInTool, getActionToolDefinitions } = deps;+ const serverNameAliases = buildServerNameAliases(rawServerNames ?? []);const isGoogle = provider === Providers.GOOGLE || provider === Providers.VERTEXAI;@@ -116,6 +135,8 @@ export async function loadToolDefinitions(}const mcpServerToolsCache = new Map<string, MCPServerTools>();+ /** Parsed key segment → the RAW server name it resolved to (direct-first). */+ const resolvedServerNames = new Map<string, string>();const mcpToolDefs: ToolDefinition[] = [];const builtInToolDefs: ToolDefinition[] = [];let actionToolDefs: ToolDefinition[] = [];@@ -157,15 +178,44 @@ export async function loadToolDefinitions(continue;}- const [, parsedServerName] = splitMCPToolKey(toolName, mcpServerNames);- const serverName = parsedServerName ?? toolName;+ /** Keys carry the normalized server name (raw in pre-normalization data),+ * so both spellings resolve the boundary. Resolution is DIRECT-FIRST: a+ * server that resolves under the parsed name as-is wins (a user-DB+ * server may be named exactly like an operator server's normalized+ * form), and only when that yields nothing is the parsed name treated+ * as a normalized spelling of a raw config name. The resolved RAW name+ * feeds config lookups and definition metadata (`serverName`, then+ * `mcpRawServerName`) — server instructions are keyed by it. */+ const [, parsedServerName] = splitMCPToolKey(toolName, [+ ...(mcpServerNames ?? []),+ ...(rawServerNames ?? []),+ ]);+ const parsed = parsedServerName ?? toolName;- if (!mcpServerToolsCache.has(serverName)) {- const serverTools = await getOrFetchMCPServerTools(userId, serverName);- mcpServerToolsCache.set(serverName, serverTools || {});+ if (!mcpServerToolsCache.has(parsed)) {+ let resolvedName = parsed;+ let fetched = await getOrFetchMCPServerTools(userId, parsed);+ if (!fetched) {+ /** Alias fallback is for "server not found" ONLY: when the parsed+ * name is a known accessible server, a null fetch means it is+ * temporarily unavailable (OAuth pending, missing user variables,+ * disconnected) and rerouting to the alias would emit the OTHER+ * server's definitions under this server's names. */+ const parsedIsKnownServer = accessibleServerNames?.includes(parsed) === true;+ const aliased = serverNameAliases.get(parsed);+ if (!parsedIsKnownServer && aliased != null && aliased !== parsed) {+ fetched = await getOrFetchMCPServerTools(userId, aliased);+ if (fetched) {+ resolvedName = aliased;+ }+ }+ }+ mcpServerToolsCache.set(parsed, fetched || {});+ resolvedServerNames.set(parsed, resolvedName);}- const serverTools = mcpServerToolsCache.get(serverName);+ const serverName = resolvedServerNames.get(parsed) ?? parsed;+ const serverTools = mcpServerToolsCache.get(parsed);if (!serverTools) {continue;}diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex c4c450b43a..83fed8dfd0 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -2872,6 +2872,71 @@ export function normalizeServerName(serverName: string): string {* is the deterministic tiebreak; resolving it properly needs the tool/server* mapping carried alongside the key rather than re-derived from the string.*/+/**+ * Maps each configured server name's normalized form back to the raw config+ * name. Model-facing tool keys embed `normalizeServerName(server)`, while the+ * registry, config maps, tool cache, and plugin-auth rows are keyed by the raw+ * name — any consumer that parses a server out of a tool key must resolve it+ * through this map before those lookups. Identity entries are included so+ * `aliases.get(name) ?? name` works uniformly.+ *+ * When two configured names normalize to the same value their tool keys are+ * inherently ambiguous; the FIRST configured name wins deterministically here,+ * and `resolveMCPServerContext` warns about the collision so the operator can+ * rename one server.+ */+export function buildServerNameAliases(rawServerNames: readonly string[]): Map<string, string> {+ const aliases = new Map<string, string>();+ /** Identity entries claim their slot FIRST regardless of configuration+ * order: a server literally named `foo` must never have its keys rerouted+ * to a `foo!` whose normalized form collides with it. */+ for (const raw of rawServerNames) {+ if (raw && normalizeServerName(raw) === raw) {+ aliases.set(raw, raw);+ }+ }+ for (const raw of rawServerNames) {+ if (!raw) {+ continue;+ }+ const normalized = normalizeServerName(raw);+ if (!aliases.has(normalized)) {+ aliases.set(normalized, raw);+ }+ }+ return aliases;+}++/**+ * Rewrites a tool key's server segment into the normalized form model-facing+ * keys carry, resolving the boundary against the configured raw names (longest+ * suffix wins, mirroring {@link splitMCPToolKey}). Returns the key unchanged+ * when no configured raw name matches — already-normalized keys, placeholder+ * tokens, and keys for servers that are no longer configured all pass through.+ * Idempotent: a normalized segment never matches a raw candidate that needs+ * rewriting.+ */+export function normalizeMCPToolKey(toolKey: string, rawServerNames: readonly string[]): string {+ let matched: string | undefined;+ for (let i = 0; i < rawServerNames.length; i++) {+ const raw = rawServerNames[i];+ if (!raw || raw.length <= (matched?.length ?? 0)) {+ continue;+ }+ if (toolKey.endsWith(`${Constants.mcp_delimiter}${raw}`)) {+ matched = raw;+ }+ }+ if (matched == null) {+ return toolKey;+ }+ const normalized = normalizeServerName(matched);+ if (normalized === matched) {+ return toolKey;+ }+ return `${toolKey.slice(0, toolKey.length - matched.length)}${normalized}`;+}+export function splitMCPToolKey(toolKey: string,knownServerNames?: readonly string[],diff --git a/packages/data-provider/src/splitMCPToolKey.spec.ts b/packages/data-provider/src/splitMCPToolKey.spec.tsindex eab45b65fd..1b05ac404d 100644--- a/packages/data-provider/src/splitMCPToolKey.spec.ts+++ b/packages/data-provider/src/splitMCPToolKey.spec.ts@@ -1,4 +1,10 @@-import { Constants, splitMCPToolKey, splitToolCallName } from './config';+import {+ Constants,+ splitMCPToolKey,+ splitToolCallName,+ normalizeMCPToolKey,+ buildServerNameAliases,+} from './config';describe('splitMCPToolKey', () => {it('splits a normal single-delimiter key like String.split would', () => {@@ -119,6 +125,73 @@ describe('splitMCPToolKey boundary alignment', () => {});});+describe('buildServerNameAliases', () => {+ it('maps normalized forms back to raw config names, including identity entries', () => {+ const aliases = buildServerNameAliases(['plain', 'Connector: Company']);+ expect(aliases.get('plain')).toBe('plain');+ expect(aliases.get('Connector__Company')).toBe('Connector: Company');+ expect(aliases.get('Connector: Company')).toBeUndefined();+ });++ it('skips empty names', () => {+ expect(buildServerNameAliases(['', 'srv']).size).toBe(1);+ });++ it('resolves normalized-name collisions to the FIRST configured name deterministically', () => {+ /** `Sales Force` and `Sales:Force` both normalize to `Sales_Force`; their+ * tool keys are inherently ambiguous, so routing must at least be stable+ * (the collision itself is warned about at context resolution). */+ const aliases = buildServerNameAliases(['Sales Force', 'Sales:Force']);+ expect(aliases.get('Sales_Force')).toBe('Sales Force');+ });++ it('an identity name owns its slot regardless of configuration order', () => {+ /** A server literally named `Sales_Force` must never have its keys+ * rerouted to a special-character server that normalizes onto it. */+ expect(buildServerNameAliases(['Sales Force', 'Sales_Force']).get('Sales_Force')).toBe(+ 'Sales_Force',+ );+ expect(buildServerNameAliases(['Sales_Force', 'Sales Force']).get('Sales_Force')).toBe(+ 'Sales_Force',+ );+ });+});++describe('normalizeMCPToolKey', () => {+ const d = Constants.mcp_delimiter;++ it('rewrites the server segment of a raw-keyed tool to its normalized form', () => {+ expect(normalizeMCPToolKey(`search${d}Connector: Company`, ['Connector: Company'])).toBe(+ `search${d}Connector__Company`,+ );+ });++ it('is a no-op for already-normalized keys and safe server names', () => {+ expect(normalizeMCPToolKey(`search${d}Connector__Company`, ['Connector: Company'])).toBe(+ `search${d}Connector__Company`,+ );+ expect(normalizeMCPToolKey(`search${d}plain`, ['plain'])).toBe(`search${d}plain`);+ });++ it('is a no-op when no configured raw name matches (unconfigured or non-MCP keys)', () => {+ expect(normalizeMCPToolKey(`search${d}gone server`, ['Connector: Company'])).toBe(+ `search${d}gone server`,+ );+ expect(normalizeMCPToolKey('web_search', ['Connector: Company'])).toBe('web_search');+ });++ it('resolves the boundary by longest raw match, preserving delimiter-bearing tool names', () => {+ /** The tool half may itself contain the delimiter (gateway-prefixed names). */+ expect(normalizeMCPToolKey(`gitlab-get${d}server_version${d}My Server`, ['My Server'])).toBe(+ `gitlab-get${d}server_version${d}My_Server`,+ );+ /** `normalizeServerName` strips the trailing `_` it substitutes for `!`. */+ expect(normalizeMCPToolKey(`search${d}My${d}Server!`, ['Server!', `My${d}Server!`])).toBe(+ `search${d}My${d}Server`,+ );+ });+});+describe('splitToolCallName oauth precedence', () => {const d = Constants.mcp_delimiter;