LibreChat/api/server/services/initializeMCPs.js
Danny Avila 1bccc2bc18
📡 fix: Refresh MCP Tools After List-Changed Notifications (#14686)
* fix(mcp): handle dynamic tool list changes

Co-authored-by: Pascal Garber <pascal@artandcode.studio>

* test(mcp): fix CI validation

* fix(mcp): keep dynamic tool catalogs live

* fix(mcp): harden dynamic catalog lifecycle

* test(mcp): use typed startup connection

* test(mcp): isolate dynamic e2e fixtures

* fix(mcp): refresh tools after reconnect

* fix(mcp): close dynamic catalog cache gaps

* test(mcp): update OAuth connection mocks

* fix(mcp): preserve app snapshot ownership

* style(mcp): sort connection imports

* fix(mcp): close review race conditions

* fix(mcp): preserve cache ownership edges

* fix(mcp): harden recovery lifecycle

* fix(mcp): guard tool-less app refresh

* fix(mcp): fence distributed cache races

* fix(mcp): retire stale connection state

* fix(mcp): keep tool snapshots authoritative

* fix(mcp): fence stale app tool publications

* style(mcp): sort repository test imports

* test(mcp): mock empty startup publication

* fix(mcp): preserve app publication generations

* fix(mcp): harden publication recovery races

* fix(mcp): address tool catalogs by runtime config

* fix(mcp): load scoped catalogs for assistant writes

* fix(mcp): harden catalog publication recovery

* fix(mcp): serialize forced connection replacement

* fix(mcp): serialize ordinary creation with replacements

* fix(mcp): harden catalog fallback boundaries

* fix(mcp): close lifecycle fencing gaps

* fix(mcp): preserve catalog authority on failures

* fix(mcp): compensate failed catalog mutations

* fix(mcp): fence catalog refresh ordering

* style(mcp): sort agent loader imports

* fix(mcp): cancel stale connection creation

* fix(mcp): fence catalog coordination

* fix(mcp): close catalog race windows

* fix(mcp): harden cross-pod catalog fencing

* fix(mcp): close catalog lifecycle edges

* style(mcp): sort assistant imports

* fix(mcp): reject stale recovery authority

* fix(mcp): restore static catalog on every startup

* fix(mcp): order app catalog publications

* style(mcp): sort catalog revision imports

* fix(mcp): separate catalog allocation and commit fences

---------

Co-authored-by: Pascal Garber <pascal@artandcode.studio>
2026-08-08 13:50:21 -04:00

116 lines
4.2 KiB
JavaScript

const mongoose = require('mongoose');
const { logger } = require('@librechat/data-schemas');
const {
registerShutdownTask,
setMCPToolsChangedHandler,
setMCPToolsChangedGenerationHandler,
setMCPToolsChangedGenerationRenewalHandler,
setMCPToolsChangedRevisionHandler,
} = require('@librechat/api');
const { syncStaticTools, mergeAppTools, getAppConfig } = require('./Config');
const {
getMCPToolsCacheGeneration,
renewMCPToolsCacheGeneration,
getNextAppToolsPublicationRevision,
updateMCPServerTools,
} = require('./Config/mcp');
const { createMCPServersRegistry, createMCPManager } = require('~/config');
/**
* Resolves the current request's effective MCP allowlists from the merged (tenant-scoped)
* config. The registry calls this per inspection/connection so admin-panel `mcpSettings`
* overrides are honored without a restart. Tenant comes from the ALS context inside
* `getAppConfig`; `userId`/`role` pick up user/role-scoped overrides when an actor exists.
* @param {{ userId?: string, role?: string }} [ctx]
*/
async function resolveMCPAllowlists(ctx) {
const appConfig = await getAppConfig({ role: ctx?.role, userId: ctx?.userId });
return {
allowedDomains: appConfig?.mcpSettings?.allowedDomains,
allowedAddresses: appConfig?.mcpSettings?.allowedAddresses,
};
}
/**
* Refreshes one server's tools after it reported `notifications/tools/list_changed`.
*
* A server that builds tools at runtime is the case this exists for: without it the tool list
* stayed frozen at connection time and only a restart picked up the change (#7117). The list is
* re-fetched from the live connection and written over that server's cache entry, so tools that
* disappeared stop being advertised too.
*/
async function refreshChangedServerTools({
serverName,
userId,
tools,
serverConfig,
publicationGeneration,
publicationRevision,
}) {
await updateMCPServerTools({
userId,
serverName,
tools,
serverConfig,
...(publicationGeneration && { publicationGeneration }),
...(publicationRevision && { publicationRevision }),
});
const toolCount = tools.length;
logger.info(
`[MCP][${serverName}] Tool list changed; refreshed ${toolCount} ${toolCount === 1 ? 'tool' : 'tools'}${userId ? ` for user ${userId}` : ''}`,
);
}
/**
* Initialize MCP servers
*/
async function initializeMCPs() {
const appConfig = await getAppConfig({ baseOnly: true });
const mcpServers = appConfig.mcpConfig;
try {
createMCPServersRegistry(
mongoose,
appConfig?.mcpSettings?.allowedDomains,
appConfig?.mcpSettings?.allowedAddresses,
resolveMCPAllowlists,
);
} catch (error) {
logger.error('[MCP] Failed to initialize MCPServersRegistry:', error);
throw error;
}
try {
const mcpManager = await createMCPManager(mcpServers || {});
setMCPToolsChangedHandler(refreshChangedServerTools);
setMCPToolsChangedGenerationHandler(getMCPToolsCacheGeneration);
setMCPToolsChangedGenerationRenewalHandler(renewMCPToolsCacheGeneration);
setMCPToolsChangedRevisionHandler(({ serverName, configGeneration }) =>
getNextAppToolsPublicationRevision(serverName, configGeneration),
);
registerShutdownTask('MCP app connections', () => mcpManager.disconnectAppServers());
if (mcpServers && Object.keys(mcpServers).length > 0) {
const mcpTools = (await mcpManager.getAppToolFunctions()) || {};
try {
await mergeAppTools(mcpTools, appConfig.availableTools || {});
} finally {
await mcpManager.connectAppServers();
}
const serverCount = Object.keys(mcpServers).length;
const toolCount = Object.keys(mcpTools).length;
logger.info(
`[MCP] Initialized with ${serverCount} configured ${serverCount === 1 ? 'server' : 'servers'} and ${toolCount} ${toolCount === 1 ? 'tool' : 'tools'}.`,
);
} else {
await syncStaticTools(appConfig.availableTools || {});
logger.debug('[MCP] No servers configured. MCPManager ready for UI-based servers.');
}
} catch (error) {
logger.error('[MCP] Failed to initialize MCPManager:', error);
throw error;
}
}
module.exports = initializeMCPs;
module.exports.refreshChangedServerTools = refreshChangedServerTools;