Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🧭 fix: Reduce MCP Registry ACL Lookups (#13195)

Danny Avila749eb06e6748
diff --git a/api/server/controllers/agents/v1.js b/api/server/controllers/agents/v1.js
index 8dbe881fbb..997ced213f 100644
--- a/api/server/controllers/agents/v1.js
+++ b/api/server/controllers/agents/v1.js
@@ -189,6 +189,7 @@ const isSubagentsCapabilityEnabled = (req) => {
* @param {object} params
* @param {string[]} params.tools - Raw tool strings from the request
* @param {string} params.userId - Requesting user ID for MCP server access check
+ * @param {string} [params.role] - Requesting user's role for ACL principal resolution
* @param {Record<string, unknown>} params.availableTools - Global non-MCP tool cache
* @param {string[]} [params.existingTools] - Tools already persisted on the agent document
* @param {Record<string, unknown>} [params.configServers] - Config-source MCP servers resolved from appConfig overrides
@@ -197,6 +198,7 @@ const isSubagentsCapabilityEnabled = (req) => {
const filterAuthorizedTools = async ({
tools,
userId,
+ role,
availableTools,
existingTools,
configServers,
@@ -219,7 +221,9 @@ const filterAuthorizedTools = async ({
if (mcpServerConfigs === undefined) {
try {
mcpServerConfigs =
- (await getMCPServersRegistry().getAllServerConfigs(userId, configServers)) ?? {};
+ (role
+ ? await getMCPServersRegistry().getAllServerConfigs(userId, configServers, role)
+ : await getMCPServersRegistry().getAllServerConfigs(userId, configServers)) ?? {};
} catch (e) {
logger.warn(
'[filterAuthorizedTools] MCP registry unavailable, filtering all MCP tools',
@@ -387,6 +391,7 @@ const createAgentHandler = async (req, res) => {
agentData.tools = await filterAuthorizedTools({
tools,
userId,
+ role: req.user.role,
availableTools,
configServers,
});
@@ -620,6 +625,7 @@ const updateAgentHandler = async (req, res) => {
const approvedNew = await filterAuthorizedTools({
tools: newMCPTools,
userId: req.user.id,
+ role: req.user.role,
availableTools,
configServers,
});
@@ -781,6 +787,7 @@ const duplicateAgentHandler = async (req, res) => {
newAgentData.tools = await filterAuthorizedTools({
tools: newAgentData.tools,
userId,
+ role: req.user.role,
availableTools,
existingTools: newAgentData.tools,
configServers,
@@ -1155,6 +1162,7 @@ const revertAgentVersionHandler = async (req, res) => {
const filteredTools = await filterAuthorizedTools({
tools: updatedAgent.tools,
userId: req.user.id,
+ role: req.user.role,
availableTools,
existingTools: updatedAgent.tools,
configServers,
diff --git a/api/server/services/MCP.js b/api/server/services/MCP.js
index f2e845b927..c691c4330a 100644
--- a/api/server/services/MCP.js
+++ b/api/server/services/MCP.js
@@ -98,6 +98,10 @@ async function resolveAllMcpConfigs(userId, user) {
error,
);
}
+ if (user?.role) {
+ return await registry.getAllServerConfigs(userId, configServers, user.role);
+ }
+
return await registry.getAllServerConfigs(userId, configServers);
}
@@ -728,7 +732,9 @@ async function getMCPSetupData(userId, options = {}) {
const appConfig = await getAppConfig({ role, tenantId, userId });
const configServers = await registry.ensureConfigServers(appConfig?.mcpConfig || {});
- const mcpConfig = await registry.getAllServerConfigs(userId, configServers);
+ const mcpConfig = role
+ ? await registry.getAllServerConfigs(userId, configServers, role)
+ : await registry.getAllServerConfigs(userId, configServers);
const mcpManager = getMCPManager(userId);
/** @type {Map<string, import('@librechat/api').MCPConnection>} */
let appConnections = new Map();
diff --git a/api/server/services/__tests__/MCP.spec.js b/api/server/services/__tests__/MCP.spec.js
index 39e99d54ac..2de88cfcd0 100644
--- a/api/server/services/__tests__/MCP.spec.js
+++ b/api/server/services/__tests__/MCP.spec.js
@@ -23,6 +23,17 @@ jest.mock('~/server/services/Config', () => ({
loadCustomConfig: jest.fn(),
}));
+jest.mock('@librechat/api', () => ({
+ sendEvent: jest.fn(),
+ MCPOAuthHandler: jest.fn(),
+ isMCPDomainAllowed: jest.fn(),
+ normalizeServerName: jest.fn((name) => name),
+ normalizeJsonSchema: jest.fn((schema) => schema),
+ GenerationJobManager: jest.fn(),
+ resolveJsonSchemaRefs: jest.fn((schema) => schema),
+ buildOAuthToolCallName: jest.fn((name) => name),
+}));
+
jest.mock('~/cache', () => ({ getLogStores: jest.fn() }));
jest.mock('~/models', () => ({
findToken: jest.fn(),
@@ -99,9 +110,13 @@ describe('resolveAllMcpConfigs', () => {
cfg_srv: { name: 'cfg_srv' },
yaml_srv: { name: 'yaml_srv' },
});
- expect(mockRegistry.getAllServerConfigs).toHaveBeenCalledWith('u1', {
- cfg_srv: { name: 'cfg_srv' },
- });
+ expect(mockRegistry.getAllServerConfigs).toHaveBeenCalledWith(
+ 'u1',
+ {
+ cfg_srv: { name: 'cfg_srv' },
+ },
+ 'user',
+ );
});
it('continues with empty configServers when ensureConfigServers fails', async () => {
diff --git a/packages/api/src/acl/accessControlService.ts b/packages/api/src/acl/accessControlService.ts
index 57d072561a..eeed3a6a2f 100644
--- a/packages/api/src/acl/accessControlService.ts
+++ b/packages/api/src/acl/accessControlService.ts
@@ -1,13 +1,16 @@
-import { Types, ClientSession, DeleteResult } from 'mongoose';
-import { AllMethods, IAclEntry, createMethods, logger } from '@librechat/data-schemas';
+import { Types } from 'mongoose';
+import { createMethods, logger } from '@librechat/data-schemas';
import { AccessRoleIds, PrincipalType, ResourceType } from 'librechat-data-provider';
+import type { AllMethods, IAclEntry } from '@librechat/data-schemas';
+import type { ClientSession, DeleteResult } from 'mongoose';
+
+import type { ResolvedPrincipal } from '~/types/principal';
export class AccessControlService {
private _dbMethods: AllMethods;
- private _aclModel;
+
constructor(mongoose: typeof import('mongoose')) {
this._dbMethods = createMethods(mongoose);
- this._aclModel = mongoose.models.AclEntry;
}
/**
@@ -122,6 +125,44 @@ export class AccessControlService {
role?: string;
resourceType: string;
requiredPermissions: number;
+ }): Promise<Types.ObjectId[]> {
+ try {
+ const principalsList = await this.getUserPrincipals({ userId, role });
+ return await this.findAccessibleResourcesForPrincipals({
+ 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 [];
+ }
+ }
+
+ public async getUserPrincipals({
+ userId,
+ role,
+ }: {
+ userId: string | Types.ObjectId;
+ role?: string;
+ }): Promise<ResolvedPrincipal[]> {
+ return await this._dbMethods.getUserPrincipals({ userId, role });
+ }
+
+ public async findAccessibleResourcesForPrincipals({
+ principalsList,
+ resourceType,
+ requiredPermissions,
+ }: {
+ principalsList: ResolvedPrincipal[];
+ resourceType: string;
+ requiredPermissions: number;
}): Promise<Types.ObjectId[]> {
try {
if (typeof requiredPermissions !== 'number' || requiredPermissions < 1) {
@@ -130,12 +171,10 @@ export class AccessControlService {
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,
@@ -143,8 +182,9 @@ export class AccessControlService {
);
} catch (error) {
if (error instanceof Error) {
- logger.error(`[PermissionService.findAccessibleResources] Error: ${error.message}`);
- // Re-throw validation errors
+ logger.error(
+ `[PermissionService.findAccessibleResourcesForPrincipals] Error: ${error.message}`,
+ );
if (error.message.includes('requiredPermissions must be')) {
throw error;
}
@@ -266,7 +306,7 @@ export class AccessControlService {
throw new Error(`Invalid resource ID: ${resourceId}`);
}
- const result = await this._aclModel.deleteMany({
+ const result = await this._dbMethods.deleteAclEntries({
resourceType,
resourceId,
});
diff --git a/packages/api/src/mcp/registry/MCPServersRegistry.ts b/packages/api/src/mcp/registry/MCPServersRegistry.ts
index 1063071ac6..534cb3fd8b 100644
--- a/packages/api/src/mcp/registry/MCPServersRegistry.ts
+++ b/packages/api/src/mcp/registry/MCPServersRegistry.ts
@@ -170,11 +170,12 @@ export class MCPServersRegistry {
public async getAllServerConfigs(
userId?: string,
configServers?: Record<string, t.ParsedServerConfig>,
+ role?: string,
): Promise<Record<string, t.ParsedServerConfig>> {
if (configServers == null || !Object.keys(configServers).length) {
- return this.getBaseServerConfigs(userId);
+ return this.getBaseServerConfigs(userId, role);
}
- const base = await this.getBaseServerConfigs(userId);
+ const base = await this.getBaseServerConfigs(userId, role);
return { ...configServers, ...base };
}
@@ -185,6 +186,7 @@ export class MCPServersRegistry {
*/
private async getBaseServerConfigs(
userId?: string,
+ role?: string,
): Promise<Record<string, t.ParsedServerConfig>> {
const cacheKey = userId ?? '__no_user__';
@@ -197,7 +199,7 @@ export class MCPServersRegistry {
return pending;
}
- const fetchPromise = this.fetchBaseServerConfigs(cacheKey, userId);
+ const fetchPromise = this.fetchBaseServerConfigs(cacheKey, userId, role);
this.pendingGetAllPromises.set(cacheKey, fetchPromise);
try {
@@ -210,10 +212,11 @@ export class MCPServersRegistry {
private async fetchBaseServerConfigs(
cacheKey: string,
userId?: string,
+ role?: string,
): Promise<Record<string, t.ParsedServerConfig>> {
const result = {
...(await this.cacheConfigsRepo.getAll()),
- ...(await this.dbConfigsRepo.getAll(userId)),
+ ...(await this.dbConfigsRepo.getAll(userId, role)),
};
await this.readThroughCacheAll.set(cacheKey, result);
diff --git a/packages/api/src/mcp/registry/ServerConfigsRepositoryInterface.ts b/packages/api/src/mcp/registry/ServerConfigsRepositoryInterface.ts
index 4bf0fdd615..e55f66faa7 100644
--- a/packages/api/src/mcp/registry/ServerConfigsRepositoryInterface.ts
+++ b/packages/api/src/mcp/registry/ServerConfigsRepositoryInterface.ts
@@ -19,7 +19,7 @@ export interface IServerConfigsRepositoryInterface {
get(serverName: string, userId?: string): Promise<ParsedServerConfig | undefined>;
//ACL Entry get all accessible mcp config definitions + any mcp configured with agents
- getAll(userId?: string): Promise<Record<string, ParsedServerConfig>>;
+ getAll(userId?: string, role?: string): Promise<Record<string, ParsedServerConfig>>;
reset(): Promise<void>;
}
diff --git a/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts b/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts
index 38ed51cd99..e8c089df34 100644
--- a/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts
+++ b/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts
@@ -963,6 +963,17 @@ describe('ServerConfigsDB', () => {
});
describe('user access', () => {
+ it('should reuse resolved principals for direct and agent access lookups', async () => {
+ const findByIdSpy = jest.spyOn(mongoose.models.User, 'findById');
+
+ try {
+ await serverConfigsDB.getAll(userId, 'USER');
+ expect(findByIdSpy).toHaveBeenCalledTimes(1);
+ } finally {
+ findByIdSpy.mockRestore();
+ }
+ });
+
it('should return servers directly accessible by user', async () => {
const config1 = createSSEConfig('User Server 1');
const config2 = createSSEConfig('User Server 2');
diff --git a/packages/api/src/mcp/registry/db/ServerConfigsDB.ts b/packages/api/src/mcp/registry/db/ServerConfigsDB.ts
index d027fc273e..30e0185721 100644
--- a/packages/api/src/mcp/registry/db/ServerConfigsDB.ts
+++ b/packages/api/src/mcp/registry/db/ServerConfigsDB.ts
@@ -1,12 +1,13 @@
import { Types } from 'mongoose';
+import { logger, encryptV2, decryptV2, createMethods } from '@librechat/data-schemas';
import {
ResourceType,
AccessRoleIds,
PrincipalType,
PermissionBits,
} from 'librechat-data-provider';
-import { logger, encryptV2, decryptV2, createMethods } from '@librechat/data-schemas';
-import type { AllMethods, IAgent, MCPServerDocument } from '@librechat/data-schemas';
+import type { AllMethods, MCPServerDocument } from '@librechat/data-schemas';
+
import type { IServerConfigsRepositoryInterface } from '~/mcp/registry/ServerConfigsRepositoryInterface';
import type { ParsedServerConfig, AddServerResult } from '~/mcp/types';
import { AccessControlService } from '~/acl/accessControlService';
@@ -59,13 +60,11 @@ function sanitizeCredentialPlaceholders(
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);
}
@@ -98,13 +97,10 @@ export class ServerConfigsDB implements IServerConfigsRepositoryInterface {
return false;
}
- const Agent = this._mongoose.model('Agent');
- const exists = await Agent.exists({
- _id: { $in: accessibleAgentIds },
- mcpServerNames: serverName,
+ return await this._dbMethods.hasAgentWithMCPServerName({
+ agentIds: accessibleAgentIds,
+ serverName,
});
-
- return exists !== null;
}
/**
@@ -327,57 +323,52 @@ export class ServerConfigsDB implements IServerConfigsRepositoryInterface {
* @param userId optional user id. if not provided only publicly shared mcp configs will be returned
* @returns record of parsed configs
*/
- public async getAll(userId?: string): Promise<Record<string, ParsedServerConfig>> {
+ public async getAll(userId?: string, role?: string): Promise<Record<string, ParsedServerConfig>> {
let directlyAccessibleMCPIds: Types.ObjectId[] = [];
+ let accessibleAgentIds: 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,
- });
+ [directlyAccessibleMCPIds, accessibleAgentIds] = await Promise.all([
+ this._aclService.findPubliclyAccessibleResources({
+ resourceType: ResourceType.MCPSERVER,
+ requiredPermissions: PermissionBits.VIEW,
+ }),
+ this._aclService.findPubliclyAccessibleResources({
+ resourceType: ResourceType.AGENT,
+ 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,
- });
- }
-
- let agentMCPServerNames: string[] = [];
- let accessibleAgentIds: Types.ObjectId[] = [];
-
- if (!userId) {
- accessibleAgentIds = await this._aclService.findPubliclyAccessibleResources({
- resourceType: ResourceType.AGENT,
- requiredPermissions: PermissionBits.VIEW,
- });
- } else {
- accessibleAgentIds = await this._aclService.findAccessibleResources({
- userId,
- requiredPermissions: PermissionBits.VIEW,
- resourceType: ResourceType.AGENT,
- });
- }
-
- if (accessibleAgentIds.length > 0) {
- const Agent = this._mongoose.model('Agent');
- const agentsWithMCP = await Agent.find(
- {
- _id: { $in: accessibleAgentIds },
- mcpServerNames: { $exists: true, $not: { $size: 0 } },
- },
- { mcpServerNames: 1 },
- ).lean<Pick<IAgent, 'mcpServerNames'>[]>();
-
- agentMCPServerNames = [...new Set(agentsWithMCP.flatMap((a) => a.mcpServerNames ?? []))];
+ const principalsList = await this._aclService.getUserPrincipals({ userId, role });
+ [directlyAccessibleMCPIds, accessibleAgentIds] = await Promise.all([
+ this._aclService.findAccessibleResourcesForPrincipals({
+ principalsList,
+ requiredPermissions: PermissionBits.VIEW,
+ resourceType: ResourceType.MCPSERVER,
+ }),
+ this._aclService.findAccessibleResourcesForPrincipals({
+ principalsList,
+ requiredPermissions: PermissionBits.VIEW,
+ resourceType: ResourceType.AGENT,
+ }),
+ ]);
}
- const directResults = await this._dbMethods.getListMCPServersByIds({
+ const agentMCPServerNamesPromise: Promise<string[]> =
+ accessibleAgentIds.length > 0
+ ? this._dbMethods.getMCPServerNamesByAgentIds(accessibleAgentIds)
+ : Promise.resolve([]);
+ const directResultsPromise = this._dbMethods.getListMCPServersByIds({
ids: directlyAccessibleMCPIds,
});
+ const [agentMCPServerNames, directResults] = await Promise.all([
+ agentMCPServerNamesPromise,
+ directResultsPromise,
+ ]);
const parsedConfigs: Record<string, ParsedServerConfig> = {};
const directData = directResults.data || [];
diff --git a/packages/data-schemas/src/methods/agent.ts b/packages/data-schemas/src/methods/agent.ts
index 9078616c93..37015c21c4 100644
--- a/packages/data-schemas/src/methods/agent.ts
+++ b/packages/data-schemas/src/methods/agent.ts
@@ -282,6 +282,50 @@ export function createAgentMethods(mongoose: typeof import('mongoose'), deps: Ag
return await Agent.find(searchParameter).lean<IAgent[]>();
}
+ async function hasAgentWithMCPServerName({
+ agentIds,
+ serverName,
+ }: {
+ agentIds: Types.ObjectId[];
+ serverName: string;
+ }): Promise<boolean> {
+ if (agentIds.length === 0) {
+ return false;
+ }
+
+ const Agent = mongoose.models.Agent as Model<IAgent>;
+ const agent = await Agent.exists({
+ _id: { $in: agentIds },
+ mcpServerNames: serverName,
+ });
+
+ return agent !== null;
+ }
+
+ async function getMCPServerNamesByAgentIds(agentIds: Types.ObjectId[]): Promise<string[]> {
+ if (agentIds.length === 0) {
+ return [];
+ }
+
+ const Agent = mongoose.models.Agent as Model<IAgent>;
+ const agents = await Agent.find(
+ {
+ _id: { $in: agentIds },
+ mcpServerNames: { $exists: true, $not: { $size: 0 } },
+ },
+ { mcpServerNames: 1 },
+ ).lean<Array<Pick<IAgent, 'mcpServerNames'>>>();
+
+ const serverNames = new Set<string>();
+ for (const agent of agents) {
+ for (const serverName of agent.mcpServerNames ?? []) {
+ serverNames.add(serverName);
+ }
+ }
+
+ return Array.from(serverNames);
+ }
+
/**
* Update an agent with new data without overwriting existing properties,
* or create a new agent if it doesn't exist.
@@ -823,6 +867,8 @@ export function createAgentMethods(mongoose: typeof import('mongoose'), deps: Ag
getAgent,
getAgents,
createAgent,
+ hasAgentWithMCPServerName,
+ getMCPServerNamesByAgentIds,
updateAgent,
deleteAgent,
deleteUserAgents,