🏗️ 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

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,360 @@
import { Types, ClientSession, DeleteResult } from 'mongoose';
import { AllMethods, IAclEntry, createMethods, logger } from '@librechat/data-schemas';
import { AccessRoleIds, PrincipalType, ResourceType } from 'librechat-data-provider';
export class AccessControlService {
private _dbMethods: AllMethods;
private _aclModel;
constructor(mongoose: typeof import('mongoose')) {
this._dbMethods = createMethods(mongoose);
this._aclModel = mongoose.models.AclEntry;
}
/**
* Grant a permission to a principal for a resource using a role
* @param {Object} params - Parameters for granting role-based permission
* @param {string} params.principalType - PrincipalType.USER, PrincipalType.GROUP, or PrincipalType.PUBLIC
* @param {string|mongoose.Types.ObjectId|null} params.principalId - The ID of the principal (null for PrincipalType.PUBLIC)
* @param {string} params.resourceType - Type of resource (e.g., 'agent')
* @param {string|mongoose.Types.ObjectId} params.resourceId - The ID of the resource
* @param {string} params.accessRoleId - The ID of the role (e.g., AccessRoleIds.AGENT_VIEWER, AccessRoleIds.AGENT_EDITOR)
* @param {Types.ObjectId} params.grantedBy - User ID granting the permission
* @param {ClientSession} [params.session] - Optional MongoDB session for transactions
* @returns {Promise<IAclEntry>} The created or updated ACL entry
*/
public async grantPermission(args: {
principalType: PrincipalType;
principalId: string | Types.ObjectId | null;
resourceType: string;
resourceId: string | Types.ObjectId;
accessRoleId: AccessRoleIds;
grantedBy: string | Types.ObjectId;
session?: ClientSession;
roleId?: string | Types.ObjectId;
}): Promise<IAclEntry | null> {
const {
principalType,
principalId,
resourceType,
resourceId,
accessRoleId,
grantedBy,
session,
} = args;
try {
if (!Object.values(PrincipalType).includes(principalType)) {
throw new Error(`Invalid principal type: ${principalType}`);
}
if (principalType !== PrincipalType.PUBLIC && !principalId) {
throw new Error('Principal ID is required for user, group, and role principals');
}
// Validate principalId based on type
if (principalId && principalType === PrincipalType.ROLE) {
// Role IDs are strings (role names)
if (typeof principalId !== 'string' || principalId.trim().length === 0) {
throw new Error(`Invalid role ID: ${principalId}`);
}
} else if (
principalType &&
principalType !== PrincipalType.PUBLIC &&
(!principalId || !Types.ObjectId.isValid(principalId))
) {
// User and Group IDs must be valid ObjectIds
throw new Error(`Invalid principal ID: ${principalId}`);
}
if (!resourceId || !Types.ObjectId.isValid(resourceId)) {
throw new Error(`Invalid resource ID: ${resourceId}`);
}
this.validateResourceType(resourceType as ResourceType);
// Get the role to determine permission bits
const role = await this._dbMethods.findRoleByIdentifier(accessRoleId);
if (!role) {
throw new Error(`Role ${accessRoleId} not found`);
}
// Ensure the role is for the correct resource type
if (role.resourceType !== resourceType) {
throw new Error(
`Role ${accessRoleId} is for ${role.resourceType} resources, not ${resourceType}`,
);
}
return await this._dbMethods.grantPermission(
principalType,
principalId,
resourceType,
resourceId,
role.permBits,
grantedBy,
session,
role._id,
);
} catch (error) {
logger.error(
`[PermissionService.grantPermission] Error: ${error instanceof Error ? error.message : ''}`,
error,
);
throw error;
}
}
/**
* Find all resources of a specific type that a user has access to with specific permission bits
* @param {Object} params - Parameters for finding accessible resources
* @param {string | Types.ObjectId} params.userId - The ID of the user
* @param {string} [params.role] - Optional user role (if not provided, will query from DB)
* @param {string} params.resourceType - Type of resource (e.g., 'agent')
* @param {number} params.requiredPermissions - The minimum permission bits required (e.g., 1 for VIEW, 3 for VIEW+EDIT)
* @returns {Promise<Array>} Array of resource IDs
*/
public async findAccessibleResources({
userId,
role,
resourceType,
requiredPermissions,
}: {
userId: string | Types.ObjectId;
role?: string;
resourceType: string;
requiredPermissions: number;
}): Promise<Types.ObjectId[]> {
try {
if (typeof requiredPermissions !== 'number' || requiredPermissions < 1) {
throw new Error('requiredPermissions must be a positive number');
}
this.validateResourceType(resourceType as ResourceType);
// Get all principals for the user (user + groups + public)
const principalsList = await this._dbMethods.getUserPrincipals({ userId, role });
if (principalsList.length === 0) {
return [];
}
return await this._dbMethods.findAccessibleResources(
principalsList,
resourceType,
requiredPermissions,
);
} catch (error) {
if (error instanceof Error) {
logger.error(`[PermissionService.findAccessibleResources] Error: ${error.message}`);
// Re-throw validation errors
if (error.message.includes('requiredPermissions must be')) {
throw error;
}
}
return [];
}
}
/**
* Find all publicly accessible resources of a specific type
* @param {Object} params - Parameters for finding publicly accessible resources
* @param {ResourceType} params.resourceType - Type of resource (e.g., 'agent')
* @param {number} params.requiredPermissions - The minimum permission bits required (e.g., 1 for VIEW, 3 for VIEW+EDIT)
* @returns {Promise<Types.ObjectId[]>} Array of resource IDs
*/
public async findPubliclyAccessibleResources({
resourceType,
requiredPermissions,
}: {
resourceType: ResourceType;
requiredPermissions: number;
}): Promise<Types.ObjectId[]> {
try {
if (typeof requiredPermissions !== 'number' || requiredPermissions < 1) {
throw new Error('requiredPermissions must be a positive number');
}
this.validateResourceType(resourceType);
// Find all public ACL entries where the public principal has at least the required permission bits
const entries = await this._aclModel
.find({
principalType: PrincipalType.PUBLIC,
resourceType,
permBits: { $bitsAllSet: requiredPermissions },
})
.distinct('resourceId');
return entries;
} catch (error) {
if (error instanceof Error) {
logger.error(`[PermissionService.findPubliclyAccessibleResources] Error: ${error.message}`);
// Re-throw validation errors
if (error.message.includes('requiredPermissions must be')) {
throw error;
}
}
return [];
}
}
/**
* Get effective permissions for multiple resources in a batch operation
* Returns map of resourceId effectivePermissionBits
*
* @param {Object} params - Parameters
* @param {string|mongoose.Types.ObjectId} params.userId - User ID
* @param {string} [params.role] - User role (for group membership)
* @param {string} params.resourceType - Resource type (must be valid ResourceType)
* @param {Array<mongoose.Types.ObjectId>} params.resourceIds - Array of resource IDs
* @returns {Promise<Map<string, number>>} Map of resourceId string permission bits
* @throws {Error} If resourceType is invalid
*/
public async getResourcePermissionsMap({
userId,
role,
resourceType,
resourceIds,
}: {
userId: string | Types.ObjectId;
role: string;
resourceType: ResourceType;
resourceIds: (string | Types.ObjectId)[];
}): Promise<Map<string, number>> {
// Validate resource type - throw on invalid type
this.validateResourceType(resourceType);
// Handle empty input
if (!Array.isArray(resourceIds) || resourceIds.length === 0) {
return new Map();
}
try {
// Get user principals (user + groups + public)
const principals = await this._dbMethods.getUserPrincipals({ userId, role });
// Use batch method from aclEntry
const permissionsMap = await this._dbMethods.getEffectivePermissionsForResources(
principals,
resourceType,
resourceIds,
);
logger.debug(
`[PermissionService.getResourcePermissionsMap] Computed permissions for ${resourceIds.length} resources, ${permissionsMap.size} have permissions`,
);
return permissionsMap;
} catch (error) {
if (error instanceof Error) {
logger.error(
`[PermissionService.getResourcePermissionsMap] Error: ${error.message}`,
error,
);
}
throw error;
}
}
/**
* Remove all permissions for a resource (cleanup when resource is deleted)
* @param {Object} params - Parameters for removing all permissions
* @param {string} params.resourceType - Type of resource (e.g., 'agent', 'prompt')
* @param {string|mongoose.Types.ObjectId} params.resourceId - The ID of the resource
* @returns {Promise<DeleteResult>} Result of the deletion operation
*/
public async removeAllPermissions({
resourceType,
resourceId,
}: {
resourceType: ResourceType;
resourceId: string | Types.ObjectId;
}): Promise<DeleteResult> {
try {
this.validateResourceType(resourceType);
if (!resourceId || !Types.ObjectId.isValid(resourceId)) {
throw new Error(`Invalid resource ID: ${resourceId}`);
}
const result = await this._aclModel.deleteMany({
resourceType,
resourceId,
});
return result;
} catch (error) {
if (error instanceof Error) {
logger.error(`[PermissionService.removeAllPermissions] Error: ${error.message}`);
}
throw error;
}
}
/**
* Check if a user has specific permission bits on a resource
* @param {Object} params - Parameters for checking permissions
* @param {string|mongoose.Types.ObjectId} params.userId - The ID of the user
* @param {string} [params.role] - Optional user role (if not provided, will query from DB)
* @param {string} params.resourceType - Type of resource (e.g., 'agent')
* @param {string|mongoose.Types.ObjectId} params.resourceId - The ID of the resource
* @param {number} params.requiredPermissions - The permission bits required (e.g., 1 for VIEW, 3 for VIEW+EDIT)
* @returns {Promise<boolean>} Whether the user has the required permission bits
*/
public async checkPermission({
userId,
role,
resourceType,
resourceId,
requiredPermission,
}: {
userId: string;
role?: string;
resourceType: ResourceType;
resourceId: string | Types.ObjectId;
requiredPermission: number;
}): Promise<boolean> {
try {
if (typeof requiredPermission !== 'number' || requiredPermission < 1) {
throw new Error('requiredPermission must be a positive number');
}
this.validateResourceType(resourceType);
// Get all principals for the user (user + groups + public)
const principals = await this._dbMethods.getUserPrincipals({ userId, role });
if (principals.length === 0) {
return false;
}
return await this._dbMethods.hasPermission(
principals,
resourceType,
resourceId,
requiredPermission,
);
} catch (error) {
if (error instanceof Error) {
logger.error(`[PermissionService.checkPermission] Error: ${error.message}`);
// Re-throw validation errors
if (error.message.includes('requiredPermission must be')) {
throw error;
}
}
return false;
}
}
/**
* Validates that the resourceType is one of the supported enum values
* @param {string} resourceType - The resource type to validate
* @throws {Error} If resourceType is not valid
*/
private validateResourceType(resourceType: ResourceType): void {
const validTypes = Object.values(ResourceType);
if (!validTypes.includes(resourceType)) {
throw new Error(
`Invalid resourceType: ${resourceType}. Valid types: ${validTypes.join(', ')}`,
);
}
}
}

View file

@ -74,6 +74,11 @@ describe('updateInterfacePermissions - permissions', () => {
},
[PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: true },
[PermissionTypes.FILE_CITATIONS]: { [Permissions.USE]: true },
[PermissionTypes.MCP_SERVERS]: {
[Permissions.USE]: true,
[Permissions.CREATE]: true,
[Permissions.SHARE]: false,
},
};
const expectedPermissionsForAdmin = {
@ -103,6 +108,11 @@ describe('updateInterfacePermissions - permissions', () => {
},
[PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: true },
[PermissionTypes.FILE_CITATIONS]: { [Permissions.USE]: true },
[PermissionTypes.MCP_SERVERS]: {
[Permissions.USE]: true,
[Permissions.CREATE]: true,
[Permissions.SHARE]: true,
},
};
expect(mockUpdateAccessPermissions).toHaveBeenCalledTimes(2);
@ -182,6 +192,11 @@ describe('updateInterfacePermissions - permissions', () => {
},
[PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: false },
[PermissionTypes.FILE_CITATIONS]: { [Permissions.USE]: false },
[PermissionTypes.MCP_SERVERS]: {
[Permissions.USE]: true,
[Permissions.CREATE]: true,
[Permissions.SHARE]: false,
},
};
const expectedPermissionsForAdmin = {
@ -211,6 +226,11 @@ describe('updateInterfacePermissions - permissions', () => {
},
[PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: false },
[PermissionTypes.FILE_CITATIONS]: { [Permissions.USE]: false },
[PermissionTypes.MCP_SERVERS]: {
[Permissions.USE]: true,
[Permissions.CREATE]: true,
[Permissions.SHARE]: true,
},
};
expect(mockUpdateAccessPermissions).toHaveBeenCalledTimes(2);
@ -290,6 +310,11 @@ describe('updateInterfacePermissions - permissions', () => {
},
[PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: true },
[PermissionTypes.FILE_CITATIONS]: { [Permissions.USE]: true },
[PermissionTypes.MCP_SERVERS]: {
[Permissions.USE]: true,
[Permissions.CREATE]: true,
[Permissions.SHARE]: false,
},
};
const expectedPermissionsForAdmin = {
@ -319,6 +344,11 @@ describe('updateInterfacePermissions - permissions', () => {
},
[PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: true },
[PermissionTypes.FILE_CITATIONS]: { [Permissions.USE]: true },
[PermissionTypes.MCP_SERVERS]: {
[Permissions.USE]: true,
[Permissions.CREATE]: true,
[Permissions.SHARE]: true,
},
};
expect(mockUpdateAccessPermissions).toHaveBeenCalledTimes(2);
@ -411,6 +441,11 @@ describe('updateInterfacePermissions - permissions', () => {
},
[PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: false },
[PermissionTypes.FILE_CITATIONS]: { [Permissions.USE]: true },
[PermissionTypes.MCP_SERVERS]: {
[Permissions.USE]: true,
[Permissions.CREATE]: true,
[Permissions.SHARE]: false,
},
};
const expectedPermissionsForAdmin = {
@ -440,6 +475,11 @@ describe('updateInterfacePermissions - permissions', () => {
},
[PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: false },
[PermissionTypes.FILE_CITATIONS]: { [Permissions.USE]: true },
[PermissionTypes.MCP_SERVERS]: {
[Permissions.USE]: true,
[Permissions.CREATE]: true,
[Permissions.SHARE]: true,
},
};
expect(mockUpdateAccessPermissions).toHaveBeenCalledTimes(2);
@ -519,6 +559,11 @@ describe('updateInterfacePermissions - permissions', () => {
},
[PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: true },
[PermissionTypes.FILE_CITATIONS]: { [Permissions.USE]: true },
[PermissionTypes.MCP_SERVERS]: {
[Permissions.USE]: true,
[Permissions.CREATE]: true,
[Permissions.SHARE]: false,
},
};
const expectedPermissionsForAdmin = {
@ -548,6 +593,11 @@ describe('updateInterfacePermissions - permissions', () => {
},
[PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: true },
[PermissionTypes.FILE_CITATIONS]: { [Permissions.USE]: true },
[PermissionTypes.MCP_SERVERS]: {
[Permissions.USE]: true,
[Permissions.CREATE]: true,
[Permissions.SHARE]: true,
},
};
expect(mockUpdateAccessPermissions).toHaveBeenCalledTimes(2);
@ -630,6 +680,11 @@ describe('updateInterfacePermissions - permissions', () => {
},
[PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: true },
[PermissionTypes.FILE_CITATIONS]: { [Permissions.USE]: true },
[PermissionTypes.MCP_SERVERS]: {
[Permissions.USE]: true,
[Permissions.CREATE]: true,
[Permissions.SHARE]: false,
},
};
const expectedPermissionsForAdmin = {
@ -653,6 +708,11 @@ describe('updateInterfacePermissions - permissions', () => {
},
[PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: true },
[PermissionTypes.FILE_CITATIONS]: { [Permissions.USE]: true },
[PermissionTypes.MCP_SERVERS]: {
[Permissions.USE]: true,
[Permissions.CREATE]: true,
[Permissions.SHARE]: true,
},
};
expect(mockUpdateAccessPermissions).toHaveBeenCalledTimes(2);
@ -751,6 +811,11 @@ describe('updateInterfacePermissions - permissions', () => {
},
[PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: true },
[PermissionTypes.FILE_CITATIONS]: { [Permissions.USE]: true },
[PermissionTypes.MCP_SERVERS]: {
[Permissions.USE]: true,
[Permissions.CREATE]: true,
[Permissions.SHARE]: false,
},
};
const expectedPermissionsForAdmin = {
@ -777,6 +842,11 @@ describe('updateInterfacePermissions - permissions', () => {
},
[PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: true },
[PermissionTypes.FILE_CITATIONS]: { [Permissions.USE]: true },
[PermissionTypes.MCP_SERVERS]: {
[Permissions.USE]: true,
[Permissions.CREATE]: true,
[Permissions.SHARE]: true,
},
};
expect(mockUpdateAccessPermissions).toHaveBeenCalledTimes(2);

View file

@ -41,6 +41,8 @@ function hasExplicitConfig(
return interfaceConfig?.fileSearch !== undefined;
case PermissionTypes.FILE_CITATIONS:
return interfaceConfig?.fileCitations !== undefined;
case PermissionTypes.MCP_SERVERS:
return interfaceConfig?.mcpServers !== undefined;
default:
return false;
}
@ -256,6 +258,23 @@ export async function updateInterfacePermissions({
defaults.fileCitations,
),
},
[PermissionTypes.MCP_SERVERS]: {
[Permissions.USE]: getPermissionValue(
loadedInterface.mcpServers?.use,
defaultPerms[PermissionTypes.MCP_SERVERS]?.[Permissions.USE],
defaults.mcpServers?.use,
),
[Permissions.CREATE]: getPermissionValue(
loadedInterface.mcpServers?.create,
defaultPerms[PermissionTypes.MCP_SERVERS]?.[Permissions.CREATE],
defaults.mcpServers?.create,
),
[Permissions.SHARE]: getPermissionValue(
loadedInterface.mcpServers?.share,
defaultPerms[PermissionTypes.MCP_SERVERS]?.[Permissions.SHARE],
defaults.mcpServers?.share,
),
},
};
// Check and add each permission type if needed

View file

@ -50,12 +50,12 @@ export class ConnectionsRepository {
}
if (existingConnection) {
// Check if config was cached/updated since connection was created
if (serverConfig.lastUpdatedAt && existingConnection.isStale(serverConfig.lastUpdatedAt)) {
if (serverConfig.updatedAt && existingConnection.isStale(serverConfig.updatedAt)) {
logger.info(
`${this.prefix(serverName)} Existing connection for ${serverName} is outdated. Recreating a new connection.`,
{
connectionCreated: new Date(existingConnection.createdAt).toISOString(),
configCachedAt: new Date(serverConfig.lastUpdatedAt).toISOString(),
configCachedAt: new Date(serverConfig.updatedAt).toISOString(),
},
);

View file

@ -79,7 +79,7 @@ export abstract class UserConnectionManager {
}
connection = undefined; // Force creation of a new connection
} else if (connection) {
if (!config || (config.lastUpdatedAt && connection.isStale(config.lastUpdatedAt))) {
if (!config || (config.updatedAt && connection.isStale(config.updatedAt))) {
if (config) {
logger.info(
`[MCP][User: ${userId}][${serverName}] Config was updated, disconnecting stale connection`,

View file

@ -145,10 +145,10 @@ describe('ConnectionsRepository', () => {
isStale: jest.fn().mockReturnValue(true),
} as unknown as jest.Mocked<MCPConnection>;
// Update server config with lastUpdatedAt timestamp
// Update server config with updatedAt timestamp
const configWithCachedAt = {
...mockServerConfigs.server1,
lastUpdatedAt: configCachedAt,
updatedAt: configCachedAt,
};
mockRegistry.getServerConfig.mockResolvedValueOnce(configWithCachedAt);
@ -156,7 +156,7 @@ describe('ConnectionsRepository', () => {
const result = await repository.get('server1');
// Verify stale check was called with the config's lastUpdatedAt timestamp
// Verify stale check was called with the config's updatedAt timestamp
expect(staleConnection.isStale).toHaveBeenCalledWith(configCachedAt);
// Verify old connection was disconnected
@ -190,10 +190,10 @@ describe('ConnectionsRepository', () => {
isStale: jest.fn().mockReturnValue(false),
} as unknown as jest.Mocked<MCPConnection>;
// Update server config with lastUpdatedAt timestamp
// Update server config with updatedAt timestamp
const configWithCachedAt = {
...mockServerConfigs.server1,
lastUpdatedAt: configCachedAt,
updatedAt: configCachedAt,
};
mockRegistry.getServerConfig.mockResolvedValueOnce(configWithCachedAt);

View file

@ -59,12 +59,12 @@ export class MCPServersInitializer {
/** Initializes a single server with all its metadata and adds it to appropriate collections */
public static async initializeServer(serverName: string, rawConfig: t.MCPOptions): Promise<void> {
try {
const config = await MCPServersRegistry.getInstance().addServer(
const result = await MCPServersRegistry.getInstance().addServer(
serverName,
rawConfig,
'CACHE',
);
MCPServersInitializer.logParsedConfig(serverName, config);
MCPServersInitializer.logParsedConfig(serverName, result.config);
} catch (error) {
logger.error(`${MCPServersInitializer.prefix(serverName)} Failed to initialize:`, error);
}

View file

@ -76,11 +76,10 @@ export class MCPServersRegistry {
config: t.MCPOptions,
storageLocation: 'CACHE' | 'DB',
userId?: string,
): Promise<t.ParsedServerConfig> {
): Promise<t.AddServerResult> {
const configRepo = this.getConfigRepository(storageLocation);
const parsedConfig = await MCPServerInspector.inspect(serverName, config);
await configRepo.add(serverName, parsedConfig, userId);
return parsedConfig;
return await configRepo.add(serverName, parsedConfig, userId);
}
public async updateServer(
@ -88,10 +87,11 @@ export class MCPServersRegistry {
config: t.MCPOptions,
storageLocation: 'CACHE' | 'DB',
userId?: string,
): Promise<void> {
): Promise<t.ParsedServerConfig> {
const configRepo = this.getConfigRepository(storageLocation);
const parsedConfig = await MCPServerInspector.inspect(serverName, config);
await configRepo.update(serverName, parsedConfig, userId);
return parsedConfig;
}
// TODO: This is currently used to determine if a server requires OAuth. However, this info can

View file

@ -1,10 +1,10 @@
import { ParsedServerConfig } from '~/mcp/types';
import { ParsedServerConfig, AddServerResult } from '~/mcp/types';
/**
* Interface for future DB implementation
*/
export interface IServerConfigsRepositoryInterface {
add(serverName: string, config: ParsedServerConfig, userId?: string): Promise<void>;
add(serverName: string, config: ParsedServerConfig, userId?: string): Promise<AddServerResult>;
//ACL Entry check if update is possible
update(serverName: string, config: ParsedServerConfig, userId?: string): Promise<void>;

View file

@ -8,6 +8,18 @@ jest.mock('~/cluster', () => ({
isLeader: jest.fn().mockResolvedValue(true),
}));
// Mock ServerConfigsDB to avoid needing MongoDB for cache integration tests
jest.mock('../db/ServerConfigsDB', () => ({
ServerConfigsDB: jest.fn().mockImplementation(() => ({
get: jest.fn().mockResolvedValue(undefined),
getAll: jest.fn().mockResolvedValue({}),
add: jest.fn().mockResolvedValue({ config: {}, isNew: true }),
update: jest.fn().mockResolvedValue(undefined),
remove: jest.fn().mockResolvedValue(undefined),
reset: jest.fn().mockResolvedValue(undefined),
})),
}));
describe('MCPServersInitializer Redis Integration Tests', () => {
let MCPServersInitializer: typeof import('../MCPServersInitializer').MCPServersInitializer;
let MCPServersRegistry: typeof import('../MCPServersRegistry').MCPServersRegistry;

View file

@ -1,8 +1,22 @@
import { expect } from '@playwright/test';
import { MongoMemoryServer } from 'mongodb-memory-server';
import type * as t from '~/mcp/types';
import type { MCPServersRegistry as MCPServersRegistryType } from '../MCPServersRegistry';
// Mock ServerConfigsDB to avoid needing MongoDB for cache integration tests
jest.mock('../db/ServerConfigsDB', () => ({
ServerConfigsDB: jest.fn().mockImplementation(() => ({
get: jest.fn().mockResolvedValue(undefined),
getAll: jest.fn().mockResolvedValue({}),
add: jest.fn().mockResolvedValue({
serverName: 'mock-server',
config: {} as t.ParsedServerConfig,
}),
update: jest.fn().mockResolvedValue(undefined),
remove: jest.fn().mockResolvedValue(undefined),
reset: jest.fn().mockResolvedValue(undefined),
})),
}));
/**
* Integration tests for MCPServersRegistry using Redis-backed cache.
* For unit tests using in-memory cache, see MCPServersRegistry.test.ts
@ -18,7 +32,6 @@ describe('MCPServersRegistry Redis Integration Tests', () => {
let LeaderElection: typeof import('~/cluster/LeaderElection').LeaderElection;
let leaderInstance: InstanceType<typeof import('~/cluster/LeaderElection').LeaderElection>;
let MCPServerInspector: typeof import('../MCPServerInspector').MCPServerInspector;
let mongoServer: MongoMemoryServer;
const testParsedConfig: t.ParsedServerConfig = {
type: 'stdio',
@ -60,21 +73,12 @@ describe('MCPServersRegistry Redis Integration Tests', () => {
const leaderElectionModule = await import('~/cluster/LeaderElection');
const inspectorModule = await import('../MCPServerInspector');
const mongoose = await import('mongoose');
const { userSchema } = await import('@librechat/data-schemas');
MCPServersRegistry = registryModule.MCPServersRegistry;
keyvRedisClient = redisClients.keyvRedisClient;
LeaderElection = leaderElectionModule.LeaderElection;
MCPServerInspector = inspectorModule.MCPServerInspector;
// Set up MongoDB with MongoMemoryServer for db methods
mongoServer = await MongoMemoryServer.create();
const mongoUri = mongoServer.getUri();
if (!mongoose.default.models.User) {
mongoose.default.model('User', userSchema);
}
await mongoose.default.connect(mongoUri);
// Reset singleton and create new instance with mongoose
(MCPServersRegistry as unknown as { instance: undefined }).instance = undefined;
MCPServersRegistry.createInstance(mongoose.default);
@ -135,11 +139,6 @@ describe('MCPServersRegistry Redis Integration Tests', () => {
// Close Redis connection
if (keyvRedisClient?.isOpen) await keyvRedisClient.disconnect();
// Close MongoDB connection and stop memory server
const mongoose = await import('mongoose');
await mongoose.default.disconnect();
if (mongoServer) await mongoServer.stop();
});
// Tests for the old privateServersCache API have been removed

View file

@ -49,7 +49,7 @@ describe('MCPServersRegistry', () => {
},
},
},
lastUpdatedAt: FIXED_TIME,
updatedAt: FIXED_TIME,
};
beforeAll(() => {
jest.useFakeTimers();

View file

@ -0,0 +1,844 @@
import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import {
AccessRoleIds,
PermissionBits,
PrincipalType,
PrincipalModel,
ResourceType,
} from 'librechat-data-provider';
import { createModels, createMethods, RoleBits } from '@librechat/data-schemas';
import { ServerConfigsDB } from '../db/ServerConfigsDB';
import type { ParsedServerConfig } from '~/mcp/types';
// Mock the logger
jest.mock('@librechat/data-schemas', () => ({
...jest.requireActual('@librechat/data-schemas'),
logger: {
error: jest.fn(),
warn: jest.fn(),
debug: jest.fn(),
info: jest.fn(),
},
}));
let mongoServer: MongoMemoryServer;
let serverConfigsDB: ServerConfigsDB;
// Test data helpers
const createSSEConfig = (
title?: string,
description?: string,
oauth?: { client_secret?: string; client_id?: string },
): ParsedServerConfig => ({
type: 'sse',
url: 'https://example.com/mcp',
...(title && { title }),
...(description && { description }),
...(oauth && { oauth }),
});
let dbMethods: ReturnType<typeof createMethods>;
beforeAll(async () => {
mongoServer = await MongoMemoryServer.create();
const mongoUri = mongoServer.getUri();
await mongoose.connect(mongoUri);
// Initialize all models
createModels(mongoose);
// Create methods and seed default roles
dbMethods = createMethods(mongoose);
await dbMethods.seedDefaultRoles();
serverConfigsDB = new ServerConfigsDB(mongoose);
});
afterAll(async () => {
await mongoose.disconnect();
await mongoServer.stop();
});
beforeEach(async () => {
// Clear collections except AccessRole
await mongoose.models.MCPServer.deleteMany({});
await mongoose.models.Agent.deleteMany({});
await mongoose.models.AclEntry.deleteMany({});
});
describe('ServerConfigsDB', () => {
const userId = new mongoose.Types.ObjectId().toString();
const userId2 = new mongoose.Types.ObjectId().toString();
describe('constructor', () => {
it('should throw error when mongoose is not provided', () => {
expect(() => new ServerConfigsDB(null as unknown as typeof mongoose)).toThrow(
'ServerConfigsDB requires mongoose instance',
);
});
it('should create instance when mongoose is provided', () => {
const instance = new ServerConfigsDB(mongoose);
expect(instance).toBeInstanceOf(ServerConfigsDB);
});
});
describe('add()', () => {
it('should throw error when userId is not provided', async () => {
await expect(serverConfigsDB.add('test-server', createSSEConfig('Test'))).rejects.toThrow(
'User ID is required to create a database-stored MCP server',
);
});
it('should create server and return AddServerResult with generated serverName', async () => {
const config = createSSEConfig('My Test Server', 'A test server');
const result = await serverConfigsDB.add('temp-name', config, userId);
expect(result).toBeDefined();
expect(result.serverName).toBe('my-test-server');
expect(result.config).toMatchObject({
type: 'sse',
url: 'https://example.com/mcp',
title: 'My Test Server',
description: 'A test server',
});
expect(result.config.dbId).toBeDefined();
});
it('should grant owner ACL to the user', async () => {
const config = createSSEConfig('ACL Test Server');
const result = await serverConfigsDB.add('temp-name', config, userId);
// Verify ACL entry was created
const aclEntry = await mongoose.models.AclEntry.findOne({
principalType: PrincipalType.USER,
principalId: new mongoose.Types.ObjectId(userId),
resourceType: ResourceType.MCPSERVER,
});
expect(aclEntry).toBeDefined();
expect(aclEntry!.resourceId.toString()).toBe(result.config.dbId);
// OWNER role has VIEW | EDIT | DELETE | SHARE = 15
expect(aclEntry!.permBits).toBe(RoleBits.OWNER);
});
it('should include dbId and updatedAt in returned config', async () => {
const config = createSSEConfig('Metadata Test');
const result = await serverConfigsDB.add('temp-name', config, userId);
expect(result.config.dbId).toBeDefined();
expect(typeof result.config.dbId).toBe('string');
expect(result.config.updatedAt).toBeDefined();
expect(typeof result.config.updatedAt).toBe('number');
});
});
describe('update()', () => {
it('should throw error when userId is not provided', async () => {
await expect(serverConfigsDB.update('test-server', createSSEConfig('Test'))).rejects.toThrow(
'User ID is required to update a database-stored MCP server',
);
});
it('should update server config', async () => {
const config = createSSEConfig('Original Title', 'Original description');
const created = await serverConfigsDB.add('temp-name', config, userId);
const updatedConfig = createSSEConfig('Original Title', 'Updated description');
await serverConfigsDB.update(created.serverName, updatedConfig, userId);
const retrieved = await serverConfigsDB.get(created.serverName, userId);
expect(retrieved?.description).toBe('Updated description');
});
it('should preserve oauth.client_secret when not provided in update', async () => {
const config = createSSEConfig('OAuth Server', 'Test', {
client_id: 'my-client-id',
client_secret: 'super-secret-key',
});
const created = await serverConfigsDB.add('temp-name', config, userId);
// Update without client_secret
const updatedConfig = createSSEConfig('OAuth Server', 'Updated description', {
client_id: 'my-client-id',
// client_secret not provided
});
await serverConfigsDB.update(created.serverName, updatedConfig, userId);
// Verify the secret is preserved
const MCPServer = mongoose.models.MCPServer;
const server = await MCPServer.findOne({ serverName: created.serverName });
expect(server?.config?.oauth?.client_secret).toBe('super-secret-key');
});
it('should allow updating oauth.client_secret when explicitly provided', async () => {
const config = createSSEConfig('OAuth Server 2', 'Test', {
client_id: 'my-client-id',
client_secret: 'old-secret',
});
const created = await serverConfigsDB.add('temp-name', config, userId);
// Update with new client_secret
const updatedConfig = createSSEConfig('OAuth Server 2', 'Updated', {
client_id: 'my-client-id',
client_secret: 'new-secret',
});
await serverConfigsDB.update(created.serverName, updatedConfig, userId);
// Verify the secret is updated
const MCPServer = mongoose.models.MCPServer;
const server = await MCPServer.findOne({ serverName: created.serverName });
expect(server?.config?.oauth?.client_secret).toBe('new-secret');
});
});
describe('remove()', () => {
it('should delete server from database', async () => {
const config = createSSEConfig('Delete Test');
const created = await serverConfigsDB.add('temp-name', config, userId);
await serverConfigsDB.remove(created.serverName, userId);
const MCPServer = mongoose.models.MCPServer;
const server = await MCPServer.findOne({ serverName: created.serverName });
expect(server).toBeNull();
});
it('should remove all ACL entries for the server', async () => {
const config = createSSEConfig('ACL Delete Test');
const created = await serverConfigsDB.add('temp-name', config, userId);
// Verify ACL exists before deletion
let aclEntries = await mongoose.models.AclEntry.find({
resourceType: ResourceType.MCPSERVER,
resourceId: new mongoose.Types.ObjectId(created.config.dbId!),
});
expect(aclEntries.length).toBeGreaterThan(0);
await serverConfigsDB.remove(created.serverName, userId);
// Verify ACL entries are removed
aclEntries = await mongoose.models.AclEntry.find({
resourceType: ResourceType.MCPSERVER,
resourceId: new mongoose.Types.ObjectId(created.config.dbId!),
});
expect(aclEntries.length).toBe(0);
});
it('should handle non-existent server gracefully', async () => {
// Should not throw
await expect(serverConfigsDB.remove('non-existent-server', userId)).resolves.toBeUndefined();
});
});
describe('get()', () => {
describe('public access (no userId)', () => {
it('should return undefined for non-public server without userId', async () => {
const config = createSSEConfig('Private Server');
const created = await serverConfigsDB.add('temp-name', config, userId);
const result = await serverConfigsDB.get(created.serverName);
expect(result).toBeUndefined();
});
it('should return server when publicly shared', async () => {
const config = createSSEConfig('Public Server');
const created = await serverConfigsDB.add('temp-name', config, userId);
// Grant public access
await mongoose.models.AclEntry.create({
principalType: PrincipalType.PUBLIC,
resourceType: ResourceType.MCPSERVER,
resourceId: new mongoose.Types.ObjectId(created.config.dbId!),
permBits: PermissionBits.VIEW,
grantedBy: new mongoose.Types.ObjectId(userId),
});
const result = await serverConfigsDB.get(created.serverName);
expect(result).toBeDefined();
expect(result?.title).toBe('Public Server');
});
it('should return server with consumeOnly when accessible via public agent', async () => {
const config = createSSEConfig('Agent MCP Server');
const created = await serverConfigsDB.add('temp-name', config, userId);
// Create an agent that has this MCP server
const Agent = mongoose.models.Agent;
const agent = await Agent.create({
id: 'test-agent-id',
name: 'Test Agent',
provider: 'openai',
model: 'gpt-4',
author: new mongoose.Types.ObjectId(userId),
mcpServerNames: [created.serverName],
});
// Grant public access to the agent
await mongoose.models.AclEntry.create({
principalType: PrincipalType.PUBLIC,
resourceType: ResourceType.AGENT,
resourceId: agent._id,
permBits: PermissionBits.VIEW,
grantedBy: new mongoose.Types.ObjectId(userId),
});
const result = await serverConfigsDB.get(created.serverName);
expect(result).toBeDefined();
expect(result?.consumeOnly).toBe(true);
});
});
describe('user direct access', () => {
it('should return server when user has direct VIEW permission', async () => {
const config = createSSEConfig('Direct Access Server');
const created = await serverConfigsDB.add('temp-name', config, userId);
// The owner should have access
const result = await serverConfigsDB.get(created.serverName, userId);
expect(result).toBeDefined();
expect(result?.title).toBe('Direct Access Server');
expect(result?.consumeOnly).toBeUndefined();
});
it('should return undefined when user has no permission', async () => {
const config = createSSEConfig('Restricted Server');
await serverConfigsDB.add('temp-name', config, userId);
// Different user without access
const result = await serverConfigsDB.get('restricted-server', userId2);
expect(result).toBeUndefined();
});
it('should return server when user is granted VIEW permission', async () => {
const config = createSSEConfig('Shared Server');
const created = await serverConfigsDB.add('temp-name', config, userId);
// Grant VIEW permission to userId2
const role = await mongoose.models.AccessRole.findOne({
accessRoleId: AccessRoleIds.MCPSERVER_VIEWER,
});
await mongoose.models.AclEntry.create({
principalType: PrincipalType.USER,
principalModel: PrincipalModel.USER,
principalId: new mongoose.Types.ObjectId(userId2),
resourceType: ResourceType.MCPSERVER,
resourceId: new mongoose.Types.ObjectId(created.config.dbId!),
permBits: PermissionBits.VIEW,
roleId: role!._id,
grantedBy: new mongoose.Types.ObjectId(userId),
});
const result = await serverConfigsDB.get(created.serverName, userId2);
expect(result).toBeDefined();
expect(result?.title).toBe('Shared Server');
});
});
describe('agent-based access (consumeOnly)', () => {
it('should return server with consumeOnly when user has access via agent', async () => {
const config = createSSEConfig('Agent Accessible Server');
const created = await serverConfigsDB.add('temp-name', config, userId);
// Create an agent with this MCP server
const Agent = mongoose.models.Agent;
const agent = await Agent.create({
id: 'agent-for-user2',
name: 'Agent for User 2',
provider: 'openai',
model: 'gpt-4',
author: new mongoose.Types.ObjectId(userId),
mcpServerNames: [created.serverName],
});
// Grant agent access to userId2
const agentRole = await mongoose.models.AccessRole.findOne({
accessRoleId: AccessRoleIds.AGENT_VIEWER,
});
await mongoose.models.AclEntry.create({
principalType: PrincipalType.USER,
principalModel: PrincipalModel.USER,
principalId: new mongoose.Types.ObjectId(userId2),
resourceType: ResourceType.AGENT,
resourceId: agent._id,
permBits: PermissionBits.VIEW,
roleId: agentRole!._id,
grantedBy: new mongoose.Types.ObjectId(userId),
});
const result = await serverConfigsDB.get(created.serverName, userId2);
expect(result).toBeDefined();
expect(result?.consumeOnly).toBe(true);
expect(result?.title).toBe('Agent Accessible Server');
});
it('should prefer direct access over agent access (no consumeOnly)', async () => {
const config = createSSEConfig('Both Access Server');
const created = await serverConfigsDB.add('temp-name', config, userId);
// Create an agent with this MCP server
const Agent = mongoose.models.Agent;
const agent = await Agent.create({
id: 'agent-both-access',
name: 'Agent Both Access',
provider: 'openai',
model: 'gpt-4',
author: new mongoose.Types.ObjectId(userId),
mcpServerNames: [created.serverName],
});
// Grant userId2 both direct MCP access and agent access
const mcpRole = await mongoose.models.AccessRole.findOne({
accessRoleId: AccessRoleIds.MCPSERVER_VIEWER,
});
await mongoose.models.AclEntry.create({
principalType: PrincipalType.USER,
principalModel: PrincipalModel.USER,
principalId: new mongoose.Types.ObjectId(userId2),
resourceType: ResourceType.MCPSERVER,
resourceId: new mongoose.Types.ObjectId(created.config.dbId!),
permBits: PermissionBits.VIEW,
roleId: mcpRole!._id,
grantedBy: new mongoose.Types.ObjectId(userId),
});
const agentRole = await mongoose.models.AccessRole.findOne({
accessRoleId: AccessRoleIds.AGENT_VIEWER,
});
await mongoose.models.AclEntry.create({
principalType: PrincipalType.USER,
principalModel: PrincipalModel.USER,
principalId: new mongoose.Types.ObjectId(userId2),
resourceType: ResourceType.AGENT,
resourceId: agent._id,
permBits: PermissionBits.VIEW,
roleId: agentRole!._id,
grantedBy: new mongoose.Types.ObjectId(userId),
});
// Direct access should take precedence (no consumeOnly)
const result = await serverConfigsDB.get(created.serverName, userId2);
expect(result).toBeDefined();
expect(result?.consumeOnly).toBeUndefined();
});
});
it('should return undefined for non-existent server', async () => {
const result = await serverConfigsDB.get('non-existent-server', userId);
expect(result).toBeUndefined();
});
});
describe('getAll()', () => {
describe('public access (no userId)', () => {
it('should return empty object when no public servers exist', async () => {
const config = createSSEConfig('Private Server');
await serverConfigsDB.add('temp-name', config, userId);
const result = await serverConfigsDB.getAll();
expect(Object.keys(result)).toHaveLength(0);
});
it('should return only publicly shared servers', async () => {
const config1 = createSSEConfig('Public Server 1');
const config2 = createSSEConfig('Private Server');
const created1 = await serverConfigsDB.add('temp1', config1, userId);
await serverConfigsDB.add('temp2', config2, userId);
// Make first server public
await mongoose.models.AclEntry.create({
principalType: PrincipalType.PUBLIC,
resourceType: ResourceType.MCPSERVER,
resourceId: new mongoose.Types.ObjectId(created1.config.dbId!),
permBits: PermissionBits.VIEW,
grantedBy: new mongoose.Types.ObjectId(userId),
});
const result = await serverConfigsDB.getAll();
expect(Object.keys(result)).toHaveLength(1);
expect(result['public-server-1']).toBeDefined();
});
});
describe('user access', () => {
it('should return servers directly accessible by user', async () => {
const config1 = createSSEConfig('User Server 1');
const config2 = createSSEConfig('User Server 2');
await serverConfigsDB.add('temp1', config1, userId);
await serverConfigsDB.add('temp2', config2, userId);
// Create server by different user (not accessible)
await serverConfigsDB.add('temp3', createSSEConfig('Other User Server'), userId2);
const result = await serverConfigsDB.getAll(userId);
expect(Object.keys(result)).toHaveLength(2);
expect(result['user-server-1']).toBeDefined();
expect(result['user-server-2']).toBeDefined();
expect(result['other-user-server']).toBeUndefined();
});
it('should include agent-accessible servers with consumeOnly flag', async () => {
const config1 = createSSEConfig('Direct Server');
const config2 = createSSEConfig('Agent Only Server');
await serverConfigsDB.add('temp1', config1, userId);
const created2 = await serverConfigsDB.add('temp2', config2, userId);
// Create an agent with second MCP server, accessible by userId2
const Agent = mongoose.models.Agent;
const agent = await Agent.create({
id: 'getall-agent',
name: 'GetAll Agent',
provider: 'openai',
model: 'gpt-4',
author: new mongoose.Types.ObjectId(userId),
mcpServerNames: [created2.serverName],
});
const agentRole = await mongoose.models.AccessRole.findOne({
accessRoleId: AccessRoleIds.AGENT_VIEWER,
});
await mongoose.models.AclEntry.create({
principalType: PrincipalType.USER,
principalModel: PrincipalModel.USER,
principalId: new mongoose.Types.ObjectId(userId2),
resourceType: ResourceType.AGENT,
resourceId: agent._id,
permBits: PermissionBits.VIEW,
roleId: agentRole!._id,
grantedBy: new mongoose.Types.ObjectId(userId),
});
const result = await serverConfigsDB.getAll(userId2);
expect(Object.keys(result)).toHaveLength(1);
expect(result['agent-only-server']).toBeDefined();
expect(result['agent-only-server'].consumeOnly).toBe(true);
});
it('should deduplicate servers with both direct and agent access', async () => {
const config = createSSEConfig('Dedup Server');
const created = await serverConfigsDB.add('temp', config, userId);
// Create an agent with this MCP server
const Agent = mongoose.models.Agent;
const agent = await Agent.create({
id: 'dedup-agent',
name: 'Dedup Agent',
provider: 'openai',
model: 'gpt-4',
author: new mongoose.Types.ObjectId(userId),
mcpServerNames: [created.serverName],
});
// Grant userId2 both direct MCP access and agent access
const mcpRole = await mongoose.models.AccessRole.findOne({
accessRoleId: AccessRoleIds.MCPSERVER_VIEWER,
});
await mongoose.models.AclEntry.create({
principalType: PrincipalType.USER,
principalModel: PrincipalModel.USER,
principalId: new mongoose.Types.ObjectId(userId2),
resourceType: ResourceType.MCPSERVER,
resourceId: new mongoose.Types.ObjectId(created.config.dbId!),
permBits: PermissionBits.VIEW,
roleId: mcpRole!._id,
grantedBy: new mongoose.Types.ObjectId(userId),
});
const agentRole = await mongoose.models.AccessRole.findOne({
accessRoleId: AccessRoleIds.AGENT_VIEWER,
});
await mongoose.models.AclEntry.create({
principalType: PrincipalType.USER,
principalModel: PrincipalModel.USER,
principalId: new mongoose.Types.ObjectId(userId2),
resourceType: ResourceType.AGENT,
resourceId: agent._id,
permBits: PermissionBits.VIEW,
roleId: agentRole!._id,
grantedBy: new mongoose.Types.ObjectId(userId),
});
const result = await serverConfigsDB.getAll(userId2);
// Should only have one entry (deduplicated)
expect(Object.keys(result)).toHaveLength(1);
// Direct access takes precedence - no consumeOnly
expect(result['dedup-server']).toBeDefined();
expect(result['dedup-server'].consumeOnly).toBeUndefined();
});
it('should merge servers from multiple agents', async () => {
const config1 = createSSEConfig('Agent1 Server');
const config2 = createSSEConfig('Agent2 Server');
const created1 = await serverConfigsDB.add('temp1', config1, userId);
const created2 = await serverConfigsDB.add('temp2', config2, userId);
// Create two agents, each with a different MCP server
const Agent = mongoose.models.Agent;
const agent1 = await Agent.create({
id: 'multi-agent-1',
name: 'Multi Agent 1',
provider: 'openai',
model: 'gpt-4',
author: new mongoose.Types.ObjectId(userId),
mcpServerNames: [created1.serverName],
});
const agent2 = await Agent.create({
id: 'multi-agent-2',
name: 'Multi Agent 2',
provider: 'openai',
model: 'gpt-4',
author: new mongoose.Types.ObjectId(userId),
mcpServerNames: [created2.serverName],
});
// Grant userId2 access to both agents
const agentRole = await mongoose.models.AccessRole.findOne({
accessRoleId: AccessRoleIds.AGENT_VIEWER,
});
await mongoose.models.AclEntry.create([
{
principalType: PrincipalType.USER,
principalModel: PrincipalModel.USER,
principalId: new mongoose.Types.ObjectId(userId2),
resourceType: ResourceType.AGENT,
resourceId: agent1._id,
permBits: PermissionBits.VIEW,
roleId: agentRole!._id,
grantedBy: new mongoose.Types.ObjectId(userId),
},
{
principalType: PrincipalType.USER,
principalModel: PrincipalModel.USER,
principalId: new mongoose.Types.ObjectId(userId2),
resourceType: ResourceType.AGENT,
resourceId: agent2._id,
permBits: PermissionBits.VIEW,
roleId: agentRole!._id,
grantedBy: new mongoose.Types.ObjectId(userId),
},
]);
const result = await serverConfigsDB.getAll(userId2);
expect(Object.keys(result)).toHaveLength(2);
expect(result['agent1-server']?.consumeOnly).toBe(true);
expect(result['agent2-server']?.consumeOnly).toBe(true);
});
});
});
describe('hasAccessViaAgent() - private method integration', () => {
it('should return false when no agents exist', async () => {
const config = createSSEConfig('No Agent Server');
const created = await serverConfigsDB.add('temp', config, userId);
// Access via get() which uses hasAccessViaAgent internally
const result = await serverConfigsDB.get(created.serverName, userId2);
expect(result).toBeUndefined();
});
it('should return false when agent has MCP but user has no agent access', async () => {
const config = createSSEConfig('Inaccessible Agent Server');
const created = await serverConfigsDB.add('temp', config, userId);
// Create an agent with this MCP server but no ACL for userId2
const Agent = mongoose.models.Agent;
await Agent.create({
id: 'inaccessible-agent',
name: 'Inaccessible Agent',
provider: 'openai',
model: 'gpt-4',
author: new mongoose.Types.ObjectId(userId),
mcpServerNames: [created.serverName],
});
const result = await serverConfigsDB.get(created.serverName, userId2);
expect(result).toBeUndefined();
});
it('should return true when user has VIEW access to agent with the MCP server', async () => {
const config = createSSEConfig('Accessible Agent Server');
const created = await serverConfigsDB.add('temp', config, userId);
const Agent = mongoose.models.Agent;
const agent = await Agent.create({
id: 'accessible-agent',
name: 'Accessible Agent',
provider: 'openai',
model: 'gpt-4',
author: new mongoose.Types.ObjectId(userId),
mcpServerNames: [created.serverName],
});
const agentRole = await mongoose.models.AccessRole.findOne({
accessRoleId: AccessRoleIds.AGENT_VIEWER,
});
await mongoose.models.AclEntry.create({
principalType: PrincipalType.USER,
principalModel: PrincipalModel.USER,
principalId: new mongoose.Types.ObjectId(userId2),
resourceType: ResourceType.AGENT,
resourceId: agent._id,
permBits: PermissionBits.VIEW,
roleId: agentRole!._id,
grantedBy: new mongoose.Types.ObjectId(userId),
});
const result = await serverConfigsDB.get(created.serverName, userId2);
expect(result).toBeDefined();
expect(result?.consumeOnly).toBe(true);
});
it('should handle multiple agents - one accessible, one not', async () => {
const config = createSSEConfig('Multi Agent Access Server');
const created = await serverConfigsDB.add('temp', config, userId);
const Agent = mongoose.models.Agent;
// Agent 1: has MCP server but no user access
await Agent.create({
id: 'no-access-agent',
name: 'No Access Agent',
provider: 'openai',
model: 'gpt-4',
author: new mongoose.Types.ObjectId(userId),
mcpServerNames: [created.serverName],
});
// Agent 2: has MCP server AND user has access
const accessibleAgent = await Agent.create({
id: 'has-access-agent',
name: 'Has Access Agent',
provider: 'openai',
model: 'gpt-4',
author: new mongoose.Types.ObjectId(userId),
mcpServerNames: [created.serverName],
});
const agentRole = await mongoose.models.AccessRole.findOne({
accessRoleId: AccessRoleIds.AGENT_VIEWER,
});
await mongoose.models.AclEntry.create({
principalType: PrincipalType.USER,
principalModel: PrincipalModel.USER,
principalId: new mongoose.Types.ObjectId(userId2),
resourceType: ResourceType.AGENT,
resourceId: accessibleAgent._id,
permBits: PermissionBits.VIEW,
roleId: agentRole!._id,
grantedBy: new mongoose.Types.ObjectId(userId),
});
const result = await serverConfigsDB.get(created.serverName, userId2);
expect(result).toBeDefined();
expect(result?.consumeOnly).toBe(true);
});
});
describe('reset()', () => {
it('should be a no-op and not throw', async () => {
// Create a server first
const config = createSSEConfig('Reset Test');
await serverConfigsDB.add('temp', config, userId);
// Reset should complete without error
await expect(serverConfigsDB.reset()).resolves.toBeUndefined();
// Server should still exist (reset is no-op for DB storage)
const result = await serverConfigsDB.get('reset-test', userId);
expect(result).toBeDefined();
});
});
describe('mapDBServerToParsedConfig()', () => {
it('should include dbId from _id', async () => {
const config = createSSEConfig('Map Test');
const created = await serverConfigsDB.add('temp', config, userId);
expect(created.config.dbId).toBeDefined();
expect(typeof created.config.dbId).toBe('string');
expect(mongoose.Types.ObjectId.isValid(created.config.dbId!)).toBe(true);
});
it('should include updatedAt as timestamp', async () => {
const config = createSSEConfig('Timestamp Test');
const created = await serverConfigsDB.add('temp', config, userId);
expect(created.config.updatedAt).toBeDefined();
expect(typeof created.config.updatedAt).toBe('number');
expect(created.config.updatedAt).toBeLessThanOrEqual(Date.now());
});
});
describe('edge cases', () => {
it('should handle server with empty mcpServerNames in agent', async () => {
const config = createSSEConfig('Edge Case Server');
const created = await serverConfigsDB.add('temp', config, userId);
// Create an agent with empty mcpServerNames
const Agent = mongoose.models.Agent;
const agent = await Agent.create({
id: 'empty-mcp-agent',
name: 'Empty MCP Agent',
provider: 'openai',
model: 'gpt-4',
author: new mongoose.Types.ObjectId(userId),
mcpServerNames: [], // Empty array
});
const agentRole = await mongoose.models.AccessRole.findOne({
accessRoleId: AccessRoleIds.AGENT_VIEWER,
});
await mongoose.models.AclEntry.create({
principalType: PrincipalType.USER,
principalModel: PrincipalModel.USER,
principalId: new mongoose.Types.ObjectId(userId2),
resourceType: ResourceType.AGENT,
resourceId: agent._id,
permBits: PermissionBits.VIEW,
roleId: agentRole!._id,
grantedBy: new mongoose.Types.ObjectId(userId),
});
// Should not find the server via agent (empty mcpServerNames)
const result = await serverConfigsDB.get(created.serverName, userId2);
expect(result).toBeUndefined();
});
it('should handle agent without mcpServerNames field', async () => {
const config = createSSEConfig('No Field Server');
const created = await serverConfigsDB.add('temp', config, userId);
// Create an agent without mcpServerNames field (uses default)
const Agent = mongoose.models.Agent;
const agent = await Agent.create({
id: 'no-field-agent',
name: 'No Field Agent',
provider: 'openai',
model: 'gpt-4',
author: new mongoose.Types.ObjectId(userId),
// mcpServerNames not specified - should default to []
});
const agentRole = await mongoose.models.AccessRole.findOne({
accessRoleId: AccessRoleIds.AGENT_VIEWER,
});
await mongoose.models.AclEntry.create({
principalType: PrincipalType.USER,
principalModel: PrincipalModel.USER,
principalId: new mongoose.Types.ObjectId(userId2),
resourceType: ResourceType.AGENT,
resourceId: agent._id,
permBits: PermissionBits.VIEW,
roleId: agentRole!._id,
grantedBy: new mongoose.Types.ObjectId(userId),
});
// Should not find the server via agent
const result = await serverConfigsDB.get(created.serverName, userId2);
expect(result).toBeUndefined();
});
});
});

View file

@ -1,4 +1,4 @@
import { ParsedServerConfig } from '~/mcp/types';
import { ParsedServerConfig, AddServerResult } from '~/mcp/types';
/**
* In-memory implementation of MCP server configurations cache for single-instance deployments.
@ -10,12 +10,14 @@ import { ParsedServerConfig } from '~/mcp/types';
export class ServerConfigsCacheInMemory {
private readonly cache: Map<string, ParsedServerConfig> = new Map();
public async add(serverName: string, config: ParsedServerConfig): Promise<void> {
public async add(serverName: string, config: ParsedServerConfig): Promise<AddServerResult> {
if (this.cache.has(serverName))
throw new Error(
`Server "${serverName}" already exists in cache. Use update() to modify existing configs.`,
);
this.cache.set(serverName, { ...config, lastUpdatedAt: Date.now() });
const storedConfig = { ...config, updatedAt: Date.now() };
this.cache.set(serverName, storedConfig);
return { serverName, config: storedConfig };
}
public async update(serverName: string, config: ParsedServerConfig): Promise<void> {
@ -23,7 +25,7 @@ export class ServerConfigsCacheInMemory {
throw new Error(
`Server "${serverName}" does not exist in cache. Use add() to create new configs.`,
);
this.cache.set(serverName, { ...config, lastUpdatedAt: Date.now() });
this.cache.set(serverName, { ...config, updatedAt: Date.now() });
}
public async remove(serverName: string): Promise<void> {

View file

@ -1,7 +1,7 @@
import type Keyv from 'keyv';
import { fromPairs } from 'lodash';
import { standardCache, keyvRedisClient } from '~/cache';
import { ParsedServerConfig } from '~/mcp/types';
import { ParsedServerConfig, AddServerResult } from '~/mcp/types';
import { BaseRegistryCache } from './BaseRegistryCache';
import { IServerConfigsRepositoryInterface } from '../ServerConfigsRepositoryInterface';
@ -25,15 +25,17 @@ export class ServerConfigsCacheRedis
this.cache = standardCache(`${this.PREFIX}::Servers::${namespace}`);
}
public async add(serverName: string, config: ParsedServerConfig): Promise<void> {
public async add(serverName: string, config: ParsedServerConfig): Promise<AddServerResult> {
if (this.leaderOnly) await this.leaderCheck(`add ${this.namespace} MCP servers`);
const exists = await this.cache.has(serverName);
if (exists)
throw new Error(
`Server "${serverName}" already exists in cache. Use update() to modify existing configs.`,
);
const success = await this.cache.set(serverName, { ...config, lastUpdatedAt: Date.now() });
const storedConfig = { ...config, updatedAt: Date.now() };
const success = await this.cache.set(serverName, storedConfig);
this.successCheck(`add ${this.namespace} server "${serverName}"`, success);
return { serverName, config: storedConfig };
}
public async update(serverName: string, config: ParsedServerConfig): Promise<void> {
@ -43,7 +45,7 @@ export class ServerConfigsCacheRedis
throw new Error(
`Server "${serverName}" does not exist in cache. Use add() to create new configs.`,
);
const success = await this.cache.set(serverName, { ...config, lastUpdatedAt: Date.now() });
const success = await this.cache.set(serverName, { ...config, updatedAt: Date.now() });
this.successCheck(`update ${this.namespace} server "${serverName}"`, success);
}

View file

@ -15,14 +15,14 @@ describe('ServerConfigsCacheInMemory Integration Tests', () => {
command: 'node',
args: ['server1.js'],
env: { TEST: 'value1' },
lastUpdatedAt: FIXED_TIME,
updatedAt: FIXED_TIME,
};
const mockConfig2: ParsedServerConfig = {
command: 'python',
args: ['server2.py'],
env: { TEST: 'value2' },
lastUpdatedAt: FIXED_TIME,
updatedAt: FIXED_TIME,
};
const mockConfig3: ParsedServerConfig = {
@ -30,7 +30,7 @@ describe('ServerConfigsCacheInMemory Integration Tests', () => {
args: ['server3.js'],
url: 'http://localhost:3000',
requiresOAuth: true,
lastUpdatedAt: FIXED_TIME,
updatedAt: FIXED_TIME,
};
beforeAll(async () => {

View file

@ -1,7 +1,14 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { AllMethods, createMethods, logger } from '@librechat/data-schemas';
import { Types } from 'mongoose';
import {
AccessRoleIds,
PermissionBits,
PrincipalType,
ResourceType,
} from 'librechat-data-provider';
import { AllMethods, MCPServerDocument, createMethods, logger } from '@librechat/data-schemas';
import type { IServerConfigsRepositoryInterface } from '~/mcp/registry/ServerConfigsRepositoryInterface';
import type { ParsedServerConfig } from '~/mcp/types';
import { AccessControlService } from '~/acl/accessControlService';
import type { ParsedServerConfig, AddServerResult } from '~/mcp/types';
/**
* DB backed config storage
@ -10,35 +17,211 @@ import type { ParsedServerConfig } from '~/mcp/types';
*/
export class ServerConfigsDB implements IServerConfigsRepositoryInterface {
private _dbMethods: AllMethods;
private _aclService: AccessControlService;
private _mongoose: typeof import('mongoose');
constructor(mongoose: typeof import('mongoose')) {
if (!mongoose) {
throw new Error('ServerConfigsDB requires mongoose instance');
}
this._mongoose = mongoose;
this._dbMethods = createMethods(mongoose);
this._aclService = new AccessControlService(mongoose);
}
public async add(serverName: string, config: ParsedServerConfig, userId?: string): Promise<void> {
logger.debug('ServerConfigsDB add not yet implemented');
return;
/**
* Checks if user has access to an MCP server via an agent they can VIEW.
* @param serverName - The MCP server name to check
* @param userId - The user ID (optional - if not provided, checks publicly accessible agents)
* @returns true if user has VIEW access to at least one agent that has this MCP server
*/
private async hasAccessViaAgent(serverName: string, userId?: string): Promise<boolean> {
let accessibleAgentIds: Types.ObjectId[];
if (!userId) {
// Get publicly accessible agents
accessibleAgentIds = await this._aclService.findPubliclyAccessibleResources({
resourceType: ResourceType.AGENT,
requiredPermissions: PermissionBits.VIEW,
});
} else {
// Get user-accessible agents
accessibleAgentIds = await this._aclService.findAccessibleResources({
userId,
requiredPermissions: PermissionBits.VIEW,
resourceType: ResourceType.AGENT,
});
}
if (accessibleAgentIds.length === 0) {
return false;
}
// Check if any accessible agent has this MCP server
const Agent = this._mongoose.model('Agent');
const exists = await Agent.exists({
_id: { $in: accessibleAgentIds },
mcpServerNames: serverName,
});
return exists !== null;
}
/**
* Creates a new MCP server and grants owner permissions to the user.
* @param serverName - Temporary server name (not persisted) will be replaced by the nano id generated by the db method
* @param config - Server configuration to store
* @param userId - ID of the user creating the server (required)
* @returns The created server result with serverName and config (including dbId)
* @throws Error if userId is not provided
*/
public async add(
serverName: string,
config: ParsedServerConfig,
userId?: string,
): Promise<AddServerResult> {
logger.debug(
`[ServerConfigsDB.add] Starting Creating server with temp servername: ${serverName} for the user with the ID ${userId}`,
);
if (!userId) {
throw new Error(
'[ServerConfigsDB.add] User ID is required to create a database-stored MCP server.',
);
}
const createdServer = await this._dbMethods.createMCPServer({ config: config, author: userId });
await this._aclService.grantPermission({
principalType: PrincipalType.USER,
principalId: userId,
resourceType: ResourceType.MCPSERVER,
resourceId: createdServer._id,
accessRoleId: AccessRoleIds.MCPSERVER_OWNER,
grantedBy: userId,
});
return {
serverName: createdServer.serverName,
config: this.mapDBServerToParsedConfig(createdServer),
};
}
/**
*
* @param serverName mcp server unique identifier "serverName"
* @param config new Configuration to update
* @param userId user id required to update DB server config
*/
public async update(
serverName: string,
config: ParsedServerConfig,
userId?: string,
): Promise<void> {
logger.debug('ServerConfigsDB update not yet implemented');
return;
if (!userId) {
throw new Error(
'[ServerConfigsDB.update] User ID is required to update a database-stored MCP server.',
);
}
// Preserve sensitive fields (like oauth.client_secret) that may not be sent from the client
// Create a copy to avoid mutating the input parameter
let mergedConfig = config;
const existingServer = await this._dbMethods.findMCPServerById(serverName);
if (existingServer?.config?.oauth?.client_secret && !config.oauth?.client_secret) {
mergedConfig = {
...config,
oauth: {
...config.oauth,
client_secret: existingServer.config.oauth.client_secret,
},
};
}
// specific user permissions for action permission will be handled in the controller calling the update method of the registry
await this._dbMethods.updateMCPServer(serverName, { config: mergedConfig });
}
/**
* Deletes an MCP server and removes all associated ACL entries.
* @param serverName - The serverName of the server to remove
* @param userId - User performing the deletion (for logging)
*/
public async remove(serverName: string, userId?: string): Promise<void> {
logger.debug('ServerConfigsDB remove not yet implemented');
return;
logger.debug(`[ServerConfigsDB.remove] removing ${serverName}. UserId: ${userId}`);
const deletedServer = await this._dbMethods.deleteMCPServer(serverName);
if (deletedServer && deletedServer._id) {
logger.debug(`[ServerConfigsDB.remove] removing all permissions entries of ${serverName}.`);
await this._aclService.removeAllPermissions({
resourceType: ResourceType.MCPSERVER,
resourceId: deletedServer._id!,
});
return;
}
logger.warn(`[ServerConfigsDB.remove] server with serverName ${serverName} does not exist`);
}
/**
* Retrieves a single MCP server configuration by its serverName.
* @param serverName - The serverName of the server to retrieve
* @param userId - the user id provide the scope of the request. If the user Id is not provided, only publicly visible servers are returned.
* @returns The parsed server config or undefined if not found. If accessed via agent, consumeOnly will be true.
*/
public async get(serverName: string, userId?: string): Promise<ParsedServerConfig | undefined> {
logger.debug('ServerConfigsDB get not yet implemented');
return;
const server = await this._dbMethods.findMCPServerById(serverName);
if (!server) return undefined;
// Check public access if no userId
if (!userId) {
const directlyAccessibleMCPIds = (
await this._aclService.findPubliclyAccessibleResources({
resourceType: ResourceType.MCPSERVER,
requiredPermissions: PermissionBits.VIEW,
})
).map((id) => id.toString());
if (directlyAccessibleMCPIds.indexOf(server._id.toString()) > -1) {
return this.mapDBServerToParsedConfig(server);
}
// Check access via publicly accessible agents
const hasAgentAccess = await this.hasAccessViaAgent(serverName);
if (hasAgentAccess) {
logger.debug(
`[ServerConfigsDB.get] accessing ${serverName} via public agent (consumeOnly)`,
);
return {
...this.mapDBServerToParsedConfig(server),
consumeOnly: true,
};
}
return undefined;
}
// Check direct user access
const userHasDirectAccess = await this._aclService.checkPermission({
userId,
resourceType: ResourceType.MCPSERVER,
requiredPermission: PermissionBits.VIEW,
resourceId: server._id,
});
if (userHasDirectAccess) {
logger.debug(
`[ServerConfigsDB.get] getting ${serverName} for user with the UserId: ${userId}`,
);
return this.mapDBServerToParsedConfig(server);
}
// Check agent access (user can VIEW an agent that has this MCP server)
const hasAgentAccess = await this.hasAccessViaAgent(serverName, userId);
if (hasAgentAccess) {
logger.debug(
`[ServerConfigsDB.get] user ${userId} accessing ${serverName} via agent (consumeOnly)`,
);
return {
...this.mapDBServerToParsedConfig(server),
consumeOnly: true,
};
}
return undefined;
}
/**
@ -47,13 +230,109 @@ export class ServerConfigsDB implements IServerConfigsRepositoryInterface {
* @returns record of parsed configs
*/
public async getAll(userId?: string): Promise<Record<string, ParsedServerConfig>> {
// TODO: Implement DB-backed config retrieval
logger.debug('[ServerConfigsDB] getAll not yet implemented', { userId });
return {};
// 1. Get directly accessible MCP IDs
let directlyAccessibleMCPIds: Types.ObjectId[] = [];
if (!userId) {
logger.debug(`[ServerConfigsDB.getAll] fetching all publicly shared mcp servers`);
directlyAccessibleMCPIds = await this._aclService.findPubliclyAccessibleResources({
resourceType: ResourceType.MCPSERVER,
requiredPermissions: PermissionBits.VIEW,
});
} else {
logger.debug(
`[ServerConfigsDB.getAll] fetching mcp servers directly shared with the user with ID: ${userId}`,
);
directlyAccessibleMCPIds = await this._aclService.findAccessibleResources({
userId,
requiredPermissions: PermissionBits.VIEW,
resourceType: ResourceType.MCPSERVER,
});
}
// 2. Get agent-accessible MCP server names
let agentMCPServerNames: string[] = [];
let accessibleAgentIds: Types.ObjectId[] = [];
if (!userId) {
// Get publicly accessible agents
accessibleAgentIds = await this._aclService.findPubliclyAccessibleResources({
resourceType: ResourceType.AGENT,
requiredPermissions: PermissionBits.VIEW,
});
} else {
// Get user-accessible agents
accessibleAgentIds = await this._aclService.findAccessibleResources({
userId,
requiredPermissions: PermissionBits.VIEW,
resourceType: ResourceType.AGENT,
});
}
if (accessibleAgentIds.length > 0) {
// Efficient query: get agents with non-empty mcpServerNames
const Agent = this._mongoose.model('Agent');
const agentsWithMCP = await Agent.find(
{
_id: { $in: accessibleAgentIds },
mcpServerNames: { $exists: true, $not: { $size: 0 } },
},
{ mcpServerNames: 1 },
).lean();
// Flatten and dedupe server names
agentMCPServerNames = [
...new Set(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
agentsWithMCP.flatMap((a: any) => a.mcpServerNames || []),
),
];
}
// 3. Fetch directly accessible MCP servers
const directResults = await this._dbMethods.getListMCPServersByIds({
ids: directlyAccessibleMCPIds,
});
// 4. Build result with direct access servers
const parsedConfigs: Record<string, ParsedServerConfig> = {};
const directServerNames = new Set<string>();
for (const s of directResults.data || []) {
parsedConfigs[s.serverName] = this.mapDBServerToParsedConfig(s);
directServerNames.add(s.serverName);
}
// 5. Fetch agent-accessible servers (excluding already direct)
const agentOnlyServerNames = agentMCPServerNames.filter((name) => !directServerNames.has(name));
if (agentOnlyServerNames.length > 0) {
const agentServers = await this._dbMethods.getListMCPServersByNames({
names: agentOnlyServerNames,
});
for (const s of agentServers.data || []) {
parsedConfigs[s.serverName] = {
...this.mapDBServerToParsedConfig(s),
consumeOnly: true,
};
}
}
return parsedConfigs;
}
/** No-op for DB storage; logs a warning if called. */
public async reset(): Promise<void> {
logger.warn('Attempt to reset the DB config storage');
return;
}
/** Maps a MongoDB server document to the ParsedServerConfig format. */
private mapDBServerToParsedConfig(serverDBDoc: MCPServerDocument): ParsedServerConfig {
return {
...serverDBDoc.config,
dbId: (serverDBDoc._id as Types.ObjectId).toString(),
updatedAt: serverDBDoc.updatedAt?.getTime(),
};
}
}

View file

@ -153,8 +153,15 @@ export type ParsedServerConfig = MCPOptions & {
tools?: string;
toolFunctions?: LCAvailableTools;
initDuration?: number;
lastUpdatedAt?: number;
updatedAt?: number;
dbId?: string;
/** True if access is only via agent (not directly shared with user) */
consumeOnly?: boolean;
};
export type AddServerResult = {
serverName: string;
config: ParsedServerConfig;
};
export interface BasicConnectionOptions {

View file

@ -45,3 +45,30 @@ export function sanitizeUrlForLogging(url: string | URL): string {
return '[invalid URL]';
}
}
/**
* Escapes special regex characters in a string so they are treated literally.
* @param str - The string to escape
* @returns The escaped string safe for use in a regex pattern
*/
export function escapeRegex(str: string): string {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/**
* Generates a URL-friendly server name from a title.
* Converts to lowercase, replaces spaces with hyphens, removes special characters.
* @param title - The display title to convert
* @returns A slug suitable for use as serverName (e.g., "GitHub MCP Tool" "github-mcp-tool")
*/
export function generateServerNameFromTitle(title: string): string {
const slug = title
.toLowerCase()
.trim()
.replace(/[^a-z0-9\s-]/g, '') // Remove special chars except spaces and hyphens
.replace(/\s+/g, '-') // Replace spaces with hyphens
.replace(/-+/g, '-') // Remove consecutive hyphens
.replace(/^-|-$/g, ''); // Trim leading/trailing hyphens
return slug || 'mcp-server'; // Fallback if empty
}

View file

@ -11,12 +11,26 @@ import {
import './AnimatePopover.css';
import { cn } from '~/utils';
type MultiSelectItem<T extends string> = T | { label: string; value: T };
function getItemValue<T extends string>(item: MultiSelectItem<T>): T {
return typeof item === 'string' ? item : item.value;
}
function getItemLabel<T extends string>(item: MultiSelectItem<T>): string {
return typeof item === 'string' ? item : item.label;
}
interface MultiSelectProps<T extends string> {
items: T[];
items: MultiSelectItem<T>[];
label?: string;
placeholder?: string;
onSelectedValuesChange?: (values: T[]) => void;
renderSelectedValues?: (values: T[], placeholder?: string) => React.ReactNode;
renderSelectedValues?: (
values: T[],
placeholder?: string,
items?: MultiSelectItem<T>[],
) => React.ReactNode;
className?: string;
itemClassName?: string;
labelClassName?: string;
@ -33,11 +47,22 @@ interface MultiSelectProps<T extends string> {
) => React.ReactNode;
}
function defaultRender<T extends string>(values: T[], placeholder?: string) {
function defaultRender<T extends string>(
values: T[],
placeholder?: string,
items?: MultiSelectItem<T>[],
) {
if (values.length === 0) {
return placeholder || 'Select...';
}
if (values.length === 1) {
// Find the item to get its label
if (items) {
const item = items.find((item) => getItemValue(item) === values[0]);
if (item) {
return getItemLabel(item);
}
}
return values[0];
}
return `${values.length} items selected`;
@ -90,7 +115,7 @@ export default function MultiSelect<T extends string>({
>
{selectIcon && <span>{selectIcon as React.JSX.Element}</span>}
<span className="mr-auto hidden truncate md:block">
{renderSelectedValues(selectedValues, placeholder)}
{renderSelectedValues(selectedValues, placeholder, items)}
</span>
<SelectArrow className="ml-1 hidden stroke-1 text-base opacity-75 md:block" />
</Select>
@ -109,11 +134,13 @@ export default function MultiSelect<T extends string>({
popoverClassName,
)}
>
{items.map((value) => {
{items.map((item) => {
const value = getItemValue(item);
const label = getItemLabel(item);
const defaultContent = (
<>
<SelectItemCheck className="mr-0.5 text-primary" />
<span className="truncate">{value}</span>
<span className="truncate">{label}</span>
</>
);
const isCurrentItemSelected = selectedValues.includes(value);

View file

@ -8,6 +8,7 @@
"declaration": true,
"declarationMap": true,
"declarationDir": "./dist/types",
"sourceMap": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,

View file

@ -45,6 +45,7 @@ export type TAccessLevel = 'none' | 'viewer' | 'editor' | 'owner';
export enum ResourceType {
AGENT = 'agent',
PROMPTGROUP = 'promptGroup',
MCPSERVER = 'mcpServer',
}
/**
@ -71,6 +72,9 @@ export enum AccessRoleIds {
PROMPTGROUP_VIEWER = 'promptGroup_viewer',
PROMPTGROUP_EDITOR = 'promptGroup_editor',
PROMPTGROUP_OWNER = 'promptGroup_owner',
MCPSERVER_VIEWER = 'mcpServer_viewer',
MCPSERVER_EDITOR = 'mcpServer_editor',
MCPSERVER_OWNER = 'mcpServer_owner',
}
// ===== ZOD SCHEMAS =====
@ -269,6 +273,12 @@ export const effectivePermissionsResponseSchema = z.object({
*/
export type TEffectivePermissionsResponse = z.infer<typeof effectivePermissionsResponseSchema>;
/**
* All effective permissions response type
* Map of resourceId to permissionBits for all accessible resources
*/
export type TAllEffectivePermissionsResponse = Record<string, number>;
// ===== UTILITY TYPES =====
/**

View file

@ -231,6 +231,8 @@ export const mcp = {
servers: `${BASE_URL}/api/mcp/servers`,
};
export const mcpServer = (serverName: string) => `${BASE_URL}/api/mcp/servers/${serverName}`;
export const revertAgentVersion = (agent_id: string) => `${agents({ path: `${agent_id}/revert` })}`;
export const files = () => `${BASE_URL}/api/files`;
@ -319,6 +321,7 @@ export const updateMemoryPermissions = (roleName: string) => `${getRole(roleName
export const updateAgentPermissions = (roleName: string) => `${getRole(roleName)}/agents`;
export const updatePeoplePickerPermissions = (roleName: string) =>
`${getRole(roleName)}/people-picker`;
export const updateMCPServersPermissions = (roleName: string) => `${getRole(roleName)}/mcp-servers`;
export const updateMarketplacePermissions = (roleName: string) =>
`${getRole(roleName)}/marketplace`;
@ -383,6 +386,9 @@ export const updateResourcePermissions = (resourceType: ResourceType, resourceId
export const getEffectivePermissions = (resourceType: ResourceType, resourceId: string) =>
`${BASE_URL}/api/permissions/${resourceType}/${resourceId}/effective`;
export const getAllEffectivePermissions = (resourceType: ResourceType) =>
`${BASE_URL}/api/permissions/${resourceType}/effective/all`;
// SharePoint Graph API Token
export const graphToken = (scopes: string) =>
`${BASE_URL}/api/auth/graph-token?scopes=${encodeURIComponent(scopes)}`;

View file

@ -515,9 +515,14 @@ const termsOfServiceSchema = z.object({
export type TTermsOfService = z.infer<typeof termsOfServiceSchema>;
const mcpServersSchema = z.object({
placeholder: z.string().optional(),
});
const mcpServersSchema = z
.object({
placeholder: z.string().optional(),
use: z.boolean().optional(),
create: z.boolean().optional(),
share: z.boolean().optional(),
})
.optional();
export type TMcpServersConfig = z.infer<typeof mcpServersSchema>;
@ -583,6 +588,11 @@ export const interfaceSchema = z
marketplace: {
use: false,
},
mcpServers: {
use: true,
create: true,
share: false,
},
fileSearch: true,
fileCitations: true,
});
@ -675,6 +685,7 @@ export type TStartupConfig = {
chatMenu?: boolean;
isOAuth?: boolean;
startup?: boolean;
iconPath?: string;
}
>;
mcpPlaceholder?: string;

View file

@ -565,6 +565,39 @@ export const getMCPServers = async (): Promise<mcp.MCPServersListResponse> => {
return request.get(endpoints.mcp.servers);
};
/**
* Get a single MCP server by ID
*/
export const getMCPServer = async (serverName: string): Promise<mcp.MCPServerDBObjectResponse> => {
return request.get(endpoints.mcpServer(serverName));
};
/**
* Create a new MCP server
*/
export const createMCPServer = async (
data: mcp.MCPServerCreateParams,
): Promise<mcp.MCPServerDBObjectResponse> => {
return request.post(endpoints.mcp.servers, data);
};
/**
* Update an existing MCP server
*/
export const updateMCPServer = async (
serverName: string,
data: mcp.MCPServerUpdateParams,
): Promise<mcp.MCPServerDBObjectResponse> => {
return request.patch(endpoints.mcpServer(serverName), data);
};
/**
* Delete an MCP server
*/
export const deleteMCPServer = async (serverName: string): Promise<{ success: boolean }> => {
return request.delete(endpoints.mcpServer(serverName));
};
/**
* Imports a conversations file.
*
@ -832,6 +865,12 @@ export function updatePeoplePickerPermissions(
);
}
export function updateMCPServersPermissions(
variables: m.UpdateMCPServersPermVars,
): Promise<m.UpdatePermResponse> {
return request.put(endpoints.updateMCPServersPermissions(variables.roleName), variables.updates);
}
export function updateMarketplacePermissions(
variables: m.UpdateMarketplacePermVars,
): Promise<m.UpdatePermResponse> {
@ -984,6 +1023,12 @@ export function getEffectivePermissions(
return request.get(endpoints.getEffectivePermissions(resourceType, resourceId));
}
export function getAllEffectivePermissions(
resourceType: permissions.ResourceType,
): Promise<permissions.TAllEffectivePermissionsResponse> {
return request.get(endpoints.getAllEffectivePermissions(resourceType));
}
// SharePoint Graph API Token
export function getGraphApiToken(params: q.GraphTokenParams): Promise<q.GraphTokenResponse> {
return request.get(endpoints.graphToken(params.scopes));

View file

@ -59,6 +59,7 @@ export enum QueryKeys {
graphToken = 'graphToken',
/* MCP Servers */
mcpServers = 'mcpServers',
mcpServer = 'mcpServer',
}
// Dynamic query keys that require parameters

View file

@ -3,6 +3,13 @@ import { TokenExchangeMethodEnum } from './types/agents';
import { extractEnvVariable } from './utils';
const BaseOptionsSchema = z.object({
/** Display name for the MCP server - only letters, numbers, and spaces allowed */
title: z
.string()
.regex(/^[a-zA-Z0-9 ]+$/, 'Title can only contain letters, numbers, and spaces')
.optional(),
/** Description of the MCP server */
description: z.string().optional(),
/**
* Controls whether the MCP server is initialized during application startup.
* - true (default): Server is initialized during app startup and included in app-level connections

View file

@ -52,6 +52,10 @@ export enum PermissionTypes {
* Type for using the "File Citations" feature in agents
*/
FILE_CITATIONS = 'FILE_CITATIONS',
/**
* Type for MCP Server Permissions
*/
MCP_SERVERS = 'MCP_SERVERS',
}
/**
@ -144,6 +148,13 @@ export const fileCitationsPermissionsSchema = z.object({
});
export type TFileCitationsPermissions = z.infer<typeof fileCitationsPermissionsSchema>;
export const mcpServersPermissionsSchema = z.object({
[Permissions.USE]: z.boolean().default(true),
[Permissions.CREATE]: z.boolean().default(true),
[Permissions.SHARE]: z.boolean().default(false),
});
export type TMcpServersPermissions = z.infer<typeof mcpServersPermissionsSchema>;
// Define a single permissions schema that holds all permission types.
export const permissionsSchema = z.object({
[PermissionTypes.PROMPTS]: promptPermissionsSchema,
@ -158,4 +169,5 @@ export const permissionsSchema = z.object({
[PermissionTypes.MARKETPLACE]: marketplacePermissionsSchema,
[PermissionTypes.FILE_SEARCH]: fileSearchPermissionsSchema,
[PermissionTypes.FILE_CITATIONS]: fileCitationsPermissionsSchema,
[PermissionTypes.MCP_SERVERS]: mcpServersPermissionsSchema,
});

View file

@ -493,6 +493,20 @@ export const useGetEffectivePermissionsQuery = (
});
};
export const useGetAllEffectivePermissionsQuery = (
resourceType: ResourceType,
config?: UseQueryOptions<permissions.TAllEffectivePermissionsResponse>,
): QueryObserverResult<permissions.TAllEffectivePermissionsResponse> => {
return useQuery<permissions.TAllEffectivePermissionsResponse>({
queryKey: [QueryKeys.effectivePermissions, 'all', resourceType],
queryFn: () => dataService.getAllEffectivePermissions(resourceType),
enabled: !!resourceType,
refetchOnWindowFocus: false,
staleTime: 30000,
...config,
});
};
export const useMCPServerConnectionStatusQuery = (
serverName: string,
config?: UseQueryOptions<MCPServerConnectionStatusResponse>,

View file

@ -14,6 +14,7 @@ import {
temporaryChatPermissionsSchema,
peoplePickerPermissionsSchema,
fileCitationsPermissionsSchema,
mcpServersPermissionsSchema,
} from './permissions';
/**
@ -89,6 +90,11 @@ const defaultRolesSchema = z.object({
[PermissionTypes.FILE_CITATIONS]: fileCitationsPermissionsSchema.extend({
[Permissions.USE]: z.boolean().default(true),
}),
[PermissionTypes.MCP_SERVERS]: mcpServersPermissionsSchema.extend({
[Permissions.USE]: z.boolean().default(true),
[Permissions.CREATE]: z.boolean().default(true),
[Permissions.SHARE]: z.boolean().default(true),
}),
}),
}),
[SystemRoles.USER]: roleSchema.extend({
@ -147,6 +153,11 @@ export const roleDefaults = defaultRolesSchema.parse({
[PermissionTypes.FILE_CITATIONS]: {
[Permissions.USE]: true,
},
[PermissionTypes.MCP_SERVERS]: {
[Permissions.USE]: true,
[Permissions.CREATE]: true,
[Permissions.SHARE]: true,
},
},
},
[SystemRoles.USER]: {
@ -170,6 +181,7 @@ export const roleDefaults = defaultRolesSchema.parse({
},
[PermissionTypes.FILE_SEARCH]: {},
[PermissionTypes.FILE_CITATIONS]: {},
[PermissionTypes.MCP_SERVERS]: {},
},
},
});

View file

@ -333,7 +333,7 @@ export type ActionMetadataRuntime = ActionMetadata & {
};
export type MCP = {
mcp_id: string;
serverName: string;
metadata: MCPMetadata;
} & ({ assistant_id: string; agent_id?: never } | { assistant_id?: never; agent_id?: string });

View file

@ -1 +1,2 @@
export * from './queries';
export * from './mcpServers';

View file

@ -1,4 +1,3 @@
import { PermissionBits } from '../accessPermissions';
import type { MCPOptions, MCPServerUserInput } from '../mcp';
/**
@ -7,7 +6,7 @@ import type { MCPOptions, MCPServerUserInput } from '../mcp';
*/
export interface IMCPServerDB {
_id?: string; // MongoDB ObjectId (used for ACL/permissions)
mcp_id: string;
serverName: string;
config: MCPOptions;
author?: string | null;
createdAt?: Date;
@ -41,12 +40,10 @@ export type MCPServerUpdateParams = {
* Response for MCP server list endpoint
*/
export type MCPServerDBObjectResponse = {
_id?: string;
mcp_id?: string;
author?: string | null;
createdAt?: Date;
updatedAt?: Date;
effectivePermissions?: PermissionBits;
dbId?: string;
serverName: string;
/** True if access is only via agent (not directly shared with user) */
consumeOnly?: boolean;
} & MCPOptions;
export type MCPServersListResponse = Record<string, MCPServerDBObjectResponse>;

View file

@ -274,6 +274,7 @@ export type UpdatePromptPermVars = UpdatePermVars<p.TPromptPermissions>;
export type UpdateMemoryPermVars = UpdatePermVars<p.TMemoryPermissions>;
export type UpdateAgentPermVars = UpdatePermVars<p.TAgentPermissions>;
export type UpdatePeoplePickerPermVars = UpdatePermVars<p.TPeoplePickerPermissions>;
export type UpdateMCPServersPermVars = UpdatePermVars<p.TMcpServersPermissions>;
export type UpdatePermResponse = r.TRole;
@ -305,6 +306,13 @@ export type UpdatePeoplePickerPermOptions = MutationOptions<
types.TError | null | undefined
>;
export type UpdateMCPServersPermOptions = MutationOptions<
UpdatePermResponse,
UpdateMCPServersPermVars,
unknown,
types.TError | null | undefined
>;
export type UpdateMarketplacePermVars = UpdatePermVars<p.TMarketplacePermissions>;
export type UpdateMarketplacePermOptions = MutationOptions<

View file

@ -200,6 +200,9 @@ describe('AccessRole Model Tests', () => {
AccessRoleIds.PROMPTGROUP_EDITOR,
AccessRoleIds.PROMPTGROUP_OWNER,
AccessRoleIds.PROMPTGROUP_VIEWER,
AccessRoleIds.MCPSERVER_EDITOR,
AccessRoleIds.MCPSERVER_OWNER,
AccessRoleIds.MCPSERVER_VIEWER,
].sort(),
);

View file

@ -146,6 +146,27 @@ export function createAccessRoleMethods(mongoose: typeof import('mongoose')) {
resourceType: ResourceType.PROMPTGROUP,
permBits: RoleBits.OWNER,
},
{
accessRoleId: AccessRoleIds.MCPSERVER_VIEWER,
name: 'com_ui_mcp_server_role_viewer',
description: 'com_ui_mcp_server_role_viewer_desc',
resourceType: ResourceType.MCPSERVER,
permBits: RoleBits.VIEWER,
},
{
accessRoleId: AccessRoleIds.MCPSERVER_EDITOR,
name: 'com_ui_mcp_server_role_editor',
description: 'com_ui_mcp_server_role_editor_desc',
resourceType: ResourceType.MCPSERVER,
permBits: RoleBits.EDITOR,
},
{
accessRoleId: AccessRoleIds.MCPSERVER_OWNER,
name: 'com_ui_mcp_server_role_owner',
description: 'com_ui_mcp_server_role_owner_desc',
resourceType: ResourceType.MCPSERVER,
permBits: RoleBits.OWNER,
},
];
const result: Record<string, IAccessRole> = {};

View file

@ -679,4 +679,276 @@ describe('AclEntry Model Tests', () => {
expect(effective).toBe(PermissionBits.VIEW);
});
});
describe('Batch Permission Queries', () => {
test('should get effective permissions for multiple resources in single query', async () => {
const resource1 = new mongoose.Types.ObjectId();
const resource2 = new mongoose.Types.ObjectId();
const resource3 = new mongoose.Types.ObjectId();
/** Grant different permissions to different resources */
await methods.grantPermission(
PrincipalType.USER,
userId,
ResourceType.MCPSERVER,
resource1,
PermissionBits.VIEW,
grantedById,
);
await methods.grantPermission(
PrincipalType.USER,
userId,
ResourceType.MCPSERVER,
resource2,
PermissionBits.VIEW | PermissionBits.EDIT,
grantedById,
);
await methods.grantPermission(
PrincipalType.GROUP,
groupId,
ResourceType.MCPSERVER,
resource3,
PermissionBits.DELETE,
grantedById,
);
/** Get permissions for all resources */
const permissionsMap = await methods.getEffectivePermissionsForResources(
[{ principalType: PrincipalType.USER, principalId: userId }],
ResourceType.MCPSERVER,
[resource1, resource2, resource3],
);
expect(permissionsMap.size).toBe(2); // Only resource1 and resource2 for user
expect(permissionsMap.get(resource1.toString())).toBe(PermissionBits.VIEW);
expect(permissionsMap.get(resource2.toString())).toBe(PermissionBits.VIEW | PermissionBits.EDIT);
expect(permissionsMap.get(resource3.toString())).toBeUndefined(); // User has no access
});
test('should combine permissions from multiple principals in batch query', async () => {
const resource1 = new mongoose.Types.ObjectId();
const resource2 = new mongoose.Types.ObjectId();
/** User has VIEW on both resources */
await methods.grantPermission(
PrincipalType.USER,
userId,
ResourceType.MCPSERVER,
resource1,
PermissionBits.VIEW,
grantedById,
);
await methods.grantPermission(
PrincipalType.USER,
userId,
ResourceType.MCPSERVER,
resource2,
PermissionBits.VIEW,
grantedById,
);
/** Group has EDIT on resource1 */
await methods.grantPermission(
PrincipalType.GROUP,
groupId,
ResourceType.MCPSERVER,
resource1,
PermissionBits.EDIT,
grantedById,
);
/** Get combined permissions for user + group */
const permissionsMap = await methods.getEffectivePermissionsForResources(
[
{ principalType: PrincipalType.USER, principalId: userId },
{ principalType: PrincipalType.GROUP, principalId: groupId },
],
ResourceType.MCPSERVER,
[resource1, resource2],
);
expect(permissionsMap.size).toBe(2);
/** Resource1 should have VIEW | EDIT (from user + group) */
expect(permissionsMap.get(resource1.toString())).toBe(PermissionBits.VIEW | PermissionBits.EDIT);
/** Resource2 should have only VIEW (from user) */
expect(permissionsMap.get(resource2.toString())).toBe(PermissionBits.VIEW);
});
test('should handle empty resource list', async () => {
const permissionsMap = await methods.getEffectivePermissionsForResources(
[{ principalType: PrincipalType.USER, principalId: userId }],
ResourceType.MCPSERVER,
[],
);
expect(permissionsMap.size).toBe(0);
});
test('should handle resources with no permissions', async () => {
const resource1 = new mongoose.Types.ObjectId();
const resource2 = new mongoose.Types.ObjectId();
/** Only grant permission to resource1 */
await methods.grantPermission(
PrincipalType.USER,
userId,
ResourceType.MCPSERVER,
resource1,
PermissionBits.VIEW,
grantedById,
);
const permissionsMap = await methods.getEffectivePermissionsForResources(
[{ principalType: PrincipalType.USER, principalId: userId }],
ResourceType.MCPSERVER,
[resource1, resource2], // resource2 has no permissions
);
expect(permissionsMap.size).toBe(1);
expect(permissionsMap.get(resource1.toString())).toBe(PermissionBits.VIEW);
expect(permissionsMap.get(resource2.toString())).toBeUndefined();
});
test('should include public permissions in batch query', async () => {
const resource1 = new mongoose.Types.ObjectId();
const resource2 = new mongoose.Types.ObjectId();
/** User has VIEW on resource1 */
await methods.grantPermission(
PrincipalType.USER,
userId,
ResourceType.MCPSERVER,
resource1,
PermissionBits.VIEW | PermissionBits.EDIT,
grantedById,
);
/** Public has VIEW on resource2 */
await methods.grantPermission(
PrincipalType.PUBLIC,
null,
ResourceType.MCPSERVER,
resource2,
PermissionBits.VIEW,
grantedById,
);
/** Query with user + public principals */
const permissionsMap = await methods.getEffectivePermissionsForResources(
[
{ principalType: PrincipalType.USER, principalId: userId },
{ principalType: PrincipalType.PUBLIC },
],
ResourceType.MCPSERVER,
[resource1, resource2],
);
expect(permissionsMap.size).toBe(2);
expect(permissionsMap.get(resource1.toString())).toBe(PermissionBits.VIEW | PermissionBits.EDIT);
expect(permissionsMap.get(resource2.toString())).toBe(PermissionBits.VIEW);
});
test('should handle large batch efficiently', async () => {
/** Create 50 resources with various permissions */
const resources = Array.from({ length: 50 }, () => new mongoose.Types.ObjectId());
/** Grant permissions to first 30 resources */
for (let i = 0; i < 30; i++) {
await methods.grantPermission(
PrincipalType.USER,
userId,
ResourceType.MCPSERVER,
resources[i],
PermissionBits.VIEW,
grantedById,
);
}
/** Grant group permissions to resources 20-40 (overlap with user) */
for (let i = 20; i < 40; i++) {
await methods.grantPermission(
PrincipalType.GROUP,
groupId,
ResourceType.MCPSERVER,
resources[i],
PermissionBits.EDIT,
grantedById,
);
}
const startTime = Date.now();
const permissionsMap = await methods.getEffectivePermissionsForResources(
[
{ principalType: PrincipalType.USER, principalId: userId },
{ principalType: PrincipalType.GROUP, principalId: groupId },
],
ResourceType.MCPSERVER,
resources,
);
const duration = Date.now() - startTime;
/** Should be reasonably fast (under 1 second for 50 resources) */
expect(duration).toBeLessThan(1000);
/** Verify results */
expect(permissionsMap.size).toBe(40); // Resources 0-39 have permissions
/** Resources 0-19: USER VIEW only */
for (let i = 0; i < 20; i++) {
expect(permissionsMap.get(resources[i].toString())).toBe(PermissionBits.VIEW);
}
/** Resources 20-29: USER VIEW | GROUP EDIT */
for (let i = 20; i < 30; i++) {
expect(permissionsMap.get(resources[i].toString())).toBe(PermissionBits.VIEW | PermissionBits.EDIT);
}
/** Resources 30-39: GROUP EDIT only */
for (let i = 30; i < 40; i++) {
expect(permissionsMap.get(resources[i].toString())).toBe(PermissionBits.EDIT);
}
/** Resources 40-49: No permissions */
for (let i = 40; i < 50; i++) {
expect(permissionsMap.get(resources[i].toString())).toBeUndefined();
}
});
test('should handle mixed ObjectId and string resource IDs', async () => {
const resource1 = new mongoose.Types.ObjectId();
const resource2 = new mongoose.Types.ObjectId();
await methods.grantPermission(
PrincipalType.USER,
userId,
ResourceType.MCPSERVER,
resource1,
PermissionBits.VIEW,
grantedById,
);
await methods.grantPermission(
PrincipalType.USER,
userId,
ResourceType.MCPSERVER,
resource2,
PermissionBits.EDIT,
grantedById,
);
/** Pass mix of ObjectId and string */
const permissionsMap = await methods.getEffectivePermissionsForResources(
[{ principalType: PrincipalType.USER, principalId: userId }],
ResourceType.MCPSERVER,
[resource1, resource2.toString()], // Mix of ObjectId and string
);
expect(permissionsMap.size).toBe(2);
expect(permissionsMap.get(resource1.toString())).toBe(PermissionBits.VIEW);
expect(permissionsMap.get(resource2.toString())).toBe(PermissionBits.EDIT);
});
});
});

View file

@ -118,6 +118,58 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')) {
return effectiveBits;
}
/**
* Get effective permissions for multiple resources in a single query (BATCH)
* Returns a map of resourceId effectivePermissionBits
*
* @param principalsList - List of principals (user + groups + public)
* @param resourceType - The type of resource ('MCPSERVER', 'AGENT', etc.)
* @param resourceIds - Array of resource IDs to check
* @returns {Promise<Map<string, number>>} Map of resourceId permission bits
*
* @example
* const principals = await getUserPrincipals({ userId, role });
* const serverIds = [id1, id2, id3];
* const permMap = await getEffectivePermissionsForResources(
* principals,
* ResourceType.MCPSERVER,
* serverIds
* );
* // permMap.get(id1.toString()) → 7 (VIEW|EDIT|DELETE)
*/
async function getEffectivePermissionsForResources(
principalsList: Array<{ principalType: string; principalId?: string | Types.ObjectId }>,
resourceType: string,
resourceIds: Array<string | Types.ObjectId>,
): Promise<Map<string, number>> {
if (!Array.isArray(resourceIds) || resourceIds.length === 0) {
return new Map();
}
const AclEntry = mongoose.models.AclEntry as Model<IAclEntry>;
const principalsQuery = principalsList.map((p) => ({
principalType: p.principalType,
...(p.principalType !== PrincipalType.PUBLIC && { principalId: p.principalId }),
}));
// Batch query for all resources at once
const aclEntries = await AclEntry.find({
$or: principalsQuery,
resourceType,
resourceId: { $in: resourceIds },
}).lean();
// Compute effective permissions per resource
const permissionsMap = new Map<string, number>();
for (const entry of aclEntries) {
const rid = entry.resourceId.toString();
const currentBits = permissionsMap.get(rid) || 0;
permissionsMap.set(rid, currentBits | entry.permBits);
}
return permissionsMap;
}
/**
* Grant permission to a principal for a resource
* @param principalType - The type of principal ('user', 'group', 'public')
@ -301,6 +353,7 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')) {
findEntriesByPrincipalsAndResource,
hasPermission,
getEffectivePermissions,
getEffectivePermissionsForResources,
grantPermission,
revokePermission,
modifyPermissionBits,

View file

@ -8,6 +8,8 @@ import { createFileMethods, type FileMethods } from './file';
import { createMemoryMethods, type MemoryMethods } from './memory';
/* Agent Categories */
import { createAgentCategoryMethods, type AgentCategoryMethods } from './agentCategory';
/* MCP Servers */
import { createMCPServerMethods, type MCPServerMethods } from './mcpServer';
/* Plugin Auth */
import { createPluginAuthMethods, type PluginAuthMethods } from './pluginAuth';
/* Permissions */
@ -24,6 +26,7 @@ export type AllMethods = UserMethods &
FileMethods &
MemoryMethods &
AgentCategoryMethods &
MCPServerMethods &
UserGroupMethods &
AclEntryMethods &
ShareMethods &
@ -44,6 +47,7 @@ export function createMethods(mongoose: typeof import('mongoose')): AllMethods {
...createFileMethods(mongoose),
...createMemoryMethods(mongoose),
...createAgentCategoryMethods(mongoose),
...createMCPServerMethods(mongoose),
...createAccessRoleMethods(mongoose),
...createUserGroupMethods(mongoose),
...createAclEntryMethods(mongoose),
@ -61,6 +65,7 @@ export type {
FileMethods,
MemoryMethods,
AgentCategoryMethods,
MCPServerMethods,
UserGroupMethods,
AclEntryMethods,
ShareMethods,

View file

@ -0,0 +1,827 @@
import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import type { MCPOptions } from 'librechat-data-provider';
import type * as t from '~/types';
import { createMCPServerMethods } from './mcpServer';
import mcpServerSchema from '~/schema/mcpServer';
let mongoServer: MongoMemoryServer;
let MCPServer: mongoose.Model<t.MCPServerDocument>;
let methods: ReturnType<typeof createMCPServerMethods>;
beforeAll(async () => {
mongoServer = await MongoMemoryServer.create();
const mongoUri = mongoServer.getUri();
MCPServer = mongoose.models.MCPServer || mongoose.model('MCPServer', mcpServerSchema);
methods = createMCPServerMethods(mongoose);
await mongoose.connect(mongoUri);
});
afterAll(async () => {
await mongoose.disconnect();
await mongoServer.stop();
});
beforeEach(async () => {
await mongoose.connection.dropDatabase();
});
describe('MCPServer Model Tests', () => {
const authorId = new mongoose.Types.ObjectId();
const authorId2 = new mongoose.Types.ObjectId();
const createSSEConfig = (title?: string, description?: string): MCPOptions => ({
type: 'sse',
url: 'https://example.com/mcp',
...(title && { title }),
...(description && { description }),
});
describe('createMCPServer', () => {
test('should create server with title and generate slug from title', async () => {
const config = createSSEConfig('My Test Server', 'A test server');
const server = await methods.createMCPServer({ config, author: authorId });
expect(server).toBeDefined();
expect(server.serverName).toBe('my-test-server');
expect(server.config.title).toBe('My Test Server');
expect(server.config.description).toBe('A test server');
expect(server.author.toString()).toBe(authorId.toString());
expect(server.createdAt).toBeInstanceOf(Date);
expect(server.updatedAt).toBeInstanceOf(Date);
});
test('should create server without title and use nanoid', async () => {
const config: MCPOptions = {
type: 'sse',
url: 'https://example.com/mcp',
};
const server = await methods.createMCPServer({ config, author: authorId });
expect(server).toBeDefined();
expect(server.serverName).toMatch(/^mcp-[a-zA-Z0-9_-]{16}$/);
expect(server.config.title).toBeUndefined();
});
test('should handle title with special characters', async () => {
const config = createSSEConfig('My @#$% Server!!! 123');
const server = await methods.createMCPServer({ config, author: authorId });
expect(server.serverName).toBe('my-server-123');
});
test('should handle title with only spaces and special chars', async () => {
const config = createSSEConfig(' @#$% ');
const server = await methods.createMCPServer({ config, author: authorId });
// Should fallback to 'mcp-server'
expect(server.serverName).toBe('mcp-server');
});
test('should handle title with multiple spaces', async () => {
const config = createSSEConfig('My Multiple Spaces Server');
const server = await methods.createMCPServer({ config, author: authorId });
expect(server.serverName).toBe('my-multiple-spaces-server');
});
test('should handle string author ID', async () => {
const config = createSSEConfig('String Author Test');
const server = await methods.createMCPServer({
config,
author: authorId.toString(),
});
expect(server).toBeDefined();
expect(server.author.toString()).toBe(authorId.toString());
});
test('should create server with stdio config', async () => {
const config: MCPOptions = {
type: 'stdio',
command: 'node',
args: ['server.js'],
title: 'Stdio Server',
};
const server = await methods.createMCPServer({ config, author: authorId });
expect(server.serverName).toBe('stdio-server');
expect(server.config.type).toBe('stdio');
});
});
describe('findNextAvailableServerName', () => {
test('should return base name when no duplicates exist', async () => {
// Create server directly via model to set up initial state
await MCPServer.create({
serverName: 'other-server',
config: createSSEConfig('Other Server'),
author: authorId,
});
const config = createSSEConfig('Test Server');
const server = await methods.createMCPServer({ config, author: authorId });
expect(server.serverName).toBe('test-server');
});
test('should append -2 when base name exists', async () => {
// Create first server
await methods.createMCPServer({
config: createSSEConfig('Test Server'),
author: authorId,
});
// Create second server with same title
const server = await methods.createMCPServer({
config: createSSEConfig('Test Server'),
author: authorId,
});
expect(server.serverName).toBe('test-server-2');
});
test('should find next available number in sequence', async () => {
// Create servers with sequential names
await MCPServer.create({
serverName: 'test-server',
config: createSSEConfig('Test Server'),
author: authorId,
});
await MCPServer.create({
serverName: 'test-server-2',
config: createSSEConfig('Test Server'),
author: authorId,
});
await MCPServer.create({
serverName: 'test-server-3',
config: createSSEConfig('Test Server'),
author: authorId,
});
const server = await methods.createMCPServer({
config: createSSEConfig('Test Server'),
author: authorId,
});
expect(server.serverName).toBe('test-server-4');
});
test('should handle gaps in sequence', async () => {
// Create servers with gaps: test, test-2, test-5
await MCPServer.create({
serverName: 'test-server',
config: createSSEConfig('Test Server'),
author: authorId,
});
await MCPServer.create({
serverName: 'test-server-2',
config: createSSEConfig('Test Server'),
author: authorId,
});
await MCPServer.create({
serverName: 'test-server-5',
config: createSSEConfig('Test Server'),
author: authorId,
});
const server = await methods.createMCPServer({
config: createSSEConfig('Test Server'),
author: authorId,
});
// Should append -6 (max + 1)
expect(server.serverName).toBe('test-server-6');
});
test('should not match partial names', async () => {
// Create 'test-server-extra' which shouldn't affect 'test-server' sequence
await MCPServer.create({
serverName: 'test-server-extra',
config: createSSEConfig('Test Server Extra'),
author: authorId,
});
const server = await methods.createMCPServer({
config: createSSEConfig('Test Server'),
author: authorId,
});
// 'test-server' is available, so should use it
expect(server.serverName).toBe('test-server');
});
test('should handle special regex characters in base name', async () => {
// The slug generation removes special characters, but test the regex escaping
await MCPServer.create({
serverName: 'test-server',
config: createSSEConfig('Test Server'),
author: authorId,
});
const server = await methods.createMCPServer({
config: createSSEConfig('Test Server'),
author: authorId2,
});
expect(server.serverName).toBe('test-server-2');
});
});
describe('findMCPServerById', () => {
test('should find server by serverName', async () => {
const created = await methods.createMCPServer({
config: createSSEConfig('Find By Id Test'),
author: authorId,
});
const found = await methods.findMCPServerById(created.serverName);
expect(found).toBeDefined();
expect(found?.serverName).toBe('find-by-id-test');
expect(found?.config.title).toBe('Find By Id Test');
});
test('should return null when server not found', async () => {
const found = await methods.findMCPServerById('non-existent-server');
expect(found).toBeNull();
});
test('should return lean document', async () => {
await methods.createMCPServer({
config: createSSEConfig('Lean Test'),
author: authorId,
});
const found = await methods.findMCPServerById('lean-test');
// Lean documents don't have mongoose methods
expect(found).toBeDefined();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect(typeof (found as any).save).toBe('undefined');
});
});
describe('findMCPServerByObjectId', () => {
test('should find server by MongoDB ObjectId', async () => {
const created = await methods.createMCPServer({
config: createSSEConfig('Object Id Test'),
author: authorId,
});
const found = await methods.findMCPServerByObjectId(created._id);
expect(found).toBeDefined();
expect(found?.serverName).toBe('object-id-test');
expect(found?._id.toString()).toBe(created._id.toString());
});
test('should find server by string ObjectId', async () => {
const created = await methods.createMCPServer({
config: createSSEConfig('String Object Id Test'),
author: authorId,
});
const found = await methods.findMCPServerByObjectId(created._id.toString());
expect(found).toBeDefined();
expect(found?.serverName).toBe('string-object-id-test');
});
test('should return null when ObjectId not found', async () => {
const randomId = new mongoose.Types.ObjectId();
const found = await methods.findMCPServerByObjectId(randomId);
expect(found).toBeNull();
});
test('should return null for invalid ObjectId string', async () => {
await expect(methods.findMCPServerByObjectId('invalid-id')).rejects.toThrow();
});
});
describe('findMCPServersByAuthor', () => {
test('should find all servers by author', async () => {
await methods.createMCPServer({
config: createSSEConfig('Author Server 1'),
author: authorId,
});
await methods.createMCPServer({
config: createSSEConfig('Author Server 2'),
author: authorId,
});
await methods.createMCPServer({
config: createSSEConfig('Other Author Server'),
author: authorId2,
});
const servers = await methods.findMCPServersByAuthor(authorId);
expect(servers).toHaveLength(2);
expect(servers.every((s) => s.author.toString() === authorId.toString())).toBe(true);
});
test('should return empty array when author has no servers', async () => {
const servers = await methods.findMCPServersByAuthor(new mongoose.Types.ObjectId());
expect(servers).toEqual([]);
});
test('should sort by updatedAt descending', async () => {
// Create servers with slight delay to ensure different timestamps
const server1 = await methods.createMCPServer({
config: createSSEConfig('First Created'),
author: authorId,
});
// Update first server to make it most recently updated
await MCPServer.findByIdAndUpdate(server1._id, {
$set: { 'config.description': 'Updated' },
});
await methods.createMCPServer({
config: createSSEConfig('Second Created'),
author: authorId,
});
const servers = await methods.findMCPServersByAuthor(authorId);
expect(servers).toHaveLength(2);
// Most recently updated should come first
expect(servers[0].serverName).toBe('second-created');
});
test('should handle string author ID', async () => {
await methods.createMCPServer({
config: createSSEConfig('String Author Server'),
author: authorId,
});
const servers = await methods.findMCPServersByAuthor(authorId.toString());
expect(servers).toHaveLength(1);
});
});
describe('getListMCPServersByIds', () => {
let server1: t.MCPServerDocument;
let server2: t.MCPServerDocument;
let server3: t.MCPServerDocument;
beforeEach(async () => {
server1 = await methods.createMCPServer({
config: createSSEConfig('Server One'),
author: authorId,
});
server2 = await methods.createMCPServer({
config: createSSEConfig('Server Two'),
author: authorId,
});
server3 = await methods.createMCPServer({
config: createSSEConfig('Server Three'),
author: authorId,
});
});
test('should return servers matching provided IDs', async () => {
const result = await methods.getListMCPServersByIds({
ids: [server1._id, server2._id],
});
expect(result.data).toHaveLength(2);
expect(result.has_more).toBe(false);
expect(result.after).toBeNull();
});
test('should return empty data for empty IDs array', async () => {
const result = await methods.getListMCPServersByIds({ ids: [] });
expect(result.data).toEqual([]);
expect(result.has_more).toBe(false);
expect(result.after).toBeNull();
});
test('should handle pagination with limit', async () => {
const result = await methods.getListMCPServersByIds({
ids: [server1._id, server2._id, server3._id],
limit: 2,
});
expect(result.data).toHaveLength(2);
expect(result.has_more).toBe(true);
expect(result.after).not.toBeNull();
});
test('should paginate using cursor', async () => {
// Get first page
const firstPage = await methods.getListMCPServersByIds({
ids: [server1._id, server2._id, server3._id],
limit: 2,
});
expect(firstPage.has_more).toBe(true);
expect(firstPage.after).not.toBeNull();
// Get second page using cursor
const secondPage = await methods.getListMCPServersByIds({
ids: [server1._id, server2._id, server3._id],
limit: 2,
after: firstPage.after,
});
expect(secondPage.data).toHaveLength(1);
expect(secondPage.has_more).toBe(false);
expect(secondPage.after).toBeNull();
// Ensure no duplicates between pages
const firstPageIds = firstPage.data.map((s) => s._id.toString());
const secondPageIds = secondPage.data.map((s) => s._id.toString());
const intersection = firstPageIds.filter((id) => secondPageIds.includes(id));
expect(intersection).toHaveLength(0);
});
test('should handle invalid cursor gracefully', async () => {
const result = await methods.getListMCPServersByIds({
ids: [server1._id, server2._id],
after: 'invalid-cursor',
});
// Should still return results, ignoring invalid cursor
expect(result.data).toHaveLength(2);
});
test('should return all when limit is null', async () => {
const result = await methods.getListMCPServersByIds({
ids: [server1._id, server2._id, server3._id],
limit: null,
});
expect(result.data).toHaveLength(3);
expect(result.has_more).toBe(false);
expect(result.after).toBeNull();
});
test('should apply additional filters via otherParams', async () => {
// Create a server with different config
const serverWithDesc = await methods.createMCPServer({
config: createSSEConfig('Filtered Server', 'Has description'),
author: authorId,
});
const result = await methods.getListMCPServersByIds({
ids: [server1._id, server2._id, serverWithDesc._id],
otherParams: { 'config.description': 'Has description' },
});
expect(result.data).toHaveLength(1);
expect(result.data[0].serverName).toBe('filtered-server');
});
test('should normalize limit to valid range', async () => {
// Limit should be clamped to 1-100
const resultLow = await methods.getListMCPServersByIds({
ids: [server1._id, server2._id, server3._id],
limit: 0,
});
expect(resultLow.data.length).toBeGreaterThanOrEqual(1);
const resultHigh = await methods.getListMCPServersByIds({
ids: [server1._id, server2._id, server3._id],
limit: 200,
});
expect(resultHigh.data).toHaveLength(3); // All 3 servers (less than 100)
});
test('should sort by updatedAt descending, _id ascending', async () => {
const result = await methods.getListMCPServersByIds({
ids: [server1._id, server2._id, server3._id],
});
expect(result.data).toHaveLength(3);
// Most recently created/updated should come first
for (let i = 0; i < result.data.length - 1; i++) {
const current = new Date(result.data[i].updatedAt!).getTime();
const next = new Date(result.data[i + 1].updatedAt!).getTime();
expect(current).toBeGreaterThanOrEqual(next);
}
});
});
describe('updateMCPServer', () => {
test('should update server config', async () => {
const created = await methods.createMCPServer({
config: createSSEConfig('Update Test', 'Original description'),
author: authorId,
});
const updated = await methods.updateMCPServer(created.serverName, {
config: createSSEConfig('Update Test', 'Updated description'),
});
expect(updated).toBeDefined();
expect(updated?.config.description).toBe('Updated description');
expect(updated?.serverName).toBe('update-test'); // serverName shouldn't change
});
test('should return null when server not found', async () => {
const updated = await methods.updateMCPServer('non-existent', {
config: createSSEConfig('Test'),
});
expect(updated).toBeNull();
});
test('should return updated document (new: true)', async () => {
const created = await methods.createMCPServer({
config: createSSEConfig('Return Test'),
author: authorId,
});
const updated = await methods.updateMCPServer(created.serverName, {
config: createSSEConfig('Return Test', 'New description'),
});
expect(updated?.config.description).toBe('New description');
});
test('should run validators on update', async () => {
const created = await methods.createMCPServer({
config: createSSEConfig('Validation Test'),
author: authorId,
});
// The update should succeed with valid config
const updated = await methods.updateMCPServer(created.serverName, {
config: createSSEConfig('Validation Test', 'Valid config'),
});
expect(updated).toBeDefined();
});
test('should update timestamps', async () => {
const created = await methods.createMCPServer({
config: createSSEConfig('Timestamp Test'),
author: authorId,
});
const originalUpdatedAt = created.updatedAt;
// Wait a bit to ensure timestamp difference
await new Promise((resolve) => setTimeout(resolve, 10));
const updated = await methods.updateMCPServer(created.serverName, {
config: createSSEConfig('Timestamp Test', 'Updated'),
});
expect(updated?.updatedAt).toBeDefined();
expect(new Date(updated!.updatedAt!).getTime()).toBeGreaterThan(
new Date(originalUpdatedAt!).getTime(),
);
});
test('should handle partial config updates', async () => {
const created = await methods.createMCPServer({
config: {
type: 'sse',
url: 'https://example.com/mcp',
title: 'Partial Update Test',
description: 'Original',
},
author: authorId,
});
const updated = await methods.updateMCPServer(created.serverName, {
config: {
type: 'sse',
url: 'https://example.com/mcp',
title: 'Partial Update Test',
description: 'New description',
iconPath: '/icons/new-icon.png',
},
});
expect(updated?.config.description).toBe('New description');
expect(updated?.config.iconPath).toBe('/icons/new-icon.png');
});
});
describe('deleteMCPServer', () => {
test('should delete existing server', async () => {
const created = await methods.createMCPServer({
config: createSSEConfig('Delete Test'),
author: authorId,
});
const deleted = await methods.deleteMCPServer(created.serverName);
expect(deleted).toBeDefined();
expect(deleted?.serverName).toBe('delete-test');
// Verify it's actually deleted
const found = await methods.findMCPServerById('delete-test');
expect(found).toBeNull();
});
test('should return null when server does not exist', async () => {
const deleted = await methods.deleteMCPServer('non-existent-server');
expect(deleted).toBeNull();
});
test('should return the deleted document', async () => {
const created = await methods.createMCPServer({
config: createSSEConfig('Delete Return Test', 'Will be deleted'),
author: authorId,
});
const deleted = await methods.deleteMCPServer(created.serverName);
expect(deleted?.config.description).toBe('Will be deleted');
});
});
describe('getListMCPServersByNames', () => {
test('should return empty data for empty names array', async () => {
const result = await methods.getListMCPServersByNames({ names: [] });
expect(result.data).toEqual([]);
});
test('should find servers by serverName strings', async () => {
await methods.createMCPServer({
config: createSSEConfig('Name Query One'),
author: authorId,
});
await methods.createMCPServer({
config: createSSEConfig('Name Query Two'),
author: authorId,
});
await methods.createMCPServer({
config: createSSEConfig('Name Query Three'),
author: authorId,
});
const result = await methods.getListMCPServersByNames({
names: ['name-query-one', 'name-query-two'],
});
expect(result.data).toHaveLength(2);
const serverNames = result.data.map((s) => s.serverName);
expect(serverNames).toContain('name-query-one');
expect(serverNames).toContain('name-query-two');
expect(serverNames).not.toContain('name-query-three');
});
test('should handle non-existent names gracefully', async () => {
await methods.createMCPServer({
config: createSSEConfig('Existing Server'),
author: authorId,
});
const result = await methods.getListMCPServersByNames({
names: ['existing-server', 'non-existent-1', 'non-existent-2'],
});
expect(result.data).toHaveLength(1);
expect(result.data[0].serverName).toBe('existing-server');
});
test('should return all matching servers for multiple names', async () => {
const server1 = await methods.createMCPServer({
config: createSSEConfig('Multi Name 1'),
author: authorId,
});
const server2 = await methods.createMCPServer({
config: createSSEConfig('Multi Name 2'),
author: authorId,
});
const server3 = await methods.createMCPServer({
config: createSSEConfig('Multi Name 3'),
author: authorId,
});
const result = await methods.getListMCPServersByNames({
names: [server1.serverName, server2.serverName, server3.serverName],
});
expect(result.data).toHaveLength(3);
});
test('should handle duplicate names in input', async () => {
await methods.createMCPServer({
config: createSSEConfig('Duplicate Test'),
author: authorId,
});
const result = await methods.getListMCPServersByNames({
names: ['duplicate-test', 'duplicate-test', 'duplicate-test'],
});
// Should only return one server (unique by serverName)
expect(result.data).toHaveLength(1);
});
});
describe('Edge Cases', () => {
test('should handle concurrent creation with retry logic for race conditions', async () => {
// Ensure indexes are created before concurrent test
await MCPServer.ensureIndexes();
// Create multiple servers with same title concurrently
// The retry logic handles TOCTOU race conditions by retrying with
// exponential backoff when duplicate key errors occur
const promises = Array.from({ length: 5 }, () =>
methods.createMCPServer({
config: createSSEConfig('Concurrent Test'),
author: authorId,
}),
);
const results = await Promise.allSettled(promises);
const successes = results.filter(
(r): r is PromiseFulfilledResult<t.MCPServerDocument> => r.status === 'fulfilled',
);
const failures = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected');
// With retry logic, all concurrent requests should succeed
// Each will get a unique serverName (concurrent-test, concurrent-test-2, etc.)
expect(successes.length).toBe(5);
expect(failures.length).toBe(0);
// Verify all servers have unique names
const serverNames = successes.map((s) => s.value.serverName);
const uniqueNames = new Set(serverNames);
expect(uniqueNames.size).toBe(5);
// Verify all servers exist in the database
const dbServers = await MCPServer.find({
serverName: { $regex: /^concurrent-test/ },
}).lean();
expect(dbServers.length).toBe(5);
});
test('should handle sequential creation with same title - no race condition', async () => {
// Create multiple servers with same title sequentially
// Each creation completes before the next one starts, so no race condition
const results: t.MCPServerDocument[] = [];
for (let i = 0; i < 5; i++) {
const server = await methods.createMCPServer({
config: createSSEConfig('Sequential Test'),
author: authorId,
});
results.push(server);
}
// All should succeed with unique serverNames
const serverNames = results.map((r) => r.serverName);
const uniqueNames = new Set(serverNames);
expect(uniqueNames.size).toBe(5);
expect(serverNames).toContain('sequential-test');
expect(serverNames).toContain('sequential-test-2');
expect(serverNames).toContain('sequential-test-3');
expect(serverNames).toContain('sequential-test-4');
expect(serverNames).toContain('sequential-test-5');
});
test('should handle very long titles', async () => {
const longTitle = 'A'.repeat(200) + ' Server';
const config = createSSEConfig(longTitle);
const server = await methods.createMCPServer({ config, author: authorId });
expect(server).toBeDefined();
expect(server.serverName).toBe('a'.repeat(200) + '-server');
});
test('should handle unicode in title', async () => {
// Unicode characters should be stripped, leaving only alphanumeric
const config = createSSEConfig('Serveur Français 日本語');
const server = await methods.createMCPServer({ config, author: authorId });
expect(server.serverName).toBe('serveur-franais');
});
test('should handle empty string title', async () => {
const config: MCPOptions = {
type: 'sse',
url: 'https://example.com/mcp',
title: '',
};
const server = await methods.createMCPServer({ config, author: authorId });
// Empty title should fallback to nanoid
expect(server.serverName).toMatch(/^mcp-[a-zA-Z0-9_-]{16}$/);
});
test('should handle whitespace-only title', async () => {
const config = createSSEConfig(' ');
const server = await methods.createMCPServer({ config, author: authorId });
// Whitespace-only title after trimming results in fallback
expect(server.serverName).toBe('mcp-server');
});
});
});

View file

@ -0,0 +1,324 @@
import type { Model, RootFilterQuery, Types } from 'mongoose';
import type { MCPServerDocument } from '../types';
import type { MCPOptions } from 'librechat-data-provider';
import logger from '~/config/winston';
import { nanoid } from 'nanoid';
const NORMALIZED_LIMIT_DEFAULT = 20;
const MAX_CREATE_RETRIES = 3;
const RETRY_BASE_DELAY_MS = 10;
/**
* Helper to check if an error is a MongoDB duplicate key error.
* Since serverName is the only unique index on MCPServer, any E11000 error
* during creation is necessarily a serverName collision.
*/
function isDuplicateKeyError(error: unknown): boolean {
if (error && typeof error === 'object' && 'code' in error) {
const mongoError = error as { code: number };
return mongoError.code === 11000;
}
return false;
}
/**
* Escapes special regex characters in a string so they are treated literally.
*/
function escapeRegex(str: string): string {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/**
* Generates a URL-friendly server name from a title.
* Converts to lowercase, replaces spaces with hyphens, removes special characters.
*/
function generateServerNameFromTitle(title: string): string {
const slug = title
.toLowerCase()
.trim()
.replace(/[^a-z0-9\s-]/g, '') // Remove special chars except spaces and hyphens
.replace(/\s+/g, '-') // Replace spaces with hyphens
.replace(/-+/g, '-') // Remove consecutive hyphens
.replace(/^-|-$/g, ''); // Trim leading/trailing hyphens
return slug || 'mcp-server'; // Fallback if empty
}
export function createMCPServerMethods(mongoose: typeof import('mongoose')) {
/**
* Finds the next available server name by checking for duplicates.
* If baseName exists, returns baseName-2, baseName-3, etc.
*/
async function findNextAvailableServerName(baseName: string): Promise<string> {
const MCPServer = mongoose.models.MCPServer as Model<MCPServerDocument>;
// Find all servers with matching base name pattern (baseName or baseName-N)
const escapedBaseName = escapeRegex(baseName);
const existing = await MCPServer.find({
serverName: { $regex: `^${escapedBaseName}(-\\d+)?$` },
})
.select('serverName')
.lean();
if (existing.length === 0) {
return baseName;
}
// Extract numbers from existing names
const numbers = existing.map((s) => {
const match = s.serverName.match(/-(\d+)$/);
return match ? parseInt(match[1], 10) : 1;
});
const maxNumber = Math.max(...numbers);
return `${baseName}-${maxNumber + 1}`;
}
/**
* Create a new MCP server with retry logic for handling race conditions.
* When multiple requests try to create servers with the same title simultaneously,
* they may get the same serverName from findNextAvailableServerName() before any
* creates the record (TOCTOU race condition). This is handled by retrying with
* exponential backoff when a duplicate key error occurs.
* @param data - Object containing config (with title, description, url, etc.) and author
* @returns The created MCP server document
*/
async function createMCPServer(data: {
config: MCPOptions;
author: string | Types.ObjectId;
}): Promise<MCPServerDocument> {
const MCPServer = mongoose.models.MCPServer as Model<MCPServerDocument>;
let lastError: unknown;
for (let attempt = 0; attempt < MAX_CREATE_RETRIES; attempt++) {
try {
// Generate serverName from title, with fallback to nanoid if no title
// Important: regenerate on each attempt to get fresh available name
let serverName: string;
if (data.config.title) {
const baseSlug = generateServerNameFromTitle(data.config.title);
serverName = await findNextAvailableServerName(baseSlug);
} else {
serverName = `mcp-${nanoid(16)}`;
}
const newServer = await MCPServer.create({
serverName,
config: data.config,
author: data.author,
});
return newServer.toObject() as MCPServerDocument;
} catch (error) {
lastError = error;
// Only retry on duplicate key errors (serverName collision)
if (isDuplicateKeyError(error) && attempt < MAX_CREATE_RETRIES - 1) {
// Exponential backoff: 10ms, 20ms, 40ms
const delay = RETRY_BASE_DELAY_MS * Math.pow(2, attempt);
logger.debug(
`[createMCPServer] Duplicate serverName detected, retrying (attempt ${attempt + 2}/${MAX_CREATE_RETRIES}) after ${delay}ms`,
);
await new Promise((resolve) => setTimeout(resolve, delay));
continue;
}
// Not a duplicate key error or out of retries - throw immediately
throw error;
}
}
// Should not reach here, but TypeScript requires a return
throw lastError;
}
/**
* Find an MCP server by serverName
* @param serverName - The MCP server ID
* @returns The MCP server document or null
*/
async function findMCPServerById(serverName: string): Promise<MCPServerDocument | null> {
const MCPServer = mongoose.models.MCPServer as Model<MCPServerDocument>;
return await MCPServer.findOne({ serverName }).lean();
}
/**
* Find an MCP server by MongoDB ObjectId
* @param _id - The MongoDB ObjectId
* @returns The MCP server document or null
*/
async function findMCPServerByObjectId(
_id: string | Types.ObjectId,
): Promise<MCPServerDocument | null> {
const MCPServer = mongoose.models.MCPServer as Model<MCPServerDocument>;
return await MCPServer.findById(_id).lean();
}
/**
* Find MCP servers by author
* @param authorId - The author's ObjectId or string
* @returns Array of MCP server documents
*/
async function findMCPServersByAuthor(
authorId: string | Types.ObjectId,
): Promise<MCPServerDocument[]> {
const MCPServer = mongoose.models.MCPServer as Model<MCPServerDocument>;
return await MCPServer.find({ author: authorId }).sort({ updatedAt: -1 }).lean();
}
/**
* Get a paginated list of MCP servers by IDs with filtering and search
* @param ids - Array of ObjectIds to include
* @param otherParams - Additional filter parameters (e.g., search)
* @param limit - Page size limit (null for no pagination)
* @param after - Cursor for pagination
* @returns Paginated list of MCP servers
*/
async function getListMCPServersByIds({
ids = [],
otherParams = {},
limit = null,
after = null,
}: {
ids?: Types.ObjectId[];
otherParams?: RootFilterQuery<MCPServerDocument>;
limit?: number | null;
after?: string | null;
}): Promise<{
data: MCPServerDocument[];
has_more: boolean;
after: string | null;
}> {
const MCPServer = mongoose.models.MCPServer as Model<MCPServerDocument>;
const isPaginated = limit !== null && limit !== undefined;
const normalizedLimit = isPaginated
? Math.min(Math.max(1, parseInt(String(limit)) || NORMALIZED_LIMIT_DEFAULT), 100)
: null;
// Build base query combining accessible servers with other filters
const baseQuery: RootFilterQuery<MCPServerDocument> = { ...otherParams, _id: { $in: ids } };
// Add cursor condition
if (after) {
try {
const cursor = JSON.parse(Buffer.from(after, 'base64').toString('utf8'));
const { updatedAt, _id } = cursor;
const cursorCondition = {
$or: [
{ updatedAt: { $lt: new Date(updatedAt) } },
{ updatedAt: new Date(updatedAt), _id: { $gt: new mongoose.Types.ObjectId(_id) } },
],
};
// Merge cursor condition with base query
if (Object.keys(baseQuery).length > 0) {
baseQuery.$and = [{ ...baseQuery }, cursorCondition];
// Remove the original conditions from baseQuery to avoid duplication
Object.keys(baseQuery).forEach((key) => {
if (key !== '$and') {
delete baseQuery[key];
}
});
}
} catch (error) {
// Invalid cursor, ignore
logger.warn('[getListMCPServersByIds] Invalid cursor provided', error);
}
}
if (normalizedLimit === null) {
// No pagination - return all matching servers
const servers = await MCPServer.find(baseQuery).sort({ updatedAt: -1, _id: 1 }).lean();
return {
data: servers,
has_more: false,
after: null,
};
}
// Paginated query - assign to const to help TypeScript
const servers = await MCPServer.find(baseQuery)
.sort({ updatedAt: -1, _id: 1 })
.limit(normalizedLimit + 1)
.lean();
const hasMore = servers.length > normalizedLimit;
const data = hasMore ? servers.slice(0, normalizedLimit) : servers;
let nextCursor = null;
if (hasMore && data.length > 0) {
const lastItem = data[data.length - 1];
nextCursor = Buffer.from(
JSON.stringify({
updatedAt: lastItem.updatedAt,
_id: lastItem._id,
}),
).toString('base64');
}
return {
data,
has_more: hasMore,
after: nextCursor,
};
}
/**
* Update an MCP server
* @param serverName - The MCP server ID
* @param updateData - Object containing config to update
* @returns The updated MCP server document or null
*/
async function updateMCPServer(
serverName: string,
updateData: { config?: MCPOptions },
): Promise<MCPServerDocument | null> {
const MCPServer = mongoose.models.MCPServer as Model<MCPServerDocument>;
return await MCPServer.findOneAndUpdate(
{ serverName },
{ $set: updateData },
{ new: true, runValidators: true },
).lean();
}
/**
* Delete an MCP server
* @param serverName - The MCP server ID
* @returns The deleted MCP server document or null
*/
async function deleteMCPServer(serverName: string): Promise<MCPServerDocument | null> {
const MCPServer = mongoose.models.MCPServer as Model<MCPServerDocument>;
return await MCPServer.findOneAndDelete({ serverName }).lean();
}
/**
* Get MCP servers by their serverName strings
* @param names - Array of serverName strings to fetch
* @returns Object containing array of MCP server documents
*/
async function getListMCPServersByNames({ names = [] }: { names: string[] }): Promise<{
data: MCPServerDocument[];
}> {
if (names.length === 0) {
return { data: [] };
}
const MCPServer = mongoose.models.MCPServer as Model<MCPServerDocument>;
const servers = await MCPServer.find({ serverName: { $in: names } }).lean();
return { data: servers };
}
return {
createMCPServer,
findMCPServerById,
findMCPServerByObjectId,
findMCPServersByAuthor,
getListMCPServersByIds,
getListMCPServersByNames,
updateMCPServer,
deleteMCPServer,
};
}
export type MCPServerMethods = ReturnType<typeof createMCPServerMethods>;

View file

@ -6,6 +6,7 @@ import { createConversationModel } from './convo';
import { createMessageModel } from './message';
import { createAgentModel } from './agent';
import { createAgentCategoryModel } from './agentCategory';
import { createMCPServerModel } from './mcpServer';
import { createRoleModel } from './role';
import { createActionModel } from './action';
import { createAssistantModel } from './assistant';
@ -39,6 +40,7 @@ export function createModels(mongoose: typeof import('mongoose')) {
Message: createMessageModel(mongoose),
Agent: createAgentModel(mongoose),
AgentCategory: createAgentCategoryModel(mongoose),
MCPServer: createMCPServerModel(mongoose),
Role: createRoleModel(mongoose),
Action: createActionModel(mongoose),
Assistant: createAssistantModel(mongoose),

View file

@ -0,0 +1,11 @@
import mcpServerSchema from '~/schema/mcpServer';
import type { MCPServerDocument } from '~/types';
/**
* Creates or returns the MCPServer model using the provided mongoose instance and schema
*/
export function createMCPServerModel(mongoose: typeof import('mongoose')) {
return (
mongoose.models.MCPServer || mongoose.model<MCPServerDocument>('MCPServer', mcpServerSchema)
);
}

View file

@ -16,7 +16,7 @@ const accessRoleSchema = new Schema<IAccessRole>(
description: String,
resourceType: {
type: String,
enum: ['agent', 'project', 'file', 'promptGroup'],
enum: ['agent', 'project', 'file', 'promptGroup', 'mcpServer'],
required: true,
default: 'agent',
},

View file

@ -112,6 +112,12 @@ const agentSchema = new Schema<IAgent>(
default: false,
index: true,
},
/** MCP server names extracted from tools for efficient querying */
mcpServerNames: {
type: [String],
default: [],
index: true,
},
},
{
timestamps: true,

View file

@ -0,0 +1,31 @@
import { Schema } from 'mongoose';
import type { MCPServerDocument } from '~/types';
const mcpServerSchema = new Schema<MCPServerDocument>(
{
serverName: {
type: String,
index: true,
unique: true,
required: true,
},
config: {
type: Schema.Types.Mixed,
required: true,
// Config contains: title, description, url, oauth, etc.
},
author: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
index: true,
},
},
{
timestamps: true,
},
);
mcpServerSchema.index({ updatedAt: -1, _id: 1 });
export default mcpServerSchema;

View file

@ -53,6 +53,11 @@ const rolePermissionsSchema = new Schema(
[PermissionTypes.FILE_CITATIONS]: {
[Permissions.USE]: { type: Boolean },
},
[PermissionTypes.MCP_SERVERS]: {
[Permissions.USE]: { type: Boolean },
[Permissions.CREATE]: { type: Boolean },
[Permissions.SHARE]: { type: Boolean },
},
},
{ _id: false },
);

View file

@ -40,4 +40,6 @@ export interface IAgent extends Omit<Document, 'model'> {
category: string;
support_contact?: ISupportContact;
is_promoted?: boolean;
/** MCP server names extracted from tools for efficient querying */
mcpServerNames?: string[];
}

View file

@ -27,3 +27,5 @@ export * from './aclEntry';
export * from './group';
/* Web */
export * from './web';
/* MCP Servers */
export * from './mcp';

View file

@ -0,0 +1,12 @@
import { Document, Types } from 'mongoose';
import type { MCPServerDB } from 'librechat-data-provider';
/**
* Mongoose document interface for MCP Server
* Extends API interface with Mongoose-specific database fields
*/
export interface MCPServerDocument
extends Omit<MCPServerDB, 'author' | '_id'>,
Document<Types.ObjectId> {
author: Types.ObjectId; // ObjectId reference in DB (vs string in API)
}

View file

@ -51,6 +51,11 @@ export interface IRole extends Document {
[PermissionTypes.FILE_CITATIONS]?: {
[Permissions.USE]?: boolean;
};
[PermissionTypes.MCP_SERVERS]?: {
[Permissions.USE]?: boolean;
[Permissions.CREATE]?: boolean;
[Permissions.SHARE]?: boolean;
};
};
}