LibreChat/api/server/services/initializeMCPs.js
Danny Avila 8c51a3f9f8
🙈 feat: Let Config Profiles Hide librechat.yaml MCP Servers and Remove Their Fields (#17327)
* 🙈 feat: Let Config Profiles Hide librechat.yaml MCP Servers and Remove Their Fields

Config profiles are the `__base__`, role, group and user documents written through `/api/admin/config`. A profile can tombstone `mcpServers.<name>`, and the merge then removes that server from the principal's resolved `mcpConfig`.

* 🛡️ fix: Apply MCP Hiding to Server Instructions, Failed Removals and the Startup Audit

- Server instructions bound for the model now leave out librechat.yaml servers hidden from the acting user, including one a model spec pins. `applyContextToAgent` passes the request user through `formatInstructionsForContext`, which drops the user's hidden set from the user-less catalog it reads.
- A config-tier candidate that removes a librechat.yaml value (a field, or a key of a record such as `headers`) and fails inspection now stands as a failed config-source entry instead of falling back to the librechat.yaml base that still carries the removed value. A failed change that removes nothing still falls back, and an entry with no transport (fields written over a hidden server) keeps the documented librechat.yaml fallback.
- The startup tombstone report reads every tenant's profiles in the system tenant scope, so it also runs from entry points without an outer system scope under strict tenant isolation, and names each profile's tenant.

* 🗂️ fix: Project the Startup MCP Tombstone Report Query and Run It Alongside Connections

* 🔑 fix: Keep Removed OAuth Headers Out of the MCP OAuth Callback

* 📝 docs: Note That Removed OAuth Headers Stay Out of MCP Sign-In

* 🔐 fix: Recheck the MCP OAuth Flow's Server Before Initiation Redirects

OAuth initiation redirected to a flow's stored authorization URL, or started
a new authorization from the flow's stored server URL, without resolving the
server again, so a principal whose profile hid the server after the flow was
created could still be sent to its authorization endpoint. The callback's
active-server check and its OAuth header fallback lived in the CJS route.

resolveMCPOAuthTarget (packages/api/src/mcp/oauth/target.ts) now owns both:
it resolves the server in the principal's current config with a strict read,
refuses a flow admitted for another server, a server the principal can no
longer use, or a redefined one, and selects the headers the flow sends (the
initiation snapshot, else the principal's config). Initiation calls it before
either redirect (404 or 400); the callback calls it before the exchange and
from the token-store fence.

* 📝 docs: Note That a Hidden MCP Server Ends OAuth Sign-Ins Already Started

* 🚩 feat: Publish the yamlMcpHide Admin Config Meta Flag

Profiles can hide librechat.yaml MCP servers and a hidden server is an
access boundary, so GET /api/admin/config/meta now reports
features.yamlMcpHide for the admin panel to gate its hide UI on. The
meta.spec probe checks the behaviour itself: the admin API stores an
mcpServers.<name> tombstone, the merged config drops the server, the
registry withholds it from principal lookups and checkout but not from
app-level lookups, process-backed servers stay, and an unreadable
principal config withholds every hideable server.

* 🧪 test: Align MCP Tombstone Specs With the Portable Config Store

The admin config handlers now write whole documents through
writeConfigDocument, so the end-to-end tombstone spec wires it in place
of the removed upsertConfig/patchConfigFields deps. A reset of a whole
MCP record now also prunes the parents it leaves empty.
2026-10-22 14:10:31 +02:00

168 lines
6.1 KiB
JavaScript

const mongoose = require('mongoose');
const { logger } = require('@librechat/data-schemas');
const { resolveMCPAppsPolicy } = require('librechat-data-provider');
const {
registerShutdownTask,
setMCPToolsChangedHandler,
getDeploymentPluginMcpServers,
setMCPToolsChangedGenerationHandler,
setMCPToolsChangedGenerationRenewalHandler,
setMCPToolsChangedRevisionHandler,
createMCPAppBindingCodec,
createMCPPolicyResolver,
reportStoredMCPTombstones,
} = require('@librechat/api');
const { syncStaticTools, mergeAppTools, getAppConfig, invalidateCachedTools } = require('./Config');
const { startMCPAuthorizationFenceRetryWorker } = require('./MCPAuthorizationFenceRetry');
const {
getMCPToolsCacheGeneration,
renewMCPToolsCacheGeneration,
getNextAppToolsPublicationRevision,
updateMCPServerTools,
} = require('./Config/mcp');
const { createMCPServersRegistry, createMCPManager } = require('~/config');
const db = require('~/models');
/**
* 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,
capabilityProfile,
}) {
await updateMCPServerTools({
userId,
serverName,
tools,
serverConfig,
...(publicationGeneration && { publicationGeneration }),
...(publicationRevision && { publicationRevision }),
capabilityProfile,
});
const toolCount = tools.length;
logger.info(
`[MCP][${serverName}] Tool list changed; refreshed ${toolCount} ${toolCount === 1 ? 'tool' : 'tools'}${userId ? ` for user ${userId}` : ''}`,
);
}
/**
* Merges Agent Plugins MCP servers under the configured servers. A plugin never
* displaces a server the operator declared in `librechat.yaml`.
*/
function withPluginServers(configured) {
const pluginServers = getDeploymentPluginMcpServers();
const names = Object.keys(pluginServers);
if (names.length === 0) {
return configured;
}
const merged = { ...configured };
for (const name of names) {
/** Own-property check: an inherited member like `toString` is not a conflict. */
if (Object.hasOwn(merged, name)) {
logger.warn(
`[MCP] Plugin server "${name}" conflicts with a configured server and was skipped.`,
);
continue;
}
/** Defined rather than assigned so a name like `__proto__` cannot reach a setter. */
Object.defineProperty(merged, name, {
value: pluginServers[name],
enumerable: true,
writable: true,
configurable: true,
});
}
return merged;
}
/**
* Initialize MCP servers
*/
async function initializeMCPs() {
const appConfig = await getAppConfig({ baseOnly: true });
const mcpServers = withPluginServers(appConfig.mcpConfig);
try {
createMCPServersRegistry(
mongoose,
appConfig?.mcpSettings?.allowedDomains,
appConfig?.mcpSettings?.allowedAddresses,
createMCPPolicyResolver(getAppConfig),
resolveMCPAppsPolicy(
appConfig?.mcpSettings?.apps,
undefined,
appConfig?.mcpAppSandbox?.maxPersistedAppBytes,
appConfig?.mcpAppSandbox?.maxAdmissionRequestsPerMinute,
appConfig?.mcpAppSandbox?.url,
appConfig?.mcpAppSandbox?.maxActiveViews,
appConfig?.mcpAppSandbox?.maxActionPreviewChars,
appConfig?.mcpAppSandbox?.operationLimits,
),
);
} catch (error) {
logger.error('[MCP] Failed to initialize MCPServersRegistry:', error);
throw error;
}
/** Runs alongside the connections below. It never rejects, so a failed start leaves no unhandled rejection. */
const tombstoneReport = reportStoredMCPTombstones(
(fieldPath) => db.listConfigTombstones(fieldPath),
appConfig?.mcpConfig,
);
try {
const mcpManager = await createMCPManager(mcpServers || {}, {
catalogRecoveryMaxStateEntries: appConfig?.mcpSettings?.catalogRecovery?.maxStateEntries,
catalogRecoveryMaxDetachedDiscoveries:
appConfig?.mcpSettings?.catalogRecovery?.maxDetachedDiscoveries,
appBindingCodec: createMCPAppBindingCodec(process.env.JWT_SECRET),
});
startMCPAuthorizationFenceRetryWorker(invalidateCachedTools, {
intervalMs: appConfig?.mcpSettings?.catalogRecovery?.authorizationFenceRetryIntervalMs,
batchSize: appConfig?.mcpSettings?.catalogRecovery?.authorizationFenceRetryBatchSize,
attemptTimeoutMs: appConfig?.mcpSettings?.catalogRecovery?.authorizationFenceTimeoutMs,
});
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;
}
await tombstoneReport;
}
module.exports = initializeMCPs;
module.exports.refreshChangedServerTools = refreshChangedServerTools;