mirror of
https://github.com/danny-avila/LibreChat.git
synced 2025-12-27 13:48:51 +01:00
🔌 feat: MCP OAuth Integration in Chat UI
- **Real-Time Connection Status**: New backend APIs and React Query hooks provide live MCP server connection monitoring with automatic UI updates - **OAuth Flow Components**: Complete MCPConfigDialog, ServerInitializationSection, and CustomUserVarsSection with OAuth URL handling and polling-based completion - **Enhanced Server Selection**: MCPSelect component with connection-aware filtering, visual status indicators, and better credential management UX (still needs a lot of refinement since there is bloat/unused vars and functions leftover from the ideation phase on how to approach OAuth and connection statuses)
This commit is contained in:
parent
b39b60c012
commit
63140237a6
27 changed files with 1760 additions and 286 deletions
|
|
@ -97,7 +97,7 @@ function createServerToolsCallback() {
|
|||
return;
|
||||
}
|
||||
await mcpToolsCache.set(serverName, serverTools);
|
||||
logger.debug(`MCP tools for ${serverName} added to cache.`);
|
||||
logger.warn(`MCP tools for ${serverName} added to cache.`);
|
||||
} catch (error) {
|
||||
logger.error('Error retrieving MCP tools from cache:', error);
|
||||
}
|
||||
|
|
@ -143,7 +143,7 @@ const getAvailableTools = async (req, res) => {
|
|||
const cache = getLogStores(CacheKeys.CONFIG_STORE);
|
||||
const cachedToolsArray = await cache.get(CacheKeys.TOOLS);
|
||||
const cachedUserTools = await getCachedTools({ userId });
|
||||
const userPlugins = convertMCPToolsToPlugins(cachedUserTools, customConfig);
|
||||
const userPlugins = await convertMCPToolsToPlugins(cachedUserTools, customConfig, userId);
|
||||
|
||||
if (cachedToolsArray && userPlugins) {
|
||||
const dedupedTools = filterUniquePlugins([...userPlugins, ...cachedToolsArray]);
|
||||
|
|
@ -202,23 +202,102 @@ const getAvailableTools = async (req, res) => {
|
|||
const serverName = parts[parts.length - 1];
|
||||
const serverConfig = customConfig?.mcpServers?.[serverName];
|
||||
|
||||
if (!serverConfig?.customUserVars) {
|
||||
logger.warn(
|
||||
`[getAvailableTools] Processing MCP tool:`,
|
||||
JSON.stringify({
|
||||
pluginKey: plugin.pluginKey,
|
||||
serverName,
|
||||
hasServerConfig: !!serverConfig,
|
||||
hasCustomUserVars: !!serverConfig?.customUserVars,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!serverConfig) {
|
||||
logger.warn(
|
||||
`[getAvailableTools] No server config found for ${serverName}, skipping auth check`,
|
||||
);
|
||||
toolsOutput.push(toolToAdd);
|
||||
continue;
|
||||
}
|
||||
|
||||
const customVarKeys = Object.keys(serverConfig.customUserVars);
|
||||
// Handle MCP servers with customUserVars (user-level auth required)
|
||||
if (serverConfig.customUserVars) {
|
||||
logger.warn(`[getAvailableTools] Processing user-level MCP server: ${serverName}`);
|
||||
const customVarKeys = Object.keys(serverConfig.customUserVars);
|
||||
|
||||
if (customVarKeys.length === 0) {
|
||||
toolToAdd.authConfig = [];
|
||||
toolToAdd.authenticated = true;
|
||||
} else {
|
||||
// Build authConfig for MCP tools
|
||||
toolToAdd.authConfig = Object.entries(serverConfig.customUserVars).map(([key, value]) => ({
|
||||
authField: key,
|
||||
label: value.title || key,
|
||||
description: value.description || '',
|
||||
}));
|
||||
toolToAdd.authenticated = false;
|
||||
|
||||
// Check actual connection status for MCP tools with auth requirements
|
||||
if (userId) {
|
||||
try {
|
||||
const mcpManager = getMCPManager(userId);
|
||||
const connectionStatus = await mcpManager.getUserConnectionStatus(userId, serverName);
|
||||
toolToAdd.authenticated = connectionStatus.connected;
|
||||
logger.warn(`[getAvailableTools] User-level connection status for ${serverName}:`, {
|
||||
connected: connectionStatus.connected,
|
||||
hasConnection: connectionStatus.hasConnection,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`[getAvailableTools] Error checking connection status for ${serverName}:`,
|
||||
error,
|
||||
);
|
||||
toolToAdd.authenticated = false;
|
||||
}
|
||||
} else {
|
||||
// For non-authenticated requests, default to false
|
||||
toolToAdd.authenticated = false;
|
||||
}
|
||||
} else {
|
||||
// Handle app-level MCP servers (no auth required)
|
||||
logger.warn(`[getAvailableTools] Processing app-level MCP server: ${serverName}`);
|
||||
toolToAdd.authConfig = [];
|
||||
|
||||
// Check if the app-level connection is active
|
||||
try {
|
||||
const mcpManager = getMCPManager();
|
||||
const allConnections = mcpManager.getAllConnections();
|
||||
logger.warn(`[getAvailableTools] All app-level connections:`, {
|
||||
connectionNames: Array.from(allConnections.keys()),
|
||||
serverName,
|
||||
});
|
||||
|
||||
const appConnection = mcpManager.getConnection(serverName);
|
||||
logger.warn(`[getAvailableTools] Checking app-level connection for ${serverName}:`, {
|
||||
hasConnection: !!appConnection,
|
||||
connectionState: appConnection?.getConnectionState?.(),
|
||||
});
|
||||
|
||||
if (appConnection) {
|
||||
const connectionState = appConnection.getConnectionState();
|
||||
logger.warn(`[getAvailableTools] App-level connection status for ${serverName}:`, {
|
||||
connectionState,
|
||||
hasConnection: !!appConnection,
|
||||
});
|
||||
|
||||
// For app-level connections, consider them authenticated if they're in 'connected' state
|
||||
// This is more reliable than isConnected() which does network calls
|
||||
toolToAdd.authenticated = connectionState === 'connected';
|
||||
logger.warn(`[getAvailableTools] Final authenticated status for ${serverName}:`, {
|
||||
authenticated: toolToAdd.authenticated,
|
||||
connectionState,
|
||||
});
|
||||
} else {
|
||||
logger.warn(`[getAvailableTools] No app-level connection found for ${serverName}`);
|
||||
toolToAdd.authenticated = false;
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`[getAvailableTools] Error checking app-level connection status for ${serverName}:`,
|
||||
error,
|
||||
);
|
||||
toolToAdd.authenticated = false;
|
||||
}
|
||||
}
|
||||
|
||||
toolsOutput.push(toolToAdd);
|
||||
|
|
@ -241,7 +320,7 @@ const getAvailableTools = async (req, res) => {
|
|||
* @param {Object} customConfig - Custom configuration for MCP servers
|
||||
* @returns {Array} Array of plugin objects
|
||||
*/
|
||||
function convertMCPToolsToPlugins(functionTools, customConfig) {
|
||||
async function convertMCPToolsToPlugins(functionTools, customConfig, userId = null) {
|
||||
const plugins = [];
|
||||
|
||||
for (const [toolKey, toolData] of Object.entries(functionTools)) {
|
||||
|
|
@ -257,7 +336,7 @@ function convertMCPToolsToPlugins(functionTools, customConfig) {
|
|||
name: parts[0], // Use the tool name without server suffix
|
||||
pluginKey: toolKey,
|
||||
description: functionData.description || '',
|
||||
authenticated: true,
|
||||
authenticated: false, // Default to false, will be updated based on connection status
|
||||
icon: undefined,
|
||||
};
|
||||
|
||||
|
|
@ -265,6 +344,7 @@ function convertMCPToolsToPlugins(functionTools, customConfig) {
|
|||
const serverConfig = customConfig?.mcpServers?.[serverName];
|
||||
if (!serverConfig?.customUserVars) {
|
||||
plugin.authConfig = [];
|
||||
plugin.authenticated = true; // No auth required
|
||||
plugins.push(plugin);
|
||||
continue;
|
||||
}
|
||||
|
|
@ -272,12 +352,30 @@ function convertMCPToolsToPlugins(functionTools, customConfig) {
|
|||
const customVarKeys = Object.keys(serverConfig.customUserVars);
|
||||
if (customVarKeys.length === 0) {
|
||||
plugin.authConfig = [];
|
||||
plugin.authenticated = true; // No auth required
|
||||
} else {
|
||||
plugin.authConfig = Object.entries(serverConfig.customUserVars).map(([key, value]) => ({
|
||||
authField: key,
|
||||
label: value.title || key,
|
||||
description: value.description || '',
|
||||
}));
|
||||
|
||||
// Check actual connection status for MCP tools with auth requirements
|
||||
if (userId) {
|
||||
try {
|
||||
const mcpManager = getMCPManager(userId);
|
||||
const connectionStatus = await mcpManager.getUserConnectionStatus(userId, serverName);
|
||||
plugin.authenticated = connectionStatus.connected;
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`[convertMCPToolsToPlugins] Error checking connection status for ${serverName}:`,
|
||||
error,
|
||||
);
|
||||
plugin.authenticated = false;
|
||||
}
|
||||
} else {
|
||||
plugin.authenticated = false;
|
||||
}
|
||||
}
|
||||
|
||||
plugins.push(plugin);
|
||||
|
|
|
|||
|
|
@ -175,14 +175,18 @@ const updateUserPluginsController = async (req, res) => {
|
|||
try {
|
||||
const mcpManager = getMCPManager(user.id);
|
||||
if (mcpManager) {
|
||||
// Extract server name from pluginKey (e.g., "mcp_myserver" -> "myserver")
|
||||
const serverName = pluginKey.replace(Constants.mcp_prefix, '');
|
||||
|
||||
logger.info(
|
||||
`[updateUserPluginsController] Disconnecting MCP connections for user ${user.id} after plugin auth update for ${pluginKey}.`,
|
||||
`[updateUserPluginsController] Disconnecting MCP connection for user ${user.id} and server ${serverName} after plugin auth update for ${pluginKey}.`,
|
||||
);
|
||||
await mcpManager.disconnectUserConnections(user.id);
|
||||
// Don't kill the server connection on revoke anymore, user can just reinitialize the server if thats what they want
|
||||
// await mcpManager.disconnectUserConnection(user.id, serverName);
|
||||
}
|
||||
} catch (disconnectError) {
|
||||
logger.error(
|
||||
`[updateUserPluginsController] Error disconnecting MCP connections for user ${user.id} after plugin auth update:`,
|
||||
`[updateUserPluginsController] Error disconnecting MCP connection for user ${user.id} after plugin auth update:`,
|
||||
disconnectError,
|
||||
);
|
||||
// Do not fail the request for this, but log it.
|
||||
|
|
|
|||
|
|
@ -106,6 +106,7 @@ router.get('/', async function (req, res) {
|
|||
const serverConfig = config.mcpServers[serverName];
|
||||
payload.mcpServers[serverName] = {
|
||||
customUserVars: serverConfig?.customUserVars || {},
|
||||
requiresOAuth: req.app.locals.mcpOAuthRequirements?.[serverName] || false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ const { MCPOAuthHandler } = require('@librechat/api');
|
|||
const { CacheKeys, Constants } = require('librechat-data-provider');
|
||||
const { findToken, updateToken, createToken, deleteTokens } = require('~/models');
|
||||
const { setCachedTools, getCachedTools, loadCustomConfig } = require('~/server/services/Config');
|
||||
const { getUserPluginAuthValue } = require('~/server/services/PluginService');
|
||||
const { getUserPluginAuthValueByPlugin } = require('~/server/services/PluginService');
|
||||
const { getMCPManager, getFlowStateManager } = require('~/config');
|
||||
const { requireJwtAuth } = require('~/server/middleware');
|
||||
const { getLogStores } = require('~/cache');
|
||||
|
|
@ -206,10 +206,89 @@ router.get('/oauth/status/:flowId', async (req, res) => {
|
|||
});
|
||||
|
||||
/**
|
||||
* Reinitialize MCP server
|
||||
* This endpoint allows reinitializing a specific MCP server
|
||||
* Get connection status for all MCP servers
|
||||
* This endpoint returns the actual connection status from MCPManager
|
||||
*/
|
||||
router.post('/:serverName/reinitialize', requireJwtAuth, async (req, res) => {
|
||||
router.get('/connection/status', requireJwtAuth, async (req, res) => {
|
||||
try {
|
||||
const user = req.user;
|
||||
|
||||
if (!user?.id) {
|
||||
return res.status(401).json({ error: 'User not authenticated' });
|
||||
}
|
||||
|
||||
const mcpManager = getMCPManager();
|
||||
const connectionStatus = {};
|
||||
|
||||
// Get all MCP server names from custom config
|
||||
const config = await loadCustomConfig();
|
||||
const mcpConfig = config?.mcpServers;
|
||||
|
||||
if (mcpConfig) {
|
||||
for (const [serverName, config] of Object.entries(mcpConfig)) {
|
||||
try {
|
||||
// Check if this is an app-level connection (exists in mcpManager.connections)
|
||||
const appConnection = mcpManager.getConnection(serverName);
|
||||
const hasAppConnection = !!appConnection;
|
||||
|
||||
// Check if this is a user-level connection (exists in mcpManager.userConnections)
|
||||
const userConnection = mcpManager.getUserConnectionIfExists(user.id, serverName);
|
||||
const hasUserConnection = !!userConnection;
|
||||
|
||||
// Determine if connected based on actual connection state
|
||||
let connected = false;
|
||||
if (hasAppConnection) {
|
||||
connected = await appConnection.isConnected();
|
||||
} else if (hasUserConnection) {
|
||||
connected = await userConnection.isConnected();
|
||||
}
|
||||
|
||||
// Determine if this server requires user authentication
|
||||
const hasAuthConfig =
|
||||
config.customUserVars && Object.keys(config.customUserVars).length > 0;
|
||||
const requiresOAuth = req.app.locals.mcpOAuthRequirements?.[serverName] || false;
|
||||
|
||||
connectionStatus[serverName] = {
|
||||
connected,
|
||||
hasAuthConfig,
|
||||
hasConnection: hasAppConnection || hasUserConnection,
|
||||
isAppLevel: hasAppConnection,
|
||||
isUserLevel: hasUserConnection,
|
||||
requiresOAuth,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`[MCP Connection Status] Error checking connection for ${serverName}:`,
|
||||
error,
|
||||
);
|
||||
connectionStatus[serverName] = {
|
||||
connected: false,
|
||||
hasAuthConfig: config.customUserVars && Object.keys(config.customUserVars).length > 0,
|
||||
hasConnection: false,
|
||||
isAppLevel: false,
|
||||
isUserLevel: false,
|
||||
requiresOAuth: req.app.locals.mcpOAuthRequirements?.[serverName] || false,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
connectionStatus,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('[MCP Connection Status] Failed to get connection status', error);
|
||||
res.status(500).json({ error: 'Failed to get connection status' });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Check which authentication values exist for a specific MCP server
|
||||
* This endpoint returns only boolean flags indicating if values are set, not the actual values
|
||||
*/
|
||||
router.get('/:serverName/auth-values', requireJwtAuth, async (req, res) => {
|
||||
try {
|
||||
const { serverName } = req.params;
|
||||
const user = req.user;
|
||||
|
|
@ -218,10 +297,206 @@ router.post('/:serverName/reinitialize', requireJwtAuth, async (req, res) => {
|
|||
return res.status(401).json({ error: 'User not authenticated' });
|
||||
}
|
||||
|
||||
const config = await loadCustomConfig();
|
||||
if (!config || !config.mcpServers || !config.mcpServers[serverName]) {
|
||||
return res.status(404).json({
|
||||
error: `MCP server '${serverName}' not found in configuration`,
|
||||
});
|
||||
}
|
||||
|
||||
const serverConfig = config.mcpServers[serverName];
|
||||
const pluginKey = `${Constants.mcp_prefix}${serverName}`;
|
||||
const authValueFlags = {};
|
||||
|
||||
// Check existence of saved values for each custom user variable (don't fetch actual values)
|
||||
if (serverConfig.customUserVars && typeof serverConfig.customUserVars === 'object') {
|
||||
for (const varName of Object.keys(serverConfig.customUserVars)) {
|
||||
try {
|
||||
const value = await getUserPluginAuthValueByPlugin(user.id, varName, pluginKey, false);
|
||||
// Only store boolean flag indicating if value exists
|
||||
authValueFlags[varName] = !!(value && value.length > 0);
|
||||
} catch (err) {
|
||||
logger.error(
|
||||
`[MCP Auth Value Flags] Error checking ${varName} for user ${user.id}:`,
|
||||
err,
|
||||
);
|
||||
// Default to false if we can't check
|
||||
authValueFlags[varName] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
serverName,
|
||||
authValueFlags,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`[MCP Auth Value Flags] Failed to check auth value flags for ${req.params.serverName}`,
|
||||
error,
|
||||
);
|
||||
res.status(500).json({ error: 'Failed to check auth value flags' });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Check if a specific MCP server requires OAuth
|
||||
* This endpoint checks if a specific MCP server requires OAuth authentication
|
||||
*/
|
||||
router.get('/:serverName/oauth/required', requireJwtAuth, async (req, res) => {
|
||||
try {
|
||||
const { serverName } = req.params;
|
||||
const user = req.user;
|
||||
|
||||
if (!user?.id) {
|
||||
return res.status(401).json({ error: 'User not authenticated' });
|
||||
}
|
||||
|
||||
const mcpManager = getMCPManager();
|
||||
const requiresOAuth = await mcpManager.isOAuthRequired(serverName);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
serverName,
|
||||
requiresOAuth,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`[MCP OAuth Required] Failed to check OAuth requirement for ${req.params.serverName}`,
|
||||
error,
|
||||
);
|
||||
res.status(500).json({ error: 'Failed to check OAuth requirement' });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Complete MCP server reinitialization after OAuth
|
||||
* This endpoint completes the reinitialization process after OAuth authentication
|
||||
*/
|
||||
router.post('/:serverName/reinitialize/complete', requireJwtAuth, async (req, res) => {
|
||||
let responseSent = false;
|
||||
|
||||
try {
|
||||
const { serverName } = req.params;
|
||||
const user = req.user;
|
||||
|
||||
if (!user?.id) {
|
||||
responseSent = true;
|
||||
return res.status(401).json({ error: 'User not authenticated' });
|
||||
}
|
||||
|
||||
logger.info(`[MCP Complete Reinitialize] Starting completion for ${serverName}`);
|
||||
|
||||
const mcpManager = getMCPManager();
|
||||
|
||||
// Wait for connection to be established via event-driven approach
|
||||
const userConnection = await new Promise((resolve, reject) => {
|
||||
// Set a reasonable timeout (10 seconds)
|
||||
const timeout = setTimeout(() => {
|
||||
mcpManager.removeListener('connectionEstablished', connectionHandler);
|
||||
reject(new Error('Timeout waiting for connection establishment'));
|
||||
}, 10000);
|
||||
|
||||
const connectionHandler = ({
|
||||
userId: eventUserId,
|
||||
serverName: eventServerName,
|
||||
connection,
|
||||
}) => {
|
||||
if (eventUserId === user.id && eventServerName === serverName) {
|
||||
clearTimeout(timeout);
|
||||
mcpManager.removeListener('connectionEstablished', connectionHandler);
|
||||
resolve(connection);
|
||||
}
|
||||
};
|
||||
|
||||
// Check if connection already exists
|
||||
const existingConnection = mcpManager.getUserConnectionIfExists(user.id, serverName);
|
||||
if (existingConnection) {
|
||||
clearTimeout(timeout);
|
||||
resolve(existingConnection);
|
||||
return;
|
||||
}
|
||||
|
||||
// Listen for the connection establishment event
|
||||
mcpManager.on('connectionEstablished', connectionHandler);
|
||||
});
|
||||
|
||||
if (!userConnection) {
|
||||
responseSent = true;
|
||||
return res.status(404).json({ error: 'User connection not found' });
|
||||
}
|
||||
|
||||
const userTools = (await getCachedTools({ userId: user.id })) || {};
|
||||
|
||||
// Remove any old tools from this server in the user's cache
|
||||
const mcpDelimiter = Constants.mcp_delimiter;
|
||||
for (const key of Object.keys(userTools)) {
|
||||
if (key.endsWith(`${mcpDelimiter}${serverName}`)) {
|
||||
delete userTools[key];
|
||||
}
|
||||
}
|
||||
|
||||
// Add the new tools from this server
|
||||
const tools = await userConnection.fetchTools();
|
||||
for (const tool of tools) {
|
||||
const name = `${tool.name}${Constants.mcp_delimiter}${serverName}`;
|
||||
userTools[name] = {
|
||||
type: 'function',
|
||||
['function']: {
|
||||
name,
|
||||
description: tool.description,
|
||||
parameters: tool.inputSchema,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Save the updated user tool cache
|
||||
await setCachedTools(userTools, { userId: user.id });
|
||||
|
||||
responseSent = true;
|
||||
res.json({
|
||||
success: true,
|
||||
message: `MCP server '${serverName}' reinitialized successfully`,
|
||||
serverName,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`[MCP Complete Reinitialize] Error completing reinitialization for ${req.params.serverName}:`,
|
||||
error,
|
||||
);
|
||||
|
||||
if (!responseSent) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Failed to complete MCP server reinitialization',
|
||||
serverName: req.params.serverName,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Reinitialize MCP server
|
||||
* This endpoint allows reinitializing a specific MCP server
|
||||
*/
|
||||
router.post('/:serverName/reinitialize', requireJwtAuth, async (req, res) => {
|
||||
let responseSent = false;
|
||||
|
||||
try {
|
||||
const { serverName } = req.params;
|
||||
const user = req.user;
|
||||
|
||||
if (!user?.id) {
|
||||
responseSent = true;
|
||||
return res.status(401).json({ error: 'User not authenticated' });
|
||||
}
|
||||
|
||||
logger.info(`[MCP Reinitialize] Reinitializing server: ${serverName}`);
|
||||
|
||||
const config = await loadCustomConfig();
|
||||
if (!config || !config.mcpServers || !config.mcpServers[serverName]) {
|
||||
responseSent = true;
|
||||
return res.status(404).json({
|
||||
error: `MCP server '${serverName}' not found in configuration`,
|
||||
});
|
||||
|
|
@ -231,6 +506,21 @@ router.post('/:serverName/reinitialize', requireJwtAuth, async (req, res) => {
|
|||
const flowManager = getFlowStateManager(flowsCache);
|
||||
const mcpManager = getMCPManager();
|
||||
|
||||
// Clean up any stale OAuth flows for this server
|
||||
try {
|
||||
const flowId = MCPOAuthHandler.generateFlowId(user.id, serverName);
|
||||
const existingFlow = await flowManager.getFlowState(flowId, 'mcp_oauth');
|
||||
if (existingFlow && existingFlow.status === 'PENDING') {
|
||||
logger.info(`[MCP Reinitialize] Cleaning up stale OAuth flow for ${serverName}`);
|
||||
await flowManager.failFlow(flowId, 'mcp_oauth', new Error('OAuth flow interrupted'));
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
`[MCP Reinitialize] Error cleaning up stale OAuth flow for ${serverName}:`,
|
||||
error,
|
||||
);
|
||||
}
|
||||
|
||||
await mcpManager.disconnectServer(serverName);
|
||||
logger.info(`[MCP Reinitialize] Disconnected existing server: ${serverName}`);
|
||||
|
||||
|
|
@ -240,7 +530,8 @@ router.post('/:serverName/reinitialize', requireJwtAuth, async (req, res) => {
|
|||
if (serverConfig.customUserVars && typeof serverConfig.customUserVars === 'object') {
|
||||
for (const varName of Object.keys(serverConfig.customUserVars)) {
|
||||
try {
|
||||
const value = await getUserPluginAuthValue(user.id, varName, false);
|
||||
const pluginKey = `${Constants.mcp_prefix}${serverName}`;
|
||||
const value = await getUserPluginAuthValueByPlugin(user.id, varName, pluginKey, false);
|
||||
if (value) {
|
||||
customUserVars[varName] = value;
|
||||
}
|
||||
|
|
@ -251,6 +542,8 @@ router.post('/:serverName/reinitialize', requireJwtAuth, async (req, res) => {
|
|||
}
|
||||
|
||||
let userConnection = null;
|
||||
let oauthRequired = false;
|
||||
|
||||
try {
|
||||
userConnection = await mcpManager.getUserConnection({
|
||||
user,
|
||||
|
|
@ -263,9 +556,79 @@ router.post('/:serverName/reinitialize', requireJwtAuth, async (req, res) => {
|
|||
createToken,
|
||||
deleteTokens,
|
||||
},
|
||||
oauthStart: (authURL) => {
|
||||
// This will be called if OAuth is required
|
||||
oauthRequired = true;
|
||||
responseSent = true;
|
||||
logger.info(`[MCP Reinitialize] OAuth required for ${serverName}, auth URL: ${authURL}`);
|
||||
|
||||
// Get the flow ID for polling
|
||||
const flowId = MCPOAuthHandler.generateFlowId(user.id, serverName);
|
||||
|
||||
// Return the OAuth response immediately - client will poll for completion
|
||||
res.json({
|
||||
success: false,
|
||||
oauthRequired: true,
|
||||
authURL,
|
||||
flowId,
|
||||
message: `OAuth authentication required for MCP server '${serverName}'`,
|
||||
serverName,
|
||||
});
|
||||
},
|
||||
oauthEnd: () => {
|
||||
// This will be called when OAuth flow completes
|
||||
logger.info(`[MCP Reinitialize] OAuth flow completed for ${serverName}`);
|
||||
},
|
||||
});
|
||||
|
||||
// If response was already sent for OAuth, don't continue
|
||||
if (responseSent) {
|
||||
return;
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error(`[MCP Reinitialize] Error initializing MCP server ${serverName} for user:`, err);
|
||||
|
||||
// Check if this is an OAuth error
|
||||
if (err.message && err.message.includes('OAuth required')) {
|
||||
// Try to get the OAuth URL from the flow manager
|
||||
try {
|
||||
const flowId = MCPOAuthHandler.generateFlowId(user.id, serverName);
|
||||
const existingFlow = await flowManager.getFlowState(flowId, 'mcp_oauth');
|
||||
|
||||
if (existingFlow && existingFlow.metadata) {
|
||||
const { serverUrl, oauth: oauthConfig } = existingFlow.metadata;
|
||||
if (serverUrl && oauthConfig) {
|
||||
const { authorizationUrl: authUrl } = await MCPOAuthHandler.initiateOAuthFlow(
|
||||
serverName,
|
||||
serverUrl,
|
||||
user.id,
|
||||
oauthConfig,
|
||||
);
|
||||
|
||||
return res.json({
|
||||
success: false,
|
||||
oauthRequired: true,
|
||||
authURL: authUrl,
|
||||
flowId,
|
||||
message: `OAuth authentication required for MCP server '${serverName}'`,
|
||||
serverName,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (oauthErr) {
|
||||
logger.error(`[MCP Reinitialize] Error getting OAuth URL for ${serverName}:`, oauthErr);
|
||||
}
|
||||
|
||||
responseSent = true;
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
oauthRequired: true,
|
||||
message: `OAuth authentication required for MCP server '${serverName}'`,
|
||||
serverName,
|
||||
});
|
||||
}
|
||||
|
||||
responseSent = true;
|
||||
return res.status(500).json({ error: 'Failed to reinitialize MCP server for user' });
|
||||
}
|
||||
|
||||
|
|
@ -296,6 +659,7 @@ router.post('/:serverName/reinitialize', requireJwtAuth, async (req, res) => {
|
|||
// Save the updated user tool cache
|
||||
await setCachedTools(userTools, { userId: user.id });
|
||||
|
||||
responseSent = true;
|
||||
res.json({
|
||||
success: true,
|
||||
message: `MCP server '${serverName}' reinitialized successfully`,
|
||||
|
|
@ -303,7 +667,9 @@ router.post('/:serverName/reinitialize', requireJwtAuth, async (req, res) => {
|
|||
});
|
||||
} catch (error) {
|
||||
logger.error('[MCP Reinitialize] Unexpected error', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
if (!responseSent) {
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -108,8 +108,6 @@ https://www.librechat.ai/docs/configuration/stt_tts`);
|
|||
|
||||
return null;
|
||||
} else {
|
||||
logger.info('Custom config file loaded:');
|
||||
logger.info(JSON.stringify(customConfig, null, 2));
|
||||
logger.debug('Custom config:', customConfig);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -41,6 +41,38 @@ const getUserPluginAuthValue = async (userId, authField, throwError = true) => {
|
|||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Asynchronously retrieves and decrypts the authentication value for a user's specific plugin, based on a specified authentication field and plugin key.
|
||||
*
|
||||
* @param {string} userId - The unique identifier of the user for whom the plugin authentication value is to be retrieved.
|
||||
* @param {string} authField - The specific authentication field (e.g., 'API_KEY', 'URL') whose value is to be retrieved and decrypted.
|
||||
* @param {string} pluginKey - The plugin key to filter by (e.g., 'mcp_github-mcp').
|
||||
* @param {boolean} throwError - Whether to throw an error if the authentication value does not exist. Defaults to `true`.
|
||||
* @returns {Promise<string|null>} A promise that resolves to the decrypted authentication value if found, or `null` if no such authentication value exists for the given user, field, and plugin.
|
||||
*
|
||||
* @throws {Error} Throws an error if there's an issue during the retrieval or decryption process, or if the authentication value does not exist.
|
||||
* @async
|
||||
*/
|
||||
const getUserPluginAuthValueByPlugin = async (userId, authField, pluginKey, throwError = true) => {
|
||||
try {
|
||||
const pluginAuth = await findOnePluginAuth({ userId, authField, pluginKey });
|
||||
if (!pluginAuth) {
|
||||
throw new Error(
|
||||
`No plugin auth ${authField} found for user ${userId} and plugin ${pluginKey}`,
|
||||
);
|
||||
}
|
||||
|
||||
const decryptedValue = await decrypt(pluginAuth.value);
|
||||
return decryptedValue;
|
||||
} catch (err) {
|
||||
if (!throwError) {
|
||||
return null;
|
||||
}
|
||||
logger.error('[getUserPluginAuthValueByPlugin]', err);
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
// const updateUserPluginAuth = async (userId, authField, pluginKey, value) => {
|
||||
// try {
|
||||
// const encryptedValue = encrypt(value);
|
||||
|
|
@ -119,6 +151,7 @@ const deleteUserPluginAuth = async (userId, authField, all = false, pluginKey) =
|
|||
|
||||
module.exports = {
|
||||
getUserPluginAuthValue,
|
||||
getUserPluginAuthValueByPlugin,
|
||||
updateUserPluginAuth,
|
||||
deleteUserPluginAuth,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -10,6 +10,15 @@ const { getLogStores } = require('~/cache');
|
|||
* @param {import('express').Application} app - Express app instance
|
||||
*/
|
||||
async function initializeMCPs(app) {
|
||||
// TEMPORARY: Reset all OAuth tokens for fresh testing
|
||||
try {
|
||||
logger.info('[MCP] Resetting all OAuth tokens for fresh testing...');
|
||||
await deleteTokens({});
|
||||
logger.info('[MCP] All OAuth tokens reset successfully');
|
||||
} catch (error) {
|
||||
logger.error('[MCP] Error resetting OAuth tokens:', error);
|
||||
}
|
||||
|
||||
const mcpServers = app.locals.mcpConfig;
|
||||
if (!mcpServers) {
|
||||
return;
|
||||
|
|
@ -36,7 +45,7 @@ async function initializeMCPs(app) {
|
|||
const flowManager = flowsCache ? getFlowStateManager(flowsCache) : null;
|
||||
|
||||
try {
|
||||
await mcpManager.initializeMCPs({
|
||||
const oauthRequirements = await mcpManager.initializeMCPs({
|
||||
mcpServers: filteredServers,
|
||||
flowManager,
|
||||
tokenMethods: {
|
||||
|
|
@ -64,6 +73,9 @@ async function initializeMCPs(app) {
|
|||
logger.debug('Cleared tools array cache after MCP initialization');
|
||||
|
||||
logger.info('MCP servers initialized successfully');
|
||||
|
||||
// Store OAuth requirement information in app locals for client access
|
||||
app.locals.mcpOAuthRequirements = oauthRequirements;
|
||||
} catch (error) {
|
||||
logger.error('Failed to initialize MCP servers:', error);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue