mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-16 21:08:17 +00:00
* 📇 fix: Stop an MCP Credential Refresh From Fencing Its Own Catalog Recovery Passive catalog recovery captures the tool-cache generation before discovering a cold server and discards the catalog when the stored generation has moved by the time discovery returns. A silent OAuth refresh inside that same discovery publishes a rotation of its own and then clears this replica's recovery state, so the tracker drops the flight as superseded and the generation check rejects it: the server is listed with no tools, and a concurrent catalog request starts a second discovery instead of joining the first. The authorization fence now reaches discovery through recovery's own dependencies, which report each generation a discovery's refresh publishes. The tracker adopts that generation while the flight is still running, so the flight stays current and its outcome carries the generation it produced; a rotation or clear from any other writer afterwards still supersedes it, and a refresh that completes after its discovery settled no longer touches that settled state. * 🪢 fix: Keep a Recovery Flight Joinable Through Its Own Credential Publication A refresh's authorization fence writes the new shared generation, clears local recovery state, and only then reports what it wrote. A catalog request that read the new generation during that span found the flight still keyed to the old generation, or its slot vacated by the clear, and replaced it with a second discovery; the original flight was then discarded. Discovery now runs its publication through a tracker bracket. While a flight's own publication is in progress the tracker holds any clear for that server and lets requests for the same config join the flight; when it ends, the flight adopts the generation it wrote, or applies the held clear if the publication failed or the flight settled first. The flight is registered before its discovery starts, so a publication can never precede its own registration. * ⏳ fix: Bound and Count What a Recovery Flight Holds During Its Own Publication A recovery flight held every clear for its key and admitted any request for its server for as long as its own credential publication stayed open. A clear from another writer collapsed into the fence's own clear and was dropped on adoption, leaving a backoff or reauthorization decision in place after a teardown; a publication stalled in an unbounded storage write kept every later request joined to the stalled flight; and a joiner that had already read a foreign generation could keep tools under an older adopted generation when the final generation read failed. An open publication now holds clears and admits joins only while its flight is in flight and for at most one discovery budget, after which requests take over as before. The fence clears local recovery once when it completes, so any other held clear still applies after the flight adopts its generation, and every held clear applies when the publication fails or the flight settles first. An outcome under a generation the request never observed stands only when the final shared generation read confirms it. * 🧬 fix: Correlate Catalog Recovery Clears With the Generation Their Fence Wrote Local catalog-recovery clears carried only a user and server, so the tracker could not tell a flight's own credential publication from any other writer. It counted clears and bounded its hold with a time window instead, which left a request that joined before the window expired waiting on a stalled publication, and let a late fence clear delete the flight that took over after the window. The authorization fence now hands local recovery the generation it wrote, and a clear spares state already recorded under that generation; a clear without one still clears. A flight holds the clears it receives while its own publication is open, adopts the generation that publication wrote, and then applies each held clear against it, so its own clear is spared while a teardown or another publication's clear still applies. Retry-intent cleanup inside the fence is bounded by the same per-attempt timeout as the generation write, since a leftover intent only advances the generation again, so the publication itself can no longer hold its joiners open and no time window is needed. * 🔏 fix: Confirm an Adopted Catalog Generation for Requests That Read None A request whose pre-discovery generation reads both failed observed no generation, so the confirmation rule exempted it. When that request's own discovery refreshed credentials, adopted the generation its publication wrote, and another replica rotated past it before a final read that also failed, the catalog was served without ever being confirmed against shared state. A flight's own result now records that its generation came from its own publication, and that mark is never copied into retained state. An outcome under a generation the request did not read needs final confirmation whenever the request read a different generation or the generation was adopted; an outcome whose generation the tracker merely carried over for a request that read nothing keeps the existing fail-open behavior, so a cache outage still preserves retained backoff and reauthorization state. * 🧭 fix: Judge In-Flight Catalog Recovery by the Shared Generation, Not a Tagged Clear A publication's local clear carries the generation it wrote, and the tracker deleted any state recorded under a different one. Generations carry no order, so a refresh that outlived its own flight could clear with an older generation and delete a flight that had started under a newer rotation from another replica, discarding a catalog that was still current. A tagged clear now only signals that the shared generation advanced. A flight still in flight under a known generation, or publishing its own credential change, is left to the requests awaiting it, which already confirm their outcome against the shared generation exactly as they do for a rotation from another replica. Retained state and flights with no known generation are cleared unless recorded under the clear's generation, and a clear without a generation still clears unconditionally. The tracker no longer holds clears during a publication: the refresh's own clear spares its flight directly, and the flight adopts the generation it wrote when the publication completes. The shared-discovery tests compared catalog maps through expect.objectContaining, which does not compare Map contents; they now assert each request's catalog with toEqual. * 🧾 fix: Confirm a Catalog Flight That a Clear for Another Generation Spared A tagged clear spares a flight still in flight, because an unordered generation cannot say whether that flight predates the rotation. The spare was not recorded, so when the request's final shared-generation read timed out, a flight that had observed its own generation kept a catalog the clear may have superseded: an older recovery whose refresh published after a replacement flight started could leave that replacement serving tools no read ever confirmed. A spared flight now records the generation each such clear carried and settles against its final generation. A clear for its own generation, including its own refresh's, changes nothing; any other marks the flight's result unconfirmed, keeps it out of retained state, and requires every request awaiting it to confirm the generation against the shared read before using its tools. A spared flight that finishes with no known generation is discarded, as the clear would have done. A tagged clear no longer spares retained state recorded under its generation.
472 lines
17 KiB
JavaScript
472 lines
17 KiB
JavaScript
const { logger } = require('@librechat/data-schemas');
|
|
const {
|
|
formatMCPServerTools,
|
|
getUserMCPAuthMap,
|
|
getMissingCustomUserVars,
|
|
loadMCPServerCatalogs: loadCatalogs,
|
|
resolveMCPReinitializeConfig,
|
|
requiresEphemeralUserConnection,
|
|
getMissingRuntimeBodyPlaceholderFields,
|
|
MCPAuthenticationRejectedError,
|
|
MCPAuthenticationRefreshError,
|
|
OpenIDReauthRequiredError,
|
|
prepareMCPAuthorizationMutation,
|
|
} = require('@librechat/api');
|
|
const { CacheKeys, Constants } = require('librechat-data-provider');
|
|
const { getMCPManager, getMCPServersRegistry, getFlowStateManager } = require('~/config');
|
|
const {
|
|
findToken,
|
|
createToken,
|
|
updateToken,
|
|
deleteTokens,
|
|
findPluginAuthsByKeys,
|
|
} = require('~/models');
|
|
const { getGraphApiToken } = require('~/server/services/GraphTokenService');
|
|
const { exchangeOboToken } = require('~/server/services/OboTokenService');
|
|
const { createOboTrustChecker } = require('~/server/services/OboPolicyService');
|
|
const {
|
|
getMCPServerTools,
|
|
cacheMCPServerTools,
|
|
getMCPToolsCacheGeneration,
|
|
updateMCPServerTools,
|
|
invalidateCachedTools,
|
|
} = require('~/server/services/Config');
|
|
const { getLogStores } = require('~/cache');
|
|
const {
|
|
clearMCPAuthorizationFenceRetry,
|
|
persistMCPAuthorizationFenceRetry,
|
|
} = require('~/server/services/MCPAuthorizationFenceRetry');
|
|
|
|
const MCP_REINITIALIZE_FAILURE_REASONS = {
|
|
MISSING_CUSTOM_USER_VARS: 'missing_custom_user_vars',
|
|
OAUTH_REQUIRED: 'oauth_required',
|
|
INITIALIZATION_FAILED: 'initialization_failed',
|
|
};
|
|
|
|
const isMCPReauthenticationError = (error) =>
|
|
error instanceof MCPAuthenticationRejectedError ||
|
|
error instanceof MCPAuthenticationRefreshError ||
|
|
error instanceof OpenIDReauthRequiredError;
|
|
|
|
/** Wires application dependencies into the passive, request-local catalog recovery service.
|
|
* @param {Object} params
|
|
* @param {IUser} params.user
|
|
* @param {Array<{ serverName: string, serverConfig: object }>} params.servers
|
|
* @param {import('@librechat/api').UpstreamTokenProvider} [params.upstreamTokenProvider] - Live upstream-token closure for OBO discovery, built at the request boundary so this layer never receives the raw Express request.
|
|
* @param {import('@librechat/api').AuthIdentityContext} [params.oboIdentityContext] - Non-template-visible OBO identity context built from the real request user.
|
|
* @param {AbortSignal} [params.signal] - Cancels queued and in-flight catalog reads when the request ends.
|
|
* @param {import('@librechat/api').MCPServerCatalogRecoveryPolicy} [params.recoveryPolicy]
|
|
*/
|
|
async function loadMCPServerCatalogs({
|
|
user,
|
|
servers,
|
|
upstreamTokenProvider,
|
|
oboIdentityContext,
|
|
signal,
|
|
recoveryPolicy,
|
|
}) {
|
|
const flowManager = getFlowStateManager(getLogStores(CacheKeys.FLOWS));
|
|
const tokenMethods = { findToken, updateToken, createToken, deleteTokens };
|
|
const mcpManager = getMCPManager();
|
|
const onOAuthCredentialsChanging = (scope) =>
|
|
prepareMCPAuthorizationMutation(scope, {
|
|
invalidateRecoveryGeneration: invalidateCachedTools,
|
|
persistPublicationRetry: persistMCPAuthorizationFenceRetry,
|
|
clearPublicationRetry: clearMCPAuthorizationFenceRetry,
|
|
clearLocalRecovery: (userId, serverName, generation) =>
|
|
mcpManager.clearCatalogRecoveryState?.(userId, serverName, generation),
|
|
retryDelaysMs: recoveryPolicy?.authorizationFenceRetryMs,
|
|
attemptTimeoutMs: recoveryPolicy?.authorizationFenceTimeoutMs,
|
|
});
|
|
return loadCatalogs(
|
|
{ user, servers, signal, recoveryPolicy },
|
|
{
|
|
loadUserMCPAuthMap: (userId, serverNames) =>
|
|
getUserMCPAuthMap({
|
|
userId,
|
|
servers: serverNames,
|
|
findPluginAuthsByKeys,
|
|
}),
|
|
discoverServerTools: (options) =>
|
|
mcpManager.discoverServerTools({
|
|
...options,
|
|
flowManager,
|
|
tokenMethods,
|
|
graphTokenResolver: getGraphApiToken,
|
|
oboTokenResolver: exchangeOboToken,
|
|
oboTrustChecker: createOboTrustChecker(),
|
|
upstreamTokenProvider,
|
|
oboIdentityContext,
|
|
}),
|
|
onOAuthCredentialsChanging,
|
|
formatServerTools: formatMCPServerTools,
|
|
recoveryTracker: mcpManager.getCatalogRecoveryTracker?.(),
|
|
getRecoveryGeneration: getMCPToolsCacheGeneration,
|
|
getCachedServerTools: getMCPServerTools,
|
|
getServerToolFunctionsSnapshot: (userId, serverName, serverConfig, options) =>
|
|
mcpManager.getServerToolFunctionsSnapshot(userId, serverName, serverConfig, options),
|
|
cacheServerTools: cacheMCPServerTools,
|
|
},
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Reinitializes an MCP server connection and discovers available tools.
|
|
* When OAuth is required, uses discovery mode to list tools without full authentication
|
|
* (per MCP spec, tool listing should be possible without auth).
|
|
* @param {Object} params
|
|
* @param {IUser} params.user - The user from the request object.
|
|
* @param {import('@librechat/api').UpstreamTokenProvider} [params.upstreamTokenProvider] - Live upstream-token closure for OBO connection establishment, built at the request boundary so this layer never receives the raw Express request.
|
|
* @param {import('@librechat/api').AuthIdentityContext} [params.oboIdentityContext] - Non-template-visible OBO identity context built from the real request user.
|
|
* @param {string} params.serverName - The name of the MCP server
|
|
* @param {boolean} params.returnOnOAuth - Whether to initiate OAuth and return, or wait for OAuth flow to finish
|
|
* @param {AbortSignal} [params.signal] - The abort signal to handle cancellation.
|
|
* @param {boolean} [params.forceNew]
|
|
* @param {number} [params.connectionTimeout]
|
|
* @param {FlowStateManager<any>} [params.flowManager]
|
|
* @param {(authURL: string, options?: { expiresAt?: number }) => Promise<void>} [params.oauthStart]
|
|
* @param {() => Promise<void>} [params.oauthEnd]
|
|
* @param {import('@librechat/api').RequestBody} [params.requestBody]
|
|
* @param {import('@librechat/api').RequestScopedMCPConnectionStore} [params.requestScopedConnections]
|
|
* @param {Record<string, Record<string, string>>} [params.userMCPAuthMap]
|
|
* @param {import('@librechat/api').MCPServerCatalogRecoveryPolicy} [params.recoveryPolicy]
|
|
*/
|
|
async function reinitMCPServer({
|
|
user,
|
|
signal,
|
|
forceNew,
|
|
serverName,
|
|
configServers,
|
|
userMCPAuthMap,
|
|
connectionTimeout,
|
|
returnOnOAuth = true,
|
|
oauthStart: _oauthStart,
|
|
flowManager: _flowManager,
|
|
serverConfig: providedConfig,
|
|
requestBody,
|
|
requestScopedConnections,
|
|
upstreamTokenProvider,
|
|
oboIdentityContext,
|
|
oauthEnd,
|
|
recoveryPolicy,
|
|
}) {
|
|
/** @type {MCPConnection | null} */
|
|
let connection = null;
|
|
let serverConfig = providedConfig;
|
|
/** @type {LCAvailableTools | null} */
|
|
let availableTools = null;
|
|
/** @type {ReturnType<MCPConnection['fetchTools']> | null} */
|
|
let tools = null;
|
|
let oauthRequired = false;
|
|
let oauthUrl = null;
|
|
let oauthExpiresAt;
|
|
let ephemeralServer = false;
|
|
let publicationGeneration;
|
|
let publicationRevision;
|
|
|
|
try {
|
|
const registry = getMCPServersRegistry();
|
|
const resolution = await resolveMCPReinitializeConfig(
|
|
registry,
|
|
serverName,
|
|
serverConfig ?? (await registry.getServerConfig(serverName, user?.id, configServers)),
|
|
user?.id,
|
|
);
|
|
if (resolution.result) {
|
|
return resolution.result;
|
|
}
|
|
serverConfig = resolution.serverConfig;
|
|
ephemeralServer = serverConfig ? requiresEphemeralUserConnection(serverConfig) : false;
|
|
|
|
const customUserVars = userMCPAuthMap?.[`${Constants.mcp_prefix}${serverName}`];
|
|
|
|
const missingUserVars = getMissingCustomUserVars(serverConfig ?? {}, customUserVars);
|
|
if (missingUserVars.length > 0) {
|
|
logger.warn('[MCP Reinitialize] Skipping server with missing user configuration', {
|
|
missingVariableCount: missingUserVars.length,
|
|
});
|
|
return {
|
|
availableTools: null,
|
|
success: false,
|
|
message: `MCP server '${serverName}' requires user-provided variable(s) [${missingUserVars.join(
|
|
', ',
|
|
)}] which are not set`,
|
|
failureReason: MCP_REINITIALIZE_FAILURE_REASONS.MISSING_CUSTOM_USER_VARS,
|
|
missingUserVars,
|
|
oauthRequired: false,
|
|
serverName,
|
|
oauthUrl: null,
|
|
tools: null,
|
|
};
|
|
}
|
|
|
|
/** `{{LIBRECHAT_BODY_*}}` placeholders only resolve during a chat turn; connecting
|
|
* without them would fail, so defer the connection instead of reporting a failure. */
|
|
const missingBodyFields = serverConfig
|
|
? getMissingRuntimeBodyPlaceholderFields(serverConfig, requestBody)
|
|
: [];
|
|
if (missingBodyFields.length > 0) {
|
|
logger.info(
|
|
'[MCP Reinitialize] Runtime placeholders unresolved; connection deferred to first use',
|
|
{ missingBodyFieldCount: missingBodyFields.length },
|
|
);
|
|
return {
|
|
availableTools: null,
|
|
success: true,
|
|
/** Lets clients distinguish "connection deferred to a chat turn" from a
|
|
* plain success with no tools, e.g. to attach the server at the server
|
|
* level instead of waiting for a tool list that never arrives. */
|
|
connectionDeferred: true,
|
|
message: `MCP server '${serverName}' uses request-scoped placeholders; connection will be established on first use in a chat turn`,
|
|
oauthRequired: false,
|
|
serverName,
|
|
oauthUrl: null,
|
|
tools: null,
|
|
};
|
|
}
|
|
|
|
const flowManager = _flowManager ?? getFlowStateManager(getLogStores(CacheKeys.FLOWS));
|
|
const mcpManager = getMCPManager();
|
|
const onOAuthCredentialsChanging = (scope) =>
|
|
prepareMCPAuthorizationMutation(scope, {
|
|
invalidateRecoveryGeneration: invalidateCachedTools,
|
|
persistPublicationRetry: persistMCPAuthorizationFenceRetry,
|
|
clearPublicationRetry: clearMCPAuthorizationFenceRetry,
|
|
clearLocalRecovery: (userId, changedServerName) =>
|
|
mcpManager.clearCatalogRecoveryState?.(userId, changedServerName),
|
|
retryDelaysMs: recoveryPolicy?.authorizationFenceRetryMs,
|
|
attemptTimeoutMs: recoveryPolicy?.authorizationFenceTimeoutMs,
|
|
});
|
|
const tokenMethods = { findToken, updateToken, createToken, deleteTokens };
|
|
|
|
if (!ephemeralServer) {
|
|
publicationGeneration = await getMCPToolsCacheGeneration({
|
|
userId: user.id,
|
|
serverName,
|
|
});
|
|
}
|
|
|
|
const oauthStart =
|
|
_oauthStart ??
|
|
(async (authURL, options) => {
|
|
logger.info('[MCP Reinitialize] OAuth URL received');
|
|
if (authURL !== oauthUrl) {
|
|
oauthExpiresAt = undefined;
|
|
}
|
|
oauthUrl = authURL;
|
|
if (typeof options?.expiresAt === 'number' && Number.isFinite(options.expiresAt)) {
|
|
oauthExpiresAt = options.expiresAt;
|
|
}
|
|
oauthRequired = true;
|
|
});
|
|
|
|
try {
|
|
connection = await mcpManager.getConnection({
|
|
user,
|
|
signal,
|
|
forceNew,
|
|
oauthStart,
|
|
serverName,
|
|
flowManager,
|
|
tokenMethods,
|
|
onOAuthCredentialsChanging,
|
|
returnOnOAuth,
|
|
oauthEnd,
|
|
customUserVars,
|
|
requestBody,
|
|
requestScopedConnections,
|
|
connectionTimeout,
|
|
serverConfig,
|
|
graphTokenResolver: getGraphApiToken,
|
|
oboTokenResolver: exchangeOboToken,
|
|
oboTrustChecker: createOboTrustChecker(),
|
|
upstreamTokenProvider,
|
|
oboIdentityContext,
|
|
});
|
|
|
|
logger.info('[MCP Reinitialize] Successfully established connection');
|
|
} catch (err) {
|
|
if (isMCPReauthenticationError(err)) {
|
|
throw err;
|
|
}
|
|
logger.info('[MCP Reinitialize] Connection attempt failed');
|
|
logger.info(
|
|
`[MCP Reinitialize] OAuth state - oauthRequired: ${oauthRequired}, oauthUrl: ${oauthUrl ? 'present' : 'null'}`,
|
|
);
|
|
|
|
const isOAuthError =
|
|
err.message?.includes('OAuth') ||
|
|
err.message?.includes('authentication') ||
|
|
err.message?.includes('401');
|
|
|
|
const isOAuthFlowInitiated = err.message === 'OAuth flow initiated - return early';
|
|
|
|
if (isOAuthError || oauthRequired || isOAuthFlowInitiated) {
|
|
logger.info('[MCP Reinitialize] OAuth required; attempting tool discovery without auth');
|
|
oauthRequired = true;
|
|
|
|
try {
|
|
const discoveryResult = await mcpManager.discoverServerTools({
|
|
user,
|
|
signal,
|
|
serverName,
|
|
flowManager,
|
|
tokenMethods,
|
|
onOAuthCredentialsChanging,
|
|
oauthStart,
|
|
customUserVars,
|
|
requestBody,
|
|
connectionTimeout,
|
|
configServers,
|
|
graphTokenResolver: getGraphApiToken,
|
|
oboTokenResolver: exchangeOboToken,
|
|
oboTrustChecker: createOboTrustChecker(),
|
|
upstreamTokenProvider,
|
|
oboIdentityContext,
|
|
});
|
|
|
|
if (discoveryResult.tools && discoveryResult.tools.length > 0) {
|
|
tools = discoveryResult.tools;
|
|
logger.info(
|
|
`[MCP Reinitialize] Discovered ${tools.length} tools without full authentication`,
|
|
);
|
|
}
|
|
} catch (error) {
|
|
if (isMCPReauthenticationError(error)) {
|
|
throw error;
|
|
}
|
|
logger.debug('[MCP Reinitialize] Tool discovery failed');
|
|
}
|
|
} else {
|
|
logger.error('[MCP Reinitialize] Error initializing MCP server');
|
|
}
|
|
}
|
|
|
|
if (connection && !oauthRequired) {
|
|
publicationGeneration =
|
|
mcpManager.getToolPublicationGeneration(connection) ?? publicationGeneration;
|
|
let snapshot;
|
|
if (typeof connection.fetchOrderedToolsSnapshot === 'function') {
|
|
snapshot = await connection.fetchOrderedToolsSnapshot();
|
|
} else if (typeof connection.fetchToolsSnapshot === 'function') {
|
|
snapshot = await connection.fetchToolsSnapshot();
|
|
} else {
|
|
snapshot = { tools: await connection.fetchTools(), complete: true };
|
|
}
|
|
if (snapshot.complete) {
|
|
tools = snapshot.tools;
|
|
/** Reserved before this snapshot's tools/list; an app-level catalog cannot publish
|
|
* without it, and allocating a later one here would outrank fresher tools. */
|
|
publicationRevision = snapshot.publicationRevision;
|
|
if (snapshot.orderingUnavailable && typeof connection.refreshToolList === 'function') {
|
|
/** These tools still serve this request; the connection republishes the shared
|
|
* catalog under backoff rather than leaving it cold until the next reinitialize. */
|
|
connection
|
|
.refreshToolList()
|
|
.catch((err) =>
|
|
logger.debug(
|
|
`[MCP Reinitialize] Could not schedule a catalog republish for ${serverName}: ${err?.message ?? String(err)}`,
|
|
),
|
|
);
|
|
}
|
|
} else {
|
|
logger.warn(
|
|
`[MCP Reinitialize] Preserving cached tools for ${serverName} because tools/list returned an incomplete snapshot`,
|
|
);
|
|
}
|
|
}
|
|
|
|
if (tools && !ephemeralServer && publicationGeneration) {
|
|
const currentGeneration = await getMCPToolsCacheGeneration({
|
|
userId: user.id,
|
|
serverName,
|
|
});
|
|
if (currentGeneration !== publicationGeneration) {
|
|
logger.warn(
|
|
`[MCP Reinitialize] Discarding stale tools for ${serverName} because its publication generation changed during discovery`,
|
|
);
|
|
tools = null;
|
|
}
|
|
}
|
|
|
|
if (tools) {
|
|
availableTools = await updateMCPServerTools({
|
|
userId: user.id,
|
|
serverName,
|
|
tools,
|
|
serverConfig,
|
|
...(publicationGeneration && { publicationGeneration }),
|
|
...(publicationRevision && { publicationRevision }),
|
|
});
|
|
if (availableTools == null) {
|
|
tools = null;
|
|
}
|
|
}
|
|
|
|
logger.debug('[MCP Reinitialize] Sending response', {
|
|
oauthRequired,
|
|
hasOauthUrl: Boolean(oauthUrl),
|
|
});
|
|
|
|
const getResponseMessage = () => {
|
|
if (oauthRequired && tools && tools.length > 0) {
|
|
return `MCP server '${serverName}' tools discovered, OAuth required for execution`;
|
|
}
|
|
if (oauthRequired) {
|
|
return `MCP server '${serverName}' ready for OAuth authentication`;
|
|
}
|
|
if (connection) {
|
|
return `MCP server '${serverName}' reinitialized successfully`;
|
|
}
|
|
return `Failed to reinitialize MCP server '${serverName}'`;
|
|
};
|
|
|
|
const success = Boolean(
|
|
(connection && !oauthRequired) || (oauthRequired && oauthUrl) || (tools && tools.length > 0),
|
|
);
|
|
let failureReason;
|
|
if (!success) {
|
|
failureReason = oauthRequired
|
|
? MCP_REINITIALIZE_FAILURE_REASONS.OAUTH_REQUIRED
|
|
: MCP_REINITIALIZE_FAILURE_REASONS.INITIALIZATION_FAILED;
|
|
}
|
|
const result = {
|
|
availableTools,
|
|
success,
|
|
message: getResponseMessage(),
|
|
failureReason,
|
|
oauthRequired,
|
|
serverName,
|
|
oauthUrl,
|
|
oauthExpiresAt,
|
|
tools,
|
|
};
|
|
|
|
logger.debug('[MCP Reinitialize] Response ready', {
|
|
success: result.success,
|
|
oauthRequired: result.oauthRequired,
|
|
hasOauthUrl: Boolean(result.oauthUrl),
|
|
toolsCount: tools?.length ?? 0,
|
|
});
|
|
|
|
return result;
|
|
} catch (error) {
|
|
if (isMCPReauthenticationError(error)) {
|
|
throw error;
|
|
}
|
|
logger.error('[MCP Reinitialize] Error loading MCP tools; servers may still be initializing');
|
|
} finally {
|
|
if (connection && ephemeralServer && !requestScopedConnections) {
|
|
try {
|
|
await connection.dispose();
|
|
} catch {
|
|
logger.warn('[MCP Reinitialize] Failed to dispose ephemeral server');
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
reinitMCPServer,
|
|
loadMCPServerCatalogs,
|
|
};
|