🏗️ feat: Dynamic MCP Server Infrastructure with Access Control (#10787)

* Feature: Dynamic MCP Server with Full UI Management

* 🚦 feat: Add MCP Connection Status icons to MCPBuilder panel (#10805)

* feature: Add MCP server connection status icons to MCPBuilder panel

* refactor: Simplify MCPConfigDialog rendering in MCPBuilderPanel

---------

Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com>
Co-authored-by: Danny Avila <danny@librechat.ai>

* fix: address code review feedback for MCP server management

- Fix OAuth secret preservation to avoid mutating input parameter
  by creating a merged config copy in ServerConfigsDB.update()

- Improve error handling in getResourcePermissionsMap to propagate
  critical errors instead of silently returning empty Map

- Extract duplicated MCP server filter logic by exposing selectableServers
  from useMCPServerManager hook and using it in MCPSelect component

* test: Update PermissionService tests to throw errors on invalid resource types

- Changed the test for handling invalid resource types to ensure it throws an error instead of returning an empty permissions map.
- Updated the expectation to check for the specific error message when an invalid resource type is provided.

* feat: Implement retry logic for MCP server creation to handle race conditions

- Enhanced the createMCPServer method to include retry logic with exponential backoff for handling duplicate key errors during concurrent server creation.
- Updated tests to verify that all concurrent requests succeed and that unique server names are generated.
- Added a helper function to identify MongoDB duplicate key errors, improving error handling during server creation.

* refactor: StatusIcon to use CircleCheck for connected status

- Replaced the PlugZap icon with CircleCheck in the ConnectedStatusIcon component to better represent the connected state.
- Ensured consistent icon usage across the component for improved visual clarity.

* test: Update AccessControlService tests to throw errors on invalid resource types

- Modified the test for invalid resource types to ensure it throws an error with a specific message instead of returning an empty permissions map.
- This change enhances error handling and improves test coverage for the AccessControlService.

* fix: Update error message for missing server name in MCP server retrieval

- Changed the error message returned when the server name is not provided from 'MCP ID is required' to 'Server name is required' for better clarity and accuracy in the API response.

---------

Co-authored-by: Atef Bellaaj <slalom.bellaaj@external.daimlertruck.com>
Co-authored-by: Danny Avila <danny@librechat.ai>
This commit is contained in:
Atef Bellaaj 2025-12-04 21:37:23 +01:00 committed by Danny Avila
parent 41c0a96d39
commit 99f8bd2ce6
No known key found for this signature in database
GPG key ID: BF31EEB2C5CA0956
103 changed files with 7978 additions and 1003 deletions

View file

@ -4,13 +4,15 @@
const mongoose = require('mongoose');
const { logger } = require('@librechat/data-schemas');
const { ResourceType, PrincipalType } = require('librechat-data-provider');
const { ResourceType, PrincipalType, PermissionBits } = require('librechat-data-provider');
const {
bulkUpdateResourcePermissions,
ensureGroupPrincipalExists,
getEffectivePermissions,
ensurePrincipalExists,
getAvailableRoles,
findAccessibleResources,
getResourcePermissionsMap,
} = require('~/server/services/PermissionService');
const { AclEntry } = require('~/db/models');
const {
@ -475,10 +477,58 @@ const searchPrincipals = async (req, res) => {
}
};
/**
* Get user's effective permissions for all accessible resources of a type
* @route GET /api/permissions/{resourceType}/effective/all
*/
const getAllEffectivePermissions = async (req, res) => {
try {
const { resourceType } = req.params;
validateResourceType(resourceType);
const { id: userId } = req.user;
// Find all resources the user has at least VIEW access to
const accessibleResourceIds = await findAccessibleResources({
userId,
role: req.user.role,
resourceType,
requiredPermissions: PermissionBits.VIEW,
});
if (accessibleResourceIds.length === 0) {
return res.status(200).json({});
}
// Get effective permissions for all accessible resources
const permissionsMap = await getResourcePermissionsMap({
userId,
role: req.user.role,
resourceType,
resourceIds: accessibleResourceIds,
});
// Convert Map to plain object for JSON response
const result = {};
for (const [resourceId, permBits] of permissionsMap) {
result[resourceId] = permBits;
}
res.status(200).json(result);
} catch (error) {
logger.error('Error getting all effective permissions:', error);
res.status(500).json({
error: 'Failed to get all effective permissions',
details: error.message,
});
}
};
module.exports = {
updateResourcePermissions,
getResourcePermissions,
getResourceRoles,
getUserEffectivePermissions,
getAllEffectivePermissions,
searchPrincipals,
};

View file

@ -317,7 +317,7 @@ const maybeUninstallOAuthMCP = async (userId, pluginKey, appConfig) => {
const serverConfig =
(await getMCPServersRegistry().getServerConfig(serverName, userId)) ??
appConfig?.mcpServers?.[serverName];
const oauthServers = await getMCPServersRegistry().getOAuthServers();
const oauthServers = await getMCPServersRegistry().getOAuthServers(userId);
if (!oauthServers.has(serverName)) {
// this server does not use OAuth, so nothing to do here as well
return;

View file

@ -1,9 +1,12 @@
/**
* MCP Tools Controller
* Handles MCP-specific tool endpoints, decoupled from regular LibreChat tools
*
* @import { MCPServerRegistry } from '@librechat/api'
* @import { MCPServerDocument } from 'librechat-data-provider'
*/
const { logger } = require('@librechat/data-schemas');
const { Constants } = require('librechat-data-provider');
const { Constants, MCPServerUserInputSchema } = require('librechat-data-provider');
const { cacheMCPServerTools, getMCPServerTools } = require('~/server/services/Config');
const { getMCPManager, getMCPServersRegistry } = require('~/config');
@ -133,7 +136,6 @@ const getMCPServersList = async (req, res) => {
if (!userId) {
return res.status(401).json({ message: 'Unauthorized' });
}
// TODO - Ensure DB servers loaded into registry (configs only)
// 2. Get all server configs from registry (YAML + DB)
const serverConfigs = await getMCPServersRegistry().getAllServerConfigs(userId);
@ -145,7 +147,113 @@ const getMCPServersList = async (req, res) => {
}
};
/**
* Create MCP server
* @route POST /api/mcp/servers
*/
const createMCPServerController = async (req, res) => {
try {
const userId = req.user?.id;
const { config } = req.body;
const validation = MCPServerUserInputSchema.safeParse(config);
if (!validation.success) {
return res.status(400).json({
message: 'Invalid configuration',
errors: validation.error.errors,
});
}
const result = await getMCPServersRegistry().addServer(
'temp_server_name',
validation.data,
'DB',
userId,
);
res.status(201).json({
serverName: result.serverName,
...result.config,
});
} catch (error) {
logger.error('[createMCPServer]', error);
res.status(500).json({ message: error.message });
}
};
/**
* Get MCP server by ID
*/
const getMCPServerById = async (req, res) => {
try {
const userId = req.user?.id;
const { serverName } = req.params;
if (!serverName) {
return res.status(400).json({ message: 'Server name is required' });
}
const parsedConfig = await getMCPServersRegistry().getServerConfig(serverName, userId);
if (!parsedConfig) {
return res.status(404).json({ message: 'MCP server not found' });
}
res.status(200).json(parsedConfig);
} catch (error) {
logger.error('[getMCPServerById]', error);
res.status(500).json({ message: error.message });
}
};
/**
* Update MCP server
* @route PATCH /api/mcp/servers/:serverName
*/
const updateMCPServerController = async (req, res) => {
try {
const userId = req.user?.id;
const { serverName } = req.params;
const { config } = req.body;
const validation = MCPServerUserInputSchema.safeParse(config);
if (!validation.success) {
return res.status(400).json({
message: 'Invalid configuration',
errors: validation.error.errors,
});
}
const parsedConfig = await getMCPServersRegistry().updateServer(
serverName,
validation.data,
'DB',
userId,
);
res.status(200).json(parsedConfig);
} catch (error) {
logger.error('[updateMCPServer]', error);
res.status(500).json({ message: error.message });
}
};
/**
* Delete MCP server
* @route DELETE /api/mcp/servers/:serverName
*/
const deleteMCPServerController = async (req, res) => {
try {
const userId = req.user?.id;
const { serverName } = req.params;
await getMCPServersRegistry().removeServer(serverName, 'DB', userId);
res.status(200).json({ message: 'MCP server deleted successfully' });
} catch (error) {
logger.error('[deleteMCPServer]', error);
res.status(500).json({ message: error.message });
}
};
module.exports = {
getMCPTools,
getMCPServersList,
createMCPServerController,
getMCPServerById,
updateMCPServerController,
deleteMCPServerController,
};